Files
uberbringer/internal/pkg/config/config.go
T
57_WolveandClaude Opus 5.5 1335ed0687
Security / Vulnerability check (push) Successful in 41s
Test / Lint and test (push) Successful in 1m57s
Add the notify and ntfy modules and scoped tokens
Breaking: a job with a raw element prints only with a token issued with
uberbringer token --raw. Every other token, every existing one included,
gets 403 token_scope for it, with the raw elements in details, and keeps
every other route.

The notify module prints a notification card from a title, message,
priority and tags, with topic, click, up to three actions, image,
markdown and time as options; it decodes strictly and refuses a payload
over its length caps. The ntfy module takes one ntfy message as ntfy
sends it, such as the ntfy client's $NTFY_RAW, ignores fields it does
not know, cuts text over the caps, and answers 204 for other events and
binary bodies. Both print every message plain: one message cannot tell
the first of a sequence from a replacement, since a publisher may choose
the sequence ID. internal/pkg/ntfy holds ntfy's message types.

Both print the same card. The priority picks the form: a dark URGENT
rule and a double box, a double box headed HIGH, a single box with the
title in its border, or a rule with no box. Tags print as markers in
front of the title, the rest on a Tags row; links print as QR codes with
their labels; attached PNG, JPEG, GIF and WebP images print after the
card. A line-level markdown subset is laid out without a dependency,
keeping marks inside code spans and URLs, and emoji are removed after a
few typed ones become markers. A card that cannot be laid out prints as
a plain receipt, and the server logs the fault once at ERROR and reports
it to Sentry once. [ntfy.format] and [ntfy.markers] shape the cards; the
markers table is a setting with the user's own keys, also settable as
UBERBRINGER_NTFY_MARKERS=name=value,...

uberbringer token --modules issues a token limited to those modules'
print and preview routes, job status and the module list; each route in
the table says which tokens it takes, and a scope claim that could read
as absent makes the token invalid. image elements take optional, which
also shrinks a too-wide image to the paper; a QR code that could be too
wide for the paper prints with smaller modules; box takes title_bold.
Submit takes a Meta whose source shows in job status and, with a copy
of the request ID, in every worker log line of the job.

The four ntfy cards passed on the TM-T88IV, posted as the client recipe
posts them, and their bytes are pinned in TestPaperReceipts. docs/api.md
describes the modules, the card and the client recipe, with tokens read
from a header file; docs/swagger.json is regenerated.

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

756 lines
25 KiB
Go

// Package config loads and validates the Überbringer daemon configuration
// from a TOML file and UBERBRINGER_* environment variables.
package config
import (
"bytes"
"errors"
"fmt"
"maps"
"net/netip"
"os"
"reflect"
"slices"
"strconv"
"strings"
"time"
"unicode/utf8"
"github.com/go-viper/mapstructure/v2"
"github.com/pelletier/go-toml/v2"
"github.com/spf13/viper"
)
// EnvPrefix starts the environment variables that set config keys: a key
// section.name is read from UBERBRINGER_SECTION_NAME, e.g.
// UBERBRINGER_PRINTER_ADDRESS. An environment variable wins over the file.
const EnvPrefix = "UBERBRINGER"
// 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 `mapstructure:"webserver"`
API APIConfig `mapstructure:"api"`
Printer PrinterConfig `mapstructure:"printer"`
Format FormatConfig `mapstructure:"format"`
Ntfy NtfyConfig `mapstructure:"ntfy"`
Queue QueueConfig `mapstructure:"queue"`
Images ImagesConfig `mapstructure:"images"`
Sentry SentryConfig `mapstructure:"sentry"`
Log LogConfig `mapstructure:"log"`
}
// WebServerConfig configures the HTTP listener.
type WebServerConfig struct {
BindIP string `mapstructure:"bind_ip"`
Port int `mapstructure:"port"`
// RateLimit is the number of API requests one client may make per
// RateWindow.
RateLimit int `mapstructure:"rate_limit"`
RateWindow time.Duration `mapstructure:"rate_window"`
// TrustedProxies lists proxy IPs or CIDR ranges whose ProxyHeader is
// trusted to carry the real client IP.
TrustedProxies []string `mapstructure:"trusted_proxies"`
ProxyHeader string `mapstructure:"proxy_header"`
// BodyLimit is the maximum request body size in bytes.
BodyLimit int `mapstructure:"body_limit"`
ReadTimeout time.Duration `mapstructure:"read_timeout"`
WriteTimeout time.Duration `mapstructure:"write_timeout"`
IdleTimeout time.Duration `mapstructure:"idle_timeout"`
}
// APIConfig configures API authentication.
type APIConfig struct {
// Secret is the HS256 key used to verify bearer tokens.
Secret string `mapstructure:"secret"`
}
// PrinterConfig configures the network receipt printer.
type PrinterConfig struct {
Address string `mapstructure:"address"`
Port int `mapstructure:"port"`
// Model selects a printer profile, e.g. "tm-t88" or "generic-58mm".
Model string `mapstructure:"model"`
// CodePage is the character table text is transcoded to, e.g. "cp437".
CodePage string `mapstructure:"codepage"`
// PaperWidth overrides the profile's printable width in dots. Zero keeps
// the profile default.
PaperWidth int `mapstructure:"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 `mapstructure:"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 `mapstructure:"box_line_spacing"`
DialTimeout time.Duration `mapstructure:"dial_timeout"`
WriteTimeout time.Duration `mapstructure:"write_timeout"`
// Retries is how many times a failed send is retried before the job is
// marked failed.
Retries int `mapstructure:"retries"`
RetryDelay time.Duration `mapstructure:"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 `mapstructure:"max_lines"`
// Timezone is the zone the times modules print are in: an IANA name
// such as "Europe/London", "UTC", or "Local" for the host's zone.
Timezone string `mapstructure:"timezone"`
// TimeLayout is the Go time layout those times are printed in.
TimeLayout string `mapstructure:"time_layout"`
}
// Values of NtfyFormatConfig's settings.
var (
NtfyStyles = []string{"auto", "box", "compact"}
NtfyQRModes = []string{"all", "first", "none"}
)
// Limits of the ntfy settings: the largest ntfy.format.max_lines, and the
// most characters in a marker.
const (
MaxNtfyLines = 400
MaxMarker = 16
)
// NtfyConfig configures how notifications print, from the notify and ntfy
// modules.
type NtfyConfig struct {
Format NtfyFormatConfig `mapstructure:"format"`
// Markers override the markers printed for tags, by tag: an empty
// marker hides the tag.
Markers map[string]string `mapstructure:"markers"`
}
// NtfyFormatConfig configures the layout of a notification.
type NtfyFormatConfig struct {
// Style is auto, which picks the form from the priority, box or
// compact.
Style string `mapstructure:"style"`
// MaxLines is how many lines of a message print, as written.
MaxLines int `mapstructure:"max_lines"`
// QR is all, first or none: which links print as QR codes.
QR string `mapstructure:"qr"`
// Images prints attached images.
Images bool `mapstructure:"images"`
// Markdown lays out markdown messages.
Markdown bool `mapstructure:"markdown"`
}
// QueueConfig configures the print queue.
type QueueConfig struct {
// Size is the number of jobs that may wait to be printed.
Size int `mapstructure:"size"`
// History is the number of finished jobs whose status is kept.
History int `mapstructure:"history"`
}
// ImagesConfig configures image elements.
type ImagesConfig struct {
Timeout time.Duration `mapstructure:"timeout"`
MaxBytes int64 `mapstructure:"max_bytes"`
// MaxPixels caps the decoded image size to guard against decompression
// bombs.
MaxPixels int `mapstructure:"max_pixels"`
// MaxHeight caps the printed image height in dots after scaling.
MaxHeight int `mapstructure:"max_height"`
// AllowPrivateNetworks permits fetching from loopback, private and
// link-local addresses.
AllowPrivateNetworks bool `mapstructure:"allow_private_networks"`
// AllowedHosts, when non-empty, restricts fetching to these hosts. Listed
// hosts may resolve to private addresses.
AllowedHosts []string `mapstructure:"allowed_hosts"`
}
// SentryConfig configures error reporting.
type SentryConfig struct {
DSN string `mapstructure:"dsn"`
Environment string `mapstructure:"environment"`
Debug bool `mapstructure:"debug"`
}
// LogConfig configures structured logging.
type LogConfig struct {
Level string `mapstructure:"level"`
Format string `mapstructure:"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,
Timezone: "Local",
TimeLayout: "02 Jan 15:04",
},
Ntfy: NtfyConfig{
Format: NtfyFormatConfig{
Style: "auto",
MaxLines: 40,
QR: "all",
Images: true,
Markdown: true,
},
},
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 builds the configuration from [Default], the TOML file at path and
// UBERBRINGER_* environment variables, in rising order of precedence, and
// validates the result. An empty path reads no file, for configuration by
// environment alone. Keys in the file that Config does not have are 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) {
v := viper.New()
keys := make(map[string]keyKind)
registerDefaults(v, "", reflect.ValueOf(Default()), keys)
// Each setting is bound to its own variable. Viper's automatic lookup
// would also read a variable named after a section, such as
// UBERBRINGER_PRINTER, and let it hide every setting in that section.
var envSet []string
bound := map[string]bool{PathEnvVar: true}
for _, key := range slices.Sorted(maps.Keys(keys)) {
if keys[key] == section {
continue
}
name := envVar(key)
bound[name] = true
if err := v.BindEnv(key, name); err != nil {
return nil, fmt.Errorf("binding %s: %w", name, err)
}
// Viper treats an empty variable as unset. One that holds only
// spaces is refused: for a list it would clear the file's list.
value := os.Getenv(name)
if value != "" && strings.TrimSpace(value) == "" {
return nil, fmt.Errorf("config: %s holds only spaces; unset it or give it a value", name)
}
if value != "" {
envSet = append(envSet, name)
}
}
if path != "" {
table, err := readFile(path)
if err != nil {
return nil, err
}
unknown, clashes := checkKeys(table, "", "", keys)
if len(clashes) > 0 {
slices.Sort(clashes)
return nil, fmt.Errorf("config %s: keys that differ only in case: %s", path, strings.Join(clashes, "; "))
}
if len(unknown) > 0 {
slices.Sort(unknown)
return nil, fmt.Errorf("config %s: unknown keys: %s", path, strings.Join(unknown, ", "))
}
if err := v.MergeConfigMap(table); err != nil {
return nil, fmt.Errorf("config %s: %w", path, err)
}
}
// The names of the variables that were set, never their values, so a
// bad value can be traced to the file or the environment.
source := strings.Join(slices.Concat(slices.DeleteFunc([]string{path}, isEmpty), envSet), ", ")
if source == "" {
source = "(no file and no " + EnvPrefix + "_* settings)"
}
var cfg Config
err := v.Unmarshal(&cfg,
viper.DecodeHook(mapstructure.ComposeDecodeHookFunc(
durations(),
stringToList(),
stringToTable(),
refuseFractions(),
stringToNumberOrFlag(),
)),
// Values are taken as written, apart from the strings that hooks
// above parse: environment variables are strings.
func(dc *mapstructure.DecoderConfig) { dc.WeaklyTypedInput = false },
)
if err != nil {
return nil, fmt.Errorf("config %s: %w%s", source, err, unusedVariables(bound))
}
if cfg.Sentry.DSN == "" {
cfg.Sentry.DSN = os.Getenv("SENTRY_DSN")
}
if err := cfg.Validate(); err != nil {
return nil, fmt.Errorf("config %s: %w%s", source, err, unusedVariables(bound))
}
return &cfg, nil
}
// PathEnvVar names the config file for the command line's --config. Load
// does not read it, but does not count it as a misspelt setting either.
const PathEnvVar = EnvPrefix + "_CONFIG"
// envVar returns the environment variable that sets the dotted config key,
// e.g. UBERBRINGER_PRINTER_ADDRESS for printer.address.
func envVar(key string) string {
return EnvPrefix + "_" + strings.ToUpper(strings.ReplaceAll(key, ".", "_"))
}
// unusedVariables returns a note naming the set UBERBRINGER_* variables
// that match no setting, which are likely misspelt, or "" when there are
// none. Only names are given, never values.
func unusedVariables(bound map[string]bool) string {
var unused []string
for _, entry := range os.Environ() {
name, value, _ := strings.Cut(entry, "=")
if strings.HasPrefix(name, EnvPrefix+"_") && value != "" && !bound[name] {
unused = append(unused, name)
}
}
if len(unused) == 0 {
return ""
}
slices.Sort(unused)
return "\n" + EnvPrefix + "_* variables that set nothing: " + strings.Join(unused, ", ")
}
func isEmpty(s string) bool { return s == "" }
// readFile parses the TOML file at path into a table.
func readFile(path string) (map[string]any, error) {
data, err := os.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("reading config %s: %w", path, err)
}
if bytes.HasPrefix(data, []byte("\xff\xfe")) || bytes.HasPrefix(data, []byte("\xfe\xff")) {
return nil, fmt.Errorf("config %s: the file is UTF-16; save it as UTF-8", path)
}
// A byte order mark, which some Windows editors write at the start of a
// UTF-8 file, is not part of the TOML.
data = bytes.TrimPrefix(data, []byte("\xef\xbb\xbf"))
var table map[string]any
if err := toml.Unmarshal(data, &table); err != nil {
var decodeErr *toml.DecodeError
if errors.As(err, &decodeErr) {
row, col := decodeErr.Position()
return nil, fmt.Errorf("config %s: line %d, column %d: %w", path, row, col, err)
}
return nil, fmt.Errorf("config %s: %w", path, err)
}
return table, nil
}
// keyKind tells a setting from a section that holds settings, and from a
// table setting, whose keys are the user's own.
type keyKind int
const (
setting keyKind = iota + 1
section
tableSetting
)
// registerDefaults sets every field of the config struct rv as a Viper
// default under its dotted mapstructure key, and records each key in keys.
func registerDefaults(v *viper.Viper, prefix string, rv reflect.Value, keys map[string]keyKind) {
rt := rv.Type()
for i := range rt.NumField() {
tag := rt.Field(i).Tag.Get("mapstructure")
if tag == "" {
continue
}
key := tag
if prefix != "" {
key = prefix + "." + tag
}
field := rv.Field(i)
switch field.Kind() {
case reflect.Struct:
keys[key] = section
registerDefaults(v, key, field, keys)
case reflect.Map:
// A default table would merge with the file's instead of
// giving way to it; the table settings default to empty.
keys[key] = tableSetting
default:
v.SetDefault(key, field.Interface())
keys[key] = setting
}
}
}
// checkKeys walks the file's table under prefix. It returns the keys Config
// does not have (unknown names, empty tables included, a setting written as
// a table, a section written as a value, and a quoted name with a dot, which
// is one key rather than a path) and the names in one table that differ only
// in case. Names match case-insensitively, as Viper reads them, and Viper
// would keep only one of two such names. lookup is the lowercase dotted path
// of prefix, which names it as written.
func checkKeys(table map[string]any, prefix, lookup string, keys map[string]keyKind) (unknown, clashes []string) {
names := slices.Sorted(maps.Keys(table))
seen := make(map[string]string, len(names))
for _, name := range names {
path := displayKey(name)
key := strings.ToLower(name)
if prefix != "" {
path = prefix + "." + path
key = lookup + "." + key
}
if other, ok := seen[key]; ok {
clashes = append(clashes, other+" and "+path)
continue
}
seen[key] = path
sub, isTable := table[name].(map[string]any)
kind := keys[key]
if strings.Contains(name, ".") {
kind = 0
}
switch {
case isTable && kind == section:
u, c := checkKeys(sub, path, key, keys)
unknown = append(unknown, u...)
clashes = append(clashes, c...)
case isTable && kind == tableSetting:
u, c := checkTable(sub, path)
unknown = append(unknown, u...)
clashes = append(clashes, c...)
case !isTable && kind == setting:
default:
unknown = append(unknown, path)
}
}
return unknown, clashes
}
// checkTable checks the entries of a table setting at path, whose names are
// the user's own. Like checkKeys, it returns as unknown a name with a dot
// and an entry that is itself a table, and the names that differ only in
// case.
func checkTable(entries map[string]any, path string) (unknown, clashes []string) {
seen := make(map[string]string, len(entries))
for _, name := range slices.Sorted(maps.Keys(entries)) {
entry := path + "." + displayKey(name)
if other, ok := seen[strings.ToLower(name)]; ok {
clashes = append(clashes, other+" and "+entry)
continue
}
seen[strings.ToLower(name)] = entry
if _, isTable := entries[name].(map[string]any); isTable || strings.Contains(name, ".") {
unknown = append(unknown, entry)
}
}
return unknown, clashes
}
// displayKey quotes a key name that TOML would need quoted, so that spaces,
// dots and empty names show in messages.
func displayKey(name string) string {
if name != "" && strings.Trim(name, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-") == "" {
return name
}
return strconv.Quote(name)
}
// durations decodes a duration from a string such as "1m30s". A bare number
// is refused, since the decoder would read it as nanoseconds.
func durations() mapstructure.DecodeHookFunc {
durationType := reflect.TypeFor[time.Duration]()
return func(from, to reflect.Type, data any) (any, error) {
if to != durationType || from == durationType {
return data, nil
}
s, ok := data.(string)
if !ok {
return nil, errors.New(`expected a duration as a string, such as "5s"`)
}
d, err := time.ParseDuration(strings.TrimSpace(s))
if err != nil {
return nil, errors.New(`expected a duration such as "5s" or "1m30s"`)
}
return d, nil
}
}
// refuseFractions refuses a number with a fraction for an integer setting,
// which the decoder would otherwise truncate.
func refuseFractions() mapstructure.DecodeHookFunc {
return func(from, to reflect.Type, data any) (any, error) {
if from.Kind() != reflect.Float32 && from.Kind() != reflect.Float64 {
return data, nil
}
switch to.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return nil, errors.New("expected a whole number")
}
return data, nil
}
}
// stringToNumberOrFlag parses a string, such as an environment variable, for
// a number or flag setting: decimal digits for a number, true or false for a
// flag. Spaces around the value are ignored.
func stringToNumberOrFlag() mapstructure.DecodeHookFunc {
return func(from, to reflect.Type, data any) (any, error) {
if from.Kind() != reflect.String {
return data, nil
}
s := strings.TrimSpace(data.(string))
switch to.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
n, err := strconv.ParseInt(s, 10, to.Bits())
if err != nil {
return nil, numberError(err)
}
return reflect.ValueOf(n).Convert(to).Interface(), nil
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
n, err := strconv.ParseUint(s, 10, to.Bits())
if err != nil {
return nil, numberError(err)
}
return reflect.ValueOf(n).Convert(to).Interface(), nil
case reflect.Bool:
switch s {
case "true":
return true, nil
case "false":
return false, nil
}
return nil, errors.New("expected true or false")
}
return data, nil
}
}
func numberError(err error) error {
if errors.Is(err, strconv.ErrRange) {
return errors.New("number out of range")
}
return errors.New("expected a whole number in decimal digits")
}
// stringToList splits a string, such as an environment variable, into a list
// at commas and trims the spaces around each item, so "a, b" and "a,b" give
// the same list. An empty item, from a doubled or trailing comma, is refused.
func stringToList() mapstructure.DecodeHookFunc {
return func(from, to reflect.Type, data any) (any, error) {
if from.Kind() != reflect.String || to.Kind() != reflect.Slice {
return data, nil
}
raw := strings.TrimSpace(data.(string))
if raw == "" {
return []string{}, nil
}
items := strings.Split(raw, ",")
for i := range items {
items[i] = strings.TrimSpace(items[i])
if items[i] == "" {
return nil, errors.New("a list item is empty; check for a doubled or trailing comma")
}
}
return items, nil
}
}
// stringToTable reads a table setting from a string, such as an
// environment variable: entries name=value, separated by commas, with the
// spaces around each trimmed, so "a=[A], b=" sets a to "[A]" and b to "". A
// value cannot hold a comma.
func stringToTable() mapstructure.DecodeHookFunc {
return func(from, to reflect.Type, data any) (any, error) {
if from.Kind() != reflect.String || to.Kind() != reflect.Map {
return data, nil
}
entries := make(map[string]string)
raw := strings.TrimSpace(data.(string))
if raw == "" {
return entries, nil
}
for item := range strings.SplitSeq(raw, ",") {
name, value, ok := strings.Cut(item, "=")
name = strings.ToLower(strings.TrimSpace(name))
if !ok || name == "" {
return nil, errors.New("expected entries name=value separated by commas, e.g. backup=[B],skull=")
}
if _, dup := entries[name]; dup {
return nil, fmt.Errorf("%q is given twice", name)
}
entries[name] = strings.TrimSpace(value)
}
return entries, 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(strings.TrimSpace(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")
if c.Format.Timezone == "" {
errs = append(errs, errors.New(`format.timezone is required: an IANA name such as "Europe/London", "UTC" or "Local"`))
} else if _, err := time.LoadLocation(c.Format.Timezone); err != nil {
errs = append(errs, fmt.Errorf(`format.timezone: %q is not a known time zone; use an IANA name such as "Europe/London", "UTC" or "Local"`, c.Format.Timezone))
}
check(showsTime(c.Format.TimeLayout),
`format.time_layout: %q shows no date or time; write it in Go's layout, such as "02 Jan 15:04"`, c.Format.TimeLayout)
nf := c.Ntfy.Format
check(slices.Contains(NtfyStyles, nf.Style), "ntfy.format.style: %q must be one of %s", nf.Style, strings.Join(NtfyStyles, ", "))
check(nf.MaxLines >= 1 && nf.MaxLines <= MaxNtfyLines, "ntfy.format.max_lines must be 1-%d", MaxNtfyLines)
check(slices.Contains(NtfyQRModes, nf.QR), "ntfy.format.qr: %q must be one of %s", nf.QR, strings.Join(NtfyQRModes, ", "))
for _, tag := range slices.Sorted(maps.Keys(c.Ntfy.Markers)) {
check(strings.TrimSpace(tag) != "", "ntfy.markers: a tag name is empty")
check(utf8.RuneCountInString(c.Ntfy.Markers[tag]) <= MaxMarker,
"ntfy.markers.%s: %q is longer than %d characters", tag, c.Ntfy.Markers[tag], MaxMarker)
}
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...)
}
// showsTime reports whether layout prints something of the time it
// formats: two times that differ in every field format differently. A
// layout with none of Go's reference values, such as "HH:MM", prints
// itself.
func showsTime(layout string) bool {
a := time.Date(2001, 2, 3, 4, 5, 6, 0, time.UTC)
b := time.Date(2012, 11, 22, 16, 47, 58, 0, time.FixedZone("X", 3600))
return a.Format(layout) != b.Format(layout)
}
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
}