diff --git a/CHANGELOG.md b/CHANGELOG.md index 35d0149..5d99429 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,27 @@ version may break callers; such changes are listed under **Breaking**. (`go generate ./...`), served at `GET /openapi.json` without a token, and shipped in the release archives and the Docker build. CI fails when it is out of date. +- `list` block: `items` with a `dot`, `dash`, `number` or `checkbox` + bullet, and `done` to tick checklist items (`[√]`, or `[x]` on code pages + without `√`). Long items wrap with a hanging indent. A list can stand + alone or go inside a box. +- Modules, which build a receipt from a few plain fields: + - `POST /api/v1/print/:module` queues it and `POST /api/v1/preview/:module` + previews it. `?copies=` sets the copies; `?printer=` is reserved and + takes only `default`. + - `GET /api/v1/modules` lists the modules. + - The `note` module prints a box with a title, the text, a checklist and + the time in the bottom border, from + `{"title", "text", "items", "done"}`, with `style`, `footer` and `stamp` + as options. `docs/api.md` § Modules describes it. +- Error codes `invalid_payload` (400), `invalid_query` (400), + `unknown_printer` (400), `module_not_found` (404) and `module_failed` + (422), for the module routes. +- `format.timezone` (default `Local`) and `format.time_layout` (default + `02 Jan 15:04`) set how modules print times. The binary carries the time + zone database, so zone names load on Windows and in slim containers. +- `uberbringer preview --module ` shows the receipt a module builds + from a payload. ## [0.2.0] - 2026-11-30 diff --git a/CLAUDE.md b/CLAUDE.md index 72b5dd1..3481339 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -40,7 +40,8 @@ it to the server in its config, so the generator never builds the package that embeds its own output. The module path is the bare `uberbringer`, so imports read `uberbringer/internal/...`. Imports point down: -- server → printqueue, receipt, printer, escpos +- server → modules, printqueue, receipt, printer, escpos +- modules → receipt - printqueue → receipt - receipt → escpos, raster - printer → escpos diff --git a/README.md b/README.md index d458fd5..dc2307b 100644 --- a/README.md +++ b/README.md @@ -13,8 +13,11 @@ REST API and prints them on an EPSON ESC/POS network receipt printer. character size, so words are never cut in half. - **Rich elements**: bold, underline, inverse, sizes 1–8, two fonts, alignment, QR codes, EAN/UPC/CODE39/CODE128 barcodes, images, raw ESC/POS. -- **Boxes, rules and key-value rows**: single or double CP437 borders with - titles, dividers and footers, sized to the paper when the job prints. +- **Boxes, rules, key-value rows and lists**: single or double CP437 + borders with titles, dividers and footers, and bulleted, numbered or + 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. - **Preview**: see the exact lines a job prints, without using paper. - **Images that print well**: PNG, JPEG, GIF or WebP from a URL or base64, scaled to the paper and dithered. Image URLs can't reach internal network @@ -123,7 +126,7 @@ make run ## API [docs/api.md](docs/api.md) is the API reference: the routes, the print -elements and blocks, and the error codes. +elements and blocks, the modules, and the error codes. [docs/swagger.json](docs/swagger.json) is the OpenAPI 3.1 document, generated from the route table; the daemon serves it at `GET /openapi.json`. @@ -182,6 +185,14 @@ Settings worth knowing: - `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`. +- `format.timezone` (default `Local`) and `format.time_layout` (default + `02 Jan 15:04`): how [modules](docs/api.md#modules) print times, such as + a note's stamp. The zone is an IANA name such as `Europe/London`, `UTC`, + or `Local` for the host's zone; the binary carries the zone database, so + names load on hosts and containers without one. The layout is Go's + notation, in which `02 Jan 2006 15:04:05` stands for the parts of a date, + e.g. `2006-01-02 15:04`. A layout that shows no part of a date is an + error. - `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`. @@ -201,9 +212,13 @@ Settings worth knowing: and one Sentry event. - A print job that fails after its retries is logged as ERROR `job failed` with its `job_id`, and is reported to Sentry. + - A module that builds an invalid receipt (`422` `module_failed`) is + logged as ERROR `module built an invalid receipt`, with the `module` and + the number of `problems` but not the problems themselves, and is + reported to Sentry once. - Refusals are never logged at ERROR and never go to Sentry. Refusals are - 4xx answers, the `queue_full` and `shutting_down` 503s, and 503s from - `/healthz`. + 4xx answers other than `module_failed`, the `queue_full` and + `shutting_down` 503s, and 503s from `/healthz`. ## Command line @@ -212,6 +227,7 @@ uberbringer [--config config.toml] run the daemon (default command) uberbringer secret print a new random API secret uberbringer token [--subject s] [--ttl 720h] print a signed bearer token uberbringer preview [file.json|-] show the lines a job would print +uberbringer preview --module note [file|-] show the receipt a module builds uberbringer config get print one setting, e.g. webserver.port uberbringer version print the version ``` @@ -229,8 +245,10 @@ file. argument, and lays it out for the printer in the config, as `/api/v1/preview` does. It prints nothing and fetches no images. On a terminal it shows bold, underlined and inverted text as such; warnings go -to standard error. It reads the same config as the daemon, so -`api.secret` and `printer.address` must be set even though neither is used. +to standard error. With `--module`, the input is that module's payload, as +`/api/v1/print/:module` takes it, built at the time now. It reads the same +config as the daemon, so `api.secret` and `printer.address` must be set even +though neither is used. The daemon shuts down gracefully on SIGINT/SIGTERM. A receipt that is already printing is finished, and jobs still waiting are marked failed. @@ -295,6 +313,7 @@ internal/app/uberbringer/ CLI commands and wiring internal/pkg/config/ Config from TOML and UBERBRINGER_* variables (Viper): defaults, validation internal/pkg/escpos/ ESC/POS command builder, code pages, barcodes, QR, raster, status, interpreter internal/pkg/receipt/ Job format, validation, text folding, word wrap, blocks, rendering, preview +internal/pkg/modules/ Modules that build jobs from plain payloads, such as note; strict payload decoding internal/pkg/raster/ Image decoding, scaling and dithering internal/pkg/safehttp/ SSRF-guarded image fetching internal/pkg/printer/ TCP printer client (port 9100) and status queries diff --git a/cmd/uberbringer/main.go b/cmd/uberbringer/main.go index 54a2b21..f54eb41 100644 --- a/cmd/uberbringer/main.go +++ b/cmd/uberbringer/main.go @@ -9,6 +9,10 @@ import ( "os/signal" "syscall" + // Embeds the IANA time zone database, which Windows and slim container + // images lack, so that any format.timezone name loads. + _ "time/tzdata" + "uberbringer/internal/app/uberbringer" ) diff --git a/configs/config.example.toml b/configs/config.example.toml index faafb4b..2ac6e57 100644 --- a/configs/config.example.toml +++ b/configs/config.example.toml @@ -73,6 +73,12 @@ # instead of printing; /api/v1/preview answers 422. max_lines = 2000 + # Times that modules print, such as a note's stamp: the zone, as an IANA + # name ("Europe/London", "UTC") or "Local" for the host's, and the layout, + # in Go's notation, where 02 Jan 2006 15:04 stands for the parts of a date. + timezone = "Local" + time_layout = "02 Jan 15:04" + [queue] size = 100 # jobs that may wait; more get 503 history = 1000 # finished jobs whose status is kept diff --git a/docs/api.md b/docs/api.md index d0e28e0..92bcefa 100644 --- a/docs/api.md +++ b/docs/api.md @@ -1,8 +1,8 @@ # Überbringer API -The HTTP API, the print elements and blocks, and the error codes. -[README.md](../README.md) covers installing, configuring and running the -daemon. +The HTTP API, the print elements and blocks, the modules, and the error +codes. [README.md](../README.md) covers installing, configuring and running +the daemon. ## Contents @@ -15,6 +15,8 @@ daemon. - [Elements](#elements) - [Blocks](#blocks) - [Glyphs and code pages](#glyphs-and-code-pages) +- [Modules](#modules) + - [`note`](#note) ## API @@ -30,6 +32,9 @@ included, carry `Cache-Control: no-store`. |--------|--------------------|------------------------------------------| | POST | `/api/v1/print` | Queue a print job | | POST | `/api/v1/preview` | Show the lines a job prints, without printing it | +| POST | `/api/v1/print/:module` | Queue the receipt a [module](#modules) builds from its payload | +| POST | `/api/v1/preview/:module` | Show the lines that receipt prints, without printing it | +| GET | `/api/v1/modules` | List the modules | | GET | `/api/v1/jobs/:id` | Job status | | GET | `/healthz` | Printer and queue health (no auth) | | GET | `/openapi.json` | This API's OpenAPI 3.1 document (no auth) | @@ -196,21 +201,30 @@ Errors are JSON: - `code` is stable and meant for clients to match on. - `error` is for people and may change. It never repeats the HTTP framework's own text; for example, an unknown route answers `not found`. -- `details` appears only when an `invalid_job` fails validation. Each entry - names the element by its path, e.g. - `elements[0].children[3] (qr): not allowed inside a box; place it after the box`. +- `details` lists every problem when a job fails validation (`invalid_job`), + a module payload is invalid (`invalid_payload`) or a module builds an + invalid receipt (`module_failed`). Each job problem names the element by + its path, e.g. + `elements[0].children[3] (qr): not allowed inside a box; place it after the box`, + and each payload problem names the field, e.g. + `done[0]: index 5 is out of range`. | Status | `code` | Meaning | |--------|--------|---------| | 400 | `invalid_job` | Malformed JSON, an unknown field, trailing data after the job, or invalid elements. When elements are invalid, `details` lists every problem. A `{"data": [...]}` body gets a message pointing to the [element format](#elements) | +| 400 | `invalid_payload` | A [module](#modules) payload that is not a JSON object, has an unknown field or a field of the wrong type, or is invalid, e.g. `invalid payload for module "note"`. `details` lists every problem | +| 400 | `invalid_query` | On a module route: `copies` outside 1–5, a parameter given twice, or a parameter other than `copies` and `printer` | +| 400 | `unknown_printer` | On a module route: `printer` names a printer other than `default` | | 400 | `bad_request` | A malformed HTTP request, refused by the server itself | | 401 | `unauthorized` | `missing bearer token`, or `invalid or expired token`. Sent with `WWW-Authenticate` | | 404 | `not_found` | Unknown route | | 404 | `job_not_found` | Unknown, expired or malformed job ID | +| 404 | `module_not_found` | Unknown module, e.g. `module "notx" not found` | | 405 | `method_not_allowed` | Known route, wrong method, e.g. `DELETE /api/v1/print` with a valid token (without one, `/api/v1` answers `401` first). Sent with `Allow` | | 408 | `request_timeout` | The request was not received in time | | 413 | `body_too_large` | Body larger than `webserver.body_limit` | -| 422 | `too_many_lines` | From `/api/v1/preview`: the job would print more than `format.max_lines` lines | +| 422 | `too_many_lines` | From `/api/v1/preview` and `/api/v1/preview/:module`: the job would print more than `format.max_lines` lines | +| 422 | `module_failed` | A module built a receipt that fails validation, e.g. `module "note" built an invalid receipt`, with the problems in `details`. This is a bug in the module; it is logged and reported to Sentry | | 429 | `rate_limited` | Rate limit exceeded. `Retry-After` gives the seconds to wait | | 431 | `headers_too_large` | Request headers too large | | 500 | `internal_error` | Unexpected failure. The cause is logged and reported to Sentry, never sent to the client | @@ -230,8 +244,8 @@ to the printer unless the whole receipt rendered. A job is `{"elements": [...], "copies": 1}`. `copies` is 1–5, and each copy is cut separately. A partial cut is added after the last element unless that -element is already a `cut`. Boxes, rules and key-value rows are described -under [Blocks](#blocks). +element is already a `cut`. Boxes, rules, key-value rows and lists are +described under [Blocks](#blocks). ### `text` @@ -327,10 +341,10 @@ or link-local addresses (including cloud metadata endpoints) are refused unless ## Blocks -`box`, `rule` and `kv` are blocks: they are laid out when the job prints, from -the printer model, so one job fits the TM-T88's 42 columns as well as the -TM-T20's 48. A block starts on a new line, and what follows it starts at the -left margin. These fields work on all three: +`box`, `rule`, `kv` and `list` are blocks: they are laid out when the job +prints, from the printer model, so one job fits the TM-T88's 42 columns as +well as the TM-T20's 48. A block starts on a new line, and what follows it +starts at the left margin. These fields work on all four: | Field | Default | Values | |-----------|---------|--------| @@ -389,6 +403,7 @@ borders: | `feed` | `lines` | Empty lines between the borders | | `rule` | `style` (`single` or `double`), `text`, `align`, `bold` | A divider joined to the side borders: `├──┤`, `╞══╡`, `╟──╢` or `╠══╣` to suit the box. A label reads `├── Label ───┤` | | `kv` | `pairs`, `leader` | Key-value rows across the inside of the box | +| `list` | `items`, `bullet`, `done` | A list across the inside of the box | `box`, `qr`, `barcode`, `image`, `raw` and `cut` cannot go inside a box; place them after it. Children count toward the 500-element limit. @@ -426,6 +441,47 @@ A value too long for its line wraps into the room after the key, and its further lines are right-aligned. A key too long for the line is cut with `...`. +### `list` + +```json +{"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]} +]} +``` + +```text +┌─ Shopping ─────────────────────────────┐ +│ Milk, eggs and the good bread from the │ +│ bakery on Elm St. │ +│ │ +│ [ ] Milk │ +│ [ ] Eggs │ +│ [√] Bread │ +└──────────────────────── 29 Nov 21:04 ──┘ +``` + +| Field | Default | Values | +|----------|---------|--------| +| `items` | | Required. 1–200 strings, none empty | +| `bullet` | `dot` | `dot` `· `, `dash` `- `, `number` `1. ` (right-aligned to the widest number), or `checkbox` `[ ] ` | +| `done` | | Indexes into `items`, from 0, of the ticked items of a `checkbox` list: they print as `[√] `. Each index once | + +An item too long for its line wraps, and its further lines are indented to +line up under its first. A `dot` list and a `number` list: + +```text +· Replace drive bay 3 +· Order 2x 8 TB +1. First item that is long enough to wrap + with a hanging indent +2. Second +``` + +On code pages without `√` (cp850, cp858, cp1252), a done item prints as +`[x]`. + ### Glyphs and code pages CP437, the default, has every glyph the blocks draw with. Other code pages @@ -451,3 +507,69 @@ For your own text on CP437: receipt, for checking the borders on paper. Send it as the body of `/api/v1/print`, or look at it first with `uberbringer preview examples/blocks.json`. + +## Modules + +A module takes a few plain fields, its payload, and builds the receipt from +them, so a script or a phone shortcut does not have to lay one out from +elements. `GET /api/v1/modules` lists them: + +```json +[{"name": "note", "description": "Boxed note with an optional checklist"}] +``` + +```sh +curl -X POST https://printer.example.com/api/v1/print/note \ + -H "Authorization: Bearer $TOKEN" \ + -H "Content-Type: application/json" \ + -d '{"title": "Shopping", "text": "Milk, eggs and the good bread from the bakery on Elm St.", + "items": ["Milk", "Eggs", "Bread"], "done": [2]}' +``` + +`POST /api/v1/print/:module` answers as `/api/v1/print` does: `202` with the +job and a `Location` header, or `503` when the queue is full or closing. +`POST /api/v1/preview/:module` takes the same payload and answers as +[`/api/v1/preview`](#preview-a-receipt) does. On both routes: + +- `204` with no body means the module had nothing to print. +- `400` `invalid_payload` lists every problem with the payload in `details`. + Payloads are decoded strictly: an unknown field, or a field name in + another case, is a problem. +- `404` `module_not_found` names an unknown module. +- `422` `module_failed` means the module built a receipt that fails + validation. That is a bug in the module, and it is logged. +- The query may set `copies` (1–5, each copy cut separately) and `printer`, + which is reserved: only `default` is accepted. Any other query parameter, + or one given twice, is `400` `invalid_query`, and another printer name is + `400` `unknown_printer`. + +`uberbringer preview --module note payload.json` shows the receipt without +the daemon. + +### `note` + +A box with the text, then, when there are items, an empty line and a +checklist. The time it was built, in `format.timezone` and +`format.time_layout` ([configuration](../README.md#configuration)), goes in +the bottom border. The request above prints: + +```text +┌─ Shopping ─────────────────────────────┐ +│ Milk, eggs and the good bread from the │ +│ bakery on Elm St. │ +│ │ +│ [ ] Milk │ +│ [ ] Eggs │ +│ [√] Bread │ +└──────────────────────── 29 Nov 21:04 ──┘ +``` + +| Field | Default | Values | +|----------|----------|--------| +| `text` | | Required. The body; it wraps at word boundaries, and `\n` starts a new paragraph | +| `title` | | Set into the top border; a long title is cut with `...` | +| `items` | | Up to 200 checklist items, none empty | +| `done` | | Indexes into `items`, from 0, of the ticked items. Each index once | +| `style` | `single` | The border: `single`, `double`, `double-h` or `double-v`, as on a [`box`](#box) | +| `footer` | | Text for the bottom border in place of the time | +| `stamp` | `true` | `false` leaves the bottom border empty when there is no `footer` | diff --git a/docs/design.md b/docs/design.md index f752793..12b00a9 100644 --- a/docs/design.md +++ b/docs/design.md @@ -73,6 +73,38 @@ client ─HTTPS─▶ Caddy ─▶ server ── validate ──▶ printqueue ( (owner, 2026-11-30), so `printer.box_line_spacing` stays 0 by default. The bytes of that calibration receipt, `examples/blocks.json`, are pinned in a receipt test. + - A `list` follows the same rules. `done` is a set of indexes into + `items`, so an index out of range or given twice is a validation + problem, and so is an empty item. A done item's `√` prints as `x` where + the code page lacks it. +- **Modules build ordinary jobs.** A module (`internal/pkg/modules`) turns a + plain payload into a `receipt.Job` made of the existing elements and + blocks, which then takes the same path as a `/print` job: validation, the + queue and the renderer. Payload text only lands in string fields of + elements, so a module cannot send printer commands. + - Payloads are decoded strictly and report every problem at once. Field + names match exactly, not case-insensitively as `encoding/json` would. + Decoding problems are reported before the module's own checks, because a + field of the wrong type would otherwise also be reported as missing. + - A module checks its payload for everything the blocks would refuse, and + words the problems in the payload's terms (`done[0]: index 5 is out of + range`). A built job that still fails validation is a bug in the module: + the client gets `422` `module_failed` with the problems, and it is + logged and reported to Sentry once, without the problems, which can + quote the payload. + - A module never reads the clock. It gets the time, zone and layout in an + `Env`, from `format.timezone` and `format.time_layout`, so its output is + reproducible in tests. The binary embeds the zone database, because + Windows and slim containers have none. + - Module routes take `copies` and the reserved `printer` (only `default` + until a second printer is configured) in the query. Any other parameter + is refused, for the same reason unknown config keys are: a typo must + not be ignored. + - The registry lists modules sorted by name. + - The module routes are entries in the route table like any other. The + OpenAPI document describes their body as a JSON object whose fields the + module defines, not as a strict schema: one route serves every module, + and each module checks its own payload. - **The preview reads the bytes back.** `escpos.Interpret` parses the stream the renderer produced, so the preview and the tests show what the printer receives rather than what the layout meant. It simulates the printer's own @@ -162,8 +194,9 @@ client ─HTTPS─▶ Caddy ─▶ server ── validate ──▶ printqueue ( ## Planned: formatters Modules, ntfy among them, that turn plain input into receipts built from the -blocks. The plan is `docs/plans/formatters.md`; its first phase, the blocks -and the preview, is built. Decided so far (owner, 2026-11-29): +blocks. The plan is `docs/plans/formatters.md`. Its first two phases are +built: the blocks and the preview, then the `list` block, the module layer +and the `note` module. Decided so far (owner, 2026-11-29): - ntfy is an input: its notifications are printed. The server is self-hosted at a public URL, the subscriber authenticates with a token, and diff --git a/docs/plans/formatters.md b/docs/plans/formatters.md index 828054a..4d85f22 100644 --- a/docs/plans/formatters.md +++ b/docs/plans/formatters.md @@ -1,6 +1,6 @@ # Plan: CP437 blocks, modules and ntfy printing -Status: **phase 1 is done**: box, rule and kv, text folding and the preview are built and checked on paper (README § Blocks, design.md). Phases 2-5 are not started. Every design decision for phases 2-4 is made; the open questions left are an assumed default, config values and the second printer. Each phase runs in its own session, briefed from its section. +Status: **phases 1 and 2 are done**. Phase 1: box, rule and kv, text folding and the preview. Phase 2: the list block, the module layer, the note module and its routes, and `[format] timezone` and `time_layout`. Both are built and checked on paper (docs/api.md § Blocks and § Modules, design.md). Phases 3-5 are not started. Every design decision for phases 3-4 is made; the open questions left are an assumed default, config values and the second printer. Each phase runs in its own session, briefed from its section. ## Decisions (owner, 2026-11-29) @@ -42,9 +42,9 @@ 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=