Files
uberbringer/internal/pkg/modules/notify.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

231 lines
6.6 KiB
Go

package modules
import (
"context"
"encoding/json"
"errors"
"fmt"
"math"
"strconv"
"strings"
"time"
"unicode/utf8"
"uberbringer/internal/pkg/receipt"
)
// Notify payload limits, besides the notice limits.
const (
// MaxNotifyActions is how many actions a notification may have. With
// click, at most maxLinks links print in all.
MaxNotifyActions = 3
// maxUnixSeconds is the last second of the year 9999.
maxUnixSeconds = 253402300799
)
// Notify returns the notify module: a notification card from a title,
// message, priority and tags, for scripts, cron jobs and phone shortcuts.
func Notify() Module {
return notify{}
}
type notify struct{}
// notifyPayload is the body of a notification. priority and time take a
// number or a string, so they are checked after decoding.
type notifyPayload struct {
Title string `json:"title"`
Message string `json:"message"`
Priority any `json:"priority"`
Tags []string `json:"tags"`
Topic string `json:"topic"`
Click string `json:"click"`
Markdown bool `json:"markdown"`
Time any `json:"time"`
Actions []json.RawMessage `json:"actions"`
Image string `json:"image"`
}
// notifyAction is a link of a notification.
type notifyAction struct {
Label string `json:"label"`
URL string `json:"url"`
}
func (notify) Name() string { return "notify" }
func (notify) Description() string {
return "Notification card from title, message, priority and tags"
}
// Build lays the notification out as a card.
func (notify) Build(_ context.Context, body []byte, env Env) (receipt.Job, error) {
var p notifyPayload
if err := DecodeStrict(body, &p); err != nil {
return receipt.Job{}, err
}
n, problems := p.notice()
if len(problems) > 0 {
return receipt.Job{}, &PayloadError{Problems: problems}
}
return noticeJob(n, env)
}
// notice checks the payload and turns it into a Notice.
func (p notifyPayload) notice() (Notice, []string) {
n := Notice{
Topic: p.Topic,
Title: p.Title,
Message: p.Message,
Markdown: p.Markdown,
Tags: p.Tags,
Image: p.Image,
}
var problems []string
switch size := len(p.Message); {
case strings.TrimSpace(p.Message) == "":
problems = append(problems, "message: required")
case size > MaxMessage:
problems = append(problems, fmt.Sprintf("message: %d bytes, limit is %d", size, MaxMessage))
}
problems = append(problems, tooLong("title", p.Title, MaxTitle)...)
problems = append(problems, tooLong("topic", p.Topic, MaxTopic)...)
if count := len(p.Tags); count > MaxTags {
problems = append(problems, fmt.Sprintf("tags: %d tags, limit is %d", count, MaxTags))
}
for i, tag := range p.Tags {
problems = append(problems, tooLong(fmt.Sprintf("tags[%d]", i), tag, MaxTag)...)
}
var err error
if n.Priority, err = parsePriority(p.Priority); err != nil {
problems = append(problems, "priority: "+err.Error())
}
if n.Time, err = parseTime(p.Time); err != nil {
problems = append(problems, "time: "+err.Error())
}
if p.Click != "" {
if problem := urlProblem("click", p.Click); problem != "" {
problems = append(problems, problem)
} else {
n.Links = append(n.Links, Link{URL: p.Click})
}
}
if p.Image != "" {
if problem := urlProblem("image", p.Image); problem != "" {
problems = append(problems, problem)
}
}
if count := len(p.Actions); count > MaxNotifyActions {
problems = append(problems, fmt.Sprintf("actions: %d actions, limit is %d", count, MaxNotifyActions))
}
for i, raw := range p.Actions {
field := fmt.Sprintf("actions[%d]", i)
var a notifyAction
if err := DecodeStrict(raw, &a); err != nil {
problems = append(problems, nestedProblems(field, err)...)
continue
}
problems = append(problems, tooLong(field+".label", a.Label, MaxLabel)...)
if a.URL == "" {
problems = append(problems, field+".url: required")
} else if problem := urlProblem(field+".url", a.URL); problem != "" {
problems = append(problems, problem)
} else {
n.Links = append(n.Links, Link(a))
}
}
return n, problems
}
// tooLong returns a problem for field when s is longer than limit
// characters.
func tooLong(field, s string, limit int) []string {
if n := utf8.RuneCountInString(s); n > limit {
return []string{fmt.Sprintf("%s: %d characters, limit is %d", field, n, limit)}
}
return nil
}
// urlProblem returns the problem with field's URL s, or "".
func urlProblem(field, s string) string {
switch {
case !webURL(s):
return field + ": must be an http or https URL"
case len(s) > MaxURL:
return fmt.Sprintf("%s: %d bytes, limit is %d", field, len(s), MaxURL)
}
return ""
}
// nestedProblems prefixes each problem of a nested object's *PayloadError
// with field, the object's place in the payload.
func nestedProblems(field string, err error) []string {
var pe *PayloadError
if !errors.As(err, &pe) {
return []string{field + ": " + err.Error()}
}
problems := make([]string, len(pe.Problems))
for i, problem := range pe.Problems {
if rest, ok := strings.CutPrefix(problem, "body: "); ok {
problems[i] = field + ": " + rest
continue
}
problems[i] = field + "." + problem
}
return problems
}
// parsePriority reads a priority given as 1-5 or by name. nil is the
// default priority.
func parsePriority(v any) (int, error) {
bad := fmt.Errorf("must be 1-5, or min, low, default, high, max or urgent")
switch p := v.(type) {
case nil:
return defaultPriority, nil
case float64:
if p != math.Trunc(p) || p < minPriority || p > maxPriority {
return 0, bad
}
return int(p), nil
case string:
s := strings.ToLower(strings.TrimSpace(p))
if n, ok := priorityNames[s]; ok {
return n, nil
}
if n, err := strconv.Atoi(s); err == nil && n >= minPriority && n <= maxPriority {
return n, nil
}
}
return 0, bad
}
// parseTime reads a time given as Unix seconds or in RFC 3339. nil is the
// zero time, which stands for the time the card is built.
func parseTime(v any) (time.Time, error) {
bad := fmt.Errorf("must be Unix seconds or an RFC 3339 time, e.g. 2026-11-29T21:04:05Z")
switch t := v.(type) {
case nil:
return time.Time{}, nil
case float64:
if t != math.Trunc(t) || t <= 0 || t > maxUnixSeconds {
return time.Time{}, bad
}
return time.Unix(int64(t), 0), nil
case string:
parsed, err := time.Parse(time.RFC3339, strings.TrimSpace(t))
if err == nil {
return parsed, nil
}
}
return time.Time{}, bad
}
// noticeJob lays out n as a card with the options in env. A *FallbackError
// comes with the plain receipt, which still prints.
func noticeJob(n Notice, env Env) (receipt.Job, error) {
return Card(n, env.Card, env)
}