890d267c71
Nothing told the operator that a run was waiting for a person or had failed; they found out by going looking. A run that needs attention now reaches the ntfy they already run, and the app answers "what needs me now" in one live, ordered surface. Server (smallest change, reusing the existing publisher): - internal/server/notify.go adds notifyRun, called from finishRunState (failed) and when a run parks on a human (runner.go runLoop). It publishes to the same already-configured `system` destination through the unchanged stage.PublishNtfy, so there is no second publisher, topic or service and the token handling is the stage's own. runAttentionEvent maps only waiting and failed; queued, running, succeeded, canceled and interrupted publish nothing. - No storms: runner.attentionSent records sequence:event per run before publishing, so a run that stays waiting is never republished on a re-request or restart, and a stage notify policy that already covers the same event marks it first so the run-level default is suppressed. The set is dropped when the run is terminal. A delivery failure is logged, never fails the run, and is not retried. - The payload names the run and pipeline and carries a click action pipelines://run/<id> (validated: absolute URL, no userinfo, no fragment, no credentials). PublishNtfy gained the optional click parameter; existing callers pass "". App: - AndroidManifest/MainActivity declare the pipelines://run/<id> deep link (singleTop); runIdFromDeepLink parses it and PipelinesApp opens that run once, clearing the link. It opens a run; it starts nothing. - ui/Attention.kt is the pure model (status -> Decision/Failed/Finished or nothing, ordered by kind then newest-first) and ui/components/AttentionSurface.kt is the floating indicator plus bottom sheet. It is derived from the same run events the server already pushes, so an entry appears with no refresh and clears when resolved; a finished run clears once looked at, and any entry can be dismissed, persisted in SettingsRepository. The existing destinations, pill and bottom strip are untouched and no competing navigation surface is added. Checked before committing: - Packaged authoring skill references: internal/author/skill/references/ notifications.md documents the automatic run-attention notifications and the app surface. The only packaged "template" carrying notify is that reference; no pipeline definition template exists to update and install.go's managed file list is unchanged (notifications.md already existed). - Repository guidelines: docs/ntfy.md gains an "Automatic run-attention notifications" section and no longer claims "No block means no notifications"; the top-level README phone-notifications note now says a waiting/failed run notifies automatically; android/README.md gains the dated feature section and supersedes the previous section's note that the attention surface was absent. - docker.md, install docs and the CLI/TUI docs describe mechanisms this change does not alter; left as they are. Tests: go test ./internal/server/... ./internal/stage/... ./internal/author/... all ok; notify_test.go covers the event mapping and the real HTTP delivery (destination, topic, click, no duplicate). Android :app:testDebugUnitTest -> BUILD SUCCESSFUL, 58 suites / 531 tests / 0 failures (new AttentionTest, 13 cases, covering ordering, appearing from a push, clearing on resolution, dismissal, the empty case, persistence and the deep link). Device screenshots and the phone's own notification are visual review's per the brief's device policy. Scope: android/ plus the smallest server change; no new dependency, no run started from the app, no installer or Docker change.
216 lines
8.3 KiB
Go
216 lines
8.3 KiB
Go
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. 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.
|
|
func PublishNtfy(ctx context.Context, destination, title, summary, filename string, data []byte, click string) (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")
|
|
}
|
|
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 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 == ""
|
|
}
|