Refactor to Go standards; add print queue and own ESC/POS library
CI / Lint, test and scan (push) Successful in 1m41s

Restructure the daemon to follow the project's Go coding standards and
expand its features.

Layout and tooling
- cmd/uberbringer/main.go is now thin; all logic lives under internal/.
- Module path is git.anomalous.dev/57_Wolve/uberbringer, go 1.26, every
  dependency upgraded, vendor/ removed.
- staticcheck, govulncheck and goimports pinned as go tools; add a
  Makefile, CI workflow, goreleaser v2 config and Alpine Dockerfile.

Features
- Background print queue with job status (GET /api/v1/jobs/:id), send
  retries with backoff, and graceful shutdown.
- New {"elements": [...]} job format on POST /api/v1/print. Breaking:
  replaces {"data": [...]}, and the response is now JSON 202.
- In-house ESC/POS library replacing justinmichaelvieira/escpos: sizes
  1-8, Font B, CODE39/CODE128, QR, banded raster images, DLE EOT status.
- UTF-8 text transcoded to CP437 (configurable) with word-aware wrapping.
- Images from URL or base64, scaled and dithered; URL fetches refuse
  internal addresses (SSRF guard).
- Fiber v3 HTTP server, TypeID (UUIDv7) job and request IDs, /healthz
  with live printer status, `secret` and `token` subcommands.

Fixes
- Jobs are validated before anything is sent; a failed printer dial no
  longer panics.
- Request logs never contain tokens; Sentry no longer receives the
  Authorization header or print contents.
- Rate limiting is per client behind nginx (X-Real-IP).
- install.sh writes the [printer] section, runs the service as a
  dedicated user and uses a current nginx TLS config.

config.toml is no longer tracked; start from configs/config.example.toml.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
57_WolveandClaude Opus 5.5 committed 2026-11-29 21:17:16 -06:00
1 parent bb73348433
commit 6502d9551d
807 files changed
+6659 -500291

No files matched your search

+313 -41
View File
@@ -1,52 +1,324 @@
# Überbringer
Bringer of information
*Bringer of information.* A small daemon that takes print jobs as JSON over a
REST API and prints them on an EPSON ESC/POS network receipt printer.
EPOS Network Printer via REST API
- **Queue with job status**: jobs return immediately with an ID and print in
order on a background worker, with retries when the printer is offline.
- **Plain-text input**: send UTF-8 text, including accents, `£ ° ±` and
box-drawing `┌─┐│└┘░▒▓`. It is transcoded to the printer's code page
(CP437 by default).
- **Word wrap**: text wraps at word boundaries for the paper width and
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.
- **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
addresses unless you allow it.
- **Health endpoint** with live printer status: paper low or out, cover open,
errors.
Just a fun little project to take a REST API input and generate an output to a network printer.
## Contents
- [Quick start](#quick-start)
- [API](#api)
- [Elements](#elements)
- [Migrating from the old format](#migrating-from-the-old-format)
- [Configuration](#configuration)
- [Command line](#command-line)
- [Development](#development)
## Quick start
# TO DO
- Print Queue for incoming jobs (create background loop that checks queue)
- Re-work API Data Input Format to slim it down for basic commands that don't need size/text input.
## Example Usage:
### Debian/Ubuntu server with nginx and TLS
```sh
sudo ./install.sh printer.example.com you@example.com 192.168.1.245
```
curl --request POST \
--url http://127.0.0.1:8080/api/v1/print \
--header 'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoidWJlcmJyaW5nZXIifQ.TWB3oK8fuoad7oP6FHTP7HhAQB7iRhZRtL1N71irVNc' \
--header 'Content-Type: application/json' \
--header 'User-Agent: Insomnia/2023.5.5' \
--data '{
"data": [
{
"type": 6,
"size": 1,
"text": "B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2"
},
{
"type": 6,
"size": 1,
"text": "2020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020DAC4C4C4C4C4C4C4C4C4C4C4C4C4C4C4C4C4C4BF20202020202020202020202020202020202020202020B3202121212041434854554E47202121212020B320202020202020202020202020202020202020202020C0C4C4C4C4C4C4C4C4C4C4C4C4C4C4C4C4C4C4D92020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020"
},
{
"type": 6,
"size": 1,
"text": "B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2"
},
{
"type": 6,
"size": 1,
"text": "202020202020202020202020202020205F0A2020202020202020202020202020207C455D0A202020202020202020202020202E2D7C3D3D3D3D3D2D2E0A202020202020202020202020207C207C206D61696C207C0A202020202020202020205F5F5F7C5F5F5F5F5F5F5F5F7C0A20202020202020202020202020202020207C7C0A20202020202020202020202020202020207C7C0A20202020202020202020202020202020207C7C2020207777770A202020202020202020202C3B2C202020207C7C202020295F282C3B3B3B2C0A202020202020202020203C5F3E20205C207C7C2020205C7C2F205C5F2F0A202020202020202020205C7C2F20205C5C7C7C20205C5C7C2020207C2F2F0A5F5F5F5F5F5F5F5F5F5F5C7C2F2F5F5C5C7C2F2F2F5F5C562F5F5C7C2F2F5F5F5F5F5F5F5F5F5F5F5F5F"
},
{
"type": 5,
"size": 3,
"text": ""
}
The script installs the latest release as a systemd service running as a
dedicated `uberbringer` user. It also sets up nginx with a Let's Encrypt
certificate, writes `/etc/uberbringer/config.toml` with a fresh secret, and
prints an API token.
### Docker
```sh
docker build -t uberbringer .
docker run -d -p 8080:8080 -v "$PWD/config.toml:/etc/uberbringer/config.toml:ro" uberbringer
```
Inside a container, set `bind_ip = "0.0.0.0"` in the `[webserver]` section.
### From source
```sh
cp configs/config.example.toml config.toml
go run ./cmd/uberbringer secret # paste into api.secret
$EDITOR config.toml # set printer.address
go run ./cmd/uberbringer token # prints a bearer token
make run
```
## API
All `/api/v1` routes need an `Authorization: Bearer <token>` header. Issue
tokens with `uberbringer token`. Tokens created by the old install script keep
working as long as the secret is unchanged. Tokens in query strings are not
accepted, because they leak into proxy logs.
| Method | Path | Purpose |
|--------|--------------------|------------------------------------------|
| POST | `/api/v1/print` | Queue a print job |
| GET | `/api/v1/jobs/:id` | Job status |
| GET | `/healthz` | Printer and queue health (no auth) |
| GET | `/` | Version information (no auth) |
### Print a receipt
```sh
curl -X POST https://printer.example.com/api/v1/print \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{
"elements": [
{"type": "text", "text": "▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓"},
{"type": "text", "text": "┌─────────────────────┐\n│ !!! ACHTUNG !!! │\n└─────────────────────┘", "align": "center"},
{"type": "text", "text": "Überbringer", "size": 2, "bold": true, "align": "center"},
{"type": "feed"},
{"type": "text", "text": "Long paragraphs wrap at word boundaries for the paper width, so a word is never split across two lines."},
{"type": "text", "text": "Total: ", "newline": false},
{"type": "text", "text": "£12.50", "bold": true},
{"type": "qr", "data": "https://example.com", "align": "center"},
{"type": "feed", "lines": 3}
]
}'
}'
```
The response is `202 Accepted` with a `Location` header:
```json
{"id": "job_01kbx4n6m3ex8tq0wq3r5vrzq1", "status": "queued", "created_at": "2026-11-29T21:04:05Z"}
```
Job IDs are [TypeIDs](https://github.com/jetify-com/typeid): UUIDv7 values
with a `job_` prefix, so they sort by creation time.
### Job status
```sh
curl -H "Authorization: Bearer $TOKEN" https://printer.example.com/api/v1/jobs/job_01kbx4n6m3ex8tq0wq3r5vrzq1
```
```json
{
"id": "job_01kbx4n6m3ex8tq0wq3r5vrzq1",
"status": "done",
"attempts": 1,
"created_at": "2026-11-29T21:04:05Z",
"started_at": "2026-11-29T21:04:05Z",
"finished_at": "2026-11-29T21:04:06Z"
}
```
`status` is `queued`, `printing`, `done` or `failed`. A failed job includes an
`error` field. The last `queue.history` finished jobs are kept.
### Health
`GET /healthz` returns `200` when the printer is reachable and ready, and
`503` when it is unreachable or not ready (paper out, cover open, error).
```json
{"status": "ok", "printer": {"reachable": true, "status": "ready", "online": true, "cover_open": false, "paper": "near_end"}, "queue": {"pending": 0}}
```
A printer that accepts connections but does not answer status requests is
reported as `"status": "unknown"` with HTTP `200`.
### Errors
Errors are JSON: `{"error": "message", "details": ["..."]}`.
| Status | Meaning |
|--------|---------|
| 400 | Malformed JSON, an unknown field, or invalid elements. `details` lists every problem, e.g. `elements[2] (text): size, width and height must be 1-8` |
| 401 | Missing, invalid or expired token |
| 404 | Unknown route or job |
| 413 | Body larger than `webserver.body_limit` |
| 429 | Rate limit exceeded |
| 503 | Queue full (with `Retry-After`) or the server is shutting down |
Validation happens before a job is queued. Images are fetched by the worker,
so a blocked or broken image URL shows up as a `failed` job. Nothing is sent
to the printer unless the whole receipt rendered.
## Elements
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`.
### `text`
| Field | Default | Values |
|-------------|---------|--------|
| `text` | `""` | UTF-8 text. `\n` starts a new line |
| `size` | `1` | 1–8, sets width and height |
| `width`, `height` | `size` | 1–8 each, for stretched text |
| `bold` | `false` | |
| `underline` | `0` | 0, 1 (thin) or 2 (thick) |
| `invert` | `false` | white on black |
| `font` | `a` | `a` (48 columns on 80 mm) or `b` (64 columns, smaller) |
| `align` | `left` | `left`, `center`, `right` |
| `newline` | `true` | `false` keeps the next element on the same line |
| `wrap` | `true` | `false` sends the text as-is and lets the printer wrap |
**Encoding.** Text is transcoded from UTF-8 to `printer.codepage`, CP437 by
default. Characters the code page lacks, such as emoji, print as `?`. Control
characters are removed so text can never be read as printer commands.
**Word wrap.** The line width comes from the printer model and the character
size: 48 characters at size 1, 24 at size 2, and so on. Lines break at spaces,
and only a word longer than a whole line (a long URL, say) is split. The
renderer tracks the position across `"newline": false` elements, so mixed
sizes on one line still wrap correctly.
### `feed`
| Field | Default | Values |
|---------|---------|--------|
| `lines` | `1` | 1–255 |
### `qr`
| Field | Default | Values |
|--------------|---------|--------|
| `data` | | Required. Encoded as UTF-8, up to 7089 bytes |
| `size` | `6` | Module size in dots, 1–16 |
| `correction` | `M` | `L`, `M`, `Q`, `H` |
| `align` | `left` | |
### `barcode`
| Field | Default | Values |
|-------------|---------|--------|
| `symbology` | | Required. `ean13`, `ean8`, `upca`, `upce`, `code39`, `code128` |
| `data` | | Required. Digits for EAN/UPC, where a supplied check digit is verified. `A–Z 0–9 -.$/+%` and space for CODE39. Printable ASCII for CODE128 |
| `height` | `80` | Bar height in dots, 1–255 |
| `width` | `3` | Module width, 2–6 |
| `hri` | `below` | Human-readable text: `none`, `above`, `below`, `both` |
| `align` | `left` | |
### `image`
| Field | Default | Values |
|----------|---------|--------|
| `url` | | `http`/`https` URL, or use `base64` |
| `base64` | | Image data, or a `data:image/png;base64,...` URI |
| `width` | natural | Target width in dots, up to the paper width (576 on 80 mm) |
| `align` | `left` | |
PNG, JPEG, GIF and WebP are supported. Images wider than the paper are scaled
down to fit, and every image is dithered to black and white. URL fetches have
a timeout, a size cap and a pixel cap. URLs that resolve to loopback, private
or link-local addresses (including cloud metadata endpoints) are refused unless
`images.allow_private_networks` is true or the host is in
`images.allowed_hosts`.
### `raw`
| Field | Values |
|-------|--------|
| `hex` | ESC/POS bytes as hex, spaces allowed, e.g. `"1B 61 01"` |
### `cut`
| Field | Default | Values |
|--------|-----------|--------|
| `mode` | `partial` | `partial`, `full` |
## Migrating from the old format
The endpoint is still `POST /api/v1/print`, but the body changed from
`{"data": [...]}` to `{"elements": [...]}`. The response changed from the text
`OK - <id>` to the JSON shown above. Old-format bodies get a `400` that points
here.
| Old `type` | Old meaning | New element |
|------------|-------------|-------------|
| 1 | Text | `{"type": "text", "text": "...", "size": n, "newline": false}` |
| 2 | Bold text | `{"type": "text", "text": "...", "bold": true, "newline": false}` |
| 3 | QR code | `{"type": "qr", "data": "...", "size": n, "correction": "H"}` |
| 4 | Line feed | `{"type": "feed"}` |
| 5 | n line feeds | `{"type": "feed", "lines": n}` |
| 6 | Raw hex | `{"type": "raw", "hex": "..."}`, or plain UTF-8 `text` for CP437 art |
| 7 | Image URL | `{"type": "image", "url": "..."}` |
Old text items did not end the line, hence `"newline": false`. You can usually
drop it now and let each `text` element be a line. Hex-encoded CP437 box
drawing can become plain text: `B3 20 21 21 21` is `"│ !!!"`.
## Configuration
Copy [configs/config.example.toml](configs/config.example.toml) to
`config.toml`. Only `api.secret` (at least 32 bytes) and `printer.address` are
required; every other setting has a default, which the example shows. Configs
written by the old install script still load. Unknown keys are reported as
errors, so a typo can't silently fall back to a default.
Settings worth knowing:
- `printer.model`: `tm-t20` (default), `tm-t88`, `generic-80mm` or
`generic-58mm`. It sets the paper width and characters per line.
`paper_width` and `columns` override it.
- `printer.codepage`: `cp437` (default), `cp850`, `cp858` (has €) or
`cp1252`.
- `webserver.trusted_proxies` / `proxy_header`: the real client IP for
per-client rate limits comes from the `X-Real-IP` header set by nginx on
`127.0.0.1`.
- `sentry.dsn`: error reporting. Falls back to the `SENTRY_DSN` environment
variable, then to a DSN built into release binaries (from the `SENTRY_DSN`
CI secret). Request bodies are never sent to Sentry.
## Command line
```text
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 version print the version
```
The daemon shuts down gracefully on SIGINT/SIGTERM. A receipt that is already
printing is finished, and jobs still waiting are marked failed.
## Development
Go 1.26 or newer is required. Use the latest patch release, since govulncheck
flags standard-library fixes.
```sh
make check # gofmt, go vet, staticcheck, go test -race, govulncheck
make build # bin/uberbringer
make fmt # gofmt + goimports
```
The linters are pinned as Go tools in `go.mod`, so `go tool staticcheck`,
`go tool govulncheck` and `go tool goimports` need no separate install.
```text
cmd/uberbringer/ main: build info, signals, exit code
internal/app/uberbringer/ CLI commands and wiring
server/ Fiber HTTP API, auth, health
internal/pkg/config/ TOML config: defaults and validation
internal/pkg/escpos/ ESC/POS command builder, code pages, barcodes, QR, raster, status
internal/pkg/receipt/ Job format, validation, word wrap, rendering
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
internal/pkg/printqueue/ Job queue, worker and status history
configs/ Example configuration
```
Releases are built by GoReleaser when a `v*` tag is pushed.