package stage import ( "bytes" "context" "encoding/json" "fmt" "io" "maps" "mime" "net/http" "net/url" "os" "path/filepath" "regexp" "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": 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 } // PublishNtfy is shared by native delivery stages and stage notification hooks. // An empty filename publishes an event without an attachment. func PublishNtfy(ctx context.Context, destination, title, summary, filename string, data []byte) (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 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 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 }