Files
pipelines/internal/stage/ntfy.go
T
alan ed9072b79a Claude accounts: switch a chat refused for usage to another saved account and continue it
When Claude Code refuses an operator chat's turn for a usage limit, the
server marks the refused account until its reset and, if the chat's Claude
home allows it (claude_account_auto_switch / `pipelines claude-account auto
on|off`, on by default, kept in pipelines-accounts/settings.json), switches
the home to the saved account with the most usage left through the
claude_account_use path. Switches of one home are serialized, so chats
refused together switch once. Each refused chat gets one queued prompt,
marked as sent automatically, that asks the agent to check it is on track
before continuing; the app's auto-continue-at-reset prompt for the refusal is
removed (and refused if it arrives later), and the operator gets a
low-priority notification.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 00:23:43 +00:00

284 lines
11 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
}
// 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")
}
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 nil, fmt.Errorf("configure only one ntfy token source")
}
file, err := os.Open(path)
if err != nil {
return nil, fmt.Errorf("cannot read ntfy token file")
}
contents, err := io.ReadAll(io.LimitReader(file, 4097))
file.Close()
if err != nil || len(contents) > 4096 {
return nil, fmt.Errorf("invalid ntfy token file")
}
token = strings.TrimSpace(string(contents))
if token == "" {
return nil, 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 nil, 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 nil, fmt.Errorf("invalid ntfy token configuration")
}
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 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
}
// 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
}