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

+92
View File
@@ -0,0 +1,92 @@
// Package raster prepares images for thermal printing: it decodes them within
// a pixel budget, scales them to the print head width, and dithers them to
// pure black and white.
package raster
import (
"bytes"
"errors"
"fmt"
"image"
"image/color"
"image/draw"
// Register the formats Decode accepts.
_ "image/gif" // registers GIF decoding
_ "image/jpeg" // registers JPEG decoding
_ "image/png" // registers PNG decoding
xdraw "golang.org/x/image/draw"
_ "golang.org/x/image/webp" // registers WebP decoding
)
var (
// ErrTooLarge is returned when an image exceeds the pixel budget.
ErrTooLarge = errors.New("raster: image exceeds pixel limit")
// ErrInvalidSize is returned for zero or negative target sizes.
ErrInvalidSize = errors.New("raster: invalid size")
)
// Decode decodes PNG, JPEG, GIF or WebP data. The header is checked first,
// so an image whose declared size exceeds maxPixels is rejected before any
// pixel memory is allocated.
func Decode(data []byte, maxPixels int) (image.Image, error) {
cfg, format, err := image.DecodeConfig(bytes.NewReader(data))
if err != nil {
return nil, fmt.Errorf("reading image header: %w", err)
}
if cfg.Width <= 0 || cfg.Height <= 0 {
return nil, fmt.Errorf("%w: %dx%d", ErrInvalidSize, cfg.Width, cfg.Height)
}
if int64(cfg.Width)*int64(cfg.Height) > int64(maxPixels) {
return nil, fmt.Errorf("%w: %dx%d is more than %d pixels", ErrTooLarge, cfg.Width, cfg.Height, maxPixels)
}
img, _, err := image.Decode(bytes.NewReader(data))
if err != nil {
return nil, fmt.Errorf("decoding %s image: %w", format, err)
}
return img, nil
}
// palette is the two-colour palette thermal printers can reproduce.
// Index 0 is white so a freshly allocated image is blank paper.
func palette() color.Palette {
return color.Palette{color.White, color.Black}
}
// Monochrome scales img to width dots, keeping its aspect ratio, composites it
// onto white paper, and Floyd–Steinberg dithers it to black and white.
func Monochrome(img image.Image, width int) (*image.Paletted, error) {
src := img.Bounds()
if width <= 0 || src.Dx() <= 0 || src.Dy() <= 0 {
return nil, fmt.Errorf("%w: cannot scale %dx%d to width %d", ErrInvalidSize, src.Dx(), src.Dy(), width)
}
height := max(1, int(int64(src.Dy())*int64(width)/int64(src.Dx())))
// Scale onto white grayscale so transparency becomes paper and the
// dither works on luminance rather than RGB distance.
gray := image.NewGray(image.Rect(0, 0, width, height))
draw.Draw(gray, gray.Bounds(), image.White, image.Point{}, draw.Src)
xdraw.CatmullRom.Scale(gray, gray.Bounds(), img, src, draw.Over, nil)
out := image.NewPaletted(gray.Bounds(), palette())
draw.FloydSteinberg.Draw(out, out.Bounds(), gray, image.Point{})
return out, nil
}
// Place returns a width-dot-wide white canvas with img drawn at x. It is used
// to align images, because printers do not apply justification to raster
// images consistently.
func Place(img *image.Paletted, width, x int) (*image.Paletted, error) {
b := img.Bounds()
if width < b.Dx() || x < 0 || x+b.Dx() > width {
return nil, fmt.Errorf("%w: cannot place %d-dot image at %d on %d dots", ErrInvalidSize, b.Dx(), x, width)
}
if x == 0 && width == b.Dx() {
return img, nil
}
out := image.NewPaletted(image.Rect(0, 0, width, b.Dy()), palette())
draw.Draw(out, image.Rect(x, 0, x+b.Dx(), b.Dy()), img, b.Min, draw.Src)
return out, nil
}
+133
View File
@@ -0,0 +1,133 @@
package raster_test
import (
"bytes"
"errors"
"image"
"image/color"
"image/png"
"testing"
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/raster"
)
func encodePNG(t *testing.T, img image.Image) []byte {
t.Helper()
var buf bytes.Buffer
if err := png.Encode(&buf, img); err != nil {
t.Fatal(err)
}
return buf.Bytes()
}
func gradient(w, h int) *image.Gray {
img := image.NewGray(image.Rect(0, 0, w, h))
for y := range h {
for x := range w {
img.SetGray(x, y, color.Gray{Y: uint8(x * 255 / max(1, w-1))})
}
}
return img
}
func TestDecode(t *testing.T) {
data := encodePNG(t, gradient(40, 20))
img, err := raster.Decode(data, 1000)
if err != nil {
t.Fatal(err)
}
if img.Bounds().Dx() != 40 || img.Bounds().Dy() != 20 {
t.Errorf("bounds = %v", img.Bounds())
}
}
func TestDecodeRejectsOversizedBeforeDecoding(t *testing.T) {
data := encodePNG(t, gradient(40, 20))
if _, err := raster.Decode(data, 799); !errors.Is(err, raster.ErrTooLarge) {
t.Errorf("err = %v, want ErrTooLarge", err)
}
}
func TestDecodeRejectsGarbage(t *testing.T) {
if _, err := raster.Decode([]byte("not an image"), 1000); err == nil {
t.Error("expected an error")
}
}
func TestMonochromeScalesAndKeepsAspect(t *testing.T) {
out, err := raster.Monochrome(gradient(1152, 400), 576)
if err != nil {
t.Fatal(err)
}
if got := out.Bounds(); got.Dx() != 576 || got.Dy() != 200 {
t.Errorf("bounds = %v, want 576x200", got)
}
}
func TestMonochromeIsBlackAndWhiteAndDithers(t *testing.T) {
out, err := raster.Monochrome(gradient(200, 50), 200)
if err != nil {
t.Fatal(err)
}
if len(out.Palette) != 2 {
t.Fatalf("palette has %d colours, want 2", len(out.Palette))
}
// A dither of a left-to-right gradient has mixed pixels in the middle,
// unlike a hard threshold which would split it into two solid halves.
black := 0
for y := range 50 {
for x := 90; x < 110; x++ {
if out.ColorIndexAt(x, y) == 1 {
black++
}
}
}
if total := 50 * 20; black == 0 || black == total {
t.Errorf("mid-gradient has %d/%d black pixels, want a mix", black, total)
}
}
func TestMonochromeTransparentBecomesWhite(t *testing.T) {
src := image.NewNRGBA(image.Rect(0, 0, 16, 16)) // fully transparent
out, err := raster.Monochrome(src, 16)
if err != nil {
t.Fatal(err)
}
for i, idx := range out.Pix {
if idx != 0 {
t.Fatalf("pixel %d is black, want white paper", i)
}
}
}
func TestMonochromeInvalidWidth(t *testing.T) {
if _, err := raster.Monochrome(gradient(10, 10), 0); !errors.Is(err, raster.ErrInvalidSize) {
t.Errorf("err = %v, want ErrInvalidSize", err)
}
}
func TestPlace(t *testing.T) {
img, err := raster.Monochrome(image.NewGray(image.Rect(0, 0, 8, 2)), 8) // all black
if err != nil {
t.Fatal(err)
}
out, err := raster.Place(img, 24, 8)
if err != nil {
t.Fatal(err)
}
if out.Bounds().Dx() != 24 {
t.Fatalf("width = %d", out.Bounds().Dx())
}
for x := range 24 {
want := uint8(0)
if x >= 8 && x < 16 {
want = 1
}
if got := out.ColorIndexAt(x, 0); got != want {
t.Errorf("x=%d index=%d, want %d", x, got, want)
}
}
if _, err := raster.Place(img, 12, 8); !errors.Is(err, raster.ErrInvalidSize) {
t.Errorf("overflowing place err = %v", err)
}
}