Files
uberbringer/docs/plans/formatters.md
T
57_WolveandClaude Opus 5.5 9b91109550
Test / Lint, test and build (push) Successful in 3m17s
Adopt norn's CI, release, API and docs practices; bare module path
Module
- The module path is now the bare "uberbringer"; imports read
  uberbringer/internal/... The banner keeps the Gitea URL.

CI and releases
- Workflows move to .gitea/workflows: test.yml (every branch push:
  gofmt, goimports, tidy, vet, staticcheck, race tests, goreleaser
  snapshot), security.yml (govulncheck weekly and on main) and a hardened
  release.yml (v* tags on main only, tags fetched, goreleaser pinned to
  2.20.3). The broken labeler workflow is removed.
- go.mod pins toolchain go1.27.4, which fixes GO-2026-6859; workflows
  check that the running Go matches it.
- .goreleaser.yaml: tidy check that never writes, reproducible file times,
  prerelease: auto, a release header linking CHANGELOG.md, and archives
  that ship CHANGELOG.md, the example config and the systemd unit.
- Makefile mirrors the CI gate; .dockerignore is an allowlist.

API and tests
- Every error answers {"error", "code", "details"} with a stable code from
  server/errors.go; the framework's own error text is never sent.
- Panics and unexpected errors are logged and reported to Sentry once;
  refusals are not logged as failures. /healthz sends no-store.
- TestRoutesConform requires auth, rate limiting and the body limit on
  every /api/v1 route.
- Race-prone tests no longer rely on freed ports or sleeps; serve takes
  an injected listener.
- The test config uses a placeholder secret instead of a real one.

Install and packaging
- install.sh resolves the latest release through the Gitea API, verifies
  checksums, requests a certificate only when none exists, installs the
  hardened packaging/uberbringer.service and writes the first token to a
  0600 file instead of printing it. It is now executable in git.

Docs
- CLAUDE.md, CHANGELOG.md (0.2.0 with breaking changes and upgrade
  steps), docs/design.md, and docs/plans/formatters.md for the planned
  CP437 blocks, modules and ntfy printing. README updated throughout.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 23:27:48 -06:00

56 KiB
Raw Blame History

Plan: CP437 blocks, modules and ntfy printing

Status: draft. Phase 1 can start; the remaining open questions only affect phases 3-5. Nothing here is built yet. 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 safehttp PrivateHosts exception is needed; drop it from phase 4.
  • 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".

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, a narrow safehttp PrivateHosts exception, the time/tzdata import, and Submit Meta for traceability.

WHAT SHIPS WHEN (about 12-13 developer days to the end of phase 4)

  1. Boxes and preview, 3-4 days. One /print element gives the single or double CP437 boxes the owner liked. POST /api/v1/preview and uberbringer preview show the exact output without using paper.
  2. Notes and modules, 2 days. POST /api/v1/print/note {title, text, items} prints a boxed checklist.
  3. Notifications, 3 days. POST /api/v1/print/notify {title, message, priority, tags} is for scripts and phone shortcuts. POST /api/v1/print/ntfy takes the ntfy CLI's $NTFY_RAW unchanged. After this phase, ntfy printing needs only a client.yml entry and no jq.
  4. Built-in ntfy subscriber, 4 days. You only change the config. It reconnects safely, removes duplicates, caps the backlog and folds floods into a digest receipt.
  5. Later, on demand: quiet hours, 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.
  • A byte-compatibility test, captured before any renderer change, pins today's output.
  • One deliberate change (approved): characters that print as '?' today print as close ASCII matches: smart quotes, dashes and the ellipsis. An emoji sequence prints as one '?' instead of several.
  • Emoji are removed only on the module and ntfy paths.

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.
  • Tight line spacing: off by default until a calibration print has been checked.
  • Scoped tokens: in phase 3, before any integration token is handed out.
  • Quiet hours: phase 5 unless you want them sooner (open question 5).

Open questions

Before phase 3:

  1. Topics and auth: which topics should print? A dedicated read-only ntfy user with an access token is assumed.
  2. Card extras: should the click link print as a QR code (first, all or none)? Should image attachments print? Should ntfy updates (sequence_id) print again marked '(updated)', or be skipped?
  3. Integration tokens: is it OK that tokens created with --modules can only use module routes, while existing tokens keep full access including raw ESC/POS?

Before phase 4:

  1. Paper budget: how many receipts per window before messages fold into a digest (the plan assumes 10 per 10 minutes)? Should priority 5 always bypass the limit?
  2. Quiet hours: wanted? If so: the window, the days, the priority that still prints, and whether held messages print as a morning digest or are dropped. A yes moves this into phase 4.

After phase 1's calibration print:

  1. Are the small gaps in vertical borders acceptable, or should boxes use tighter line spacing (box_line_spacing)?

When the second printer arrives:

  1. Which jobs and ntfy topics go to which printer, and should urgent messages print on both?

Mockups (42 columns, CP437)

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

--- 1. ntfy priority 4 (high)
╔═ HIGH ═════════════════════════════════╗
║ [!] Disk almost full                   ║
╟────────────────────────────────────────╢
║ /var is at 94% on nas01                ║
║                                        ║
║ Tags: nas01                            ║
╚═══════════════ alerts · 29 Nov 21:04 ══╝

         [qr: grafana.lan/d/disk]
              Open dashboard

       [image 384 dots: graph.png]
- - - - - - - partial cut - - - - - - - -
  Input: the brief's example message.
  Row 2 prints bold. [!] is the "warning"
  tag; "nas01" has no marker, so it is
  listed. **/var** *94%* prints plain.
  The QR is the click URL. The view action
  has the same URL, so its label is the
  caption. [...] lines are real graphics.

--- 2. ntfy priority 5 (max/urgent)
▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ URGENT ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
╔════════════════════════════════════════╗
║ (!) Backup FAILED on nas01             ║
╠════════════════════════════════════════╣
║ Job nightly-offsite exited with code 2 ║
║ after 3h12m. Last good run: 2 days     ║
║ ago.                                   ║
╚══════════════ backups · 29 Nov 21:04 ══╝
▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
  Row 3 prints bold and inverted. (!) is
  the "rotating_light" tag.

--- 3. ntfy priority 3 (default)
┌─ [√] Nightly backup ───────────────────┐
│ restic: 2.1 GB added in 14m 02s, 0     │
│ errors.                                │
│                                        │
│ Tags: restic                           │
└────────────── backups · 29 Nov 03:12 ──┘
  The title prints bold in the top border.

--- 4. ntfy priority 1-2 (no box)
── backups · 29 Nov 03:12 ────────────────
Prune finished
41 snapshots kept, 3 removed.
  "Prune finished" (the title) is bold.

--- 5. Single box note: POST /print/note
┌─ Shopping ─────────────────────────────┐
│ Milk, eggs and the good bread from the │
│ bakery on Elm St.                      │
│                                        │
│ [ ] Milk                               │
│ [ ] Eggs                               │
│ [√] Bread                              │
└──────────────────────── 29 Nov 21:04 ──┘

--- 6. Double box, capped title, centred
╔═╡ ACHTUNG ╞════════════════════════════╗
║ The coffee machine is being descaled.  ║
║        Do not use until 10:30.         ║
╚════════════════════════════════════════╝

--- 7. fit:true, one element each
         ┌─────────────────────┐
         │   !!! ACHTUNG !!!   │
         └─────────────────────┘

          ╔═══════════════════╗
          ║  !!! ACHTUNG !!!  ║
          ╚═══════════════════╝

--- 8. Box with kv, labelled rule and list
┌─ NAS REPORT ───────────────────────────┐
│ Host ........................... nas01 │
│ Pool ................... tank (raidz2) │
│ Used ............................. 94% │
├── Services ────────────────────────────┤
│ · grafana up                           │
│ · offsite-backup DOWN since 19:00      │
└──────────────────────── 29 Nov 21:04 ──┘
  A pair can set "bold" (e.g. Used 94%).

--- 9a. rule: single double light medium
──────────────────────────────────────────
══════════════════════════════════════════
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒

--- 9b. dark solid dashed dotted ascii
▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
██████████████████████████████████████████
- - - - - - - - - - - - - - - - - - - - -
··········································
------------------------------------------
───────────────── TODAY ──────────────────
═════════════════ TOTAL ══════════════════
── Notes ─────────────────────────────────
  The last three are labelled rules.

--- 10. kv (long value wraps) and list
Host ............................... nas01
Note ... The scrub finished with 0 errors.
                  Next scrub Sunday 03:00.

· Replace drive bay 3
· Order 2x 8 TB
1. First item that is long enough to wrap
   with a hanging indent
2. Second
[√] Done item
[ ] Open item

--- 11. Box styles and divider junctions
┌──────┐ ╔══════╗ ╒══════╕ ╓──────╖
│single│ ║double║ │dbl-h │ ║dbl-v ║
└──────┘ ╚══════╝ ╘══════╛ ╙──────╜
+------+
|ascii |
+------+

├──────┤ single box, single rule
╞══════╡ single box, double rule
╟──────╢ double box, single rule
╠══════╣ double box, double rule
  cp850/858: double-h and double-v fall
  back to double. cp1252: every box is
  ascii (+-|). Preview shows the result.

--- 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: • (not in any code
page), ► ◄ → ← 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","created_at":"2026-11-29T21:04:05Z"}

==== PHASE 1: new elements in POST /api/v1/print ====

Fields shared by the blocks (box, rule, kv, list):

  • size: 1-3. Scales the borders and the text together.
  • font: a or b.
  • Borders are never bold.

box

  • style: single (default, ┌─┐│└┘), double (╔═╗║╚╝), double-h (╒═╕│╘═╛), double-v (╓─╖║╙─╜) or ascii (+-|).
  • title: text set into the top border.
  • title_style: inline (default, ┌─ Title ──┐) or capped (╔═╡ Title ╞═╗).
  • footer: text set into the bottom border, on the right.
  • text: shorthand for the body. It wraps, and "\n" starts a new paragraph. It takes bold, underline and invert.
  • children: alternative to text. Allowed child types are text, rule, kv, list (phase 2) and feed.
  • text and children cannot both be set.
  • align: alignment of the shorthand text, and the default for text children.
  • padding: 0-3, default 1.
  • fit: true shrinks the box to its content and centres it.
  • columns: a fixed outer width. It is clamped to the paper, and a narrower box is centred.

Children inside a box:

  • text: may set bold, underline, invert, align and wrap. size, width, height and font are inherited from the box, and newline:false is not allowed.
  • rule: only single or double, optionally with text as a label. It becomes a divider whose junctions join the side borders.
  • Not allowed: box, qr, barcode, image, raw and cut. Place them after the box.

rule

  • style: single (default) ─, double ═, light ░, medium ▒, dark ▓, solid █, dashed "- ", dotted · or ascii -.
  • text: an optional label.
  • align: where the label sits. center is the default.
  • bold: applies to the label only.
  • columns.

kv

  • pairs: [{key, value, bold}], 1-100 of them.
  • leader: one of . (default), ·, space, _, - or ─.

list (phase 2)

  • items: 1-200 strings.
  • bullet: dot (default), dash, number or checkbox.
  • done: indexes of finished items, checkbox only. They print as [√], or [x] on code pages without √.

image (phase 3)

  • New field optional: true. If the image can't be fetched or decoded, the receipt prints "[image unavailable]" instead of failing the whole job.

Example 1: a boxed note in one element (mockup 5, with list from phase 2) POST /api/v1/print {"elements":[ {"type":"box","title":"Shopping","footer":"29 Nov 21:04","children":[ {"type":"text","text":"Milk, eggs and the good bread from the bakery on Elm St."}, {"type":"feed"}, {"type":"list","bullet":"checkbox","items":["Milk","Eggs","Bread"],"done":[2]} ]} ]}

Example 2: the owner's test-print look (mockups 6 and 7) {"elements":[ {"type":"box","style":"double","title":"ACHTUNG","title_style":"capped","align":"center", "text":"The coffee machine is being descaled.\nDo not use until 10:30."}, {"type":"box","fit":true,"padding":3,"text":"!!! ACHTUNG !!!"} ]}

Example 3: status report with kv rows and a labelled divider (mockup 8) {"elements":[ {"type":"box","title":"NAS REPORT","footer":"29 Nov 21:04","children":[ {"type":"kv","pairs":[{"key":"Host","value":"nas01"},{"key":"Pool","value":"tank (raidz2)"},{"key":"Used","value":"94%","bold":true}]}, {"type":"rule","text":"Services","align":"left"}, {"type":"list","items":["grafana up","offsite-backup DOWN since 19:00"]} ]}, {"type":"rule","style":"double","text":"TOTAL"}, {"type":"text","text":"Total: ","newline":false}, {"type":"text","text":"£12.50","bold":true} ]}

Example 4: validation (400, same shape as today, now with nested paths) {"error":"invalid job","details":[ "elements[0].children[3] (qr): not allowed inside a box; place it after the box", "elements[0].children[1] (rule): inside a box, style must be single or double", "elements[1] (box): set text or children, not both", "elements[2] (kv): pairs[2]: key is required", "elements[3] (rule): field "pairs" does not apply to rule"]}

Render-time limit:

  • If a job would print more lines than [format].max_lines (default 2000), the job fails with "receipt would print 2412 lines, limit is 2000". That is visible on GET /api/v1/jobs/{id}, and synchronously on /preview.

==== PHASE 1: POST /api/v1/preview ====

  • Takes the same body as /print and validates it the same way (400 on problems).
  • Nothing is printed and no images are fetched.

Default response: 200 text/plain; charset=utf-8, the exact lines the bytes would print: ┌─ Shopping ─────────────────────────────┐ │ Milk, eggs and the good bread from the │ ... [qr: https://grafana.lan/d/disk] [image 384 dots: graph.png]

              • partial cut - - - - - - - -

With Accept: application/json: {"columns":42,"codepage":"cp437","line_count":9, "lines":[{"kind":"text","text":"╔═ HIGH ═══...═╗"}, {"kind":"text","text":"║ [!] Disk almost full ...║","runs":[{"from":2,"to":40,"bold":true}]}, {"kind":"qr","data":"https://grafana.lan/d/disk"}, {"kind":"cut","data":"partial"}], "warnings":["elements[2]: 1 character not in cp437 printed as ?"]}

  • 422 {"error":"receipt would print 2412 lines, limit is 2000"}
  • CLI: uberbringer preview [--config c.toml] [--module ntfy] [file.json|-]. It prints to the terminal, showing bold and invert with the existing liamg/tml dependency.

==== PHASE 2: modules ====

GET /api/v1/modules [{"name":"note","description":"Boxed note with an optional checklist"}, {"name":"notify","description":"Notification card from title, message, priority and tags"}, {"name":"ntfy","description":"One ntfy message object, e.g. the CLI's $NTFY_RAW"}]

POST /api/v1/print/{module}?copies=1

  • The body is the module's own payload.
  • 202: the normal job response.
  • 204: the module had nothing to print, e.g. an ntfy keepalive.
  • 400: {"error":"invalid payload for module "note"","details":["text: required","done[0]: index 5 is out of range"]}
  • 403: the token's scope does not include this module (phase 3).
  • 404: {"error":"module "notx" not found"}
  • 422: {"error":"module "note" built an invalid receipt","details":[...]}. This is a bug; ntfy and notify print the fallback receipt instead.
  • 429 and 503 behave as on /print.
  • ?printer= is reserved. Until several printers are configured, any value other than "default" returns 400.

POST /api/v1/preview/{module} takes the same payload and returns the preview response.

note payload (mockup 5): POST /api/v1/print/note {"title":"Shopping","text":"Milk, eggs and the good bread from the bakery on Elm St.","items":["Milk","Eggs","Bread"],"done":[2]}

  • Optional fields: style (single, double, double-h or double-v), footer (a string), stamp (default true: with no footer, the print time goes in the bottom border).
  • Decoded strictly: unknown fields are 400.

==== PHASE 3: notifications ====

notify payload (strict; for scripts, cron jobs and phone shortcuts): POST /api/v1/print/notify {"title":"Disk almost full","message":"/var is at 94% on nas01","priority":"high","tags":["warning","nas01"], "topic":"alerts","click":"https://grafana.lan/d/disk","markdown":false}

  • Optional fields:
    • time: Unix seconds or RFC 3339. Default now.
    • actions: up to 3 [{label, url}].
    • image: a URL.
  • priority is 1-5, or one of min, low, default, high, max, urgent.
  • Minimal call: {"message":"Back at 3"} prints a priority-3 single box.

ntfy payload: one ntfy subscribe-API message, exactly as received.

  • Decoded leniently: unknown fields are ignored, so new ntfy versions keep working. POST /api/v1/print/ntfy {"id":"sPs71M8A2Tq9","time":1764450245,"event":"message","topic":"alerts","title":"Disk almost full", "message":"/var is at 94% on nas01","content_type":"text/markdown","priority":4,"tags":["warning","nas01"], "click":"https://grafana.lan/d/disk", "actions":[{"id":"a1","action":"view","label":"Open dashboard","url":"https://grafana.lan/d/disk","clear":false}], "attachment":{"name":"graph.png","type":"image/png","size":33848,"expires":1764461045,"url":"https://ntfy.example.com/file/sPs71M8A2Tq9.png"}}
  • 202: prints mockup 1.
  • 204: open, keepalive, poll_request, message_delete and message_clear events, and encoding=base64.

ntfy CLI recipe (works after phase 3; no jq). Linux, in ~/.config/ntfy/client.yml or /etc/ntfy/client.yml: default-host: https://ntfy.sh default-token: tk_... subscribe:

  • topic: alerts command: | printf '%s' "$NTFY_RAW" | curl -fsS -X POST
    -H "Authorization: Bearer $UBERBRINGER_TOKEN" -H "Content-Type: application/json"
    --data-binary @- https://printer.example.com/api/v1/print/ntfy if: priority: default,high,urgent

Windows: cmd.exe breaks %NTFY_RAW%, so use PowerShell: command: powershell -NoProfile -Command "Invoke-RestMethod -Method Post -Uri https://printer.example.com/api/v1/print/ntfy -Headers @{Authorization=('Bearer ' + $env:UBERBRINGER_TOKEN)} -ContentType 'application/json' -Body ([Text.Encoding]::UTF8.GetBytes($env:NTFY_RAW))"

Scoped tokens:

  • uberbringer token --subject ntfy-cli --modules ntfy,notify adds the claim "mod":["ntfy","notify"].
  • A token with that claim may only call:
    • POST /api/v1/print/{m} and /api/v1/preview/{m} for the listed modules
    • GET /api/v1/modules
    • GET /api/v1/jobs/{id}
  • Anything else returns 403 {"error":"token is limited to modules ntfy, notify"}.
  • Tokens without the claim keep full access, so existing tokens keep working.

Job status:

  • GET /api/v1/jobs/{id} gains "source", e.g. "module:ntfy" or, in phase 4, "ntfy:home".

==== PHASE 3-4: configuration (strict TOML, as today) ====

[format] max_lines = 2000 # phase 1 timezone = "Local" # phase 2; IANA name, checked with time.LoadLocation time_layout = "02 Jan 15:04" [printer] box_line_spacing = 0 # phase 1; ESC 3 units around boxes; 0 = printer default (until calibrated) [ntfy.format] # phase 3 style = "auto" # auto | box | compact max_lines = 40 qr = "first" # first | all | none images = true markdown = true updates = "print" # print | skip (sequence_id updates) [ntfy.markers] # optional overrides; "" hides a tag backup = "[B]" [ntfy] # phase 4 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 = 10 # receipts per rate_window; the rest go into one digest rate_window = "10m" bypass_priority = 5 keepalive = "45s"

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 (phase 3) and the subscriber (phase 4). modules imports it for the Message type. serve.go connects the subscriber to modules through a callback, so ntfy never imports modules.
  • printqueue is unchanged apart from Submit(job, Meta).

INVARIANTS (all match the current code)

  1. receipt.Job stays printer-neutral. Blocks are sized at render time from Options.Columns or Profile.Columns(font). The same job therefore prints correctly on a TM-T88IV, TM-T88VII or TM-m50II, and on several printers later.
  2. 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
  3. Layout never fails on a valid job. Widths clamp, titles are cut with "...", and over-long words split the way wrap() already splits them. The only new render-time failure is the [format].max_lines backstop (default 2000).
  4. Renderer.Render is still the only path to printer bytes, and still all-or-nothing.
  5. New code never emits raw ESC/POS. Payload text only ever lands in string fields of elements. The raw element stays available on /print only, and scoped tokens cannot reach it.
  6. /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 (new or changed)

escpos func (cp CodePage) CanEncode(r rune) bool // r encodes to a byte >= 0x20, not 0x7F func (cp CodePage) Decode(b []byte) string type Span struct{ From, To int } type Run struct{ From, To int; Bold, Underline, Invert bool; Font Font; W, H int } type PreviewLine struct{ Kind string /* text|qr|barcode|image|raw|cut */; Text string; Runs []Run; Data string } func Interpret(stream []byte, cp CodePage, opaque []Span) ([]PreviewLine, error)

receipt TypeBox, TypeRule, TypeKV (phase 1); TypeList (phase 2) Element gains: Children []Element, Title, TitleStyle, Footer, Style, Padding *int, Fit bool, Columns int, Pairs []Pair, Leader (phase 1); Items []string, Done []int, Bullet (phase 2); Optional bool on image (phase 3) type Pair struct{ Key, Value string; Bold bool } type Preview struct{ Columns int; CodePage string; LineCount int; Lines []escpos.PreviewLine; Warnings []string } func (r *Renderer) Preview(ctx context.Context, job Job) (Preview, error) func StripEmoji(s string) string Options gain MaxLines and BoxLineSpacing

modules (phase 2; Notice and Card in phase 3) type Env struct{ Now time.Time; Location *time.Location; TimeLayout string; Card CardOptions } type Module interface{ Name() string; Description() string; Build(ctx context.Context, body []byte, env Env) (receipt.Job, error) } var ErrSkip = errors.New("nothing to print") // 204 type PayloadError struct{ Problems []string } // 400 type Registry; Get(name string) (Module, bool); List() []Info type Notice struct{ ID, Topic, Title, Message string; Markdown bool; Priority int; Tags []string; Time time.Time; Links []Link; Image string; File *File; Updated bool } func FromNtfy(m ntfy.Message) (Notice, error) // ErrSkip for non-message events func Card(n Notice, o CardOptions, env Env) receipt.Job

ntfy type Message, Action, Attachment // mirror ntfy model/model.go func (m Message) Priority() int // 0 or missing becomes 3 type Subscriber // phase 4 func (s *Subscriber) Run(ctx context.Context, handle func(context.Context, Message) error) error

server New(config Config, deps Deps, logger *slog.Logger) type Deps struct{ Jobs Jobs; Printer Printer; Previewer Previewer; Modules Modules }

printqueue Submit(job receipt.Job, meta Meta) (Status, error) type Meta struct{ Source, Ref string } Status gains Source

BLOCK LAYOUT RULES (receipt/blocklayout.go and receipt/glyphs.go)

Width

  • cols = Profile.Columns(font), or Options.Columns for Font A, divided by size (1-3). That gives 42 Font A or 56 Font B columns on all three Epson models.
  • columns clamps to cols.
  • fit sets the width to the smallest of: cols, and the larger of (widest content + 2 + 2*padding) and (title + 6).
  • A block narrower than the line is centred with leading spaces.

Box

  • Each body row is: border, padding, content, padding, border. The content width is width - 2 - 2*padding, which is 38 at the defaults.
  • Bold, underline and invert apply only to the content run. Borders are never styled.
  • Top border, inline title: ┌─ Title ───┐. The title is cut with "..." beyond width-6.
  • Top border, capped title: ╔═╡ Title ╞══╗, using ┤├ on boxes with single horizontal lines.
  • Bottom border: └──── footer ──┘. The footer is cut beyond width-7.

Dividers (a rule child inside a box) span the full width and join the side borders:

  • single box: ├─┤ for a single rule, ╞═╡ for a double rule
  • double box: ╟─╢ single, ╠═╣ double
  • double-h box: ├─┤ single, ╞═╡ double
  • double-v box: ╟─╢ single, ╠═╣ double
  • A labelled divider looks like ├── Label ───┤.

kv

  • Layout: key, a space, a leader fill of at least 2, a space, then the value.
  • When the line is too long, the value wraps to width - len(key) - 4 and the continuation lines are right-aligned.

list

  • Bullets: "· ", "- ", "N. " (numbers right-aligned to the widest), "[ ] " and "[√] ".
  • Wrapped lines get a hanging indent.

Glyph fallback, chosen per glyph set with CanEncode

  • double-h and double-v fall back to double, then single, then ascii (+ - | =).
  • A junction the code page lacks first switches to the other rule weight. On cp850, ╟╢ becomes ╠╣ and ╞╡ becomes ├┤.
  • Shades fall back to #, · to . and √ to x.
  • Checked with the Python codecs:
    • cp437 has every glyph used here.
    • cp850 and cp858 lack ╒╓╕╖╘╙╛╜╞╟╡╢╤╥╧╨╪╫, ▌▐, ∙ and √.
    • cp1252 has no box drawing or shade characters.
    • No supported code page has • (U+2022).
    • ► ◄ → ← map to 0x10-0x1F, which the printer reads as control codes.

Emitting lines

  • For each line: Justify(left), the left margin, then for each run Font, Size, Bold, Underline and Reverse, then Text(cp.Encode(run)), then LineFeed.
  • Styles are reset afterwards exactly as p.text does today.
  • When Options.BoxLineSpacing > 0, ESC 3 n is sent before a box and ESC 2 after it.

Images

  • Boxes cannot contain images, so loadImages keeps keying images by element index and no flatten step is needed.

TEXT NORMALIZATION (receipt/normalize.go) It runs before wrap, so one rune is one column and one byte. Steps, in order:

  1. sanitize, as today.
  2. Unicode NFC, using golang.org/x/text/unicode/norm. golang.org/x/text is already a dependency.
  3. Fold only runes the code page cannot encode:
    • “ ” „ become "
    • ‘ ’ become '
    • – becomes -, and — becomes --
    • … becomes ...
    • • becomes ·
    • → becomes -> and ← becomes <-
    • ✓ and ✔ become √, or x where √ is missing
    • × becomes x
    • € becomes EUR (cp858 keeps €)
    • ™ becomes TM
    • a non-breaking space becomes a space
  4. Remove U+FE0E, U+FE0F, U+200B-U+200D, skin-tone modifiers and tag characters.
  5. Emoji:
    • On /print, each remaining emoji cluster becomes a single '?'.
    • Modules call StripEmoji after mapping a few typed emoji to markers: ⚠ to [!], ✅ to [√], ❌ to [x], 🚨 to (!), 👍 to (+1). The number of '?' left feeds the preview warnings.

PREVIEW (receipt/preview.go and escpos/interpret.go)

  • Renderer.Preview renders with a placeholder fetcher. It produces a blank raster at the requested or default width and never fetches anything.
  • It records the byte range of each raw element (Builder.Len before and after), then interprets the body with escpos.Interpret. Raw ranges become "[raw N bytes]", because arbitrary raw bytes cannot be parsed reliably.
  • Interpret understands every command the renderer emits: ESC @ t a M E - 3 2 d, GS ! B V, GS ( k, GS k and GS v 0.
  • The tests use the same interpreter in place of printedLines, so the preview always shows what the bytes actually say.

NTFY AND NOTIFY CARD (modules/card.go) The same card is used for /print/notify, /print/ntfy and the subscriber.

Skip

  • event other than "message", or encoding = "base64": ErrSkip, which returns 204.

Priority

  • A missing or 0 priority counts as 3.

Style ladder (style = auto; box and compact force one form):

  • 5: a dark rule "URGENT", a double box, the title row bold and inverted, a double divider, the body, the footer, then another dark rule.
  • 4: a double box with "HIGH" in the top border, a bold title row, a single divider, then the body.
  • 3: a single box with the bold title set into the top border.
  • 1-2: a left-labelled rule "topic · time", then a bold title line and the body, with no box.

Title

  • The title; if empty, the topic; if that is empty too, "Notification".
  • Up to 2 tag markers go in front of it.
  • " (updated)" goes after it when sequence_id differs from id. With updates = skip, such messages are not printed.

Tag markers (exact lowercase match)

  • warning → [!]
  • rotating_light, fire, boom → (!)
  • white_check_mark, heavy_check_mark, ballot_box_with_check → [√]
  • x, negative_squared_cross_mark, no_entry, no_entry_sign → [x]
  • information_source → (i)
  • question → (?)
  • +1, thumbsup → (+1)
  • -1, thumbsdown → (-1)
  • loudspeaker, mega → <!>
  • tada → \o/
  • skull → x_x
  • hourglass → (...) [ntfy.markers] in the config can override any marker, and "" hides a tag. Any other tag prints as text on a "Tags: a, b" row.

Body

  • The message, with the markdown subset applied when content_type is text/markdown (or markdown: true on notify):
    • #, ## and ### headings → bold lines
          • items → · list
      1. items → numbered list
    • quotes → a "│ " prefix

    • --- → a divider
    • inline ** __ * _ ` ~~ → removed
    • t → t, with u added to the links
    • a → [image: a]
  • The body is capped at [ntfy.format].max_lines (default 40), followed by "... N more lines".
  • The "You received a file: X" placeholder becomes a "File" row.

Footer

  • " ·

Links

  • The links are the click URL plus view actions (http or https), with duplicates removed, at most 3.
  • qr = first (default): the first link prints as a centred QR code (size 5, correction M) with a Font B caption, the action's label or else host/path. The others print as "» label" plus the URL.
  • qr = all prints every link as a QR code; qr = none prints them all as text.
  • http, broadcast and copy actions are never printed, because their headers and body can hold secrets.

Attachments

  • An image (type image/*, or a .png, .jpg, .jpeg, .gif or .webp name) that has not expired, with images = true: an image element with optional:true, 384 dots wide, centred. The renderer fetches it through safehttp.
  • Otherwise: a kv row such as "File ... name (33 KB)".
  • icon is ignored.

Failures

  • Card never fails. Any internal error produces the plain fallback receipt: title, message, topic and time.

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.
  • 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.

Images and logging

  • The subscription's own server host is added to safehttp Options.PrivateHosts, so images.allow_private_networks stays off.
  • 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 1: Boxes, rules, kv and preview (3-4 days)

Goal. One /print element gives the single and double CP437 boxes the owner liked. The output can be seen without using paper. Existing jobs print byte for byte as they do today.

Work.

Do this first: commit byte-compatibility fixtures. Put internal/pkg/receipt/testdata/compat/*.json and *.hex, rendered by the current code, in place before touching the renderer.

internal/pkg/escpos

  • codepage.go: CanEncode(r rune) bool and Decode([]byte) string.
  • interpret.go (new): Interpret(stream, cp, opaque []Span) ([]PreviewLine, error).
    • It parses ESC @ t a M E - 3 2 d, GS ! B V, GS ( k, GS k and GS v 0.
    • Output is text runs with their styles, plus placeholders for qr, barcode, image, raw and cut.

internal/pkg/receipt

  • job.go:
    • TypeBox, TypeRule and TypeKV.
    • New fields: Children, Title, TitleStyle, Footer, Style, Padding *int, Fit, Columns, Pairs, Leader; type Pair.
    • validate() recurses with path prefixes.
    • checkFields keeps a per-type allowed set. It applies to the new types; old types stay lenient.
    • Child rules allow only one level of nesting, and children count toward MaxElements.
    • The doc comment explains that columns, not width, sets a block's width.
  • block.go (new): boxSpec, ruleSpec and kvSpec. These checks are structural and independent of geometry.
  • glyphs.go (new): border sets, the junction table and the CanEncode fallback chain.
  • normalize.go (new):
    • NFC, using golang.org/x/text/unicode/norm.
    • The fold table, applied only to runes the code page can't encode.
    • Removal of variation selectors and ZWJ.
    • The emoji policy: replace on /print.
    • A count of '?' left over, for warnings.
    • It is called before wrap; wrap() itself is unchanged.
  • cells.go (new): style, run and line types.
  • blocklayout.go (new):
    • layoutBox, layoutRule and layoutKV. Every line they return is exactly the block width.
    • fit, columns clamping, title and footer truncation, and centring.
  • render.go:
    • Cases for box, rule and kv that lay out and then emit.
    • Line counting against Options.MaxLines.
    • ESC 3 n / ESC 2 around boxes when Options.BoxLineSpacing > 0.
    • Raw elements record their byte spans for preview.
  • preview.go (new): Renderer.Preview, using a placeholder fetcher and escpos.Interpret, and returning warnings.

internal/app/uberbringer/server

  • server.go: New(config, Deps{Jobs, Printer, Previewer}, logger) and the route POST /api/v1/preview.
  • handlers_preview.go (new): text/plain by default, JSON for Accept: application/json, 422 for max_lines.

internal/pkg/config

  • [format] max_lines and [printer] box_line_spacing, with defaults and validation.

internal/app/uberbringer

  • serve.go: passes MaxLines and BoxLineSpacing into receipt.Options, and the renderer as the Previewer.
  • cli.go: the preview [--config] file|- command, rendering bold and invert with liamg/tml.

Docs and examples

  • README.md: a Blocks section (field tables for box, rule and kv), a CP437 glyph cheat sheet (what prints and what doesn't), and a Preview section. Replace the hand-drawn ACHTUNG example with a box element.
  • configs/config.example.toml.
  • examples/blocks.json (new): a calibration gallery covering every style, padding, size 1-3, font b, dividers and fit.

Tests.

internal/pkg/escpos

  • CanEncode tables for each code page:
    • cp437 encodes every glyph used.
    • cp850 and cp858 lack ╒╓╕╖╘╙╛╜╞╟╡╢╤╥╧╨╪╫, ▌▐, ∙ and √.
    • cp1252 lacks all box and shade glyphs.
    • • and ► fail everywhere.
  • Decode round trip.
  • Interpret applied to Builder output for every command the renderer emits, including raw spans and unknown bytes.

internal/pkg/receipt

  • TestRenderCompat: the existing fixtures render identical bytes.
  • Golden tests: testdata/blocks/*.json rendered to *.txt through Preview, regenerated with -update. They cover:
    • box: 5 styles × inline and capped titles × padding 0-3 × size 1-3 × font a and b
    • fit, columns and footer
    • titles too long for the border
    • every divider junction, with and without labels
    • kv overflow
    • every rule style
    • the same set on cp850 and cp1252, to check fallbacks
  • FuzzBlocks, over random block trees and options:
    • every text line is exactly the block width and no wider than cols
    • corners and verticals sit in the first and last columns
    • no byte below 0x20 appears inside text runs
  • Validation table tests:
    • nested paths
    • checkFields
    • children that are not allowed (qr, image, raw, box)
    • text together with children
    • MaxElements counting children
  • normalize tables:
    • a decomposed é becomes one rune
    • fold runs before wrap (… takes 3 columns)
    • one emoji cluster becomes one '?'
    • ZWJ and VS16 are dropped
    • encodable text is untouched
  • receipt_test.go uses escpos.Interpret in place of printedLines. All existing tests stay green.

server

  • preview returns 200 text/plain and 200 JSON, 400 for an invalid job, 401 without a token, and 422 when max_lines is exceeded.

cli

  • A golden test of the preview command's output.

Done when.

  • the full gate passes (CLAUDE.md lists it), including staticcheck and govulncheck, and the compat fixtures are byte-identical.
  • The README examples, mockups 6 and 7, print from one element each.
  • /api/v1/preview shows the same lines.
  • examples/blocks.json has been printed on the TM-T88IV and the owner has looked at the border gaps. box_line_spacing is then either set to a value checked on paper or left at 0.

Phase 2: Notes and the module layer (2 days)

Goal. Basic inputs print advanced layouts. POST /api/v1/print/note with {title, text, items} prints a boxed checklist, and the module layer is ready for notifications.

Work.

internal/pkg/receipt

  • TypeList: items, bullet, done.
  • Changes to job.go, block.go and blocklayout.go. list is allowed inside boxes.

internal/pkg/modules (new)

  • registry.go: the Module interface, Env, Info, Registry (Get, List), ErrSkip, PayloadError, and a strict JSON decode helper that collects every problem.
  • note.go: {title, text, items, done, style, footer, stamp} becomes a box with text, feed and a checkbox list. The default footer is Env.Now in [format].time_layout.

internal/app/uberbringer/server

  • Deps gains Modules.
  • Routes: POST /api/v1/print/:module, POST /api/v1/preview/:module and GET /api/v1/modules.
  • handlers_modules.go (new): route params are cloned with strings.Clone, as handleJob already does.
  • The shared s.submit(c, job) is extracted from handlePrint and keeps the queue-full (503 + Retry-After) and closed handling.
  • Error mapping: ErrSkip gives 204, PayloadError 400, unknown module 404, an invalid built job 422.
  • ?copies works on module routes. ?printer is reserved: 400 unless it is "default".

internal/pkg/config

  • [format] timezone (checked with time.LoadLocation) and time_layout.

internal/app/uberbringer

  • serve.go: builds the registry and the Env factory.
  • cli.go: preview --module name payload.json.

cmd/uberbringer/main.go

  • import _ "time/tzdata", because Windows builds have no zoneinfo.

Docs

  • README: a Modules section and the note payload table. Update configs/config.example.toml.

Tests.

internal/pkg/receipt

  • list goldens:
    • each bullet style
    • numbers 1-12, right-aligned
    • done items
    • hanging indent
    • fallback on cp850
    • a list inside a box

internal/pkg/modules

  • note golden previews with a fixed clock in Europe/London:
    • title present and absent
    • with and without items
    • done items
    • every style
    • stamp=false
    • footer override
  • Payload validation:
    • unknown field
    • missing text
    • done index out of range
    • more than 200 items
  • Registry tests: lookup, List order, duplicate names.

internal/app/uberbringer/server

  • Using the fakeJobs pattern with a fake module: 202 with Location, 204, 400 with details, 404, 422, 503 when the queue is full, ?printer=office returns 400, and GET /modules.

internal/pkg/config

  • Rejects a bad timezone.

Done when.

  • curl -d '{"title":"Shopping","text":"...","items":["Milk","Eggs","Bread"],"done":[2]}' /api/v1/print/note prints mockup 5.
  • /api/v1/preview/note shows the same lines.
  • GET /api/v1/modules lists note.
  • The full gate passes (CLAUDE.md lists it).

Phase 3: Notifications, the notify and ntfy modules (3 days)

Goal. ntfy prints with minimal effort. The ntfy CLI posts $NTFY_RAW unchanged, and scripts can send {title, message, priority, tags}. Both print the same priority-styled card. Integration tokens can't send raw ESC/POS.

Work.

internal/pkg/ntfy (new)

  • message.go: Message, Action and Attachment, following ntfy model.go, plus Priority().

internal/pkg/modules

  • notice.go: the Notice type. Priority names min, low, default, high, max and urgent map to 1-5.
  • notify.go: strict decode into a Notice.
  • ntfy.go: lenient decode into ntfy.Message, then FromNtfy into a Notice. It returns ErrSkip for events other than message and for encoding=base64.
  • card.go: Card(Notice, CardOptions, Env) builds the receipt.Job using the priority ladder, title and markers, body cap, footer, links and QR, the attachment image or File row, and the updates policy.
  • markers.go: the tag and typed-emoji marker table, merged with the [ntfy.markers] overrides, then StripEmoji.
  • markdown.go: the line-level subset described in the architecture section, about 150 lines, with no new dependency.
  • fallback.go: a plain receipt (title, message, topic, time). Card falls back to it on any internal error.

internal/pkg/receipt

  • image optional: loadImages returns a placeholder for an optional image that fails, and the renderer prints "[image unavailable]".
  • StripEmoji is exported.

internal/pkg/printqueue

  • Submit(job, Meta{Source, Ref}).
  • Status.Source.
  • Source and ref are added to the worker logs.
  • Callers in server and serve.go are updated.

internal/app/uberbringer/server

  • auth.go: parse the optional "mod" claim and enforce the allowed routes, returning 403 otherwise.
  • handleJob: shows source.

internal/app/uberbringer

  • cli.go: token --modules ntfy,notify.

internal/pkg/config

  • [ntfy.format] (style, max_lines, qr, images, markdown, updates) and [ntfy.markers], with validation.

Docs

  • README: notify and ntfy sections, the ntfy CLI recipe for Linux client.yml and Windows PowerShell, token scopes, and a warning that public ntfy.sh topics can be guessed. Update configs/config.example.toml.

Tests.

internal/pkg/modules

  • Card golden previews:
    • priorities 1-5 × style auto, box and compact (mockups 1-4)
    • the brief's example message rendered exactly
  • Markers: built-in table, a config override, hiding a tag with "", and the unmapped tag row.
  • Markdown subset golden tests, plus FuzzMarkdown: no panic, and every line fits.
  • FromNtfy table:
    • unknown fields ignored
    • priority 0 or missing becomes 3
    • missing title falls back to the topic
    • the 'You received a file' placeholder becomes a File row
    • an image attachment becomes an optional image; an expired one becomes a File row
    • an attachment with no type is sniffed by extension
    • sequence_id gives "(updated)", or a skip with updates=skip
    • non-message and base64 events give ErrSkip
  • http, broadcast and copy actions never print: assert their URL, header and body strings appear nowhere in the preview.
  • A body longer than max_lines gives '... N more lines'.
  • Typed ⚠ becomes [!], and other emoji are stripped.
  • Links: deduped, at most 3; qr=first, all and none.
  • notify: strict decode errors.
  • Fallback: Card with a forced internal error still returns a valid job.

internal/pkg/receipt

  • An optional image that fails prints the placeholder, while a non-optional failure still fails the whole job and produces nothing.

internal/app/uberbringer/server

  • Scoped token:
    • 202 on /print/ntfy
    • 403 on /print and /print/note
    • 200 on GET /jobs/{id}
  • An unscoped token is unchanged.
  • 204 for a keepalive body.

internal/pkg/printqueue

  • Meta appears in Status.

Done when.

  • On the owner's machine, the ntfy CLI recipe prints mockup 1 for the brief's example message and mockups 2-4 for priority 5, 3 and 1.
  • /api/v1/preview/ntfy and uberbringer preview --module ntfy show the same output.
  • A token from uberbringer token --modules ntfy gets 403 on /api/v1/print.
  • The full gate passes (CLAUDE.md lists it).

Phase 4: Built-in ntfy subscriber (4 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.

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.
  • status.go: snapshots for /healthz.

internal/pkg/modules

  • digest.go: the digest card (mockup 12).

internal/pkg/safehttp

  • Options.PrivateHosts: exact hosts that may resolve to private addresses without switching on allowlist-only mode. It is filled with the server hosts of subscriptions that have images enabled.

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
    • 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

internal/pkg/safehttp

  • PrivateHosts admits only the exact host.

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.
  • 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.

  • Quiet hours (or move them into phase 4 if the owner wants them now). Config: [ntfy.subscriptions.quiet] start, end, days, timezone, min_priority, action = digest | drop. Boundaries are computed with time.Date in the zone, so they cross midnight and handle DST correctly.
  • Second printer, for the TM-T88VII and TM-m50II:
    • a printqueue Pool with one Queue and worker per printer
    • [printers.] config decoded through toml.Primitive onto the 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.