Files
uberbringer/internal/pkg/config/config.go
T
57_WolveandClaude Opus 5.5 4562f0cebb
Security / Vulnerability check (push) Successful in 50s
Test / Lint and test (push) Successful in 1m59s
Add box, rule and kv blocks, text folding and receipt preview
Phase 1 of docs/plans/formatters.md: single and double CP437 boxes from
one /print element, and a way to see a receipt without using paper.

- receipt: box, rule and kv elements, laid out when the job renders from
  the printer profile, size and font (never fixed widths). Boxes take a
  title (inline or capped), a footer, padding, fit and columns, and a
  body of text or children (text, feed, kv, and rules as dividers joined
  to the borders). Glyphs a code page lacks fall back per set: double-h
  and double-v to double, then single, then ascii; a missing junction
  switches line weight first.
- Validation names nested elements (elements[0].children[3] (qr)),
  checks fields per block type, allows one level of children and counts
  them toward the 500-element limit. Block fields on the older types are
  problems, as they were unknown fields before.
- Text is composed to NFC and characters the code page lacks fold to
  look-alikes (curly quotes, dashes, ellipsis, arrows, check marks, euro,
  trademark), as the owner approved on 2026-11-29. An emoji sequence
  prints as one '?'. Encodable text is untouched.
- escpos: CodePage.CanEncode and Decode, and Interpret, which reads a
  command stream back as the printer would print it. It takes the
  profile so that it can follow the printer's own wrapping and
  alignment; raw spans stay opaque.
- POST /api/v1/preview and `uberbringer preview` show the lines a job
  prints, as text or JSON with styles, without fetching images.
- Config: [format] max_lines (default 2000), refused with 422
  too_many_lines on preview; printer.box_line_spacing (default 0).

Byte compatibility: testdata/compat fixtures were rendered by 9b91109
before the renderer changed, and still match it and the new renderer.
examples/blocks.json was printed on the TM-T88IV; the owner judged the
border gaps at the default spacing fine (2026-11-30), so
box_line_spacing stays 0, and TestPaperReceipts pins its bytes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 00:49:45 -06:00

298 lines
9.4 KiB
Go

// Package config loads and validates the Überbringer daemon configuration
// from a TOML file.
package config
import (
"errors"
"fmt"
"net/netip"
"os"
"slices"
"strings"
"time"
"github.com/BurntSushi/toml"
)
// MinSecretLength is the minimum API secret length in bytes. HS256 keys
// shorter than the 256-bit hash output weaken the signature (RFC 7518 §3.2).
const MinSecretLength = 32
// MaxLineSpacing is the largest printer.box_line_spacing, the most ESC 3
// takes.
const MaxLineSpacing = 255
// Log formats accepted by [LogConfig.Format].
const (
LogFormatText = "text"
LogFormatJSON = "json"
)
// Config is the root daemon configuration.
type Config struct {
WebServer WebServerConfig `toml:"webserver"`
API APIConfig `toml:"api"`
Printer PrinterConfig `toml:"printer"`
Format FormatConfig `toml:"format"`
Queue QueueConfig `toml:"queue"`
Images ImagesConfig `toml:"images"`
Sentry SentryConfig `toml:"sentry"`
Log LogConfig `toml:"log"`
}
// WebServerConfig configures the HTTP listener.
type WebServerConfig struct {
BindIP string `toml:"bind_ip"`
Port int `toml:"port"`
// RateLimit is the number of API requests one client may make per
// RateWindow.
RateLimit int `toml:"rate_limit"`
RateWindow time.Duration `toml:"rate_window"`
// TrustedProxies lists proxy IPs or CIDR ranges whose ProxyHeader is
// trusted to carry the real client IP.
TrustedProxies []string `toml:"trusted_proxies"`
ProxyHeader string `toml:"proxy_header"`
// BodyLimit is the maximum request body size in bytes.
BodyLimit int `toml:"body_limit"`
ReadTimeout time.Duration `toml:"read_timeout"`
WriteTimeout time.Duration `toml:"write_timeout"`
IdleTimeout time.Duration `toml:"idle_timeout"`
}
// APIConfig configures API authentication.
type APIConfig struct {
// Secret is the HS256 key used to verify bearer tokens.
Secret string `toml:"secret"`
}
// PrinterConfig configures the network receipt printer.
type PrinterConfig struct {
Address string `toml:"address"`
Port int `toml:"port"`
// Model selects a printer profile, e.g. "tm-t88" or "generic-58mm".
Model string `toml:"model"`
// CodePage is the character table text is transcoded to, e.g. "cp437".
CodePage string `toml:"codepage"`
// PaperWidth overrides the profile's printable width in dots. Zero keeps
// the profile default.
PaperWidth int `toml:"paper_width"`
// Columns overrides the number of Font A characters per line used for
// word wrapping. Zero derives it from the paper width.
Columns int `toml:"columns"`
// BoxLineSpacing is the line spacing, in motion units (ESC 3), used
// while a box prints, to close the gaps in its vertical borders. Zero
// keeps the printer's default spacing.
BoxLineSpacing int `toml:"box_line_spacing"`
DialTimeout time.Duration `toml:"dial_timeout"`
WriteTimeout time.Duration `toml:"write_timeout"`
// Retries is how many times a failed send is retried before the job is
// marked failed.
Retries int `toml:"retries"`
RetryDelay time.Duration `toml:"retry_delay"`
}
// FormatConfig configures how receipts are laid out.
type FormatConfig struct {
// MaxLines fails a job that would print more lines, all copies
// counted. It is a backstop against runaway text.
MaxLines int `toml:"max_lines"`
}
// QueueConfig configures the print queue.
type QueueConfig struct {
// Size is the number of jobs that may wait to be printed.
Size int `toml:"size"`
// History is the number of finished jobs whose status is kept.
History int `toml:"history"`
}
// ImagesConfig configures image elements.
type ImagesConfig struct {
Timeout time.Duration `toml:"timeout"`
MaxBytes int64 `toml:"max_bytes"`
// MaxPixels caps the decoded image size to guard against decompression
// bombs.
MaxPixels int `toml:"max_pixels"`
// MaxHeight caps the printed image height in dots after scaling.
MaxHeight int `toml:"max_height"`
// AllowPrivateNetworks permits fetching from loopback, private and
// link-local addresses.
AllowPrivateNetworks bool `toml:"allow_private_networks"`
// AllowedHosts, when non-empty, restricts fetching to these hosts. Listed
// hosts may resolve to private addresses.
AllowedHosts []string `toml:"allowed_hosts"`
}
// SentryConfig configures error reporting.
type SentryConfig struct {
DSN string `toml:"dsn"`
Environment string `toml:"environment"`
Debug bool `toml:"debug"`
}
// LogConfig configures structured logging.
type LogConfig struct {
Level string `toml:"level"`
Format string `toml:"format"`
}
// Default returns a configuration with every optional setting at its
// default. API.Secret and Printer.Address have no defaults.
func Default() Config {
return Config{
WebServer: WebServerConfig{
BindIP: "127.0.0.1",
Port: 8080,
RateLimit: 60,
RateWindow: time.Minute,
TrustedProxies: []string{"127.0.0.1", "::1"},
ProxyHeader: "X-Real-IP",
BodyLimit: 4 << 20,
ReadTimeout: 15 * time.Second,
WriteTimeout: 15 * time.Second,
IdleTimeout: 60 * time.Second,
},
Printer: PrinterConfig{
Port: 9100,
// The narrower 512-dot profile is the safe default: on a wider
// printer lines are just shorter, while a profile wider than the
// printer makes it break words at the right edge.
Model: "tm-t88",
CodePage: "cp437",
DialTimeout: 5 * time.Second,
WriteTimeout: 30 * time.Second,
Retries: 3,
RetryDelay: time.Second,
},
Format: FormatConfig{
MaxLines: 2000,
},
Queue: QueueConfig{
Size: 100,
History: 1000,
},
Images: ImagesConfig{
Timeout: 10 * time.Second,
MaxBytes: 10 << 20,
MaxPixels: 25_000_000,
MaxHeight: 4000,
},
Sentry: SentryConfig{
Environment: "production",
},
Log: LogConfig{
Level: "info",
Format: LogFormatText,
},
}
}
// Load reads the TOML file at path on top of [Default] and validates the
// result. Keys not recognised by Config are reported as errors so typos do not
// silently fall back to defaults. When sentry.dsn is unset, the SENTRY_DSN
// environment variable is used.
func Load(path string) (*Config, error) {
cfg := Default()
meta, err := toml.DecodeFile(path, &cfg)
if err != nil {
return nil, fmt.Errorf("reading config %s: %w", path, err)
}
if undecoded := meta.Undecoded(); len(undecoded) > 0 {
keys := make([]string, len(undecoded))
for i, key := range undecoded {
keys[i] = key.String()
}
return nil, fmt.Errorf("config %s: unknown keys: %s", path, strings.Join(keys, ", "))
}
if cfg.Sentry.DSN == "" {
cfg.Sentry.DSN = os.Getenv("SENTRY_DSN")
}
if err := cfg.Validate(); err != nil {
return nil, fmt.Errorf("config %s: %w", path, err)
}
return &cfg, nil
}
// Validate reports every problem with the configuration.
func (c *Config) Validate() error {
var errs []error
check := func(ok bool, format string, args ...any) {
if !ok {
errs = append(errs, fmt.Errorf(format, args...))
}
}
ws := c.WebServer
_, ipErr := netip.ParseAddr(ws.BindIP)
check(ipErr == nil, "webserver.bind_ip: %q is not an IP address", ws.BindIP)
check(validPort(ws.Port), "webserver.port: %d is out of range 1-65535", ws.Port)
check(ws.RateLimit > 0, "webserver.rate_limit must be positive")
check(ws.RateWindow > 0, "webserver.rate_window must be positive")
check(ws.BodyLimit > 0, "webserver.body_limit must be positive")
check(ws.ReadTimeout > 0 && ws.WriteTimeout > 0 && ws.IdleTimeout > 0,
"webserver read/write/idle timeouts must be positive")
for _, proxy := range ws.TrustedProxies {
check(validIPOrPrefix(proxy), "webserver.trusted_proxies: %q is not an IP or CIDR", proxy)
}
check(len(c.API.Secret) >= MinSecretLength,
"api.secret must be at least %d bytes (generate one with `uberbringer secret`)", MinSecretLength)
p := c.Printer
check(p.Address != "", "printer.address is required")
check(validPort(p.Port), "printer.port: %d is out of range 1-65535", p.Port)
check(p.PaperWidth >= 0, "printer.paper_width must not be negative")
check(p.Columns >= 0, "printer.columns must not be negative")
check(p.BoxLineSpacing >= 0 && p.BoxLineSpacing <= MaxLineSpacing,
"printer.box_line_spacing must be 0-%d", MaxLineSpacing)
check(p.DialTimeout > 0 && p.WriteTimeout > 0, "printer dial/write timeouts must be positive")
check(p.Retries >= 0, "printer.retries must not be negative")
check(p.RetryDelay > 0, "printer.retry_delay must be positive")
check(c.Format.MaxLines > 0, "format.max_lines must be positive")
check(c.Queue.Size > 0, "queue.size must be positive")
check(c.Queue.History >= 0, "queue.history must not be negative")
img := c.Images
check(img.Timeout > 0, "images.timeout must be positive")
check(img.MaxBytes > 0, "images.max_bytes must be positive")
check(img.MaxPixels > 0, "images.max_pixels must be positive")
check(img.MaxHeight > 0, "images.max_height must be positive")
check(slices.Contains([]string{"debug", "info", "warn", "error"}, c.Log.Level),
"log.level: %q must be one of debug, info, warn, error", c.Log.Level)
check(c.Log.Format == LogFormatText || c.Log.Format == LogFormatJSON,
"log.format: %q must be %q or %q", c.Log.Format, LogFormatText, LogFormatJSON)
return errors.Join(errs...)
}
func validPort(port int) bool {
return port >= 1 && port <= 65535
}
func validIPOrPrefix(s string) bool {
if _, err := netip.ParseAddr(s); err == nil {
return true
}
_, err := netip.ParsePrefix(s)
return err == nil
}