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

+381
View File
@@ -0,0 +1,381 @@
package ntfy
import (
"context"
"fmt"
"slices"
"testing"
"testing/synctest"
"time"
)
// A flood larger than the 512 IDs kept at least, inside the overlap a
// reconnect replays, still prints once: every message a replay can send
// again is remembered. Once the cursor has moved on, the state keeps the
// last 512 only.
func TestFloodInTheOverlapPrintsOnce(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
f := newFakeServer()
h := &recorder{}
o := testOptions(f, t.TempDir())
s, stop := start(t, o, h)
defer stop()
synctest.Wait()
for i := range 600 {
f.publish(Message{Title: fmt.Sprintf("flood %d", i), RawPriority: 5})
}
synctest.Wait()
f.drop()
time.Sleep(10 * time.Second)
synctest.Wait()
if n := len(f.streams()); n != 2 {
t.Fatalf("%d stream requests, want a reconnect", n)
}
ids := h.printed()
slices.Sort(ids)
if len(ids) != 600 || len(slices.Compact(slices.Clone(ids))) != 600 {
t.Errorf("%d cards for 600 messages", len(ids))
}
if st := s.Status(); st.Printed != 600 {
t.Errorf("status %+v", st)
}
time.Sleep(10 * time.Minute)
synctest.Wait()
if st, err := loadState(o.StateFile); err != nil || len(st.Seen) != ringSize {
t.Errorf("state keeps %d IDs once the flood is out of reach, want %d (%v)", len(st.Seen), ringSize, err)
}
})
}
// A flood larger than the IDs the subscription keeps still prints once:
// when it forgets IDs a replay could send again, the next replay starts
// after them.
func TestFloodPastTheLimitPrintsOnce(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
f := newFakeServer()
h := &recorder{}
o := testOptions(f, t.TempDir())
s, err := New(o)
if err != nil {
t.Fatal(err)
}
s.seenLimit = 600
ctx, cancel := context.WithCancel(context.Background())
done := make(chan struct{})
go func() { defer close(done); _ = s.Run(ctx, h) }()
defer func() { cancel(); <-done }()
synctest.Wait()
for i := range 700 {
f.publish(Message{Title: fmt.Sprintf("flood %d", i), RawPriority: 5})
}
synctest.Wait()
f.drop()
time.Sleep(10 * time.Second)
synctest.Wait()
if n := len(f.streams()); n != 2 {
t.Fatalf("%d stream requests, want a reconnect", n)
}
if got := h.printed(); len(got) != 700 {
t.Errorf("%d cards for 700 messages", len(got))
}
after := f.publish(Message{Title: "after the flood", RawPriority: 5})
synctest.Wait()
if got := h.printed(); len(got) != 701 || got[700] != after.ID {
t.Errorf("%d cards; the message after the flood did not print once", len(got))
}
})
}
// After a first start, a reconnect does not reach back before it: a
// message published shortly before the start never prints.
func TestFirstStartFloor(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
f := newFakeServer()
before := f.publish(Message{Title: "a minute before the start"})
time.Sleep(time.Minute)
h := &recorder{}
o := testOptions(f, t.TempDir())
_, stop := start(t, o, h)
defer stop()
synctest.Wait()
started := time.Now().Unix()
time.Sleep(20 * time.Second)
f.drop()
time.Sleep(10 * time.Second)
synctest.Wait()
streams := f.streams()
if since, ok := sinceOf(t, streams[len(streams)-1]); !ok || since != started {
t.Errorf("since = %d, %v; want the start, %d", since, ok, started)
}
if got := h.printed(); slices.Contains(got, before.ID) {
t.Errorf("printed %v, a message from before the first start", got)
}
})
}
// max_backlog is measured by the server's clock: with the host's clock ten
// hours behind it, a ten-hour outage still replays only the last hour.
func TestBacklogUsesTheServerClock(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
f := newFakeServer()
f.skew = 10 * time.Hour
o := testOptions(f, t.TempDir())
serverNow := func() int64 { return time.Now().Add(f.skew).Unix() }
// The subscription last ran ten hours ago by the server's clock.
if err := saveState(o.StateFile, state{Cursor: serverNow() - 10*3600}); err != nil {
t.Fatal(err)
}
old := f.publish(Message{Title: "five hours ago", Time: serverNow() - 5*3600})
recent := f.publish(Message{Title: "half an hour ago", Time: serverNow() - 1800})
h := &recorder{}
_, stop := start(t, o, h)
defer stop()
synctest.Wait()
if got := h.printed(); !slices.Equal(got, []string{recent.ID}) || slices.Contains(got, old.ID) {
t.Errorf("printed %v, want only %v", got, recent.ID)
}
})
}
// max_backlog follows the stream's clock, the open event's time or else
// the answer's Date: with the host's clock hours ahead of or behind the
// server's, the host's clock never decides what a replay leaves out, and
// the floor never lands in the server's future. The credentials check
// fails here, which changes nothing, since it never tells the clock.
func TestBacklogFollowsTheStreamClock(t *testing.T) {
for _, tt := range []struct {
name string
skew time.Duration
noDate bool
}{
{"host 3 hours ahead", -3 * time.Hour, false},
{"host 10 hours behind", 10 * time.Hour, false},
{"host 10 hours behind, no Date", 10 * time.Hour, true},
} {
t.Run(tt.name, func(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
f := newFakeServer()
f.skew, f.authFails, f.noDate = tt.skew, true, tt.noDate
o := testOptions(f, t.TempDir())
serverNow := func() int64 { return time.Now().Add(f.skew).Unix() }
if err := saveState(o.StateFile, state{Cursor: serverNow() - 2*3600}); err != nil {
t.Fatal(err)
}
old := f.publish(Message{Title: "ninety minutes ago", Time: serverNow() - 5400})
recent := f.publish(Message{Title: "half an hour ago", Time: serverNow() - 1800})
h := &recorder{}
_, stop := start(t, o, h)
defer stop()
synctest.Wait()
if got := h.printed(); !slices.Equal(got, []string{recent.ID}) || slices.Contains(got, old.ID) {
t.Fatalf("printed %v, want only %v", got, recent.ID)
}
time.Sleep(10 * time.Minute)
f.drop()
synctest.Wait()
during := f.publish(Message{Title: "published while the stream was down"})
time.Sleep(10 * time.Second)
synctest.Wait()
if got := h.printed(); !slices.Contains(got, during.ID) {
t.Errorf("printed %v, want the message published during the outage", got)
}
stop()
if st, err := loadState(o.StateFile); err != nil || st.Floor > serverNow() {
t.Errorf("floor %d is in the server's future, now %d (%v)", st.Floor, serverNow(), err)
}
})
})
}
}
// A keepalive's time is not taken for the server's clock: it may have
// waited in the connection while the subscription paused.
func TestKeepaliveDoesNotSetTheClock(t *testing.T) {
f := newFakeServer()
s, err := New(testOptions(f, t.TempDir()))
if err != nil {
t.Fatal(err)
}
r := s.start(&recorder{})
r.conn = &conn{since: true}
now := time.Now()
r.message(context.Background(), Message{ID: "k", Event: EventKeepalive, Time: now.Unix() - 7200}, now, now)
if r.conn.clockKnown || r.conn.checked {
t.Errorf("a keepalive set the clock: %+v", r.conn)
}
r.message(context.Background(), Message{ID: "o", Event: EventOpen, Time: now.Unix() + 60}, now, now)
if !r.conn.clockKnown || r.conn.serverTime != now.Unix()+60 || !r.conn.checked {
t.Errorf("the open event did not set the clock: %+v", r.conn)
}
}
// MaxBacklog is measured from the connection's own clock and the time
// passed since it read it, never from a clock learned before: a stale one,
// as after the host's clock was stepped, neither loses messages nor
// prints old ones. The credentials check's Date here disagrees with the
// stream by hours.
func TestBacklogIgnoresAnEarlierClock(t *testing.T) {
for _, tt := range []struct {
name string
authSkew time.Duration
}{
{"earlier clock ahead", 9 * time.Hour},
{"earlier clock behind", -3 * time.Hour},
} {
t.Run(tt.name, func(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
f := newFakeServer()
f.authSkew = tt.authSkew
o := testOptions(f, t.TempDir())
if err := saveState(o.StateFile, state{Cursor: time.Now().Unix() - 2*3600}); err != nil {
t.Fatal(err)
}
old := f.publish(Message{Title: "ninety minutes ago", Time: time.Now().Unix() - 5400})
recent := f.publish(Message{Title: "half an hour ago", Time: time.Now().Unix() - 1800})
h := &recorder{}
_, stop := start(t, o, h)
defer stop()
synctest.Wait()
if since, ok := sinceOf(t, f.streams()[0]); !ok || since != time.Now().Unix()-2*3600-120 {
t.Errorf("since = %d, %v; want the cursor less the slack, unclamped", since, ok)
}
if got := h.printed(); !slices.Equal(got, []string{recent.ID}) || slices.Contains(got, old.ID) {
t.Fatalf("printed %v, want only %v", got, recent.ID)
}
time.Sleep(10 * time.Minute)
f.drop()
synctest.Wait()
during := f.publish(Message{Title: "published while the stream was down"})
time.Sleep(10 * time.Second)
synctest.Wait()
if got := h.printed(); !slices.Contains(got, during.ID) {
t.Errorf("printed %v, want the message published during the outage", got)
}
stop()
if st, err := loadState(o.StateFile); err != nil || st.Floor > time.Now().Unix() {
t.Errorf("floor %d is in the server's future (%v)", st.Floor, err)
}
})
})
}
}
// ntfy's open event tells the clock, not the answer's Date, which a proxy
// in front of ntfy may write from a clock of its own: with the proxy hours
// off, the backlog is still exact, nothing new is left out and the floor
// is never in ntfy's future.
func TestBacklogPrefersTheOpenEvent(t *testing.T) {
for _, tt := range []struct {
name string
dateSkew time.Duration
}{
{"proxy 2 hours ahead", 2 * time.Hour},
{"proxy 3 hours behind", -3 * time.Hour},
} {
t.Run(tt.name, func(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
f := newFakeServer()
f.dateSkew = tt.dateSkew
o := testOptions(f, t.TempDir())
if err := saveState(o.StateFile, state{Cursor: time.Now().Unix() - 2*3600}); err != nil {
t.Fatal(err)
}
old := f.publish(Message{Title: "ninety minutes ago", Time: time.Now().Unix() - 5400})
recent := f.publish(Message{Title: "half an hour ago", Time: time.Now().Unix() - 1800})
h := &recorder{}
_, stop := start(t, o, h)
defer stop()
synctest.Wait()
if got := h.printed(); !slices.Equal(got, []string{recent.ID}) || slices.Contains(got, old.ID) {
t.Fatalf("printed %v, want only %v", got, recent.ID)
}
live := f.publish(Message{Title: "live"})
synctest.Wait()
time.Sleep(10 * time.Minute)
f.drop()
synctest.Wait()
during := f.publish(Message{Title: "published while the stream was down"})
time.Sleep(10 * time.Second)
synctest.Wait()
if got := h.printed(); !slices.Contains(got, live.ID) || !slices.Contains(got, during.ID) {
t.Errorf("printed %v, want the live message and the one from the outage", got)
}
stop()
if st, err := loadState(o.StateFile); err != nil || st.Floor > time.Now().Unix() {
t.Errorf("floor %d is in ntfy's future (%v)", st.Floor, err)
}
})
})
}
}
// The stream answer's Date alone tells the clock when the open event
// carries no time.
func TestBacklogFromTheDate(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
f := newFakeServer()
f.skew, f.openNoTime = 10*time.Hour, true
o := testOptions(f, t.TempDir())
serverNow := func() int64 { return time.Now().Add(f.skew).Unix() }
if err := saveState(o.StateFile, state{Cursor: serverNow() - 10*3600}); err != nil {
t.Fatal(err)
}
old := f.publish(Message{Title: "five hours ago", Time: serverNow() - 5*3600})
recent := f.publish(Message{Title: "half an hour ago", Time: serverNow() - 1800})
h := &recorder{}
_, stop := start(t, o, h)
defer stop()
synctest.Wait()
if got := h.printed(); !slices.Equal(got, []string{recent.ID}) || slices.Contains(got, old.ID) {
t.Errorf("printed %v, want only %v", got, recent.ID)
}
})
}
// Only a message that got a row on a digest counts as printed: one held
// past the 50 rows is only counted, so a later message of its sequence is
// not marked as an update.
func TestHeldPastTheRowsIsNotPrinted(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
f := newFakeServer()
h := &recorder{}
o := testOptions(f, t.TempDir())
o.RateLimit = 1
_, stop := start(t, o, h)
defer stop()
synctest.Wait()
f.publish(Message{Title: "takes the budget"})
for i := range MaxDigestRows + 1 {
f.publish(Message{Title: fmt.Sprintf("held %d", i), SequenceID: fmt.Sprintf("seq-%d", i)})
}
time.Sleep(o.RateWindow + time.Second)
synctest.Wait()
if ds := h.digestList(); len(ds) != 1 || ds[0].Count != MaxDigestRows+1 {
t.Fatalf("digests %+v", ds)
}
time.Sleep(o.RateWindow)
f.publish(Message{Title: "update of a row", SequenceID: "seq-0"})
time.Sleep(o.RateWindow)
f.publish(Message{Title: "update of a counted one", SequenceID: fmt.Sprintf("seq-%d", MaxDigestRows)})
synctest.Wait()
cards := h.cardList()
if len(cards) != 3 {
t.Fatalf("%d cards, want 3", len(cards))
}
if !cards[1].updated || cards[2].updated {
t.Errorf("updated = %v and %v; want only the update of a row marked", cards[1].updated, cards[2].updated)
}
})
}