Add the notify and ntfy modules and scoped tokens
Security / Vulnerability check (push) Successful in 41s
Test / Lint and test (push) Successful in 1m57s

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>
This commit is contained in:
57_WolveandClaude Opus 5.5 committed 2026-11-30 13:57:08 -06:00
1 parent fa15cb27b1
commit 1335ed0687
119 files changed
+5626 -468

No files matched your search

+130 -6
View File
@@ -14,6 +14,7 @@ import (
"strconv"
"strings"
"time"
"unicode/utf8"
"github.com/go-viper/mapstructure/v2"
"github.com/pelletier/go-toml/v2"
@@ -45,6 +46,7 @@ type Config struct {
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"`
@@ -127,6 +129,48 @@ type FormatConfig struct {
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.
@@ -203,6 +247,15 @@ func Default() Config {
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,
@@ -240,7 +293,7 @@ func Load(path string) (*Config, error) {
var envSet []string
bound := map[string]bool{PathEnvVar: true}
for _, key := range slices.Sorted(maps.Keys(keys)) {
if keys[key] != setting {
if keys[key] == section {
continue
}
name := envVar(key)
@@ -290,6 +343,7 @@ func Load(path string) (*Config, error) {
viper.DecodeHook(mapstructure.ComposeDecodeHookFunc(
durations(),
stringToList(),
stringToTable(),
refuseFractions(),
stringToNumberOrFlag(),
)),
@@ -363,12 +417,14 @@ func readFile(path string) (map[string]any, error) {
return table, nil
}
// keyKind tells a setting from a section that holds settings.
// 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
@@ -385,13 +441,18 @@ func registerDefaults(v *viper.Viper, prefix string, rv reflect.Value, keys map[
key = prefix + "." + tag
}
field := rv.Field(i)
if field.Kind() == reflect.Struct {
switch field.Kind() {
case reflect.Struct:
keys[key] = section
registerDefaults(v, key, field, keys)
continue
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
}
v.SetDefault(key, field.Interface())
keys[key] = setting
}
}
@@ -428,6 +489,10 @@ func checkKeys(table map[string]any, prefix, lookup string, keys map[string]keyK
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)
@@ -436,6 +501,26 @@ func checkKeys(table map[string]any, prefix, lookup string, keys map[string]keyK
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 {
@@ -546,6 +631,35 @@ func stringToList() mapstructure.DecodeHookFunc {
}
}
// 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
@@ -591,6 +705,16 @@ func (c *Config) Validate() error {
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")
+133 -1
View File
@@ -300,6 +300,66 @@ func TestLoadErrors(t *testing.T) {
body: "\xff\xfe[\x00a\x00p\x00i\x00]\x00",
wantErr: "the file is UTF-16; save it as UTF-8",
},
{
name: "ntfy style",
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n[ntfy.format]\nstyle = \"fancy\"\n",
wantErr: `ntfy.format.style: "fancy" must be one of auto, box, compact`,
},
{
name: "ntfy max lines zero",
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n[ntfy.format]\nmax_lines = 0\n",
wantErr: "ntfy.format.max_lines must be 1-400",
},
{
name: "ntfy max lines too many",
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n[ntfy.format]\nmax_lines = 401\n",
wantErr: "ntfy.format.max_lines must be 1-400",
},
{
name: "ntfy qr",
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n[ntfy.format]\nqr = \"some\"\n",
wantErr: `ntfy.format.qr: "some" must be one of all, first, none`,
},
{
name: "ntfy images not a flag",
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n[ntfy.format]\nimages = \"yes\"\n",
wantErr: "'ntfy.format.images' expected true or false",
},
{
name: "unknown ntfy key",
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n[ntfy]\nserver = \"https://ntfy.sh\"\n",
wantErr: "unknown keys: ntfy.server",
},
{
name: "marker too long",
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n[ntfy.markers]\nbackup = \"[a very long marker]\"\n",
wantErr: `ntfy.markers.backup: "[a very long marker]" is longer than 16 characters`,
},
{
name: "marker that is not a string",
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n[ntfy.markers]\nbackup = 1\n",
wantErr: "ntfy.markers",
},
{
name: "marker table",
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n[ntfy.markers.backup]\nmarker = \"[B]\"\n",
wantErr: "unknown keys: ntfy.markers.backup",
},
{
name: "marker name with a dot",
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n[ntfy.markers]\n\"a.b\" = \"[B]\"\n",
wantErr: `unknown keys: ntfy.markers."a.b"`,
},
{
name: "markers that differ only in case",
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n[ntfy.markers]\nbackup = \"[b]\"\nBackup = \"[B]\"\n",
wantErr: "keys that differ only in case: ntfy.markers.Backup and ntfy.markers.backup",
},
{
name: "markers as a value",
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n[ntfy]\nmarkers = \"backup=[B]\"\n",
wantErr: "unknown keys: ntfy.markers",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
@@ -326,11 +386,74 @@ func TestExampleConfigLoads(t *testing.T) {
if def := config.Default(); cfg.WebServer.RateLimit != def.WebServer.RateLimit ||
cfg.Images.MaxBytes != def.Images.MaxBytes || cfg.Printer.Model != def.Printer.Model ||
cfg.Format.MaxLines != def.Format.MaxLines || cfg.Printer.BoxLineSpacing != def.Printer.BoxLineSpacing ||
cfg.Format.Timezone != def.Format.Timezone || cfg.Format.TimeLayout != def.Format.TimeLayout {
cfg.Format.Timezone != def.Format.Timezone || cfg.Format.TimeLayout != def.Format.TimeLayout ||
cfg.Ntfy.Format != def.Ntfy.Format || len(cfg.Ntfy.Markers) != 0 {
t.Error("example config values drifted from the defaults it documents")
}
}
func TestLoadNtfy(t *testing.T) {
def := config.Default().Ntfy.Format
if def != (config.NtfyFormatConfig{Style: "auto", MaxLines: 40, QR: "all", Images: true, Markdown: true}) {
t.Errorf("defaults %+v", def)
}
cfg, err := config.Load(writeConfig(t, `
[api]
secret = "`+validSecret+`"
[printer]
address = "p"
[ntfy.format]
style = "compact"
max_lines = 400
qr = "first"
images = false
markdown = false
[ntfy.markers]
backup = "[B]"
skull = ""
"+1" = "+1"
`))
if err != nil {
t.Fatal(err)
}
want := config.NtfyFormatConfig{Style: "compact", MaxLines: 400, QR: "first", Images: false, Markdown: false}
if cfg.Ntfy.Format != want {
t.Errorf("format %+v, want %+v", cfg.Ntfy.Format, want)
}
if m := cfg.Ntfy.Markers; len(m) != 3 || m["backup"] != "[B]" || m["skull"] != "" || m["+1"] != "+1" {
t.Errorf("markers %q", m)
}
t.Run("environment", func(t *testing.T) {
t.Setenv("UBERBRINGER_API_SECRET", validSecret)
t.Setenv("UBERBRINGER_PRINTER_ADDRESS", "p")
t.Setenv("UBERBRINGER_NTFY_FORMAT_STYLE", "box")
t.Setenv("UBERBRINGER_NTFY_MARKERS", " Backup = [B] , skull= ")
cfg, err := config.Load("")
if err != nil {
t.Fatal(err)
}
if cfg.Ntfy.Format.Style != "box" {
t.Errorf("style %q", cfg.Ntfy.Format.Style)
}
if m := cfg.Ntfy.Markers; len(m) != 2 || m["backup"] != "[B]" || m["skull"] != "" {
t.Errorf("markers %q", m)
}
})
t.Run("environment wins over the file", func(t *testing.T) {
t.Setenv("UBERBRINGER_NTFY_MARKERS", "tada=\\o/")
cfg, err := config.Load(writeConfig(t, "[api]\nsecret = \""+validSecret+"\"\n[printer]\naddress = \"p\"\n[ntfy.markers]\nbackup = \"[B]\"\n"))
if err != nil {
t.Fatal(err)
}
if m := cfg.Ntfy.Markers; len(m) != 1 || m["tada"] != `\o/` {
t.Errorf("markers %q", m)
}
})
}
func TestLoadEnvironmentOverridesFile(t *testing.T) {
path := writeConfig(t, `
[api]
@@ -485,6 +608,10 @@ func TestLoadEnvironmentErrors(t *testing.T) {
{"trailing comma", "UBERBRINGER_WEBSERVER_TRUSTED_PROXIES", "10.0.0.1,", "a list item is empty"},
{"number for a flag", "UBERBRINGER_SENTRY_DEBUG", "1", "expected true or false"},
{"unknown time zone", "UBERBRINGER_FORMAT_TIMEZONE", "Mars/Olympus", "format.timezone"},
{"marker without a value", "UBERBRINGER_NTFY_MARKERS", "backup", "expected entries name=value separated by commas"},
{"marker without a name", "UBERBRINGER_NTFY_MARKERS", "=[B]", "expected entries name=value separated by commas"},
{"marker given twice", "UBERBRINGER_NTFY_MARKERS", "backup=[B],Backup=[b]", `"backup" is given twice`},
{"ntfy style", "UBERBRINGER_NTFY_FORMAT_QR", "every", "ntfy.format.qr"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
@@ -509,6 +636,7 @@ func TestLoadMissingFile(t *testing.T) {
func TestValue(t *testing.T) {
cfg := config.Default()
cfg.Images.AllowedHosts = []string{"a.lan", "b.lan"}
cfg.Ntfy.Markers = map[string]string{"skull": "", "backup": "[B]"}
tests := []struct {
key, want, wantErr string
}{
@@ -520,6 +648,10 @@ func TestValue(t *testing.T) {
{key: "images.allow_private_networks", want: "false"},
{key: "format.timezone", want: "Local"},
{key: "format.time_layout", want: "02 Jan 15:04"},
{key: "ntfy.format.style", want: "auto"},
{key: "ntfy.format.images", want: "true"},
{key: "ntfy.markers", want: "backup=[B],skull="},
{key: "ntfy.format", wantErr: `"ntfy.format" is a section`},
{key: "printer", wantErr: `"printer" is a section`},
{key: "printer.adress", wantErr: `unknown key "printer.adress"`},
{key: "printer.port.x", wantErr: `unknown key "printer.port.x"`},
+10 -1
View File
@@ -2,14 +2,17 @@ package config
import (
"fmt"
"maps"
"reflect"
"slices"
"strings"
"time"
)
// Value returns the setting at the dotted key, such as "webserver.port", in
// the form a config file or an environment variable gives it: durations such
// as "15s", lists comma-separated. Key names match case-insensitively.
// as "15s", lists comma-separated, and tables as name=value entries, sorted
// and comma-separated. Key names match case-insensitively.
func (c *Config) Value(key string) (string, error) {
v := reflect.ValueOf(*c)
for part := range strings.SplitSeq(key, ".") {
@@ -27,6 +30,12 @@ func (c *Config) Value(key string) (string, error) {
return value.String(), nil
case []string:
return strings.Join(value, ","), nil
case map[string]string:
entries := make([]string, 0, len(value))
for _, name := range slices.Sorted(maps.Keys(value)) {
entries = append(entries, name+"="+value[name])
}
return strings.Join(entries, ","), nil
default:
return fmt.Sprint(value), nil
}