diff --git a/.dockerignore b/.dockerignore index 015410a..6476813 100644 --- a/.dockerignore +++ b/.dockerignore @@ -1,14 +1,7 @@ -# Only the Go sources are needed to build the image. -.git -.github -.idea -.vscode -bin -dist -*.exe -*.test -*.out -config.toml -Dockerfile -README.md -install.sh +# The image is built from the Go sources alone; everything else, the local +# config.toml with its API secret included, stays out of the build context. +* +!go.mod +!go.sum +!cmd +!internal diff --git a/.gitea/workflows/release.yml b/.gitea/workflows/release.yml new file mode 100644 index 0000000..95a3611 --- /dev/null +++ b/.gitea/workflows/release.yml @@ -0,0 +1,65 @@ +name: Release + +on: + push: + tags: + - 'v*' + +jobs: + goreleaser: + name: Publish the release with GoReleaser + runs-on: ubuntu-latest + if: github.ref_type == 'tag' && startsWith(github.ref, 'refs/tags/v') + steps: + - name: Checkout + uses: actions/checkout@v4 + with: + fetch-depth: 0 + + # The runner's checkout does not reliably fetch tags, and goreleaser + # needs the previous tag to list the commits since it. + - name: Fetch tags + run: git fetch --force --tags + + # Releases come from main only. + - name: Verify the tag is on main + run: | + git fetch origin +refs/heads/main:refs/remotes/origin/main + if ! git merge-base --is-ancestor "$GITHUB_SHA" origin/main; then + echo "Tag $GITHUB_REF_NAME is not on main; refusing to release." + exit 1 + fi + + - name: Set up Go + uses: actions/setup-go@v5 + with: + go-version-file: go.mod + + # Releases are built with go.mod's toolchain line. setup-go@v5 installs + # the go line's release and the go command switches; fail if it did not. + - name: Check the Go toolchain + run: | + want="$(sed -n 's/^toolchain //p' go.mod)" + have="$(go env GOVERSION)" + echo "go.mod toolchain: ${want:-none}; running: $have" + [ "$have" = "$want" ] + + # prerelease: auto in .goreleaser.yaml publishes vX.Y.Z-rc.N as a + # prerelease, so it never becomes the latest release. + - name: Run GoReleaser + uses: goreleaser/goreleaser-action@v6 + with: + distribution: goreleaser + # Pinned so that re-running a tag uses the same goreleaser. Same + # pin as the snapshot step in test.yml. + version: '2.20.3' + args: release --clean + env: + GITEA_TOKEN: ${{ secrets.TOKEN_GITEA }} + GORELEASER_FORCE_TOKEN: gitea + # The tag that triggered this run. Left to itself, goreleaser takes + # the highest-sorting tag on the commit, and vX.Y.Z-rc.N sorts + # above vX.Y.Z. + GORELEASER_CURRENT_TAG: ${{ github.ref_name }} + # Optional default Sentry DSN baked into release binaries. + SENTRY_DSN: ${{ secrets.SENTRY_DSN }} diff --git a/.gitea/workflows/security.yml b/.gitea/workflows/security.yml new file mode 100644 index 0000000..56b91a8 --- /dev/null +++ b/.gitea/workflows/security.yml @@ -0,0 +1,37 @@ +name: Security + +# govulncheck reads the live vulnerability database, so the weekly run +# reports a new advisory against code that has not changed. Scheduled runs +# use the default branch's copy of this file. +on: + push: + branches: [main] + schedule: + - cron: '0 6 * * 1' + +jobs: + govulncheck: + name: Vulnerability check + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Set up Go + uses: actions/setup-go@v5 + with: + go-version-file: go.mod + + # The scan covers the standard library of the Go release that runs it, + # which must be go.mod's toolchain line, the one releases are built + # with. setup-go@v5 installs the go line's release and the go command + # switches; fail if it did not. + - name: Check the Go toolchain + run: | + want="$(sed -n 's/^toolchain //p' go.mod)" + have="$(go env GOVERSION)" + echo "go.mod toolchain: ${want:-none}; running: $have" + [ "$have" = "$want" ] + + - name: govulncheck + run: go tool govulncheck ./... diff --git a/.gitea/workflows/test.yml b/.gitea/workflows/test.yml new file mode 100644 index 0000000..f517f3c --- /dev/null +++ b/.gitea/workflows/test.yml @@ -0,0 +1,72 @@ +name: Test + +# Every branch push, and no pull_request trigger: branches are pushed +# directly, so each commit runs once. Tag pushes are left to release.yml. +on: + push: + branches: ['**'] + +jobs: + check: + name: Lint, test and build + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Set up Go + uses: actions/setup-go@v5 + with: + go-version-file: go.mod + + # setup-go@v5 installs the release named by go.mod's go line; the go + # command then switches to its toolchain line. Fail if it did not. + - name: Check the Go toolchain + run: | + want="$(sed -n 's/^toolchain //p' go.mod)" + have="$(go env GOVERSION)" + echo "go.mod toolchain: ${want:-none}; running: $have" + [ "$have" = "$want" ] + + # The gofmt on PATH is setup-go's; the one under GOROOT belongs to the + # toolchain the go command switched to. + - name: gofmt + run: | + unformatted="$("$(go env GOROOT)/bin/gofmt" -l .)" + if [ -n "$unformatted" ]; then + echo "These files need gofmt:"; echo "$unformatted"; exit 1 + fi + + - name: goimports + run: | + unformatted="$(go tool goimports -l .)" + if [ -n "$unformatted" ]; then + echo "These files need goimports:"; echo "$unformatted"; exit 1 + fi + + # Prints the change and fails, without writing, if go.mod or go.sum + # is not tidy. + - name: go mod tidy + run: go mod tidy -diff + + - name: go vet + run: go vet ./... + + - name: staticcheck + run: go tool staticcheck ./... + + # The limit is per package: a hung test fails with every goroutine's + # stack instead of being killed by the runner. + - name: Test (race detector) + run: go test -race -timeout 5m ./... + + # The release build without publishing: runs the before hooks, + # cross-compiles every shipped target and packs the archives, so a + # config error or a missing archive file fails here, not on a tag. + # Same pin as release.yml. + - name: Release snapshot + uses: goreleaser/goreleaser-action@v6 + with: + distribution: goreleaser + version: '2.20.3' + args: release --snapshot --clean diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml deleted file mode 100644 index 237ba96..0000000 --- a/.github/workflows/ci.yml +++ /dev/null @@ -1,40 +0,0 @@ -name: CI - -on: - push: - pull_request: - -jobs: - check: - name: Lint, test and scan - runs-on: ubuntu-latest - steps: - - name: Checkout - uses: actions/checkout@v4 - - - name: Set up Go - uses: actions/setup-go@v5 - with: - # Latest patch of the current release, so standard-library security - # fixes are picked up without editing this file. - go-version: "1.27.x" - check-latest: true - - - name: gofmt - run: | - unformatted="$(gofmt -l .)" - if [ -n "$unformatted" ]; then - echo "These files need gofmt:"; echo "$unformatted"; exit 1 - fi - - - name: go vet - run: go vet ./... - - - name: staticcheck - run: go tool staticcheck ./... - - - name: Test (race detector) - run: go test -race ./... - - - name: govulncheck - run: go tool govulncheck ./... diff --git a/.github/workflows/labeler.yml b/.github/workflows/labeler.yml deleted file mode 100644 index d15bb5d..0000000 --- a/.github/workflows/labeler.yml +++ /dev/null @@ -1,11 +0,0 @@ -name: Pull Request Labeler -on: - pull_request_target - -jobs: - label: - runs-on: ubuntu-latest - steps: - - uses: actions/labeler@v3.0.2 - with: - repo-token: "${{ secrets.TOKEN_GITHUB }}" \ No newline at end of file diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml deleted file mode 100644 index 6af7448..0000000 --- a/.github/workflows/release.yml +++ /dev/null @@ -1,34 +0,0 @@ -name: Create Release & Upload Assets - -on: - push: - tags: - - "v*" # e.g. v1.0, v20.15.10 - -jobs: - goreleaser: - name: Upload Assets To Gitea w/ goreleaser - runs-on: ubuntu-latest - steps: - - name: Checkout - uses: actions/checkout@v4 - with: - fetch-depth: 0 - - - name: Set up Go - uses: actions/setup-go@v5 - with: - go-version: "1.27.x" - check-latest: true - - - name: Run GoReleaser - uses: goreleaser/goreleaser-action@v6 - with: - distribution: goreleaser - version: "~> v2" - args: release --clean - env: - GITEA_TOKEN: ${{ secrets.TOKEN_GITEA }} - GORELEASER_FORCE_TOKEN: gitea - # Optional default Sentry DSN baked into release binaries. - SENTRY_DSN: ${{ secrets.SENTRY_DSN }} diff --git a/.gitignore b/.gitignore index c8ca11a..53a0f45 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,7 @@ # Build output /bin/ /dist/ +/uberbringer *.exe *.test *.out @@ -18,3 +19,6 @@ go.work.sum .vscode/ *.swp .DS_Store + +# Claude Code +.claude/ diff --git a/.goreleaser.yaml b/.goreleaser.yaml index e5de2ec..de198f4 100644 --- a/.goreleaser.yaml +++ b/.goreleaser.yaml @@ -1,3 +1,4 @@ +# yaml-language-server: $schema=https://goreleaser.com/static/schema.json version: 2 project_name: uberbringer @@ -9,7 +10,9 @@ gitea_urls: before: hooks: - - go mod tidy + # A release builds from the committed go.mod and go.sum: print the + # change and fail, without writing, if tidy would alter them. + - go mod tidy -diff builds: - id: uberbringer @@ -32,10 +35,29 @@ builds: # SENTRY_DSN comes from a CI secret; when unset, binaries report # nothing unless sentry.dsn or the SENTRY_DSN env var is configured. - -s -w -X main.version={{ .Version }} -X main.commit={{ .ShortCommit }} -X main.sentryDSN={{ index .Env "SENTRY_DSN" }} + # File times from the commit, not the build, so rebuilding a tag gives + # the same binaries. + mod_timestamp: "{{ .CommitTimestamp }}" archives: - formats: [tar] name_template: "{{ .ProjectName }}_{{ .Os }}_{{ .Arch }}{{ if .Arm }}v{{ .Arm }}{{ end }}" + # Listing files replaces goreleaser's defaults, so the license, README and + # changelog are listed too. Each must exist; paths are kept, and install.sh + # takes packaging/uberbringer.service from the unpacked archive. + files: + - src: LICENSE.txt + info: &commit-mtime + mtime: "{{ .CommitDate }}" + - src: README.md + info: *commit-mtime + - src: CHANGELOG.md + info: *commit-mtime + - src: configs/config.example.toml + info: *commit-mtime + - src: packaging/uberbringer.service + info: *commit-mtime + builds_info: *commit-mtime source: enabled: true @@ -49,3 +71,10 @@ release: owner: 57_Wolve name: uberbringer draft: false + # vX.Y.Z-rc.N is published as a prerelease, so it never becomes the + # latest release. + prerelease: auto + header: | + **uberbringer {{ .Tag }}**, built {{ .Date }} from `{{ .ShortCommit }}`. + + Breaking changes and upgrade steps are in [CHANGELOG.md](https://git.anomalous.dev/57_Wolve/uberbringer/src/tag/{{ .Tag }}/CHANGELOG.md). diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..c2821f3 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,244 @@ +# Changelog + +All notable changes to Überbringer are recorded here. The format follows +[Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and versions follow +[Semantic Versioning](https://semver.org/spec/v2.0.0.html). Until 1.0, a minor +version may break callers; such changes are listed under **Breaking**. + +## [Unreleased] + +Planned as 0.2.0. The daemon is rewritten, and so are its install script and +release process. Read **Breaking** before you upgrade a 0.1 install. + +### Breaking + +- `POST /api/v1/print` takes `{"elements": [...]}` instead of + `{"data": [...]}`. A body in the old format is refused with `400` + `invalid_job`, and its message points to the README. README § Migrating + from the old format maps each 0.1 item type to an element. +- `POST /api/v1/print` answers `202 Accepted` with a `Location` header and a + JSON job (`id`, `status`, `created_at`). 0.1 answered `200` with the text + `OK - `. Job IDs are `job_` TypeIDs instead of numbers. +- Every error is JSON: `{"error": "...", "code": "...", "details": [...]}`. + Clients should match on `code`. 0.1 answered with `{"message": "..."}` or + plain text. +- Bearer tokens are read only from the `Authorization` header. A token in a + `?token=` query string gets `401`. 0.1 tokens keep working in the header + while `api.secret` is unchanged. +- `printer.address` is required. The 0.1 install script did not write it, so + add a `[printer]` section with `address` to such a config before starting + 0.2. Unknown config keys are now errors, so a typo no longer falls back to a + default silently. `api.secret` must be at least 32 bytes; secrets generated + by the 0.1 install script are long enough. +- `config.toml` is no longer tracked in the repository. If a clone uses it, + copy it aside before pulling and put it back afterwards; git then leaves it + untracked. New setups start from `configs/config.example.toml`. + +### Added + +- Print queue. A job is accepted at once and printed in order by a single + background worker. A failed send is retried with a doubling delay + (`printer.retries`, `printer.retry_delay`). A full queue answers `503` + `queue_full` with `Retry-After: 10`. +- `GET /api/v1/jobs/:id` reports `queued`, `printing`, `done` or `failed`. A + failed job includes an `error`. The last `queue.history` finished jobs are + kept. +- Elements: + - `text`: sizes 1–8 (or separate width and height), bold, underline, + invert, Font B and alignment; + - `feed` and `qr`; + - `barcode`: EAN-13, EAN-8, UPC-A, UPC-E, CODE39 and CODE128; + - `image`, `raw` and `cut`. +- `copies` (1–5) prints the job several times, cutting after each copy. +- UTF-8 text is transcoded to `printer.codepage`: `cp437` by default, or + `cp850`, `cp858` or `cp1252`. A character the code page lacks prints as + `?`. Control characters are removed. +- Word wrap at word boundaries for the paper width and character size. The + position is tracked across `"newline": false` elements. +- Images come from a URL or base64, as PNG, JPEG, GIF or WebP. Each is scaled + to the paper and dithered, with limits on download size, pixel count and + printed height. +- Printer profiles, chosen with `printer.model`: + - `tm-t88` (TM-T88IV to VII), the default; + - `tm-m50` (TM-m50, TM-m50II); + - `tm-t20` (TM-T20, II, III); + - `generic-80mm` and `generic-58mm`. + + `printer.paper_width` and `printer.columns` override the profile. +- `GET /healthz` reports live printer status: paper near end or out, cover + open, errors. + - It answers `200` when the printer is ready or does not answer status + requests, and `503` when it is unreachable, not ready or too slow to + answer. + - A printer that looks not ready is read again 750 ms later, so a printer + that is busy cutting or feeding raises no false alarm. +- A stable `code` in every error response, listed in README § Errors. + Examples are `job_not_found` and `not_found` for `404`, and `queue_full` and + `shutting_down` for `503`. A `405` carries `Allow`, and a `429` carries + `Retry-After`. +- `Cache-Control: no-store` on `/healthz` and on every `/api/v1` response, + error responses included. +- Commands `uberbringer secret`, which prints a new API secret, and + `uberbringer token [--subject] [--ttl]`, which prints a signed bearer token. +- Config sections: + - `[webserver]`: rate limit, trusted proxies, body limit and timeouts; + - `[queue]`, `[images]` and `[sentry]`; + - `[log]`: level, and text or JSON format. + + Every optional key has a default, shown in `configs/config.example.toml`. +- Graceful shutdown on SIGINT and SIGTERM. A receipt that is printing is + finished, and waiting jobs are marked failed. +- Logging: + - one `request` line per request, at INFO, or at WARN for a 5xx answer; + - for an unexpected failure, one ERROR `request failed` line and one Sentry + event; + - for a recovered panic, one ERROR `panic` line with its stack trace and one + Sentry event. +- An Alpine `Dockerfile` that runs as a non-root user. +- A hardened systemd unit, `packaging/uberbringer.service`, shipped in the + release archives and installed to `/usr/local/lib/systemd/system/`. + - It has no capabilities and a read-only file system, and its address + families and system calls are restricted. + - It sets start-rate limits. + - Customise it with `systemctl edit uberbringer` drop-ins. +- `install.sh`: + - takes the printer address as its third argument; + - installs a given release with `UBERBRINGER_VERSION=vX.Y.Z`; + - installs on arm64, armv7 and armv6 as well as amd64. +- Release archives contain `LICENSE.txt`, `README.md`, + `configs/config.example.toml` and `packaging/uberbringer.service` next to + the binary. +- A weekly govulncheck run (Mondays 06:00 UTC, and on every push to main), so + a new advisory against unchanged dependencies is reported. +- A Makefile for development. `make check` runs the CI gate in the same order, + `make vuln` runs govulncheck and `make snapshot` builds the release archives + without publishing them. `make` builds report the version without a leading + `v`, as release binaries do. + +### Changed + +- The HTTP server is Fiber v3 instead of Echo. ESC/POS commands come from an + in-house package instead of justinmichaelvieira/escpos. +- `printer.model` defaults to `tm-t88`: 512 dots, 42 Font A columns. On a + 576-dot printer such as a TM-T20, set `model = "tm-t20"` to use the full + width. A profile wider than the printer makes it break words at the right + edge; a narrower one only shortens lines. +- Request IDs are `req_` TypeIDs (UUIDv7). +- Rate limiting is per client and covers `/api` only: `webserver.rate_limit` + requests per `webserver.rate_window`, 60 per minute by default. Behind + nginx, the client is the `X-Real-IP` set by the proxy on 127.0.0.1. 0.1 + allowed about one request per second on every route. +- Error messages are fixed texts set by the server. The HTTP framework's own + text, which can quote bytes of the request, is never sent; an unknown route + answers `not found`. +- Expected refusals are not logged as errors or sent to Sentry: 4xx answers, + a full queue, shutdown, and an unhealthy `/healthz`. +- Release binaries take their default Sentry DSN from the `SENTRY_DSN` CI + secret instead of from the repository. `sentry.dsn` and the `SENTRY_DSN` + environment variable override it. +- `install.sh`, user and secrets: + - The service runs as a dedicated `uberbringer` user instead of root. + - The config is written under umask 027 and set to 0640 + root:uberbringer. + - The first API token goes to `/etc/uberbringer/initial-token` (0600, root) + instead of the terminal. Re-runs create no new tokens. +- `install.sh`, download and certificate: + - The download is checked against the release's `checksums.txt` (sha256) + before anything is installed. + - A certificate is requested only when none is installed, and acme.sh's cron + job renews it. The CA is now explicitly Let's Encrypt; acme.sh's default + is ZeroSSL. + - `apt-get update` runs before packages are installed, and apt output goes + to `/var/log/uberbringer-install.log`. +- `install.sh`, re-runs and validation: + - A re-run keeps the config, the certificate and unit drop-ins. It restarts + the service only when the binary, the unit or the config changed. + - A unit at `/etc/systemd/system/uberbringer.service` written by the 0.1 + script is disabled and renamed to `.bak`. + - Domains and printer addresses that contain anything other than host-name + or IP-address characters are rejected. +- Go: + - The minimum is Go 1.26. + - The toolchain is pinned in `go.mod` as `toolchain go1.27.4`, which fixes + GO-2026-6859. CI, the security scan and releases all use it. + - Every dependency is upgraded, and `vendor/` is gone. + - The module path is still the bare `uberbringer`, so build from a clone. +- CI moved from `.github/workflows` to `.gitea/workflows`. `test.yml` runs + once per branch push, and its gate is gofmt, goimports, + `go mod tidy -diff`, go vet, staticcheck, `go test -race -timeout 5m` and a + goreleaser snapshot of every shipped target. +- Releases: + - Releases are cut only from `v*` tags whose commit is on main, with + goreleaser pinned to 2.20.3. + - `-rc.N` tags are published as prereleases, and an rc tag on the same + commit as the final tag cannot be picked by mistake. + - A release fails, instead of silently rewriting `go.mod` and `go.sum`, when + they are not tidy. + - File times come from the tag's commit, so rebuilding a tag gives + byte-identical archives. + - Release notes start with a link to this file. + +### Removed + +- The `{"data": [...]}` job format with numeric item types, and token lookup + from query strings (see **Breaking**). +- The pull-request labeler workflow, which had no configuration. +- The `vendor/` directory and the `.idea/` project files. + +### Fixed + +- A job is validated in full before it is queued; the `400` lists every + problem. Nothing reaches the printer unless the whole receipt rendered. +- A failed connection to the printer is retried, and the job is then marked + failed. In 0.1 it panicked the request handler, which answered `500`. +- Request logs never contain tokens. +- Sentry no longer receives the `Authorization` header or print contents. +- `install.sh` writes the `[printer]` section. Without it, 0.1 dialled port + 9100 on the local host. + +### Security + +- The `config.toml` tracked in 0.1.x held an API secret, and that secret is + still readable in the repository history. + - An install that uses it must replace `api.secret` with the output of + `uberbringer secret`, then issue new tokens. Every token signed with the + old secret stops working. + - Installs set up by `install.sh` generated their own secret and are not + affected. +- The 0.1 install script left `/etc/uberbringer/config.toml` readable by every + user (mode 0644 under the usual umask). Re-running the new script keeps the + file as it is. On an upgraded host, after the re-run has created the + `uberbringer` group, run + `chown root:uberbringer /etc/uberbringer/config.toml` and + `chmod 0640 /etc/uberbringer/config.toml`. +- Image URLs are fetched through an SSRF guard. + - A URL is refused when it resolves to a loopback, private or link-local + address, cloud metadata endpoints included. + - The check runs at connect time, after DNS resolution, and again on every + redirect. + - `images.allow_private_networks` turns the address check off. + `images.allowed_hosts` limits fetches to the listed hosts, which may then + be on the LAN. + - 0.1 fetched any URL. +- `api.secret` must be at least 32 bytes (see **Breaking**). + +## [0.1.2] - 2025-01-12 + +### Added + +- Item type 7 prints the image at the URL given in `text`. + +## [0.1.1] - 2025-01-12 + +### Added + +- First release: + - `POST /api/v1/print` with `{"data": [...]}` items of types 1–6: text, + bold text, QR code, line feed, n line feeds and raw hex; + - HS256 bearer tokens; + - `install.sh` for Debian and Ubuntu with nginx and an acme.sh + certificate. + +[Unreleased]: https://git.anomalous.dev/57_Wolve/uberbringer/compare/v0.1.2...main +[0.1.2]: https://git.anomalous.dev/57_Wolve/uberbringer/compare/v0.1.1...v0.1.2 +[0.1.1]: https://git.anomalous.dev/57_Wolve/uberbringer/src/tag/v0.1.1 diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..19adba9 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,140 @@ +# Überbringer + +Notes for agents working in this repository. Überbringer is a single Go +binary. It takes JSON print jobs over a REST API (Fiber v3) and queues them in +memory. It renders each job to ESC/POS and sends it over TCP port 9100 to one +Epson receipt printer. It ships in two forms: as release tarballs, which +`install.sh` installs behind nginx, and as the Alpine image built from the +root `Dockerfile`. + +## Read first + +- Coding rules: `R:\Current Storage\Projects\AI-Memory\Golang-Programming-Standards.md`. + Every change follows it. `.gitea/workflows/`, `packaging/`, the root + `Dockerfile` and `install.sh` take the place of the standards' `build/` and + `scripts/`. +- `README.md` is the reference for the API, elements, error codes, + configuration, command line and package layout. There is no api.md or + OpenAPI document. +- `docs/design.md` explains why the daemon is shaped as it is and lists what + is deferred. Change it in the same commit as any code that departs from it. +- `docs/plans/.md` holds a feature until it ships. A decision made + while planning goes into design.md at once. Once the feature is done, delete + the plan. + +## Layout + +`cmd/uberbringer` is a thin main. `internal/app/uberbringer` holds the CLI and +the wiring, and `server/` holds the HTTP API. `internal/pkg/*` holds the +libraries. README § Development lists them. The module path is the bare +`uberbringer`, so imports read `uberbringer/internal/...`. Imports point down: + +- server → printqueue, receipt, printer, escpos +- printqueue → receipt +- receipt → escpos, raster +- printer → escpos + +Only `internal/app` reads config or wires in safehttp. Packages under +`internal/pkg` take plain values, and escpos knows nothing of JSON or HTTP. + +## Gate + +There is no `make` and no `docker` on this workstation. Run the steps of +`make check` directly, in PowerShell. The race detector needs cgo, which +works from PowerShell and fails from Git Bash. + + gofmt -l . # must print nothing (fix: gofmt -w .) + go tool goimports -l . # must print nothing (fix: go tool goimports -w .) + go mod tidy -diff + go vet ./... + go tool staticcheck ./... + go test -race -timeout 5m ./... *> "$env:TEMP\uberbringer-test.txt"; "exit $LASTEXITCODE" + go tool govulncheck ./... # after any dependency or toolchain change, and before a tag + goreleaser release --snapshot --clean # into dist/; after a change to .goreleaser.yaml or packaging/ + +Read the test output back from the file. The per-package `-timeout 5m` makes a +hung test fail with every goroutine's stack. Without it, the tool's own time +limit would kill the run first. staticcheck, goimports and govulncheck are +pinned as tools in `go.mod`, so never install them separately. +`.gitea/workflows/test.yml` runs the same gate on every branch push, and +`security.yml` runs govulncheck weekly and on pushes to main. A change is done +when the gate passes and README and CHANGELOG.md say what changed. + +## Go version + +- The `go` line in `go.mod` (1.26.0) is the minimum Go. Raise it only when the + code needs a newer language or library feature. README § Development states + the same minimum. +- The `toolchain` line is the pinned build toolchain. CI tests, scans and + releases with it, and a local Go that is older switches to it. Bump it to + each new patch release, since govulncheck flags standard-library fixes. Bump + the tool modules (golang.org/x/tools, golang.org/x/vuln, honnef.co/go/tools) + in the same commit. +- goreleaser is pinned to the same version in `test.yml` and `release.yml`. + Move both together. + +## Rules + +- Nothing reaches the printer unless the whole receipt rendered. The order is + validate, render in full, then send. +- Text is transcoded to the configured code page and stripped of control + characters, so data can never become printer commands. Only the `raw` + element sends bytes as given. +- Layout comes from the printer profile's dots and glyph widths. Never + hard-code 42 or 512. +- The printer takes one TCP connection at a time, and it can report a passing + problem while it cuts or feeds. A status read cut short by our own deadline + is a timeout, never a printer fault. Anything that acts on status re-checks + first, as `/healthz` does. +- Every refusal is an `apiError` with a code from `server/errors.go`. A code is + part of the API: never rename one, and add a new code to the README table. + Refusals are not logged as failures. An unexpected error is logged and sent + to Sentry once. +- Print contents, tokens and the API secret never reach logs or Sentry. The + root `config.toml` is untracked and holds the secret. Never commit it, and + never echo its secret. +- These changes land in one commit with their docs: + - A config key: `internal/pkg/config` (the default and the validation), + `configs/config.example.toml` and README § Configuration. + - A route, element field, status or error code: its code, its tests and + README. A new route also needs its case in `TestRoutesConform`, which + fails for a route without one. +- Dependencies are at their latest stable release when added or bumped. +- Commit, push, tag or release only when the owner asks. Releases are + `vX.Y.Z` tags on `main`; `release.yml` refuses a tag whose commit is not on + `main`. + +## Comments and docs + +- Code comments describe the code only: what it does and why. They never + mention docs, plans, other repositories or history ("pre-refactor", "the old + format"). This holds for Go, shell, YAML, TOML, the systemd unit, the + Dockerfile and the Makefile. +- `docs/` stays tidy. When something there is finished or superseded, delete + it or fold it in. Keep no "was considered" history and no answered question + lists. +- `CHANGELOG.md`: every user-visible change gets an entry under + `## [Unreleased]`, which becomes the version's section when the tag is cut. + A change that breaks an existing caller, config or install goes under + **Breaking**. + +## Testing on the printer + +Unit tests run against fakes and pin command bytes. Passing tests do not +prove a change to what prints, such as layout, wrapping, code pages, images, +barcodes, QR codes or cuts, or a change to how status is read. Only the paper +proves it. + +- The printer is an Epson TM-T88IV at 192.168.1.245:9100. Its model is + `tm-t88`: 512 dots, 42 Font A and 56 Font B columns, CP437. A TM-T88VII and + a TM-m50II are planned, with the same geometry. +- It is live and uses real paper. Ask the owner before printing anything. Say + what to look for (line breaks, characters, image edges, the cut), print one + short receipt at a time, and wait for his report or photo. +- Judge by what printed and by `/healthz`, never by a log line or a `202`. +- To print: `go run ./cmd/uberbringer` reads the root `config.toml`, and + `go run ./cmd/uberbringer token` prints a token. Write the job to a file + outside the repository, then send it: + `curl.exe -H "Authorization: Bearer " -H "Content-Type: application/json" --data-binary "@job.json" http://127.0.0.1:8080/api/v1/print` +- Once the owner passes a receipt, pin its rendered bytes in a receipt test, + so that a later change to them shows up in `go test`. diff --git a/Makefile b/Makefile index 8a44af4..dbb6bf9 100644 --- a/Makefile +++ b/Makefile @@ -1,14 +1,16 @@ -.PHONY: build test lint fmt vet tidy vuln check run +.PHONY: build test lint fmt fmt-check vet tidy tidy-check vuln snapshot check run -VERSION ?= $(shell git describe --tags --always --dirty 2>/dev/null || echo dev) +# Without the leading v, as goreleaser's {{ .Version }} reports it. +VERSION ?= $(patsubst v%,%,$(shell git describe --tags --always --dirty 2>/dev/null || echo dev)) COMMIT ?= $(shell git rev-parse --short HEAD 2>/dev/null || echo none) LDFLAGS := -s -w -X main.version=$(VERSION) -X main.commit=$(COMMIT) build: go build -trimpath -ldflags "$(LDFLAGS)" -o bin/ ./cmd/... +# The limit is per package: a hung test fails with every goroutine's stack. test: - go test -race ./... + go test -race -timeout 5m ./... lint: go tool staticcheck ./... @@ -18,18 +20,31 @@ fmt: gofmt -w . go tool goimports -w . +fmt-check: + @test -z "$$(gofmt -l .)" || (echo "gofmt needed:"; gofmt -l .; exit 1) + @test -z "$$(go tool goimports -l .)" || (echo "goimports needed:"; go tool goimports -l .; exit 1) + vet: go vet ./... tidy: go mod tidy +# Prints the change and fails, without writing, if go.mod or go.sum is not tidy. +tidy-check: + go mod tidy -diff + vuln: go tool govulncheck ./... -# Everything CI runs. -check: vet lint test vuln - @test -z "$$(gofmt -l .)" || (echo "gofmt needed:"; gofmt -l .; exit 1) +# Cross-compiles every shipped target and packs the release archives into +# dist/, publishing nothing. +snapshot: + goreleaser release --snapshot --clean + +# The gate .gitea/workflows/test.yml runs, in the same order. +# .gitea/workflows/security.yml runs vuln. +check: fmt-check tidy-check vet lint test snapshot run: go run ./cmd/uberbringer --config config.toml diff --git a/README.md b/README.md index e3cc1d3..28d48ef 100644 --- a/README.md +++ b/README.md @@ -36,10 +36,57 @@ REST API and prints them on an EPSON ESC/POS network receipt printer. sudo ./install.sh printer.example.com you@example.com 192.168.1.245 ``` -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. +The arguments are the server's domain, the email address for Let's Encrypt, +and the printer's address. The domain may contain only letters, digits, dots +and hyphens. The printer address may also contain colons, for IPv6. + +The script does the following: + +- It downloads the latest release for the host's architecture and checks it + against the release's `checksums.txt` (sha256). If the check fails, nothing + is installed. To install a given release, name its tag: + `sudo UBERBRINGER_VERSION=v0.2.0 ./install.sh `. +- It installs the binary to `/usr/local/bin/uberbringer` and the systemd unit + to `/usr/local/lib/systemd/system/uberbringer.service`. The unit comes from + the release archive, or from this checkout's `packaging/` directory if the + archive lacks it. The service runs as a dedicated `uberbringer` user. +- It writes `/etc/uberbringer/config.toml` (0640, root:uberbringer) with a + fresh secret. +- It sets up nginx as the HTTPS reverse proxy. The certificate comes from + Let's Encrypt through acme.sh, whose cron job renews it. +- It writes the first API token to `/etc/uberbringer/initial-token` (0600, + readable by root only) instead of printing it. Copy the token to your + client, then delete the file. + +The install log, apt output included, is `/var/log/uberbringer-install.log`. + +Running the script again upgrades the binary and the unit, and restarts the +service only if the binary, the unit or the config changed. It also rewrites +the nginx site files `/etc/nginx/sites-available/default.conf` and +`reverse-proxy.conf`, so local edits to them are lost. It keeps: + +- **The config.** The printer-address argument is ignored on a re-run, so + edit `printer.address` in `/etc/uberbringer/config.toml` instead. +- **The certificate.** One is requested only when `fullchain.pem` or + `privkey.pem` in `/etc/letsencrypt/live//` is missing or empty. +- **Tokens.** A re-run creates none. Issue more with + `uberbringer token --config /etc/uberbringer/config.toml --subject `. + +The systemd unit ships as +[packaging/uberbringer.service](packaging/uberbringer.service): + +- **Changing it.** Use `systemctl edit uberbringer`, never the installed unit + file. Those drop-ins survive re-runs. +- **Sandboxing.** The unit has no capabilities and a read-only file system, + and it can reach the network over IPv4 and IPv6 only. Check it on the host + with `systemd-analyze security uberbringer`. +- **The 0.1 unit.** The 0.1 install script wrote + `/etc/systemd/system/uberbringer.service`, and a re-run renames that file to + `uberbringer.service.bak`. Any other file at that path overrides the + packaged unit; the script leaves it in place and warns. + +Upgrading a 0.1 install needs a few manual steps; see +[Migrating from the old format](#migrating-from-the-old-format). ### Docker @@ -67,6 +114,9 @@ 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. +Responses from `/healthz` and every `/api/v1` route, error responses +included, carry `Cache-Control: no-store`. + | Method | Path | Purpose | |--------|--------------------|------------------------------------------| | POST | `/api/v1/print` | Queue a print job | @@ -153,16 +203,37 @@ Details: ### Errors -Errors are JSON: `{"error": "message", "details": ["..."]}`. +Errors are JSON: -| 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 | +```json +{"error": "invalid job", "code": "invalid_job", "details": ["elements[2] (text): size, width and height must be 1-8"]} +``` + +- `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. + +| 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 new format](#migrating-from-the-old-format) | +| 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 | +| 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` | +| 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 | +| 501 | `not_implemented` | A request body with an unsupported transfer coding. An unknown HTTP method (e.g. `FOO /healthz`) is refused by the HTTP server itself with a plain-text `501` | +| 503 | `queue_full` | The print queue is full. Sent with `Retry-After: 10` | +| 503 | `shutting_down` | The server is shutting down | + +Any other status that the HTTP layer produces itself gets the code +`http_`, e.g. `http_502`. `/healthz` answers `503` with its own body, +shown under [Health](#health), not with this shape. 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 @@ -274,13 +345,44 @@ 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 `"│ !!!"`. +These changes also affect 0.1 clients and installs. +[CHANGELOG.md](CHANGELOG.md) lists every change. + +- Tokens are read only from the `Authorization` header. A `?token=` query + string gets `401`. +- Errors have the [JSON shape above](#errors) instead of `{"message": "..."}` + or plain text. +- `printer.model` defaults to `tm-t88` (512 dots). On a TM-T20, set + `model = "tm-t20"` to use the full 576-dot width. + +To upgrade a server set up by the 0.1 install script: + +1. Add a `[printer]` section to `/etc/uberbringer/config.toml`. The 0.1 + script did not write one, `printer.address` is now required, and + `install.sh` keeps an existing config as it is, so without this step the + service does not start: + + ```toml + [printer] + address = "192.168.1.245" + ``` + +2. Run the new `install.sh` with the domain, the email address and the + printer address; it needs all three, although the printer address in the + kept config is the one used. It creates the `uberbringer` user, installs + the new unit and moves the 0.1 unit aside. +3. The 0.1 script left the config readable by every user. Once the + `uberbringer` group exists, fix that with + `sudo chown root:uberbringer /etc/uberbringer/config.toml && sudo chmod 0640 /etc/uberbringer/config.toml`. + ## 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. +from 0.1 still load, because their keys are unchanged, but `printer.address` +is now required. Unknown keys are reported as errors, so a typo can't +silently fall back to a default. Settings worth knowing: @@ -307,7 +409,22 @@ Settings worth knowing: `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. + CI secret). Request bodies and the `Authorization` header are never sent + to Sentry. +- `log.level` (`debug`, `info`, `warn`, `error`) and `log.format` (`text` or + `json`) control what is logged: + - Each request is logged once, as `request`: at INFO, or at WARN when the + status is 5xx. Only the path is logged, never the query string, the body + or the token. + - An unexpected failure adds one ERROR `request failed` line, with `err` and + `request_id`, and one Sentry event. + - A recovered panic adds one ERROR `panic` line, with `panic` and `stack`, + 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. + - 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`. ## Command line @@ -323,17 +440,43 @@ 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. +The Go version is set in `go.mod`: + +- The `go 1.26.0` line is the minimum, and builds with `GOTOOLCHAIN=local` + need at least that. +- The `toolchain go1.27.4` line picks the Go release that CI tests, scans and + releases with. With the default `GOTOOLCHAIN=auto`, an older local Go + downloads go1.27.4 by itself. +- To move to a new Go release, change the toolchain line. In the same commit, + bump the tool modules golang.org/x/tools, golang.org/x/vuln and + honnef.co/go/tools. The workflows read the version from `go.mod`. ```sh -make check # gofmt, go vet, staticcheck, go test -race, govulncheck -make build # bin/uberbringer -make fmt # gofmt + goimports +make check # the CI gate, below +make build # bin/uberbringer +make fmt # gofmt + goimports +make vuln # govulncheck +make snapshot # release archives in dist/; publishes nothing ``` +`make check` runs the same steps as `.gitea/workflows/test.yml`, in the same +order: + +1. `fmt-check`: gofmt and goimports. +2. `tidy-check`: `go mod tidy -diff`. +3. `go vet`. +4. staticcheck. +5. `go test -race -timeout 5m`. +6. `snapshot`: `goreleaser release --snapshot --clean`. + +It needs goreleaser installed. govulncheck is not part of it; run +`make vuln`. `make` builds report the version without the leading `v`, e.g. +`0.1.2-3-gabc1234`, as release binaries do. + 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. +`go tool govulncheck` and `go tool goimports` need no separate install. The +module path is `uberbringer`, so packages import as +`uberbringer/internal/...`. Build from a clone of the repository. ```text cmd/uberbringer/ main: build info, signals, exit code @@ -347,6 +490,27 @@ 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 +packaging/ systemd unit +docs/ Design notes and feature plans ``` -Releases are built by GoReleaser when a `v*` tag is pushed. +[docs/design.md](docs/design.md) explains why the daemon is shaped as it is. +[CHANGELOG.md](CHANGELOG.md) lists the changes in each release. + +### CI and releases + +CI runs on the Gitea runner from `.gitea/workflows/`. The repository has no +`.github/` directory. + +- `test.yml` runs the `make check` gate on every branch push. It does not run + on pull requests or tags. +- `security.yml` runs govulncheck on pushes to main and every Monday at + 06:00 UTC. Scheduled runs use main's copy of the workflow. +- `release.yml` builds and publishes a release with goreleaser 2.20.3 when a + `v*` tag is pushed. + - It runs only for tags whose commit is on main, and refuses any other tag. + - `vX.Y.Z-rc.N` tags are published as prereleases, so they never become the + latest release that `install.sh` installs. + - Each archive holds the binary, `LICENSE.txt`, `README.md`, + `configs/config.example.toml` and `packaging/uberbringer.service`. + - The release notes link to `CHANGELOG.md` at the tag. diff --git a/cmd/uberbringer/main.go b/cmd/uberbringer/main.go index 50d7f42..54a2b21 100644 --- a/cmd/uberbringer/main.go +++ b/cmd/uberbringer/main.go @@ -9,7 +9,7 @@ import ( "os/signal" "syscall" - "git.anomalous.dev/57_Wolve/uberbringer/internal/app/uberbringer" + "uberbringer/internal/app/uberbringer" ) // Set at build time with -ldflags "-X main.version=... -X main.commit=...". diff --git a/docs/design.md b/docs/design.md new file mode 100644 index 0000000..b1346c9 --- /dev/null +++ b/docs/design.md @@ -0,0 +1,129 @@ +# Überbringer: design + +Status: the daemon is built and has been checked on paper on the TM-T88IV. +Next is the release of CHANGELOG.md § Unreleased as 0.2.0, and the formatters +work in `docs/plans/formatters.md`. This page records why the daemon is +shaped as it is. README.md describes how to use it. + +## Why + +Scripts and services on the owner's network send short JSON jobs, and one +Epson receipt printer prints them. The daemon replaces the 0.1 one on the +same endpoint, `POST /api/v1/print` behind nginx, and 0.1 installs are +deployed. It is one static binary with no database, sized for receipt rates +on one printer. + +```text +client ─HTTPS─▶ nginx ─▶ server ── validate ──▶ printqueue (memory, 1 worker) + │ │ receipt.Render: whole job + │ │ to bytes, images via safehttp + │ ▼ + └─ /healthz ──────▶ printer.Client ─TCP 9100─▶ printer + (one connection at a time) +``` + +## Decisions + +- **One printer per instance.** The config names one printer, and its client + holds one connection to it at a time, shared by sends and status reads. A + second printer means a second instance with its own config and port. + The planned TM-T88VII and TM-m50II (owner, 2026-11-29) have the same + geometry as the TM-T88IV, so a single profile default covers all three. +- **The queue lives in memory, on purpose.** ESC/POS gives no + acknowledgement of what has printed. A queue replayed after a crash could + therefore print a receipt twice. A lost job, by contrast, shows as failed + or unknown, and the client can send it again. Waiting jobs are marked + failed at shutdown. After a crash their IDs answer `job_not_found`. One + worker keeps jobs in submission order, and the history is capped by + `queue.history`. +- **Render, then send.** The handler validates the whole job, and a `400` + lists every problem. The worker then renders the complete receipt, images + included, to one byte stream that starts with a printer reset (ESC @). It + sends that stream over one connection. A failure before the send, such as a + broken image, costs no paper and leaves no half-printed receipt. A retry + resends the same bytes and does not render again. A send that fails + part-way can print part of a receipt twice. That is accepted, because + retries are what let a job survive a printer that is briefly offline. +- **Text in, code page out.** Clients send UTF-8, which is transcoded to + `printer.codepage`. The default is CP437, for the box drawing and shading + the owner prints (owner, 2026-11-29). Control characters are stripped, so + data can never become a printer command. Only the `raw` element sends bytes + as given. +- **Profiles set the layout, and the default is the narrower one.** Columns + are the profile's dots per line divided by the glyph width; nothing + hard-codes 42 or 512. The first paper test ran the 576-dot `tm-t20` + profile on the TM-T88IV, which has 512 dots, and the printer broke words at + its own edge (`seve` / `ral`). A profile wider than the printer breaks + words, while a narrower one only shortens lines. So `tm-t88` (512 dots, 42 + columns) is the default. +- **Status is read in a way that tolerates a busy printer.** `/healthz` sends + DLE EOT 1 to 4 over the same connection slot that sends use. + - The DLE EOT 2 bits (cover open, paper-end stop) are cleared while DLE + EOT 1 says online. Epson printers go offline for both causes, and a + TM-T88IV reported a stale cover-open bit while cutting. + - A not-ready reading is re-read 750 ms later. + - A read cut short by our own deadline is `timeout` with `503`. It never + counts as "status unsupported", because an unknown state must not look + healthy. + - A printer that never answers status gets `200` `unknown`. + - The TM-T88VII does not report paper near-end through DLE EOT 4. +- **Health is for monitors.** `/healthz` answers `200` when the printer is + ready, or when it cannot report status. It answers `503` when a job could + not print now: the printer is unreachable, not ready or timed out. A `503` + from it is a refusal: it is logged at WARN by the request line and never + sent to Sentry. +- **Images are fetched by the worker, through an SSRF guard.** A slow or + broken image URL holds no HTTP request and shows up as a `failed` job. + `safehttp` checks the resolved address at connect time, so DNS rebinding + and redirects cannot reach loopback, private, link-local or cloud metadata + addresses. Exceptions are configured explicitly (`images.*`). Time, size, + pixel and height limits bound each image. +- **Errors are flat JSON with a stable code.** The shape is + `{"error", "code", "details"}`. `code` is the contract with clients, and + `error` is for people. A refusal is answered and never logged as a failure. + An unexpected error or panic is logged once and reported to Sentry once, + without the body or the `Authorization` header. +- **What stays compatible with 0.1.** The endpoint, the HS256 tokens and the + config keys stay as they were. The 0.1 body and its plain-text answer do + not. A 0.1 body gets a `400` that points to the migration table, instead of + being translated. Tokens are read only from the header, because tokens in + query strings end up in proxy logs. +- **Stack choices (owner, 2026-11-29):** + - Fiber v3 instead of Echo. + - TypeID (UUIDv7) job and request IDs instead of snowflakes. They sort by + time and need no node configuration. + - An Alpine Docker image. +- **Packaging.** The release tarballs are built for linux amd64, armv6, armv7 + and arm64. `install.sh` sets up nginx (TLS, `X-Real-IP`), acme.sh and the + sandboxed unit from `packaging/`. The daemon binds 127.0.0.1 by default and + serves no TLS itself. + +## Planned: formatters + +Layout blocks and modules, ntfy among them, that turn plain input into +receipts. The plan is `docs/plans/formatters.md`. 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 + attachments come from a public host, so image fetches need no + private-network exception. +- Which priorities print is configurable per subscription. By default every + priority prints, and priorities 1 and 2 print in a compact form. +- On `/print`, characters the code page lacks fold to ASCII look-alikes + (smart quotes, dashes, the ellipsis), and an emoji sequence prints as one + `?`. Today each such character prints as `?`. +- Labels are in English. The footer's time zone and date format come from + the config. + +## Deferred + +- **Paper near-end on the TM-T88VII**, which `GS r 1` reports. Add it when + that printer arrives. +- **Several printers from one instance**, through routing or a pool. Until + then, run one instance per printer. +- **A durable queue.** It needs a way to tell which receipts printed before a + crash. +- **Printer alerts sent out to ntfy** (paper out, cover open). They have not + been requested. Printing incoming ntfy messages is part of the formatters + plan. diff --git a/docs/plans/formatters.md b/docs/plans/formatters.md new file mode 100644 index 0000000..cf641e6 --- /dev/null +++ b/docs/plans/formatters.md @@ -0,0 +1,1111 @@ +# 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=