Add ntfy subscriptions with digests, quiet hours and a cut feed
[[ntfy.subscriptions]] tables make the daemon subscribe to ntfy topics itself and print each message as a notification card, so the phone's ntfy app is the only client. Each subscription is one ntfy.Subscriber in the daemon's errgroup: one event loop owns its state, and one goroutine per connection reads the JSON stream. internal/app hands its messages to modules.FromNtfy, Card, Validate and Submit with the source ntfy:<name> and the message's ID as ref, so ntfy never imports modules. The cursor is ntfy server time, never an ID. ntfy sends open before the replay, so only keepalives and messages dealt with move it, and a reconnect asks for two minutes before it, since a message is dated before its attachment is stored. The IDs of the messages a replay could send again are kept, at least the last 512 and 20,000 at most, so a flood in the overlap never reprints; when the cap forgets IDs a replay could send, the floor rises past them. A saved floor bounds replays: a first start sets it to the open event's time, and max_backlog (default 1h, at most 12h), measured by the server's clock as each connection tells it (its open event, else its Date, then the monotonic clock), never the host's, so replays are requested unclamped and filtered as they arrive, raises it when it clamps, so what it left out stays out. The state, with the held messages and the receipt times, is written atomically at most once a second and at shutdown. Redirects are never followed, so credentials never go to another address or over plain http. A stalled stream reconnects after twice the keepalive plus 15 s, failures back off 5 to 120 s with jitter, a 429 waits for Retry-After, and refused credentials, checked at startup through /auth, show as unauthorized and retry every 5 minutes. A full print queue pauses reading and retries the message from 1 s to 30 s, and the cursor moves past it only once it is queued. The paper budget is a strict window: at most rate_limit receipts (5) in any rate_window (10m), digests included; the rest are held and print on one digest card once there is room, and outside quiet hours bypass_priority (5) and above print at once. Quiet hours hold everything below their min_priority for one Overnight digest when the window ends, or drop it; windows cross midnight and keep their times of day when clocks change, also where the change skips midnight or a window's end. A message whose sequence printed before, on a card or a digest row, is marked (updated), or skipped with ntfy.format.updates = "skip"; the first of a sequence its publisher named prints plain. /healthz lists the subscriptions without changing how its status code is decided, and no credential, topic or message text reaches it, the logs or a config error. Subscriptions come from the file only, with strict keys and per-entry defaults; credentials are optional, at most one kind. ntfy.state_dir is required with a subscription: the unit gains StateDirectory=uberbringer, install.sh writes the path into a new config, and the Docker image sets it for a volume and runs as the fixed user 10001. README explains how to lock a self-hosted ntfy server down so that only your publishers can print. Breaking: printer.cut_feed (default 3) feeds blank lines before every cut, so the last line no longer sits right at the cut. They count toward format.max_lines once per copy, so a job within 3 lines a copy of the limit now fails. The renderer's option is 0 unless set, so the pinned receipts keep their bytes. testing/synctest drives the subscriber on a virtual clock, including a 24-hour soak with floods, repeats, refusals, a full queue, quiet hours and a restart that fails on any leaked goroutine; it replaces a 24-hour run on hardware. Tests over real sockets cover net/http's goroutines and redirects to plain http and to another port. Checked on the TM-T88IV against a live ntfy server: a phone message, quiet hours with priorities 3 and 5 and the Overnight digest, a stale cursor, a 30-minute outage with an update, a wrong token, and the three-line cut feed. The digest and the cut-feed card are pinned in TestPaperReceipts. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
1335ed0687
commit
fb76284129
52 files changed
+6464
-390
No files matched your search
+380
-19
@@ -8,8 +8,10 @@ import (
|
||||
"fmt"
|
||||
"maps"
|
||||
"net/netip"
|
||||
"net/url"
|
||||
"os"
|
||||
"reflect"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -34,6 +36,9 @@ const MinSecretLength = 32
|
||||
// takes.
|
||||
const MaxLineSpacing = 255
|
||||
|
||||
// MaxCutFeed is the largest printer.cut_feed, the most ESC d feeds at once.
|
||||
const MaxCutFeed = 255
|
||||
|
||||
// Log formats accepted by [LogConfig.Format].
|
||||
const (
|
||||
LogFormatText = "text"
|
||||
@@ -106,6 +111,10 @@ type PrinterConfig struct {
|
||||
// keeps the printer's default spacing.
|
||||
BoxLineSpacing int `mapstructure:"box_line_spacing"`
|
||||
|
||||
// CutFeed is how many blank lines feed before each cut, so that the
|
||||
// last printed line does not sit right at the cut.
|
||||
CutFeed int `mapstructure:"cut_feed"`
|
||||
|
||||
DialTimeout time.Duration `mapstructure:"dial_timeout"`
|
||||
WriteTimeout time.Duration `mapstructure:"write_timeout"`
|
||||
|
||||
@@ -129,27 +138,152 @@ type FormatConfig struct {
|
||||
TimeLayout string `mapstructure:"time_layout"`
|
||||
}
|
||||
|
||||
// Values of NtfyFormatConfig's settings.
|
||||
// Values of the ntfy settings.
|
||||
var (
|
||||
NtfyStyles = []string{"auto", "box", "compact"}
|
||||
NtfyQRModes = []string{"all", "first", "none"}
|
||||
NtfyStyles = []string{"auto", "box", "compact"}
|
||||
NtfyQRModes = []string{"all", "first", "none"}
|
||||
NtfyUpdateModes = []string{"print", "skip"}
|
||||
NtfyQuietActions = []string{"digest", "drop"}
|
||||
NtfyDays = []string{"mon", "tue", "wed", "thu", "fri", "sat", "sun"}
|
||||
)
|
||||
|
||||
// Limits of the ntfy settings: the largest ntfy.format.max_lines, and the
|
||||
// most characters in a marker.
|
||||
// Limits of the ntfy settings.
|
||||
const (
|
||||
// MaxNtfyLines is the largest ntfy.format.max_lines.
|
||||
MaxNtfyLines = 400
|
||||
MaxMarker = 16
|
||||
|
||||
// MaxMarker is the most characters in a marker.
|
||||
MaxMarker = 16
|
||||
|
||||
// MaxNtfyTopics is how many topics one subscription may name, as many
|
||||
// as ntfy serves on one connection.
|
||||
MaxNtfyTopics = 150
|
||||
|
||||
// MaxNtfyBacklog is the longest max_backlog: ntfy keeps messages for
|
||||
// 12 hours by default.
|
||||
MaxNtfyBacklog = 12 * time.Hour
|
||||
|
||||
// MaxNtfyRateLimit is the largest rate_limit.
|
||||
MaxNtfyRateLimit = 1000
|
||||
|
||||
// MinNtfyKeepalive and MaxNtfyKeepalive bound keepalive.
|
||||
MinNtfyKeepalive = 5 * time.Second
|
||||
MaxNtfyKeepalive = time.Hour
|
||||
)
|
||||
|
||||
// NtfyConfig configures how notifications print, from the notify and ntfy
|
||||
// modules.
|
||||
// modules and from the subscriptions.
|
||||
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"`
|
||||
|
||||
// StateDir is the directory each subscription keeps its state in: its
|
||||
// cursor, the IDs it has seen and the messages it holds. Required when
|
||||
// a subscription is configured.
|
||||
StateDir string `mapstructure:"state_dir"`
|
||||
|
||||
// Subscriptions are the ntfy servers and topics whose messages print.
|
||||
// They come from the file only: a list of tables has no environment
|
||||
// variable.
|
||||
Subscriptions []NtfySubscription `mapstructure:"subscriptions"`
|
||||
}
|
||||
|
||||
// NtfySubscription is one connection to an ntfy server, for one or more
|
||||
// topics.
|
||||
type NtfySubscription struct {
|
||||
// Name names the subscription in /healthz, in logs, in job sources
|
||||
// (ntfy:<name>) and in its state file.
|
||||
Name string `mapstructure:"name"`
|
||||
|
||||
// Server is the ntfy server's base URL, e.g. https://ntfy.sh.
|
||||
Server string `mapstructure:"server"`
|
||||
|
||||
// Topics are the topics to print.
|
||||
Topics []string `mapstructure:"topics"`
|
||||
|
||||
// Token, TokenFile, or User with PasswordFile authenticate the
|
||||
// subscription; at most one of them is set. A file holds the secret
|
||||
// alone, and spaces around it are ignored.
|
||||
Token string `mapstructure:"token"`
|
||||
TokenFile string `mapstructure:"token_file"`
|
||||
User string `mapstructure:"user"`
|
||||
PasswordFile string `mapstructure:"password_file"`
|
||||
|
||||
// AllowInsecure allows a server URL that is http rather than https.
|
||||
AllowInsecure bool `mapstructure:"allow_insecure"`
|
||||
|
||||
// MinPriority is the lowest priority that prints, 1-5.
|
||||
MinPriority int `mapstructure:"min_priority"`
|
||||
|
||||
// MaxBacklog is how far back missed messages are printed after a
|
||||
// restart or an outage.
|
||||
MaxBacklog time.Duration `mapstructure:"max_backlog"`
|
||||
|
||||
// RateLimit receipts print per RateWindow at most; messages over it
|
||||
// are held and print together on one digest receipt.
|
||||
RateLimit int `mapstructure:"rate_limit"`
|
||||
RateWindow time.Duration `mapstructure:"rate_window"`
|
||||
|
||||
// BypassPriority is the lowest priority that prints at once, outside
|
||||
// the rate limit, 1-5.
|
||||
BypassPriority int `mapstructure:"bypass_priority"`
|
||||
|
||||
// Keepalive is the server's keepalive interval. A connection that
|
||||
// sends nothing for twice this, plus 15 seconds, is reconnected.
|
||||
Keepalive time.Duration `mapstructure:"keepalive"`
|
||||
|
||||
// Quiet sets quiet hours; nil leaves them off.
|
||||
Quiet *NtfyQuiet `mapstructure:"quiet"`
|
||||
}
|
||||
|
||||
// NtfyQuiet configures a subscription's quiet hours: a daily window in
|
||||
// which only urgent messages print.
|
||||
type NtfyQuiet struct {
|
||||
// Start and End are the window's times of day, HH:MM. An End before
|
||||
// Start ends the window on the next day.
|
||||
Start string `mapstructure:"start"`
|
||||
End string `mapstructure:"end"`
|
||||
|
||||
// Days are the days the window starts on: mon, tue, wed, thu, fri,
|
||||
// sat or sun.
|
||||
Days []string `mapstructure:"days"`
|
||||
|
||||
// Timezone is the zone Start and End are in; "" means format.timezone.
|
||||
Timezone string `mapstructure:"timezone"`
|
||||
|
||||
// MinPriority is the lowest priority that prints during the window.
|
||||
MinPriority int `mapstructure:"min_priority"`
|
||||
|
||||
// Action is digest, to print the held messages on one receipt when the
|
||||
// window ends, or drop.
|
||||
Action string `mapstructure:"action"`
|
||||
}
|
||||
|
||||
// DefaultSubscription returns a subscription with every optional setting
|
||||
// at its default. Name, Server and Topics have no defaults.
|
||||
func DefaultSubscription() NtfySubscription {
|
||||
return NtfySubscription{
|
||||
MinPriority: 1,
|
||||
MaxBacklog: time.Hour,
|
||||
RateLimit: 5,
|
||||
RateWindow: 10 * time.Minute,
|
||||
BypassPriority: 5,
|
||||
Keepalive: 45 * time.Second,
|
||||
}
|
||||
}
|
||||
|
||||
// DefaultQuiet returns quiet hours with every setting at its default.
|
||||
func DefaultQuiet() NtfyQuiet {
|
||||
return NtfyQuiet{
|
||||
Start: "22:00",
|
||||
End: "07:00",
|
||||
Days: slices.Clone(NtfyDays),
|
||||
MinPriority: 5,
|
||||
Action: "digest",
|
||||
}
|
||||
}
|
||||
|
||||
// NtfyFormatConfig configures the layout of a notification.
|
||||
@@ -169,6 +303,11 @@ type NtfyFormatConfig struct {
|
||||
|
||||
// Markdown lays out markdown messages.
|
||||
Markdown bool `mapstructure:"markdown"`
|
||||
|
||||
// Updates says what a subscription does with a message that replaces
|
||||
// one it printed: print marks its title "(updated)", skip leaves it
|
||||
// out. The module routes print every message plain.
|
||||
Updates string `mapstructure:"updates"`
|
||||
}
|
||||
|
||||
// QueueConfig configures the print queue.
|
||||
@@ -237,6 +376,7 @@ func Default() Config {
|
||||
// printer makes it break words at the right edge.
|
||||
Model: "tm-t88",
|
||||
CodePage: "cp437",
|
||||
CutFeed: 3,
|
||||
DialTimeout: 5 * time.Second,
|
||||
WriteTimeout: 30 * time.Second,
|
||||
Retries: 3,
|
||||
@@ -254,6 +394,7 @@ func Default() Config {
|
||||
QR: "all",
|
||||
Images: true,
|
||||
Markdown: true,
|
||||
Updates: "print",
|
||||
},
|
||||
},
|
||||
Queue: QueueConfig{
|
||||
@@ -293,7 +434,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] == section {
|
||||
if kind := keys[key]; kind != setting && kind != tableSetting {
|
||||
continue
|
||||
}
|
||||
name := envVar(key)
|
||||
@@ -340,13 +481,7 @@ func Load(path string) (*Config, error) {
|
||||
|
||||
var cfg Config
|
||||
err := v.Unmarshal(&cfg,
|
||||
viper.DecodeHook(mapstructure.ComposeDecodeHookFunc(
|
||||
durations(),
|
||||
stringToList(),
|
||||
stringToTable(),
|
||||
refuseFractions(),
|
||||
stringToNumberOrFlag(),
|
||||
)),
|
||||
viper.DecodeHook(decodeHooks()),
|
||||
// Values are taken as written, apart from the strings that hooks
|
||||
// above parse: environment variables are strings.
|
||||
func(dc *mapstructure.DecoderConfig) { dc.WeaklyTypedInput = false },
|
||||
@@ -417,14 +552,21 @@ func readFile(path string) (map[string]any, error) {
|
||||
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.
|
||||
// keyKind tells a setting from a section that holds settings, from a
|
||||
// table setting, whose keys are the user's own, and from a list of tables.
|
||||
type keyKind int
|
||||
|
||||
const (
|
||||
setting keyKind = iota + 1
|
||||
section
|
||||
tableSetting
|
||||
|
||||
// tableList is a list of tables, such as ntfy.subscriptions, which only
|
||||
// the file sets. listSetting and listSection are the keys of its
|
||||
// entries.
|
||||
tableList
|
||||
listSetting
|
||||
listSection
|
||||
)
|
||||
|
||||
// registerDefaults sets every field of the config struct rv as a Viper
|
||||
@@ -449,6 +591,14 @@ func registerDefaults(v *viper.Viper, prefix string, rv reflect.Value, keys 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
|
||||
case reflect.Slice:
|
||||
if elem := field.Type().Elem(); elem.Kind() == reflect.Struct {
|
||||
keys[key] = tableList
|
||||
registerListKeys(key, elem, keys)
|
||||
continue
|
||||
}
|
||||
v.SetDefault(key, field.Interface())
|
||||
keys[key] = setting
|
||||
default:
|
||||
v.SetDefault(key, field.Interface())
|
||||
keys[key] = setting
|
||||
@@ -456,6 +606,29 @@ func registerDefaults(v *viper.Viper, prefix string, rv reflect.Value, keys map[
|
||||
}
|
||||
}
|
||||
|
||||
// registerListKeys records the keys of an entry of a list of tables, a
|
||||
// struct of type t, under prefix. They have no Viper defaults: decodeHooks
|
||||
// starts each entry from its own defaults.
|
||||
func registerListKeys(prefix string, t reflect.Type, keys map[string]keyKind) {
|
||||
for i := range t.NumField() {
|
||||
tag := t.Field(i).Tag.Get("mapstructure")
|
||||
if tag == "" {
|
||||
continue
|
||||
}
|
||||
key := prefix + "." + tag
|
||||
ft := t.Field(i).Type
|
||||
if ft.Kind() == reflect.Pointer {
|
||||
ft = ft.Elem()
|
||||
}
|
||||
if ft.Kind() == reflect.Struct {
|
||||
keys[key] = listSection
|
||||
registerListKeys(key, ft, keys)
|
||||
continue
|
||||
}
|
||||
keys[key] = listSetting
|
||||
}
|
||||
}
|
||||
|
||||
// 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
|
||||
@@ -485,7 +658,7 @@ func checkKeys(table map[string]any, prefix, lookup string, keys map[string]keyK
|
||||
kind = 0
|
||||
}
|
||||
switch {
|
||||
case isTable && kind == section:
|
||||
case isTable && (kind == section || kind == listSection):
|
||||
u, c := checkKeys(sub, path, key, keys)
|
||||
unknown = append(unknown, u...)
|
||||
clashes = append(clashes, c...)
|
||||
@@ -493,7 +666,11 @@ func checkKeys(table map[string]any, prefix, lookup string, keys map[string]keyK
|
||||
u, c := checkTable(sub, path)
|
||||
unknown = append(unknown, u...)
|
||||
clashes = append(clashes, c...)
|
||||
case !isTable && kind == setting:
|
||||
case kind == tableList:
|
||||
u, c := checkList(table[name], path, key, keys)
|
||||
unknown = append(unknown, u...)
|
||||
clashes = append(clashes, c...)
|
||||
case !isTable && (kind == setting || kind == listSetting):
|
||||
default:
|
||||
unknown = append(unknown, path)
|
||||
}
|
||||
@@ -501,6 +678,38 @@ func checkKeys(table map[string]any, prefix, lookup string, keys map[string]keyK
|
||||
return unknown, clashes
|
||||
}
|
||||
|
||||
// checkList checks the entries of a list of tables at path, whose dotted
|
||||
// lowercase key is lookup. Each entry must be a table, whose keys are
|
||||
// checked as a section's; an entry is named by its index, as
|
||||
// ntfy.subscriptions[0].name. A list given as anything else is unknown.
|
||||
func checkList(value any, path, lookup string, keys map[string]keyKind) (unknown, clashes []string) {
|
||||
var entries []map[string]any
|
||||
switch list := value.(type) {
|
||||
case []map[string]any:
|
||||
entries = list
|
||||
case []any:
|
||||
for i, item := range list {
|
||||
entry, ok := item.(map[string]any)
|
||||
if !ok {
|
||||
unknown = append(unknown, fmt.Sprintf("%s[%d]", path, i))
|
||||
continue
|
||||
}
|
||||
entries = append(entries, entry)
|
||||
}
|
||||
if len(unknown) > 0 {
|
||||
return unknown, nil
|
||||
}
|
||||
default:
|
||||
return []string{path}, nil
|
||||
}
|
||||
for i, entry := range entries {
|
||||
u, c := checkKeys(entry, fmt.Sprintf("%s[%d]", path, i), lookup, keys)
|
||||
unknown = append(unknown, u...)
|
||||
clashes = append(clashes, c...)
|
||||
}
|
||||
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
|
||||
@@ -530,6 +739,50 @@ func displayKey(name string) string {
|
||||
return strconv.Quote(name)
|
||||
}
|
||||
|
||||
// decodeHooks are the hooks that decode the config: values from strings,
|
||||
// and the entries of the lists of tables from their own defaults.
|
||||
func decodeHooks() mapstructure.DecodeHookFunc {
|
||||
values := []mapstructure.DecodeHookFunc{
|
||||
durations(),
|
||||
stringToList(),
|
||||
stringToTable(),
|
||||
refuseFractions(),
|
||||
stringToNumberOrFlag(),
|
||||
}
|
||||
quiet := entryDefaults(DefaultQuiet, values)
|
||||
subscription := entryDefaults(DefaultSubscription, append(slices.Clone(values), quiet))
|
||||
return mapstructure.ComposeDecodeHookFunc(append(values, subscription, quiet)...)
|
||||
}
|
||||
|
||||
// entryDefaults decodes a table into a T, an entry of a list of tables or
|
||||
// a table inside one, starting from defaults(): the keys the table leaves
|
||||
// out keep their defaults, which Viper cannot give the entries of a list.
|
||||
// hooks decode the entry's values.
|
||||
func entryDefaults[T any](defaults func() T, hooks []mapstructure.DecodeHookFunc) mapstructure.DecodeHookFunc {
|
||||
target := reflect.TypeFor[T]()
|
||||
return func(_, to reflect.Type, data any) (any, error) {
|
||||
table, ok := data.(map[string]any)
|
||||
if to != target || !ok {
|
||||
return data, nil
|
||||
}
|
||||
entry := defaults()
|
||||
dec, err := mapstructure.NewDecoder(&mapstructure.DecoderConfig{
|
||||
DecodeHook: mapstructure.ComposeDecodeHookFunc(hooks...),
|
||||
// A list the table gives replaces the default list rather than
|
||||
// overwriting its first items.
|
||||
ZeroFields: true,
|
||||
Result: &entry,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := dec.Decode(table); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return entry, nil
|
||||
}
|
||||
}
|
||||
|
||||
// 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 {
|
||||
@@ -692,6 +945,7 @@ func (c *Config) Validate() error {
|
||||
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.CutFeed >= 0 && p.CutFeed <= MaxCutFeed, "printer.cut_feed must be 0-%d", MaxCutFeed)
|
||||
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")
|
||||
@@ -714,6 +968,8 @@ func (c *Config) Validate() error {
|
||||
check(utf8.RuneCountInString(c.Ntfy.Markers[tag]) <= MaxMarker,
|
||||
"ntfy.markers.%s: %q is longer than %d characters", tag, c.Ntfy.Markers[tag], MaxMarker)
|
||||
}
|
||||
check(slices.Contains(NtfyUpdateModes, nf.Updates), "ntfy.format.updates: %q must be one of %s", nf.Updates, strings.Join(NtfyUpdateModes, ", "))
|
||||
errs = append(errs, validateSubscriptions(c.Ntfy)...)
|
||||
|
||||
check(c.Queue.Size > 0, "queue.size must be positive")
|
||||
check(c.Queue.History >= 0, "queue.history must not be negative")
|
||||
@@ -732,6 +988,111 @@ func (c *Config) Validate() error {
|
||||
return errors.Join(errs...)
|
||||
}
|
||||
|
||||
var (
|
||||
// subscriptionName is the form of a subscription's name, which appears
|
||||
// in job sources and in a file name.
|
||||
subscriptionName = regexp.MustCompile(`^[a-z0-9][a-z0-9_-]{0,31}$`)
|
||||
|
||||
// ntfyTopic is the form of an ntfy topic name.
|
||||
ntfyTopic = regexp.MustCompile(`^[-_A-Za-z0-9]{1,64}$`)
|
||||
|
||||
// clock is a time of day, HH:MM.
|
||||
clock = regexp.MustCompile(`^([01][0-9]|2[0-3]):[0-5][0-9]$`)
|
||||
)
|
||||
|
||||
// validateSubscriptions reports every problem with the ntfy subscriptions.
|
||||
// The server URL is never quoted, since it could hold a password.
|
||||
func validateSubscriptions(n NtfyConfig) []error {
|
||||
var errs []error
|
||||
if len(n.Subscriptions) > 0 && strings.TrimSpace(n.StateDir) == "" {
|
||||
errs = append(errs, errors.New(`ntfy.state_dir is required when a subscription is configured, e.g. "/var/lib/uberbringer"`))
|
||||
}
|
||||
names := make(map[string]int)
|
||||
for i, s := range n.Subscriptions {
|
||||
at := fmt.Sprintf("ntfy.subscriptions[%d]", i)
|
||||
check := func(ok bool, format string, args ...any) {
|
||||
if !ok {
|
||||
errs = append(errs, fmt.Errorf(at+"."+format, args...))
|
||||
}
|
||||
}
|
||||
|
||||
switch other, dup := names[s.Name]; {
|
||||
case s.Name == "":
|
||||
check(false, "name is required")
|
||||
case !subscriptionName.MatchString(s.Name):
|
||||
check(false, "name: %q must be 1-32 lowercase letters, digits, - and _, starting with a letter or digit", s.Name)
|
||||
case dup:
|
||||
check(false, "name: %q is also the name of ntfy.subscriptions[%d]", s.Name, other)
|
||||
default:
|
||||
names[s.Name] = i
|
||||
}
|
||||
|
||||
u, err := url.Parse(s.Server)
|
||||
switch {
|
||||
case s.Server == "":
|
||||
check(false, "server is required, e.g. \"https://ntfy.sh\"")
|
||||
case err != nil || u.Host == "" || (u.Scheme != "https" && u.Scheme != "http"):
|
||||
check(false, "server is not an http or https URL")
|
||||
case u.User != nil:
|
||||
check(false, "server holds credentials; set token, token_file, or user and password_file instead")
|
||||
case u.RawQuery != "" || u.Fragment != "":
|
||||
check(false, "server must have no query or fragment")
|
||||
case u.Scheme == "http" && !s.AllowInsecure:
|
||||
check(false, "server is not https; set allow_insecure = true to allow plain http")
|
||||
}
|
||||
|
||||
// A topic is named by its index, never quoted: on a public server
|
||||
// its name can be all that keeps others from publishing to it.
|
||||
check(len(s.Topics) >= 1 && len(s.Topics) <= MaxNtfyTopics, "topics: name 1-%d topics", MaxNtfyTopics)
|
||||
seen := make(map[string]int, len(s.Topics))
|
||||
for j, topic := range s.Topics {
|
||||
check(ntfyTopic.MatchString(topic), "topics[%d] must be 1-64 letters, digits, - and _", j)
|
||||
if first, dup := seen[topic]; dup {
|
||||
check(false, "topics[%d] repeats topics[%d]", j, first)
|
||||
continue
|
||||
}
|
||||
seen[topic] = j
|
||||
}
|
||||
|
||||
methods := 0
|
||||
for _, set := range []bool{s.Token != "", s.TokenFile != "", s.User != "" || s.PasswordFile != ""} {
|
||||
if set {
|
||||
methods++
|
||||
}
|
||||
}
|
||||
check(methods <= 1, "set at most one of token, token_file, or user with password_file")
|
||||
check((s.User == "") == (s.PasswordFile == ""), "user and password_file go together")
|
||||
|
||||
check(s.MinPriority >= 1 && s.MinPriority <= 5, "min_priority must be 1-5")
|
||||
check(s.BypassPriority >= 1 && s.BypassPriority <= 5, "bypass_priority must be 1-5")
|
||||
check(s.MaxBacklog > 0 && s.MaxBacklog <= MaxNtfyBacklog, "max_backlog must be more than 0 and at most %s", MaxNtfyBacklog)
|
||||
check(s.RateLimit >= 1 && s.RateLimit <= MaxNtfyRateLimit, "rate_limit must be 1-%d", MaxNtfyRateLimit)
|
||||
check(s.RateWindow > 0, "rate_window must be positive")
|
||||
check(s.Keepalive >= MinNtfyKeepalive && s.Keepalive <= MaxNtfyKeepalive,
|
||||
"keepalive must be %s-%s", MinNtfyKeepalive, MaxNtfyKeepalive)
|
||||
|
||||
if q := s.Quiet; q != nil {
|
||||
check(clock.MatchString(q.Start), "quiet.start: %q is not a time of day HH:MM", q.Start)
|
||||
check(clock.MatchString(q.End), "quiet.end: %q is not a time of day HH:MM", q.End)
|
||||
check(q.Start != q.End, "quiet: start and end are both %q; the window would be empty", q.Start)
|
||||
check(len(q.Days) > 0, "quiet.days: name at least one day")
|
||||
days := make(map[string]bool, len(q.Days))
|
||||
for _, day := range q.Days {
|
||||
check(slices.Contains(NtfyDays, day), "quiet.days: %q must be one of %s", day, strings.Join(NtfyDays, ", "))
|
||||
check(!days[day], "quiet.days: %q is given twice", day)
|
||||
days[day] = true
|
||||
}
|
||||
if q.Timezone != "" {
|
||||
_, err := time.LoadLocation(q.Timezone)
|
||||
check(err == nil, `quiet.timezone: %q is not a known time zone; use an IANA name such as "Europe/London", "UTC" or "Local"`, q.Timezone)
|
||||
}
|
||||
check(q.MinPriority >= 1 && q.MinPriority <= 5, "quiet.min_priority must be 1-5")
|
||||
check(slices.Contains(NtfyQuietActions, q.Action), "quiet.action: %q must be one of %s", q.Action, strings.Join(NtfyQuietActions, ", "))
|
||||
}
|
||||
}
|
||||
return 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
|
||||
|
||||
Reference in new issue
Block a user