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

+803
View File
@@ -0,0 +1,803 @@
package modules_test
import (
"context"
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"testing"
"time"
"unicode/utf8"
"uberbringer/internal/pkg/escpos"
"uberbringer/internal/pkg/modules"
"uberbringer/internal/pkg/ntfy"
"uberbringer/internal/pkg/receipt"
)
// TestNtfyBuildsThePaperJobs checks that the ntfy module still builds the
// jobs whose printed result was checked on the TM-T88IV, and whose bytes
// the receipt package pins: the four messages in testdata/paper, built on
// a host at UTC-6 with the default card options.
func TestNtfyBuildsThePaperJobs(t *testing.T) {
for _, name := range []string{"high", "urgent", "default", "min"} {
t.Run(name, func(t *testing.T) {
body, err := os.ReadFile(filepath.Join("testdata", "paper", "ntfy-"+name+".json"))
if err != nil {
t.Fatal(err)
}
env := modules.Env{
Now: time.Unix(1796063393, 0),
Location: time.FixedZone("UTC-6", -6*60*60),
TimeLayout: "02 Jan 15:04",
}
job, err := modules.Ntfy().Build(context.Background(), body, env)
if err != nil {
t.Fatal(err)
}
data, err := os.ReadFile(filepath.Join("..", "receipt", "testdata", "paper", "ntfy-"+name+".json"))
if err != nil {
t.Fatal(err)
}
paper, err := receipt.DecodeJob(data)
if err != nil {
t.Fatal(err)
}
got, err := json.Marshal(job)
if err != nil {
t.Fatal(err)
}
want, err := json.Marshal(paper)
if err != nil {
t.Fatal(err)
}
if string(got) != string(want) {
t.Errorf("the module builds\n%s\nbut the job checked on paper is\n%s", got, want)
}
})
}
}
// ntfyEnv is the time the example ntfy messages were sent, 29 Nov 2025
// 21:04:05 UTC, in Europe/London, which is on GMT then.
func ntfyEnv(t *testing.T) modules.Env {
t.Helper()
env := fixedEnv(t)
env.Now = time.Unix(1764450245, 0)
return env
}
// checkGolden compares got with the file at path, or rewrites the file
// with -update.
func checkGolden(t *testing.T, path, got string) {
t.Helper()
if *update {
if err := os.WriteFile(path, []byte(got), 0o644); err != nil {
t.Fatal(err)
}
return
}
want, err := os.ReadFile(path)
if err != nil {
t.Fatalf("%v (run go test -run %s -update)", err, strings.Split(t.Name(), "/")[0])
}
if got != string(want) {
t.Errorf("preview differs from %s:\ngot:\n%s\nwant:\n%s", path, got, want)
}
}
// buildGoldens builds each payload in testdata/DIR/*.json with module and
// compares its preview with NAME.txt.
func buildGoldens(t *testing.T, dir string, module modules.Module, env modules.Env) {
t.Helper()
paths, err := filepath.Glob(filepath.Join("testdata", dir, "*.json"))
if err != nil {
t.Fatal(err)
}
if len(paths) == 0 {
t.Fatalf("no payloads in testdata/%s", dir)
}
for _, path := range paths {
name := strings.TrimSuffix(filepath.Base(path), ".json")
t.Run(name, func(t *testing.T) {
body, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
job, err := module.Build(context.Background(), body, env)
if err != nil {
t.Fatalf("Build: %v", err)
}
if err := job.Validate(); err != nil {
t.Fatalf("built an invalid job: %v", err)
}
checkGolden(t, filepath.Join("testdata", dir, name+".txt"), previewText(t, job))
})
}
}
// TestNtfyGoldens previews each testdata/ntfy/*.json message at the time
// it was sent. Run with -update to rewrite the .txt files, then review the
// diff.
func TestNtfyGoldens(t *testing.T) {
buildGoldens(t, "ntfy", modules.Ntfy(), ntfyEnv(t))
}
// TestNotifyGoldens previews each testdata/notify/*.json payload.
func TestNotifyGoldens(t *testing.T) {
buildGoldens(t, "notify", modules.Notify(), fixedEnv(t))
}
// TestCardStyles previews the example message at every priority in every
// style, in testdata/card/p<priority>-<style>.txt.
func TestCardStyles(t *testing.T) {
for _, style := range []string{modules.StyleAuto, modules.StyleBox, modules.StyleCompact} {
for priority := 1; priority <= 5; priority++ {
name := fmt.Sprintf("p%d-%s", priority, style)
t.Run(name, func(t *testing.T) {
n := modules.Notice{
Topic: "alerts",
Title: "Disk almost full",
Message: "/var is at 94% on nas01",
Priority: priority,
Tags: []string{"warning", "nas01"},
Links: []modules.Link{{Label: "Open dashboard", URL: "https://grafana.lan/d/disk"}},
}
job, _ := modules.Card(n, modules.CardOptions{Style: style}, fixedEnv(t))
checkGolden(t, filepath.Join("testdata", "card", name+".txt"), previewText(t, job))
})
}
}
}
// TestNtfyPriorities pins the card of an example message at priorities 5,
// 4, 3 and 1: the four forms.
func TestNtfyPriorities(t *testing.T) {
tests := []struct {
file string
want []string
}{
{"priority-high", []string{
"╔═ HIGH ═════════════════════════════════╗",
"║ [!] Disk almost full ║",
"╟────────────────────────────────────────╢",
"║ /var is at 94% on nas01 ║",
"║ ║",
"║ Tags: nas01 ║",
"╚═══════════════ alerts · 29 Nov 21:04 ══╝",
"",
"[qr: https://grafana.lan/d/disk]",
" Open dashboard",
"",
"[image 384 dots: sPs71M8A2Tq9.png]",
" - - - - - - - partial cut - - - - - - - -",
}},
{"priority-urgent", []string{
"▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ URGENT ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓",
"╔════════════════════════════════════════╗",
"║ (!) Backup FAILED on nas01 ║",
"╠════════════════════════════════════════╣",
"║ Job nightly-offsite exited with code 2 ║",
"║ after 3h12m. Last good run: 2 days ║",
"║ ago. ║",
"╚══════════════ backups · 29 Nov 21:04 ══╝",
"▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓",
" - - - - - - - partial cut - - - - - - - -",
}},
{"priority-default", []string{
"┌─ [√] Nightly backup ───────────────────┐",
"│ restic: 2.1 GB added in 14m 02s, 0 │",
"│ errors. │",
"│ │",
"│ Tags: restic │",
"└────────────── backups · 29 Nov 03:12 ──┘",
" - - - - - - - partial cut - - - - - - - -",
}},
{"priority-min", []string{
"── backups · 29 Nov 03:12 ────────────────",
"Prune finished",
"41 snapshots kept, 3 removed.",
" - - - - - - - partial cut - - - - - - - -",
}},
}
for _, tt := range tests {
t.Run(tt.file, func(t *testing.T) {
body, err := os.ReadFile(filepath.Join("testdata", "ntfy", tt.file+".json"))
if err != nil {
t.Fatal(err)
}
job, err := modules.Ntfy().Build(context.Background(), body, ntfyEnv(t))
if err != nil {
t.Fatal(err)
}
want := strings.Join(tt.want, "\n") + "\n"
if got := previewText(t, job); got != want {
t.Errorf("preview:\n%s\nwant:\n%s", got, want)
}
})
}
}
// TestCardTitleStyles checks how each form styles the title: the title row of
// a high card is bold, of an urgent card bold and inverted, and the title
// in a default card's border is bold, as is the title line of a low card.
func TestCardTitleStyles(t *testing.T) {
tests := []struct {
priority int
check func(job receipt.Job) bool
}{
{5, func(j receipt.Job) bool { c := j.Elements[1].Children[0]; return c.Bold && c.Invert }},
{4, func(j receipt.Job) bool { c := j.Elements[0].Children[0]; return c.Bold && !c.Invert }},
{3, func(j receipt.Job) bool { return j.Elements[0].TitleBold }},
{1, func(j receipt.Job) bool { return j.Elements[1].Bold }},
}
for _, tt := range tests {
job, _ := modules.Card(modules.Notice{Title: "T", Message: "m", Priority: tt.priority}, modules.CardOptions{}, fixedEnv(t))
if !tt.check(job) {
t.Errorf("priority %d: title styled wrongly: %+v", tt.priority, job.Elements)
}
}
}
func TestMarkers(t *testing.T) {
tests := []struct {
name string
overrides map[string]string
tags []string
head string // the title row of a high card
tagRow string // "" for none
}{
{"built in", nil, []string{"warning", "nas01"}, "[!] T", "Tags: nas01"},
{"two markers at most", nil, []string{"warning", "fire", "tada"}, "[!] (!) T", "Tags: tada"},
{"a marker once", nil, []string{"fire", "boom", "rotating_light"}, "(!) T", ""},
{"case", nil, []string{"Warning"}, "[!] T", ""},
{"override", map[string]string{"backup": "[B]", "warning": "/!\\"}, []string{"backup", "warning"}, "[B] /!\\ T", ""},
{"hidden", map[string]string{"nas01": ""}, []string{"warning", "nas01"}, "[!] T", ""},
{"hide a built-in", map[string]string{"warning": ""}, []string{"warning"}, "T", ""},
{"unmapped", nil, []string{"backup", "nas01", " "}, "T", "Tags: backup, nas01"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
o := modules.CardOptions{Markers: modules.NewMarkers(tt.overrides)}
job, _ := modules.Card(modules.Notice{Title: "T", Message: "m", Priority: 4, Tags: tt.tags}, o, fixedEnv(t))
children := job.Elements[0].Children
if got := children[0].Text; got != tt.head {
t.Errorf("title row %q, want %q", got, tt.head)
}
last := children[len(children)-1]
gotRow := ""
if strings.HasPrefix(last.Text, "Tags: ") {
gotRow = last.Text
}
if gotRow != tt.tagRow {
t.Errorf("tag row %q, want %q", gotRow, tt.tagRow)
}
})
}
}
func TestTypedEmoji(t *testing.T) {
n := modules.Notice{Title: "⚠\uFE0F Disk ✅ done ❌ 🚨 👍", Message: "🎉 Party\nBackup 🎉 done\nDone 🎉\n👨\u200D👩\u200D👧 family 🇬🇧 flag 1\uFE0F\u20E3 ■ → ✓", Priority: 4}
job, _ := modules.Card(n, modules.CardOptions{}, fixedEnv(t))
children := job.Elements[0].Children
if got, want := children[0].Text, "[!] Disk [√] done [x] (!) (+1)"; got != want {
t.Errorf("title %q, want %q", got, want)
}
if got, want := children[2].Text, "Party\nBackup done\nDone\nfamily flag 1 ■ → ✓"; got != want {
t.Errorf("message %q, want %q", got, want)
}
hidden := modules.CardOptions{Markers: modules.NewMarkers(map[string]string{"warning": ""})}
job, _ = modules.Card(modules.Notice{Title: "⚠\uFE0F Disk", Message: "m", Priority: 4}, hidden, fixedEnv(t))
if got := job.Elements[0].Children[0].Text; got != "Disk" {
t.Errorf("hidden marker: title %q, want %q", got, "Disk")
}
}
func TestCardLinks(t *testing.T) {
links := []modules.Link{
{URL: "https://a.example.com/x"},
{Label: "A", URL: "https://a.example.com/x"},
{Label: "Mail", URL: "mailto:someone@example.com"},
{Label: "B", URL: "https://b.example.com/"},
{Label: "C", URL: "http://c.example.com/c"},
{Label: "D", URL: "https://d.example.com/d"},
}
n := modules.Notice{Title: "T", Message: "m", Priority: 3, Links: links}
tests := []struct {
qr string
want []string
}{
{"all", []string{
"", "[qr: https://a.example.com/x]", " A",
"", "[qr: https://b.example.com/]", " B",
"", "[qr: http://c.example.com/c]", " C",
}},
{"first", []string{
"", "[qr: https://a.example.com/x]", " A",
"", "» B", "https://b.example.com/", "» C", "http://c.example.com/c",
}},
{"none", []string{
"", "» A", "https://a.example.com/x", "» B", "https://b.example.com/", "» C", "http://c.example.com/c",
}},
}
for _, tt := range tests {
t.Run(tt.qr, func(t *testing.T) {
job, _ := modules.Card(n, modules.CardOptions{QR: tt.qr}, fixedEnv(t))
lines := strings.Split(previewText(t, job), "\n")
// The card is a box of three lines; the cut and a final empty
// string follow the links.
got := lines[3 : len(lines)-2]
if strings.Join(got, "\n") != strings.Join(tt.want, "\n") {
t.Errorf("links:\n%s\nwant:\n%s", strings.Join(got, "\n"), strings.Join(tt.want, "\n"))
}
})
}
t.Run("caption without a label", func(t *testing.T) {
job, _ := modules.Card(modules.Notice{Message: "m", Links: []modules.Link{{URL: "https://grafana.lan/d/disk/?from=now"}}},
modules.CardOptions{}, fixedEnv(t))
last := job.Elements[len(job.Elements)-1]
if last.Text != "grafana.lan/d/disk" || last.Font != "b" || last.Align != "center" {
t.Errorf("caption %+v", last)
}
})
t.Run("a long link prints as text", func(t *testing.T) {
long := "https://example.com/" + strings.Repeat("x", 600)
job, _ := modules.Card(modules.Notice{Message: "m", Links: []modules.Link{{URL: long}}}, modules.CardOptions{}, fixedEnv(t))
for _, el := range job.Elements {
if el.Type == receipt.TypeQR {
t.Fatal("a 620-byte link printed as a QR code")
}
}
})
}
// TestNtfyActionsNeverPrint checks that nothing of an http, broadcast or
// copy action reaches the receipt: their URLs, headers, bodies and values
// can hold secrets.
func TestNtfyActionsNeverPrint(t *testing.T) {
body, err := os.ReadFile(filepath.Join("testdata", "ntfy", "actions-private.json"))
if err != nil {
t.Fatal(err)
}
job, err := modules.Ntfy().Build(context.Background(), body, ntfyEnv(t))
if err != nil {
t.Fatal(err)
}
encoded, err := json.Marshal(job)
if err != nil {
t.Fatal(err)
}
preview := previewText(t, job)
for _, secret := range []string{"SECRET", "hooks.example.com", "Close door", "Tasker", "Copy code"} {
if strings.Contains(preview, secret) || strings.Contains(string(encoded), secret) {
t.Errorf("%q from an action that is not a view action reached the receipt", secret)
}
}
if !strings.Contains(preview, "[qr: https://cam.example.com/garage]") {
t.Errorf("the view action did not print:\n%s", preview)
}
}
func TestCardBodyCap(t *testing.T) {
lines := make([]string, 45)
for i := range lines {
lines[i] = fmt.Sprint("line ", i+1)
}
tests := []struct {
maxLines int
message string
last string
}{
{0, strings.Join(lines, "\n"), "... 5 more lines"},
{44, strings.Join(lines, "\n"), "... 1 more line"},
{45, strings.Join(lines, "\n"), "line 45"},
{2, "a\nb\n\n\n", "b"},
}
for _, tt := range tests {
job, _ := modules.Card(modules.Notice{Message: tt.message, Priority: 3}, modules.CardOptions{MaxLines: tt.maxLines}, fixedEnv(t))
children := job.Elements[0].Children
text := children[len(children)-1].Text
rows := strings.Split(text, "\n")
if got := rows[len(rows)-1]; got != tt.last {
t.Errorf("max_lines %d: last line %q, want %q", tt.maxLines, got, tt.last)
}
}
}
func TestCardAttachments(t *testing.T) {
env := ntfyEnv(t)
image := &modules.File{Name: "graph.png", Type: "image/png", Size: 33848, URL: "https://ntfy.example.com/file/g.png"}
tests := []struct {
name string
n modules.Notice
o modules.CardOptions
image string
fileValue string
}{
{"image", modules.Notice{File: image}, modules.CardOptions{}, image.URL, ""},
{"images off", modules.Notice{File: image}, modules.CardOptions{NoImages: true}, "", "graph.png (33 KB)"},
{"expired", modules.Notice{File: &modules.File{Name: "a.png", Type: "image/png", URL: image.URL, Expires: env.Now}},
modules.CardOptions{}, "", "a.png"},
{"not yet expired", modules.Notice{File: &modules.File{Name: "a.png", Type: "image/png", URL: image.URL, Expires: env.Now.Add(time.Second)}},
modules.CardOptions{}, image.URL, ""},
{"no type, image name", modules.Notice{File: &modules.File{Name: "door.JPG", URL: "https://x.example.com/f/abc"}},
modules.CardOptions{}, "https://x.example.com/f/abc", ""},
{"no type, image URL", modules.Notice{File: &modules.File{Name: "door", URL: "https://x.example.com/f/abc.webp"}},
modules.CardOptions{}, "https://x.example.com/f/abc.webp", ""},
{"an image the printer cannot decode", modules.Notice{File: &modules.File{Name: "logo.svg", Type: "image/svg+xml", Size: 2048, URL: "https://x.example.com/logo.svg"}},
modules.CardOptions{}, "", "logo.svg (2 KB)"},
{"another file", modules.Notice{File: &modules.File{Name: "report.pdf", Type: "application/pdf", Size: 1468006, URL: "https://x.example.com/r.pdf"}},
modules.CardOptions{}, "", "report.pdf (1.4 MB)"},
{"a small file", modules.Notice{File: &modules.File{Name: "a.txt", Size: 980, URL: "https://x.example.com/a.txt"}},
modules.CardOptions{}, "", "a.txt (980 B)"},
{"notify image", modules.Notice{Image: "https://x.example.com/i.png"}, modules.CardOptions{}, "https://x.example.com/i.png", ""},
{"notify image, images off", modules.Notice{Image: "https://x.example.com/i.png"}, modules.CardOptions{NoImages: true}, "", "i.png"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
tt.n.Message, tt.n.Priority = "m", 3
job, _ := modules.Card(tt.n, tt.o, env)
var gotImage, gotFile string
for _, el := range job.Elements {
if el.Type == receipt.TypeImage {
gotImage = el.URL
if !el.Optional || el.Width != 384 || el.Align != "center" {
t.Errorf("image %+v, want optional, 384 dots and centred", el)
}
}
}
for _, el := range job.Elements[0].Children {
if el.Type == receipt.TypeKV && el.Pairs[0].Key == "File" {
gotFile = el.Pairs[0].Value
}
}
if gotImage != tt.image || gotFile != tt.fileValue {
t.Errorf("image %q and file row %q, want %q and %q", gotImage, gotFile, tt.image, tt.fileValue)
}
})
}
}
func TestFromNtfy(t *testing.T) {
tests := []struct {
name string
body string
skip bool
want func(modules.Notice) bool
}{
{"unknown fields are ignored", `{"event":"message","message":"x","colour":"red","attachment":{"url":"https://a/b.png","name":"b.png","new":1}}`,
false, func(n modules.Notice) bool { return n.Message == "x" && n.File != nil }},
{"no priority is 3", `{"event":"message","message":"x"}`, false, func(n modules.Notice) bool { return n.Priority == 3 }},
{"priority 0 is 3", `{"event":"message","message":"x","priority":0}`, false, func(n modules.Notice) bool { return n.Priority == 3 }},
{"priority out of range is 3", `{"event":"message","message":"x","priority":9}`, false, func(n modules.Notice) bool { return n.Priority == 3 }},
{"no event is a message", `{"message":"x","priority":5}`, false, func(n modules.Notice) bool { return n.Priority == 5 }},
{"markdown", `{"event":"message","message":"x","content_type":"text/markdown"}`, false, func(n modules.Notice) bool { return n.Markdown }},
{"time", `{"event":"message","message":"x","time":1764450245}`, false,
func(n modules.Notice) bool { return n.Time.Equal(time.Unix(1764450245, 0)) }},
{"file placeholder", `{"event":"message","message":"You received a file: a.pdf","attachment":{"name":"a.pdf","url":"https://a/a.pdf"}}`,
false, func(n modules.Notice) bool { return n.Message == "" && n.File.Name == "a.pdf" }},
{"other text stays", `{"event":"message","message":"See a.pdf","attachment":{"name":"a.pdf","url":"https://a/a.pdf"}}`,
false, func(n modules.Notice) bool { return n.Message == "See a.pdf" }},
{"sequence id equal to id", `{"id":"a","sequence_id":"a","event":"message","message":"x"}`, false, func(n modules.Notice) bool { return !n.Updated }},
// A publisher may choose the sequence ID, so one message cannot
// tell the first of its sequence from a replacement.
{"sequence id other than id", `{"id":"b","sequence_id":"a","event":"message","message":"x"}`, false, func(n modules.Notice) bool { return !n.Updated }},
{"view actions and click are links", `{"event":"message","message":"x","click":"https://c/",` +
`"actions":[{"action":"view","label":"V","url":"https://v/"},{"action":"http","label":"H","url":"https://h/"}]}`,
false, func(n modules.Notice) bool {
return len(n.Links) == 2 && n.Links[0].URL == "https://c/" && n.Links[1] == modules.Link{Label: "V", URL: "https://v/"}
}},
{"open", `{"id":"x","time":1,"event":"open","topic":"alerts"}`, true, nil},
{"keepalive", `{"id":"x","time":1,"event":"keepalive","topic":"alerts"}`, true, nil},
{"poll request", `{"event":"poll_request","message":"New message"}`, true, nil},
{"delete", `{"event":"message_delete","sequence_id":"a"}`, true, nil},
{"clear", `{"event":"message_clear","sequence_id":"a"}`, true, nil},
{"base64", `{"event":"message","message":"iVBORw0KGgo=","encoding":"base64"}`, true, nil},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var m ntfy.Message
if err := json.Unmarshal([]byte(tt.body), &m); err != nil {
t.Fatal(err)
}
n, err := modules.FromNtfy(m)
if tt.skip {
if !errors.Is(err, modules.ErrSkip) {
t.Errorf("err = %v, want ErrSkip", err)
}
return
}
if err != nil {
t.Fatal(err)
}
if !tt.want(n) {
t.Errorf("notice %+v", n)
}
})
}
}
func TestNtfyBuild(t *testing.T) {
ctx := context.Background()
if _, err := modules.Ntfy().Build(ctx, []byte(`{"event":"keepalive","time":1}`), ntfyEnv(t)); !errors.Is(err, modules.ErrSkip) {
t.Errorf("keepalive: err = %v, want ErrSkip", err)
}
sequence := []byte(`{"id":"b","sequence_id":"a","event":"message","title":"Disk","message":"x","priority":4}`)
job, err := modules.Ntfy().Build(ctx, sequence, ntfyEnv(t))
if err != nil {
t.Fatal(err)
}
if got := job.Elements[0].Children[0].Text; got != "Disk" {
t.Errorf("a message of a sequence: title %q, want it unmarked", got)
}
// A notice known to replace an earlier one, as the subscriber can
// tell, is marked.
job, _ = modules.Card(modules.Notice{Title: "Disk", Message: "x", Priority: 4, Updated: true}, modules.CardOptions{}, ntfyEnv(t))
if got := job.Elements[0].Children[0].Text; got != "Disk (updated)" {
t.Errorf("an update: title %q", got)
}
problems := []struct{ body, want string }{
{``, "body: empty; expected a JSON object"},
{`null`, "body: expected a JSON object, got null"},
{`[1]`, "body: expected a JSON object, got array"},
{`{"message":"x"} {}`, "body: trailing data after the payload"},
{`{"priority":"high"}`, "priority: expected a whole number"},
{`{"attachment":{"size":"big"}}`, "attachment.size: expected a whole number"},
}
for _, p := range problems {
_, err := modules.Ntfy().Build(ctx, []byte(p.body), ntfyEnv(t))
var pe *modules.PayloadError
if !errors.As(err, &pe) || strings.Join(pe.Problems, "; ") != p.want {
t.Errorf("%s: err = %v, want the problem %q", p.body, err, p.want)
}
}
}
func TestNotifyPayloadProblems(t *testing.T) {
tests := []struct {
name, body string
want []string
}{
{"unknown field", `{"message":"x","colour":"red"}`, []string{"colour: unknown field"}},
{"wrong types", `{"message":1,"tags":"a","markdown":"yes","actions":{}}`,
[]string{"actions: expected an array", "markdown: expected true or false", "message: expected a string", "tags: expected an array of strings"}},
{"missing message", `{"title":"T"}`, []string{"message: required"}},
{"long message", `{"message":"` + strings.Repeat("x", modules.MaxMessage+1) + `"}`, []string{"message: 4097 bytes, limit is 4096"}},
{"long title and topic", `{"message":"x","title":"` + strings.Repeat("é", modules.MaxTitle+1) + `","topic":"` + strings.Repeat("t", modules.MaxTopic+1) + `"}`,
[]string{"title: 251 characters, limit is 250", "topic: 65 characters, limit is 64"}},
{"too many tags", `{"message":"x","tags":[` + strings.Repeat(`"a",`, modules.MaxTags) + `"b"]}`, []string{"tags: 21 tags, limit is 20"}},
{"long tag", `{"message":"x","tags":["a","` + strings.Repeat("t", modules.MaxTag+1) + `"]}`, []string{"tags[1]: 65 characters, limit is 64"}},
{"long label and URLs", `{"message":"x","click":"https://a/` + strings.Repeat("x", modules.MaxURL) + `","image":"https://i/` + strings.Repeat("x", modules.MaxURL) +
`","actions":[{"label":"` + strings.Repeat("l", modules.MaxLabel+1) + `","url":"https://b/` + strings.Repeat("x", modules.MaxURL) + `"}]}`,
[]string{"click: 2010 bytes, limit is 2000", "image: 2010 bytes, limit is 2000",
"actions[0].label: 65 characters, limit is 64", "actions[0].url: 2010 bytes, limit is 2000"}},
{"priority number", `{"message":"x","priority":6}`, []string{"priority: must be 1-5, or min, low, default, high, max or urgent"}},
{"priority fraction", `{"message":"x","priority":2.5}`, []string{"priority: must be 1-5, or min, low, default, high, max or urgent"}},
{"priority name", `{"message":"x","priority":"loud"}`, []string{"priority: must be 1-5, or min, low, default, high, max or urgent"}},
{"priority type", `{"message":"x","priority":true}`, []string{"priority: must be 1-5, or min, low, default, high, max or urgent"}},
{"time", `{"message":"x","time":"yesterday"}`, []string{"time: must be Unix seconds or an RFC 3339 time, e.g. 2026-11-29T21:04:05Z"}},
{"negative time", `{"message":"x","time":-5}`, []string{"time: must be Unix seconds or an RFC 3339 time, e.g. 2026-11-29T21:04:05Z"}},
{"click", `{"message":"x","click":"mailto:a@example.com"}`, []string{"click: must be an http or https URL"}},
{"image", `{"message":"x","image":"/local.png"}`, []string{"image: must be an http or https URL"}},
{"too many actions", `{"message":"x","actions":[{"url":"https://a/"},{"url":"https://b/"},{"url":"https://c/"},{"url":"https://d/"}]}`,
[]string{"actions: 4 actions, limit is 3"}},
{"action problems", `{"message":"x","actions":[{"label":"A"},{"url":"ftp://x/"},{"url":"https://x/","lable":"B"},"https://y/"]}`,
[]string{"actions: 4 actions, limit is 3", "actions[0].url: required", "actions[1].url: must be an http or https URL",
"actions[2].lable: unknown field", "actions[3]: expected a JSON object, got string"}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
_, err := modules.Notify().Build(context.Background(), []byte(tt.body), fixedEnv(t))
var pe *modules.PayloadError
if !errors.As(err, &pe) {
t.Fatalf("err = %v, want *PayloadError", err)
}
if strings.Join(pe.Problems, "\n") != strings.Join(tt.want, "\n") {
t.Errorf("problems:\n%s\nwant:\n%s", strings.Join(pe.Problems, "\n"), strings.Join(tt.want, "\n"))
}
})
}
}
func TestNotifyPriorityAndTime(t *testing.T) {
tests := []struct {
body string
priority int // 5: an URGENT rule first, 4: a HIGH box, 3: a box, 1 and 2: a rule
stamp string
}{
{`{"message":"x"}`, 3, "29 Nov 21:04"},
{`{"message":"x","priority":"urgent"}`, 5, ""},
{`{"message":"x","priority":"MAX"}`, 5, ""},
{`{"message":"x","priority":"high"}`, 4, ""},
{`{"message":"x","priority":"default"}`, 3, ""},
{`{"message":"x","priority":"low"}`, 2, ""},
{`{"message":"x","priority":"min"}`, 1, ""},
{`{"message":"x","priority":"4"}`, 4, ""},
{`{"message":"x","priority":1}`, 1, ""},
{`{"message":"x","time":1764450245}`, 3, "29 Nov 21:04"},
{`{"message":"x","time":"2026-07-01T12:30:00+02:00"}`, 3, "01 Jul 11:30"},
}
for _, tt := range tests {
job, err := modules.Notify().Build(context.Background(), []byte(tt.body), fixedEnv(t))
if err != nil {
t.Errorf("%s: %v", tt.body, err)
continue
}
first := job.Elements[0]
var got int
switch {
case first.Type == receipt.TypeRule && first.Text == "URGENT":
got = 5
case first.Type == receipt.TypeBox && first.Title == "HIGH":
got = 4
case first.Type == receipt.TypeBox:
got = 3
default:
got = 1
}
want := tt.priority
if want <= 2 {
want = 1
}
if got != want {
t.Errorf("%s: printed as priority %d, want %d", tt.body, got, tt.priority)
}
if tt.stamp != "" && !strings.HasSuffix(first.Footer, tt.stamp) {
t.Errorf("%s: footer %q, want the time %s", tt.body, first.Footer, tt.stamp)
}
}
}
// TestCardFallback checks that a card that fails to lay out still prints:
// the plain fallback receipt, which passes validation.
func TestCardFallback(t *testing.T) {
restore := modules.SetCardFault(func() { panic("layout bug") })
defer restore()
n := modules.Notice{Topic: "alerts", Title: "Disk 🎉", Message: "/var is at 94%", Priority: 5}
job, err := modules.Card(n, modules.CardOptions{}, fixedEnv(t))
var fallbackErr *modules.FallbackError
if !errors.As(err, &fallbackErr) || !strings.Contains(fallbackErr.Cause, "layout bug") || fallbackErr.Stack == "" {
t.Errorf("err = %#v, want a *FallbackError with the panic and its stack", err)
}
if strings.Contains(fmt.Sprint(err), "94%") {
t.Error("the error quotes the notification")
}
if err := job.Validate(); err != nil {
t.Fatalf("fallback is invalid: %v", err)
}
// The module returns the fallback with the error, for its caller to
// report.
built, err := modules.Notify().Build(context.Background(), []byte(`{"message":"x"}`), fixedEnv(t))
if !errors.As(err, &fallbackErr) || len(built.Elements) == 0 || built.Validate() != nil {
t.Errorf("notify: job %+v, err %v; want the fallback and a *FallbackError", built, err)
}
want := "Disk\n/var is at 94%\nalerts · 29 Nov 21:04\n - - - - - - - partial cut - - - - - - - -\n"
if got := previewText(t, job); got != want {
t.Errorf("fallback:\n%s\nwant:\n%s", got, want)
}
if !job.Elements[0].Bold {
t.Error("the fallback's title is not bold")
}
}
// TestCardsAreValid builds cards from awkward notices, which must all pass
// validation without falling back.
func TestCardsAreValid(t *testing.T) {
many := make([]string, 300)
for i := range many {
many[i] = "- item"
}
notices := []modules.Notice{
{},
{Message: " \n "},
{Message: "x", Priority: -1},
{Message: "x", Priority: 3, Tags: []string{"", "warning", "x", "tada", "skull"}},
{Message: strings.Join(many, "\n"), Markdown: true, Priority: 3},
{Message: "```\nunclosed fence", Markdown: true},
{Message: "- 🎉\n# \n> \n---", Markdown: true, Priority: 1},
{Title: "\u001b@", Message: "\u0007\u001bd", Topic: "\t"},
{Message: "x", Links: []modules.Link{{URL: "https://a/"}, {URL: "https://b/"}, {URL: "https://c/"}, {URL: "https://d/"}}},
}
for _, o := range []modules.CardOptions{{}, {MaxLines: 400}, {Style: "compact", QR: "none"}, {Style: "box", QR: "first"}} {
for i, n := range notices {
job, err := modules.Card(n, o, fixedEnv(t))
if err != nil {
t.Errorf("notice %d, options %+v: %v", i, o, err)
}
if err := job.Validate(); err != nil {
t.Errorf("notice %d, options %+v: %v", i, o, err)
}
// A card starts with a box or a rule; the fallback with text.
if job.Elements[0].Type == receipt.TypeText {
t.Errorf("notice %d, options %+v: fell back to the plain receipt", i, o)
}
}
}
}
// TestCardLimits builds a card from a notice far over every limit, as an
// ntfy message may be: it is cut to a length that prints well inside
// format.max_lines, even on 58 mm paper.
func TestCardLimits(t *testing.T) {
long := strings.Repeat("word ", 20_000)
tags := make([]string, 9000)
for i := range tags {
tags[i] = fmt.Sprint("tag", i, strings.Repeat("x", 100))
}
n := modules.Notice{
Title: long,
Topic: long,
Message: strings.Repeat("x", 1_000_000),
Priority: 5,
Tags: tags,
Links: []modules.Link{
{Label: long, URL: "https://a.example.com/" + strings.Repeat("x", 300)},
{URL: "https://b.example.com/" + strings.Repeat("x", 5000)},
},
File: &modules.File{Name: long, URL: "https://f.example.com/report.pdf"},
}
job, err := modules.Card(n, modules.CardOptions{}, fixedEnv(t))
if err != nil {
t.Fatal(err)
}
for _, model := range []string{"tm-t88", "generic-58mm"} {
profile, err := escpos.LookupProfile(model)
if err != nil {
t.Fatal(err)
}
r := receipt.NewRenderer(receipt.Options{
Profile: profile, CodePage: escpos.CodePage437, MaxPixels: 1000, MaxHeight: 1000, MaxLines: 2000,
}, noFetch{})
p, err := r.Preview(context.Background(), job)
if err != nil {
t.Fatalf("%s: %v", model, err)
}
if p.LineCount > 400 {
t.Errorf("%s: the card prints %d lines", model, p.LineCount)
}
}
box := job.Elements[1]
if head := box.Children[0].Text; utf8.RuneCountInString(head) > modules.MaxTitle+4 || !strings.HasSuffix(head, "...") {
t.Errorf("title row of %d characters", utf8.RuneCountInString(head))
}
for _, el := range job.Elements {
if el.Type == receipt.TypeQR && len(el.Data) > 1000 {
t.Errorf("a %d-byte link printed", len(el.Data))
}
}
}
// TestCardTitleFallback checks that a title or tags that cleaning leaves
// empty fall back as a missing title does, and leave no empty tag.
func TestCardTitleFallback(t *testing.T) {
tests := []struct {
n modules.Notice
head string
row string
}{
{modules.Notice{Title: "🎉🎉", Topic: "alerts", Tags: []string{"warning"}}, "[!] alerts", ""},
{modules.Notice{Title: "🎉", Topic: "🎉"}, "Notification", ""},
{modules.Notice{Title: "T", Tags: []string{"🎉", "a", " ", "🧺"}}, "T", "Tags: a"},
{modules.Notice{Title: "T", Tags: []string{"🎉"}}, "T", ""},
}
for _, tt := range tests {
tt.n.Message, tt.n.Priority = "m", 4
job, _ := modules.Card(tt.n, modules.CardOptions{}, fixedEnv(t))
children := job.Elements[0].Children
row := ""
if last := children[len(children)-1].Text; strings.HasPrefix(last, "Tags:") {
row = last
}
if children[0].Text != tt.head || row != tt.row {
t.Errorf("%q with tags %q: title row %q and tags row %q, want %q and %q",
tt.n.Title, tt.n.Tags, children[0].Text, row, tt.head, tt.row)
}
}
}