Add ntfy subscriptions with digests, quiet hours and a cut feed
Security / Vulnerability check (push) Successful in 40s
Test / Lint and test (push) Failing after 6m43s

[[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:
57_WolveandClaude Opus 5.5 committed 2026-11-30 17:50:23 -06:00
1 parent 1335ed0687
commit fb76284129
52 files changed
+6464 -390

No files matched your search

+262
View File
@@ -0,0 +1,262 @@
package ntfy
import (
"encoding/json"
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
"runtime"
"time"
)
// ringSize is how many printed sequences a subscription remembers, and how
// many message IDs it keeps at least.
const ringSize = 512
// maxSeen caps the message IDs a subscription keeps, so that a flood
// cannot grow its state without bound.
const maxSeen = 20000
// stateVersion is the version of the state file's format.
const stateVersion = 1
// state is what a subscription keeps across restarts.
type state struct {
Version int `json:"version"`
// Cursor is the newest ntfy server time the subscription has dealt
// with, in Unix seconds; 0 when it has none.
Cursor int64 `json:"cursor"`
// Floor is the earliest server time a replay may start at, in Unix
// seconds: where a first start began, or where max_backlog last cut a
// replay short.
Floor int64 `json:"floor,omitempty"`
// Seen are the messages dealt with that a replay could send again,
// and at least the last ringSize, oldest first.
Seen []seenID `json:"seen"`
// Printed are the sequences of the last messages printed, on a card or
// a digest, oldest first.
Printed []string `json:"printed"`
// Prints are the times of the receipts in the paper budget, in Unix
// seconds.
Prints []int64 `json:"prints,omitempty"`
// Held are the messages waiting for the next digest.
Held *held `json:"held,omitempty"`
}
// loadState reads the state file at path. A file that does not exist
// gives an empty state. A file that cannot be read or parsed also gives an
// empty state, with the error saying why, for the caller to warn about.
func loadState(path string) (state, error) {
data, err := os.ReadFile(path)
if errors.Is(err, fs.ErrNotExist) {
return state{}, nil
}
if err != nil {
return state{}, err
}
var st state
if err := json.Unmarshal(data, &st); err != nil {
return state{}, fmt.Errorf("parsing %s: %w", path, err)
}
if st.Version != stateVersion {
return state{}, fmt.Errorf("%s has version %d, want %d", path, st.Version, stateVersion)
}
if st.Held != nil && len(st.Held.Rows) > MaxDigestRows {
st.Held.Rows = st.Held.Rows[:MaxDigestRows]
}
return st, nil
}
// saveState writes st to path atomically: to a temporary file in the same
// directory, synced to disk, then renamed over path. A crash leaves the
// old file or the new one, never part of either.
func saveState(path string, st state) error {
st.Version = stateVersion
data, err := json.Marshal(st)
if err != nil {
return err
}
dir := filepath.Dir(path)
// CreateTemp makes the file readable by its owner only: held messages
// carry titles.
f, err := os.CreateTemp(dir, filepath.Base(path)+".*.tmp")
if err != nil {
return err
}
tmp := f.Name()
_, err = f.Write(data)
if err == nil {
err = f.Sync()
}
if closeErr := f.Close(); err == nil {
err = closeErr
}
if err == nil {
err = os.Rename(tmp, path)
}
if err != nil {
_ = os.Remove(tmp)
return err
}
syncDir(dir)
return nil
}
// syncDir makes a rename in dir durable. Windows cannot open a directory
// to sync it, and its renames need no such step.
func syncDir(dir string) {
if runtime.GOOS == "windows" {
return
}
d, err := os.Open(dir)
if err != nil {
return
}
_ = d.Sync()
_ = d.Close()
}
// seenID is a message dealt with: its ID and its server time.
type seenID struct {
ID string `json:"id"`
Time int64 `json:"time"`
}
// seenSet holds the IDs of the messages dealt with, so that a message a
// replay sends again is dropped. It keeps the messages a replay could
// send, those dated at or after where a replay can start, and at least
// the last ringSize, up to limit in all.
type seenSet struct {
items []seenID
counts map[string]int
limit int
}
// newSeenSet returns a set of at most limit items holding items, oldest
// first.
func newSeenSet(items []seenID, limit int) *seenSet {
s := &seenSet{counts: make(map[string]int), limit: limit}
for _, it := range items {
s.add(it.ID, it.Time)
}
return s
}
// add records the message id of server time t. When the set is full, it
// forgets the oldest, and returns the latest server time among them, for
// the caller to keep a replay from sending them again; otherwise 0.
func (s *seenSet) add(id string, t int64) int64 {
s.items = append(s.items, seenID{ID: id, Time: t})
s.counts[id]++
extra := len(s.items) - s.limit
if extra <= 0 {
return 0
}
var latest int64
for _, it := range s.items[:extra] {
latest = max(latest, it.Time)
}
s.drop(s.items[:extra])
s.items = s.items[extra:]
return latest
}
// has reports whether id was dealt with.
func (s *seenSet) has(id string) bool {
return s.counts[id] > 0
}
// prune forgets the messages dated before start, the earliest time a
// replay can start at, apart from the last ringSize.
func (s *seenSet) prune(start int64) {
keepFrom := len(s.items) - ringSize
kept := s.items[:0]
for i, it := range s.items {
if i >= keepFrom || it.Time >= start {
kept = append(kept, it)
continue
}
s.drop([]seenID{it})
}
clear(s.items[len(kept):])
s.items = kept
}
func (s *seenSet) drop(items []seenID) {
for _, it := range items {
if s.counts[it.ID]--; s.counts[it.ID] <= 0 {
delete(s.counts, it.ID)
}
}
}
// list returns the items, oldest first.
func (s *seenSet) list() []seenID {
return append([]seenID(nil), s.items...)
}
// ring remembers the last ringSize strings added to it.
type ring struct {
items []string
counts map[string]int
}
// newRing returns a ring holding items, oldest first; only the last
// ringSize are kept.
func newRing(items []string) *ring {
r := &ring{counts: make(map[string]int)}
for _, s := range items {
r.add(s)
}
return r
}
// add remembers s, forgetting the oldest item when the ring is full. An
// item may be added more than once.
func (r *ring) add(s string) {
if len(r.items) == ringSize {
oldest := r.items[0]
r.items = r.items[1:]
if r.counts[oldest]--; r.counts[oldest] == 0 {
delete(r.counts, oldest)
}
}
r.items = append(r.items, s)
r.counts[s]++
}
// has reports whether s is remembered.
func (r *ring) has(s string) bool {
return r.counts[s] > 0
}
// list returns the items, oldest first.
func (r *ring) list() []string {
return append([]string(nil), r.items...)
}
// unixTimes returns ts in Unix seconds.
func unixTimes(ts []time.Time) []int64 {
out := make([]int64, len(ts))
for i, t := range ts {
out[i] = t.Unix()
}
return out
}
// fromUnix returns ts, in Unix seconds, as times.
func fromUnix(ts []int64) []time.Time {
out := make([]time.Time, len(ts))
for i, t := range ts {
out[i] = time.Unix(t, 0)
}
return out
}