Files
pipelines/internal/stage/ntfy.go
T
alan b91ef04ab0 Notifications: agent notify reaches every device and clears everywhere
- Server: chat ntfy messages carry a sequence id derived from their app id;
  clearing a chat app notification also clears it in ntfy (PUT
  /<topic>/<seq>/clear, verified on ntfy v2.38.1).
- Server: a turn that sent an agent notify does not also send chat_reply.
- notify tool and MCP instructions: Pipelines already notifies at reply end
  and for questions/approvals; notify is for mid-turn or background news.
- Shown notify items carry channels (apps/phone); the transcript row says
  where it went.
- App: NotificationBridge.close(tag); web closes tracked Notifications and
  tells other tabs over a BroadcastChannel; native bridge cancels by tag and
  now supports macOS. AgentNotices closes on notifications_cleared and on
  resubscribe cleared ids, and a tap sends clear_notifications.
- Docs: skill, chat reference, ntfy/notifications docs, app note.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 19:49:31 +00:00

351 lines
13 KiB
Go

package stage
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"maps"
"mime"
"net/http"
"net/url"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"time"
"unicode/utf8"
)
const NtfyType = "ntfy"
var destinationName = regexp.MustCompile(`^[a-z][a-z0-9_]{0,63}$`)
var ntfyMessageID = regexp.MustCompile(`^[A-Za-z0-9_-]{1,128}$`)
var ntfyTopic = regexp.MustCompile(`^[-_A-Za-z0-9]{1,64}$`)
var ntfyTokenValue = regexp.MustCompile(`^[A-Za-z0-9_-]+$`)
// NtfyStage publishes to an operator-configured destination. Tokens never enter
// stage prompts, definitions, output maps, or diagnostics. No automatic retries:
// an ambiguous network failure may already have delivered the notification.
type NtfyStage struct{}
func (NtfyStage) Validate(def Definition) error {
if def.Type != NtfyType {
return fmt.Errorf("expected ntfy stage")
}
for name := range def.Blocks {
switch name {
case "configs", "edges", "output":
case "skills":
return errSkillsModelOnly("ntfy")
default:
return fmt.Errorf("unexpected block %q for ntfy stage", name)
}
}
for key := range def.Configs {
if key != "destination" && key != "timeout" {
return fmt.Errorf("unknown ntfy config %q", key)
}
}
if _, err := StageTimeout(def); err != nil {
return err
}
if !destinationName.MatchString(def.Configs["destination"]) {
return fmt.Errorf("ntfy destination must be a lowercase name containing letters, digits, or underscores")
}
if def.Edges["success"] == "" {
return fmt.Errorf("ntfy stage requires a success outcome")
}
return nil
}
func (NtfyStage) Run(ctx context.Context, def Definition, input Values) (Result, error) {
if err := (NtfyStage{}).Validate(def); err != nil {
return Result{}, err
}
timeout, _ := StageTimeout(def)
ctx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
title, _ := input["title"].(string)
summary, _ := input["summary"].(string)
markdown, _ := input["markdown"].(string)
for name, text := range map[string]string{"title": title, "summary": summary, "markdown": markdown} {
if strings.TrimSpace(text) == "" || !utf8.ValidString(text) || strings.ContainsRune(text, '\x00') {
return Result{}, fmt.Errorf("ntfy input.%s must be a nonempty UTF-8 string", name)
}
}
if len(title) > 256 || len(summary) > 2048 || len(markdown) > 1<<20 {
return Result{}, fmt.Errorf("ntfy input exceeds limits (title 256 bytes, summary 2048 bytes, markdown 1 MiB)")
}
if strings.ContainsAny(title, "\r\n") || strings.ContainsAny(summary, "\r\n") {
return Result{}, fmt.Errorf("ntfy title and summary must be single-line strings")
}
delivery, err := PublishNtfy(ctx, def.Configs["destination"], title, summary, "digest.md", []byte(markdown), "")
if err != nil {
return Result{}, err
}
output := maps.Clone(input)
output["delivery"] = delivery
return Result{Outcome: "success", Output: output}, nil
}
type ntfyPriorityKey struct{}
// WithNtfyPriority makes PublishNtfy calls under ctx send ntfy priority
// (1 min to 5 max); without it ntfy uses its default, 3.
func WithNtfyPriority(ctx context.Context, priority int) context.Context {
return context.WithValue(ctx, ntfyPriorityKey{}, priority)
}
// NtfyPriority is the priority WithNtfyPriority set on ctx, 0 when none.
func NtfyPriority(ctx context.Context) int {
priority, _ := ctx.Value(ntfyPriorityKey{}).(int)
return priority
}
type ntfySequenceKey struct{}
// ntfySequenceID is the form of a sequence id this package sends: ntfy
// accepts the same characters as a topic name.
var ntfySequenceID = regexp.MustCompile(`^[-_A-Za-z0-9]{1,64}$`)
// WithNtfySequenceID makes PublishNtfy calls under ctx publish with ntfy
// sequence id sequence (X-Sequence-ID), so ClearNtfy can later dismiss the
// message on every subscribed client. An invalid id is ignored.
func WithNtfySequenceID(ctx context.Context, sequence string) context.Context {
return context.WithValue(ctx, ntfySequenceKey{}, sequence)
}
// NtfySequence is the sequence id WithNtfySequenceID set on ctx, "" when none.
func NtfySequence(ctx context.Context) string {
sequence, _ := ctx.Value(ntfySequenceKey{}).(string)
return sequence
}
// ClearNtfy marks the messages published with sequence id sequence on
// destination as read: ntfy (v2.15+) emits a message_clear event and its
// Android and web clients dismiss the notification. Clearing an unknown
// sequence id is harmless (ntfy still answers 200).
func ClearNtfy(ctx context.Context, destination, sequence string) error {
if !destinationName.MatchString(destination) || !ntfySequenceID.MatchString(sequence) {
return fmt.Errorf("invalid ntfy clear request")
}
endpoint, token, err := ntfyConnection(destination)
if err != nil {
return err
}
request, err := http.NewRequestWithContext(ctx, http.MethodPut, strings.TrimSuffix(endpoint, "/")+"/"+sequence+"/clear", nil)
if err != nil {
return fmt.Errorf("cannot create ntfy request")
}
if token != "" {
request.Header.Set("Authorization", "Bearer "+token)
}
client := &http.Client{Timeout: 20 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
response, err := client.Do(request)
if err != nil {
if ctx.Err() != nil {
return ctx.Err()
}
return fmt.Errorf("ntfy clear unconfirmed")
}
defer response.Body.Close()
_, _ = io.Copy(io.Discard, io.LimitReader(response.Body, 64<<10))
if response.StatusCode < 200 || response.StatusCode >= 300 {
return fmt.Errorf("ntfy clear returned HTTP %d", response.StatusCode)
}
return nil
}
// PublishNtfy is shared by native delivery stages and stage notification hooks.
// An empty filename publishes an event without an attachment. A non-empty click
// is an optional ntfy Click action (an absolute URL) so a tap on the notification
// opens the destination the operator should act on; it is validated here and
// never carries credentials. Optional views add ntfy "view" action buttons (for
// example "Open in browser"); each is validated as strictly as the click.
func PublishNtfy(ctx context.Context, destination, title, summary, filename string, data []byte, click string, views ...NtfyView) (Values, error) {
if !destinationName.MatchString(destination) || strings.TrimSpace(title) == "" || strings.TrimSpace(summary) == "" || len(title) > 256 || len(summary) > 2048 || !utf8.ValidString(title) || !utf8.ValidString(summary) || strings.ContainsAny(title+summary, "\r\n\x00") {
return nil, fmt.Errorf("invalid ntfy notification metadata")
}
if !ValidNtfyClick(click) {
return nil, fmt.Errorf("invalid ntfy click action")
}
actions, err := ntfyViewActions(views)
if err != nil {
return nil, err
}
if len(data) > 1<<20 || (filename != "" && (filename != filepath.Base(filename) || filename == "." || strings.ContainsAny(filename, "/\\\r\n\x00") || len(filename) > 200)) {
return nil, fmt.Errorf("invalid ntfy attachment")
}
endpoint, token, err := ntfyConnection(destination)
if err != nil {
return nil, err
}
method := http.MethodPut
if filename == "" {
method = http.MethodPost
data = []byte(summary)
}
request, err := http.NewRequestWithContext(ctx, method, endpoint, bytes.NewReader(data))
if err != nil {
return nil, fmt.Errorf("cannot create ntfy request")
}
request.Header.Set("Content-Type", "application/octet-stream")
if filename == "" {
request.Header.Set("Content-Type", "text/plain; charset=utf-8")
} else if strings.HasSuffix(filename, ".md") {
request.Header.Set("Content-Type", "text/markdown; charset=utf-8")
}
request.Header.Set("Title", mime.BEncoding.Encode("utf-8", title))
request.Header.Set("Message", mime.BEncoding.Encode("utf-8", summary))
if click != "" {
request.Header.Set("Click", click)
}
if priority, ok := ctx.Value(ntfyPriorityKey{}).(int); ok && priority >= 1 && priority <= 5 {
request.Header.Set("Priority", strconv.Itoa(priority))
}
if sequence, ok := ctx.Value(ntfySequenceKey{}).(string); ok && ntfySequenceID.MatchString(sequence) {
request.Header.Set("X-Sequence-ID", sequence)
}
if actions != "" {
request.Header.Set("Actions", actions)
}
if filename != "" {
request.Header.Set("Filename", mime.BEncoding.Encode("utf-8", filename))
}
if strings.HasSuffix(filename, ".md") {
request.Header.Set("Markdown", "yes")
}
if token != "" {
request.Header.Set("Authorization", "Bearer "+token)
}
client := &http.Client{Timeout: 20 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
response, err := client.Do(request)
if err != nil {
if ctx.Err() != nil {
return nil, ctx.Err()
}
return nil, fmt.Errorf("ntfy delivery unconfirmed; inspect destination before retrying")
}
defer response.Body.Close()
if response.StatusCode < 200 || response.StatusCode >= 300 {
return nil, fmt.Errorf("ntfy publish returned HTTP %d; delivery not confirmed", response.StatusCode)
}
body, err := io.ReadAll(io.LimitReader(response.Body, (64<<10)+1))
if err != nil || len(body) > 64<<10 {
return nil, fmt.Errorf("ntfy acknowledgment unreadable; inspect destination before retrying")
}
var ack struct {
ID string `json:"id"`
Event string `json:"event"`
Attachment struct {
URL string `json:"url"`
Name string `json:"name"`
} `json:"attachment"`
}
if json.Unmarshal(body, &ack) != nil || !ntfyMessageID.MatchString(ack.ID) || ack.Event != "message" || (filename != "" && ack.Attachment.Name != filename) {
return nil, fmt.Errorf("ntfy acknowledgment invalid or missing attachment; inspect destination before retrying")
}
if filename != "" {
attachment, err := url.Parse(ack.Attachment.URL)
if err != nil || attachment.Hostname() == "" || (attachment.Scheme != "http" && attachment.Scheme != "https") || attachment.User != nil {
return nil, fmt.Errorf("ntfy acknowledgment has no valid attachment URL; inspect destination before retrying")
}
}
return Values{"destination": destination, "message_id": ack.ID, "attachment_url": ack.Attachment.URL, "filename": filename}, nil
}
// ntfyConnection resolves destination's topic URL and token from the
// environment ("system" reads PIPELINES_NTFY_URL and its token).
func ntfyConnection(destination string) (string, string, error) {
prefix := "PIPELINES_NTFY_" + strings.ToUpper(destination)
if destination == "system" {
prefix = "PIPELINES_NTFY"
}
endpoint := os.Getenv(prefix + "_URL")
token := os.Getenv(prefix + "_TOKEN")
if path := os.Getenv(prefix + "_TOKEN_FILE"); path != "" {
if token != "" {
return "", "", fmt.Errorf("configure only one ntfy token source")
}
file, err := os.Open(path)
if err != nil {
return "", "", fmt.Errorf("cannot read ntfy token file")
}
contents, err := io.ReadAll(io.LimitReader(file, 4097))
file.Close()
if err != nil || len(contents) > 4096 {
return "", "", fmt.Errorf("invalid ntfy token file")
}
token = strings.TrimSpace(string(contents))
if token == "" {
return "", "", fmt.Errorf("ntfy token file is empty")
}
}
u, err := url.Parse(endpoint)
if err != nil || u.Hostname() == "" || (u.Scheme != "http" && u.Scheme != "https") || u.User != nil || u.RawQuery != "" || u.Fragment != "" || !ntfyTopic.MatchString(strings.TrimPrefix(u.Path, "/")) || u.RawPath != "" {
return "", "", fmt.Errorf("configure %s_URL with an HTTP(S) ntfy topic URL (no credentials or query)", prefix)
}
if token != "" && (len(token) > 4096 || !ntfyTokenValue.MatchString(token)) {
return "", "", fmt.Errorf("invalid ntfy token configuration")
}
return endpoint, token, nil
}
// ValidNtfyClick accepts an empty click or an absolute URL the ntfy server will
// hand to the operating system on tap: a scheme, no credentials, no fragment,
// no control characters and a bounded length. The value is an operator-visible
// deep link, never a place to smuggle a token.
func ValidNtfyClick(click string) bool {
if click == "" {
return true
}
if len(click) > 2048 || !utf8.ValidString(click) || strings.ContainsAny(click, "\r\n\t\x00 ") {
return false
}
u, err := url.Parse(click)
return err == nil && u.Scheme != "" && u.User == nil && u.Fragment == ""
}
// NtfyView is one ntfy "view" action button: a tap opens URL. Label is short
// printable ASCII and URL is an absolute HTTP(S) address without credentials.
type NtfyView struct {
Label string
URL string
}
// ntfyViewActions renders views in ntfy's simple Actions header format
// ("view, <label>, <url>", separated by "; "). Commas, semicolons and quotes are
// rejected rather than escaped, so a value can never split into another action.
func ntfyViewActions(views []NtfyView) (string, error) {
if len(views) > 3 { // ntfy allows at most three actions.
return "", fmt.Errorf("at most 3 ntfy actions")
}
parts := make([]string, 0, len(views))
for _, view := range views {
label := strings.TrimSpace(view.Label)
if label == "" || len(label) > 64 || strings.ContainsAny(label, ",;\"'\\=") || !printableASCII(label) {
return "", fmt.Errorf("invalid ntfy action label")
}
if view.URL == "" || !ValidNtfyClick(view.URL) || strings.ContainsAny(view.URL, ",;\"'\\") || !printableASCII(view.URL) {
return "", fmt.Errorf("invalid ntfy action URL")
}
if u, err := url.Parse(view.URL); err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Hostname() == "" {
return "", fmt.Errorf("invalid ntfy action URL")
}
parts = append(parts, "view, "+label+", "+view.URL)
}
return strings.Join(parts, "; "), nil
}
func printableASCII(text string) bool {
for i := 0; i < len(text); i++ {
if text[i] < 0x20 || text[i] > 0x7e {
return false
}
}
return true
}