Files
uberbringer/internal/pkg/config/config.go
T
57_WolveandClaude Opus 5.5 afcf96431f
CI / Lint, test and scan (push) Successful in 1m42s
Fix /healthz false alarms; default to 512-dot TM-T88 profile
Hardware testing on the real printer (an Epson TM-T88IV, not a TM-T20II)
turned up two problems, and an adversarial review found three more.

Printer status
- Treat DLE EOT 2 bits (cover open, paper-end stop) as offline causes:
  Status.Normalized clears them while DLE EOT 1 reports the printer
  online. The TM-T88IV reported online + cover open while printing and
  cutting a long receipt, which made /healthz return 503.
- PaperOut now comes only from the DLE EOT 4 roll-paper sensor; the
  paper-end stop is reported separately as PaperEndStop.
- /healthz re-reads a printer that looks not ready after 750 ms and only
  reports a problem that is still there.
- A status read cut short by the caller's deadline now returns
  context.DeadlineExceeded (503 "timeout") instead of
  ErrStatusUnsupported, which /healthz reported as 200 "unknown" and
  could hide an offline printer.

Printer profiles
- Default model is now tm-t88 (512 dots, 42/56 columns). A profile wider
  than the printer makes it break words mid-line; a narrower one only
  shortens lines.
- Add tm-m50 (TM-m50/II) and document TM-T88IV-VII, 58 mm paper on
  180-dpi printers, and that the TM-T88VII does not report paper near-end
  through real-time status.
- README example banner shortened to 42 characters to fit the default.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 21:51:12 -06:00

274 lines
8.5 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
// 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"`
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"`
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"`
}
// 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,
},
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.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.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
}