From f5f31b7bcd94087cb8f6159896c7d426f0b6c4bb Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 2 Dec 2026 12:20:22 +0000 Subject: [PATCH] Notify link=: a stage's public/ file sets the phone tap target A stage's notify block may name `link=` (validated like `open=`). When the hook fires, the newest public/ match is read (at most 4 KiB); its first non-empty line, if an absolute http(s) URL ntfy accepts as a click, becomes the ntfy Click and the app notification click, with the run kept as the app's run action and ntfy's browser view. A missing file or invalid URL keeps today's tap target and is noted on the receipt diagnostic. Android opens such an http(s) click in the browser (after clearing the notification) instead of handing it to Flutter as a route. --- .../net/awan/pipelines_app/MainActivity.kt | 22 +++- .../notify/NotificationPresenter.kt | 16 ++- .../notify/NotificationProtocolTest.kt | 14 ++ internal/author/skill/references/format.md | 7 +- .../author/skill/references/notifications.md | 12 ++ internal/pipeline/notify.go | 40 ++++-- internal/pipeline/notify_test.go | 8 +- internal/protocol/message.go | 2 + internal/server/notify.go | 84 +++++++----- internal/server/notify_link.go | 74 +++++++++++ internal/server/notify_link_test.go | 123 ++++++++++++++++++ internal/stage/ntfy.go | 8 +- 12 files changed, 355 insertions(+), 55 deletions(-) create mode 100644 internal/server/notify_link.go create mode 100644 internal/server/notify_link_test.go diff --git a/app/android/app/src/main/kotlin/net/awan/pipelines_app/MainActivity.kt b/app/android/app/src/main/kotlin/net/awan/pipelines_app/MainActivity.kt index c6775da1..ff6d5f59 100644 --- a/app/android/app/src/main/kotlin/net/awan/pipelines_app/MainActivity.kt +++ b/app/android/app/src/main/kotlin/net/awan/pipelines_app/MainActivity.kt @@ -1,6 +1,8 @@ package net.awan.pipelines_app +import android.content.ActivityNotFoundException import android.content.Intent +import android.net.Uri import android.os.Bundle import io.flutter.embedding.android.FlutterActivity import io.flutter.embedding.engine.FlutterEngine @@ -24,12 +26,16 @@ class MainActivity : FlutterActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) - if (savedInstanceState == null) clearOpenedNotification(intent) + if (savedInstanceState == null) { + clearOpenedNotification(intent) + openExternalLink(intent) + } } override fun onNewIntent(intent: Intent) { super.onNewIntent(intent) clearOpenedNotification(intent) + openExternalLink(intent) } /** @@ -41,4 +47,18 @@ class MainActivity : FlutterActivity() { intent.removeExtra(NotificationPresenter.EXTRA_NOTIFICATION_ID) NotificationDismissReceiver.queueClear(this, id) } + + /** + * A notification whose click is an http(s) page (a stage's `link=`, such + * as a published doc) opens it in the browser rather than as an app route. + */ + private fun openExternalLink(intent: Intent?) { + val link = intent?.getStringExtra(NotificationPresenter.EXTRA_EXTERNAL_LINK) ?: return + intent.removeExtra(NotificationPresenter.EXTRA_EXTERNAL_LINK) + try { + startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(link)).addCategory(Intent.CATEGORY_BROWSABLE)) + } catch (_: ActivityNotFoundException) { + // No browser: the app stays open where the tap left it. + } + } } diff --git a/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/NotificationPresenter.kt b/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/NotificationPresenter.kt index 36268065..044a9045 100644 --- a/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/NotificationPresenter.kt +++ b/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/NotificationPresenter.kt @@ -17,6 +17,8 @@ data class NotificationIntentSpec( val ids: String, val action: String?, val data: String?, + /** An http(s) page (a stage's `link=`) MainActivity opens in the browser. */ + val externalLink: String? = null, ) /** @@ -24,8 +26,9 @@ data class NotificationIntentSpec( * conversation notification with the latest artifact preview and unread count, * keyed by its server group. Thread notifications share a * group per namespace, so Android bundles them under a summary ("N chats", - * "N runs"). A tap opens the app at the `click` deep link and clears the - * thread; a dismissal is reported back so the server clears it everywhere. + * "N runs"). A tap opens the app at the `click` deep link (or an http(s) + * click in the browser) and clears the thread; a dismissal is reported back so + * the server clears it everywhere. */ class NotificationPresenter(private val context: Context) { private val manager = context.getSystemService(NotificationManager::class.java) @@ -219,6 +222,8 @@ class NotificationPresenter(private val context: Context) { Intent.FLAG_ACTIVITY_CLEAR_TOP, ) if (spec.action != null) intent.setAction(spec.action).setData(Uri.parse(spec.data)) + // Not intent data: Flutter would route it as an app location. + if (spec.externalLink != null) intent.putExtra(EXTRA_EXTERNAL_LINK, spec.externalLink) return PendingIntent.getActivity( context, requestCode, @@ -280,11 +285,14 @@ class NotificationPresenter(private val context: Context) { /** Builds the deep-link portion of a tray tap without requiring Android Context. */ fun notificationIntent(ids: List, click: String): NotificationIntentSpec { val link = notificationLink(click) - val appLink = link.substringBefore(":", "") == "pipelines" + val scheme = link.substringBefore(":", "") + val appLink = scheme == "pipelines" + val external = scheme.lowercase() in setOf("http", "https") && link.startsWith("$scheme://") return NotificationIntentSpec( ids = ids.joinToString("\n"), action = if (appLink) Intent.ACTION_VIEW else null, data = if (appLink) link else null, + externalLink = if (external) link else null, ) } @@ -309,6 +317,8 @@ class NotificationPresenter(private val context: Context) { const val ACCOUNT_CHANNEL = "pipelines.account" /** Holds the server id(s) a tap or dismissal clears, newline-separated. */ const val EXTRA_NOTIFICATION_ID = "net.awan.pipelines.notification_id" + /** Holds the http(s) page a tap opens in the browser instead of an app route. */ + const val EXTRA_EXTERNAL_LINK = "net.awan.pipelines.external_link" private val KIND_LABELS = mapOf( "run_waiting" to "Run waiting for you", "run_failed" to "Run failed", diff --git a/app/android/app/src/test/kotlin/net/awan/pipelines_app/notify/NotificationProtocolTest.kt b/app/android/app/src/test/kotlin/net/awan/pipelines_app/notify/NotificationProtocolTest.kt index 4fd69be4..069b3c3e 100644 --- a/app/android/app/src/test/kotlin/net/awan/pipelines_app/notify/NotificationProtocolTest.kt +++ b/app/android/app/src/test/kotlin/net/awan/pipelines_app/notify/NotificationProtocolTest.kt @@ -45,6 +45,20 @@ class NotificationProtocolTest { val intent = NotificationPresenter.notificationIntent(listOf("n-1"), "") assertNull(intent.action) assertNull(intent.data) + assertNull(intent.externalLink) + } + + @Test + fun externalHttpClickOpensInBrowserNotAsAppRoute() { + val doc = "https://claude.ai/public/artifacts/0f3c-standup" + val intent = NotificationPresenter.notificationIntent(listOf("n-1"), doc) + assertNull(intent.action) + assertNull(intent.data) + assertEquals(doc, intent.externalLink) + assertEquals("n-1", intent.ids) + assertNull(NotificationPresenter.notificationIntent(listOf("n-1"), "pipelines://run/7").externalLink) + assertNull(NotificationPresenter.notificationIntent(listOf("n-1"), "javascript:alert(1)").externalLink) + assertNull(NotificationPresenter.notificationIntent(listOf("n-1"), "https:claude.ai").externalLink) } @Test diff --git a/internal/author/skill/references/format.md b/internal/author/skill/references/format.md index c6c38939..9ab29d9b 100644 --- a/internal/author/skill/references/format.md +++ b/internal/author/skill/references/format.md @@ -233,6 +233,7 @@ whose branch is on `main`, the server removes the tree and branch; anything else (a failed run, unlanded commits, stray files) is kept for recovery. The `notify` block accepts `on`, optional legacy `destination`, optional -`artifacts=markdown|files`, and optional `open=`. `open` selects -an artifact in the run's shared `public/`; without it, one and only one regular -file there is selected automatically. +`artifacts=markdown|files`, optional `open=` and optional +`link=`. `open` selects an artifact in the run's shared `public/`; +without it, one and only one regular file there is selected automatically. +`link` selects a `public/` file whose first line is the http(s) tap target. diff --git a/internal/author/skill/references/notifications.md b/internal/author/skill/references/notifications.md index 1e26df29..a536de34 100644 --- a/internal/author/skill/references/notifications.md +++ b/internal/author/skill/references/notifications.md @@ -67,6 +67,18 @@ files match, the most recently modified file wins. Without `open=`, exactly one regular file in `public/` is attached automatically. Zero or multiple files produce no attached artifact. This is separate from ntfy's `artifacts=` keys. +`link=` makes a tap on the phone notification (ntfy and app) open a +URL the stage produced, such as a published doc. The pattern follows the `open=` +rules; the matched file's first non-empty line must be an absolute http(s) URL +without credentials or fragment. The run stays reachable from the notification's +run action, and `open=` still attaches its artifact. A missing file or invalid +URL keeps the usual tap target and is noted on the notification receipt: + +```notify +on=success +link=standup-link.txt +``` + ## Optional explicit delivery stage Use native delivery only when the user needs delivery as an explicit routed stage diff --git a/internal/pipeline/notify.go b/internal/pipeline/notify.go index 764b287d..e317f034 100644 --- a/internal/pipeline/notify.go +++ b/internal/pipeline/notify.go @@ -24,7 +24,7 @@ func parseNotify(text string) (*protocol.NotificationPolicy, error) { return nil, fmt.Errorf("duplicate notify setting %s", key) } switch key { - case "on", "destination", "artifacts", "open": + case "on", "destination", "artifacts", "open", "link": default: return nil, fmt.Errorf("unknown notify setting %s", key) } @@ -60,19 +60,31 @@ func parseNotify(text string) (*protocol.NotificationPolicy, error) { return nil, err } } - if open := values["open"]; open != "" { - if strings.ContainsAny(open, "\\\x00\r\n") || strings.HasPrefix(open, "/") || path.IsAbs(open) || path.Clean(open) != open { - return nil, fmt.Errorf("invalid notify open pattern") - } - for _, part := range strings.Split(open, "/") { - if part == ".." || strings.HasPrefix(part, ".") || part == "" { - return nil, fmt.Errorf("invalid notify open pattern") - } - } - if _, err := path.Match(open, ""); err != nil { - return nil, fmt.Errorf("invalid notify open pattern: %v", err) - } - p.Open = open + if p.Open, err = notifyPattern("open", values["open"]); err != nil { + return nil, err + } + if p.Link, err = notifyPattern("link", values["link"]); err != nil { + return nil, err } return p, nil } + +// notifyPattern validates an optional glob over the run's shared public/ +// directory: relative, clean, no hidden or traversal segment. +func notifyPattern(key, pattern string) (string, error) { + if pattern == "" { + return "", nil + } + if strings.ContainsAny(pattern, "\\\x00\r\n") || strings.HasPrefix(pattern, "/") || path.IsAbs(pattern) || path.Clean(pattern) != pattern { + return "", fmt.Errorf("invalid notify %s pattern", key) + } + for _, part := range strings.Split(pattern, "/") { + if part == ".." || strings.HasPrefix(part, ".") || part == "" { + return "", fmt.Errorf("invalid notify %s pattern", key) + } + } + if _, err := path.Match(pattern, ""); err != nil { + return "", fmt.Errorf("invalid notify %s pattern: %v", key, err) + } + return pattern, nil +} diff --git a/internal/pipeline/notify_test.go b/internal/pipeline/notify_test.go index 8f67b59b..9f4eee9b 100644 --- a/internal/pipeline/notify_test.go +++ b/internal/pipeline/notify_test.go @@ -12,6 +12,7 @@ func TestNotifyPolicyParsing(t *testing.T) { }{ {"on=success\ndestination=anime", true}, {"on=failure\ndestination=anime\nartifacts=files", true}, {"on=success,failure\ndestination=anime\nartifacts=markdown,files", true}, {"on=success\nopen=reports/*.md", true}, {"on=success\nopen=/secret", false}, {"on=success\nopen=../secret", false}, {"on=success\nopen=.secret", false}, {"on=success\nopen=[", false}, + {"on=success\nlink=standup-link.txt", true}, {"on=success\nlink=links/*.txt\nopen=reports/*.md", true}, {"on=success\nlink=/secret", false}, {"on=success\nlink=../secret", false}, {"on=success\nlink=.secret", false}, {"on=success\nlink=a//b", false}, {"on=success\nlink=[", false}, {"on=success\nlink=a.txt\nlink=b.txt", false}, {"on=error\ndestination=anime", false}, {"on=success,success\ndestination=anime", false}, {"destination=anime", false}, {"on=success", true}, {"on=failure\nartifacts=markdown,files", true}, {"on=success\ndestination=../secret", false}, {"on=success\ndestination=anime\ntoken=secret", false}, {"on=success\ndestination=anime\nartifacts=*", false}, {"on=success\non=failure\ndestination=anime", false}, } { source := strings.Replace(Template([]string{"one"}, true), "# stage one", "# stage one\n```notify\n"+test.text+"\n```", 1) @@ -32,7 +33,12 @@ func TestNotifyPolicyParsing(t *testing.T) { } } } - source := "# stage native\n```configs\ntype=ntfy\ndestination=anime\n```\n```notify\non=failure\ndestination=anime\n```\n```edges\nsuccess -> #success\nerror -> #failure\n```" + source := strings.Replace(Template([]string{"one"}, true), "# stage one", "# stage one\n```notify\non=success\nlink=standup-link.txt\nopen=*.md\n```", 1) + // `pipelines validate` uses this report parser. + if graph, _, err := ParseDefinitionReport(source); err != nil || graph.Stages[0].Notify.Link != "standup-link.txt" || graph.Stages[0].Notify.Open != "*.md" { + t.Fatal("notify link not validated", err) + } + source = "# stage native\n```configs\ntype=ntfy\ndestination=anime\n```\n```notify\non=failure\ndestination=anime\n```\n```edges\nsuccess -> #success\nerror -> #failure\n```" if _, err := Parse(source); err != nil { t.Fatal("notify not supported on native stage", err) } diff --git a/internal/protocol/message.go b/internal/protocol/message.go index 4f4ef957..d49ab897 100644 --- a/internal/protocol/message.go +++ b/internal/protocol/message.go @@ -57,6 +57,8 @@ type NotificationPolicy struct { Destination string `json:"destination"` Artifacts []string `json:"artifacts,omitempty"` Open string `json:"open,omitempty"` + // Link names a public/ file whose first line is the http(s) tap target. + Link string `json:"link,omitempty"` } // Public phone setup only. Never include publishing endpoints or credentials. diff --git a/internal/server/notify.go b/internal/server/notify.go index 7b2ee811..36d911dd 100644 --- a/internal/server/notify.go +++ b/internal/server/notify.go @@ -76,6 +76,19 @@ func (r *runner) notifyStep(id int64, name, workspace string, policy *protocol.N // the first ntfy publication; artifacts stay ntfy attachments. appEvent, appKind := stageNotification(event, step.Target) appArtifact, appPreview := r.resolveNotificationArtifact(id, step.Sequence, policy.Open) + // A `link=` file decides the tap target (ntfy and app alike); the run stays + // reachable through the app's run action and ntfy's browser view. + click := runAttentionClick(id) + link, linkDiagnostic := r.resolveNotificationLink(id, policy.Link) + if link != "" { + click = link + } + note := func(diagnostic string) string { + if linkDiagnostic == "" || diagnostic == "" { + return diagnostic + linkDiagnostic + } + return diagnostic + "; " + linkDiagnostic + } recorded := false ntfyOn := ntfyEnabled(ctx, r.settingsStore()) send := func(filename string, data []byte) { @@ -86,20 +99,25 @@ func (r *runner) notifyStep(id int64, name, workspace string, policy *protocol.N receipt := &receipts[len(receipts)-1] if !recorded { recorded = true - r.notes.record(ctx, runNotificationRecord(id, step.Sequence, appEvent, appKind, title, summary, appArtifact, appPreview)) + record := runNotificationRecord(id, step.Sequence, appEvent, appKind, title, summary, appArtifact, appPreview) + if link != "" { + record.Click, record.RunClick = link, runAttentionClick(id) + } + r.notes.record(ctx, record) } if !ntfyOn { receipt.Status = "sent" - receipt.Diagnostic = "ntfy disabled; delivered to app clients only" + receipt.Diagnostic = note("ntfy disabled; delivered to app clients only") persist() return } - result, err := ntfyPublish(ctx, "system", title, summary, filename, data, runAttentionClick(id), runAttentionViews(id)...) + result, err := ntfyPublish(ctx, "system", title, summary, filename, data, click, runAttentionViews(id)...) if err != nil { receipt.Status = "failed" - receipt.Diagnostic = err.Error() + receipt.Diagnostic = note(err.Error()) } else { receipt.Status = "sent" + receipt.Diagnostic = note("") receipt.MessageID, _ = result["message_id"].(string) receipt.AttachmentURL, _ = result["attachment_url"].(string) } @@ -560,6 +578,36 @@ func notificationClick(runID int64, sequence int, artifact *protocol.Notificatio // resolveNotificationArtifact selects only files in the run's shared public/. // It is deliberately independent of the ntfy attachment policy. func (r *runner) resolveNotificationArtifact(runID int64, sequence int, pattern string) (*protocol.NotificationArtifact, string) { + selected := r.publicNotificationFile(runID, pattern) + if selected == "" { + return nil, "" + } + full := filepath.Join(r.artifactsRoot, fmt.Sprint(runID), "public", filepath.FromSlash(selected)) + file, err := os.Open(full) + if err != nil { + return nil, "" + } + defer file.Close() + data, err := io.ReadAll(io.LimitReader(file, 64<<10)) + if err != nil { + return nil, "" + } + media := mime.TypeByExtension(filepath.Ext(selected)) + if media == "" { + sample := data + if len(sample) > 512 { + sample = sample[:512] + } + media = http.DetectContentType(sample) + } + a := &protocol.NotificationArtifact{RunID: runID, Sequence: sequence, Path: selected, Name: filepath.Base(selected), URL: artifactURL(runID, sequence, "public/"+selected), MediaType: media} + return a, notificationPreview(data, media, filepath.Ext(selected)) +} + +// publicNotificationFile picks a regular, non-hidden, non-symlinked file in the +// run's shared public/ as a slash path: the most recently modified match of +// pattern, or without a pattern the only file there. "" when none qualifies. +func (r *runner) publicNotificationFile(runID int64, pattern string) string { root := filepath.Join(r.artifactsRoot, fmt.Sprint(runID), "public") type candidate struct { path string @@ -602,11 +650,8 @@ func (r *runner) resolveNotificationArtifact(runID int64, sequence int, pattern candidates = append(candidates, candidate{rel, info}) return nil }) - if pattern == "" && len(candidates) != 1 { - return nil, "" - } - if len(candidates) == 0 { - return nil, "" + if (pattern == "" && len(candidates) != 1) || len(candidates) == 0 { + return "" } selected := candidates[0] for _, c := range candidates[1:] { @@ -614,26 +659,7 @@ func (r *runner) resolveNotificationArtifact(runID int64, sequence int, pattern selected = c } } - full := filepath.Join(root, filepath.FromSlash(selected.path)) - file, err := os.Open(full) - if err != nil { - return nil, "" - } - defer file.Close() - data, err := io.ReadAll(io.LimitReader(file, 64<<10)) - if err != nil { - return nil, "" - } - media := mime.TypeByExtension(filepath.Ext(selected.path)) - if media == "" { - sample := data - if len(sample) > 512 { - sample = sample[:512] - } - media = http.DetectContentType(sample) - } - a := &protocol.NotificationArtifact{RunID: runID, Sequence: sequence, Path: selected.path, Name: filepath.Base(selected.path), URL: artifactURL(runID, sequence, "public/"+selected.path), MediaType: media} - return a, notificationPreview(data, media, filepath.Ext(selected.path)) + return selected.path } var markdownSyntax = regexp.MustCompile(`[*_` + "`" + `>#\[\]()]`) diff --git a/internal/server/notify_link.go b/internal/server/notify_link.go new file mode 100644 index 00000000..33f95086 --- /dev/null +++ b/internal/server/notify_link.go @@ -0,0 +1,74 @@ +package server + +import ( + "fmt" + "git.a-wan.net/alan/pipelines/internal/stage" + "io" + "net/url" + "os" + "path/filepath" + "strings" + "syscall" +) + +// notificationLinkLimit bounds a `link=` file: it holds one URL, not a document. +const notificationLinkLimit = 4 << 10 + +// resolveNotificationLink reads the tap target a stage's `link=` pattern names +// in the run's shared public/: the first non-empty line of the most recently +// modified match, when it is an absolute http(s) URL ntfy accepts as a click. +// Otherwise it returns no link and the reason for the notification receipt. +func (r *runner) resolveNotificationLink(runID int64, pattern string) (string, string) { + if pattern == "" { + return "", "" + } + rel := r.publicNotificationFile(runID, pattern) + if rel == "" { + return "", fmt.Sprintf("notify link: no public file matches %s", pattern) + } + data, err := readNotificationLink(filepath.Join(r.artifactsRoot, fmt.Sprint(runID), "public"), rel) + if err != nil { + return "", fmt.Sprintf("notify link: public/%s %v", rel, err) + } + for _, line := range strings.Split(string(data), "\n") { + if line = strings.TrimSpace(line); line == "" { + continue + } + if !validNotificationLink(line) { + return "", fmt.Sprintf("notify link: public/%s does not start with an absolute http(s) URL", rel) + } + return line, "" + } + return "", fmt.Sprintf("notify link: public/%s is empty", rel) +} + +// readNotificationLink reads one small regular file below root without +// following a symlink out of it. +func readNotificationLink(root, rel string) ([]byte, error) { + scoped, err := os.OpenRoot(root) + if err != nil { + return nil, fmt.Errorf("is unreadable") + } + defer scoped.Close() + file, err := scoped.OpenFile(filepath.FromSlash(rel), os.O_RDONLY|syscall.O_NONBLOCK|syscall.O_NOFOLLOW, 0) + if err != nil { + return nil, fmt.Errorf("is unreadable") + } + defer file.Close() + info, err := file.Stat() + if err != nil || !info.Mode().IsRegular() || info.Size() > notificationLinkLimit { + return nil, fmt.Errorf("must be a regular file of at most 4 KiB") + } + data, err := io.ReadAll(io.LimitReader(file, notificationLinkLimit+1)) + if err != nil || len(data) > notificationLinkLimit { + return nil, fmt.Errorf("must be a regular file of at most 4 KiB") + } + return data, nil +} + +// validNotificationLink accepts only an absolute http(s) URL with a host that +// also passes the ntfy click rules (no credentials, no fragment, bounded). +func validNotificationLink(link string) bool { + u, err := url.Parse(link) + return err == nil && (u.Scheme == "http" || u.Scheme == "https") && u.Hostname() != "" && stage.ValidNtfyClick(link) +} diff --git a/internal/server/notify_link_test.go b/internal/server/notify_link_test.go new file mode 100644 index 00000000..ebcf4669 --- /dev/null +++ b/internal/server/notify_link_test.go @@ -0,0 +1,123 @@ +package server + +import ( + "context" + "fmt" + "git.a-wan.net/alan/pipelines/internal/pipeline" + "git.a-wan.net/alan/pipelines/internal/protocol" + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +// A stage hook's `link=` file decides the ntfy and app tap target when its +// first line is an http(s) URL, keeping the run one action away; anything else +// falls back to the run link and says why on the receipt. +func TestStageHookLinkClick(t *testing.T) { + t.Setenv("PIPELINES_WEB_PUBLIC_URL", "https://pipelines.example.com") + captured := newNtfyCapture(t) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + store := newOperatorStore(t) + if _, err := store.UpdateNotificationSettings(ctx, map[string]any{protocol.NotifyNtfyEnabled: true}); err != nil { + t.Fatal(err) + } + if _, err := store.Submit(ctx, "standup", pipeline.Template([]string{"one"}, true)); err != nil { + t.Fatal(err) + } + items, _ := store.List(ctx) + d, _ := store.Get(ctx, items[0].ID, 0) + artifacts := t.TempDir() + r := &runner{ctx: ctx, store: store, notes: newAppNotifier(store), artifactsRoot: artifacts} + const doc = "https://claude.ai/public/artifacts/0f3c-standup" + for _, test := range []struct { + name, link, open string + files map[string]string + click bool // the doc URL is the tap target + artifact string // the attached artifact path, by today's open= rules + diagnostic string + }{ + {name: "valid", link: "standup-link.txt", files: map[string]string{"standup-link.txt": "\n " + doc + " \r\nnotes\n", "notes.txt": "n"}, click: true}, + {name: "valid-only-file", link: "standup-link.txt", files: map[string]string{"standup-link.txt": doc}, click: true, artifact: "standup-link.txt"}, + {name: "missing", link: "standup-link.txt", diagnostic: "notify link: no public file matches standup-link.txt"}, + {name: "missing-other-file", link: "standup-link.txt", files: map[string]string{"report.md": "# Report"}, artifact: "report.md", diagnostic: "notify link: no public file matches standup-link.txt"}, + {name: "relative", link: "standup-link.txt", files: map[string]string{"standup-link.txt": "standup.html\n" + doc}, artifact: "standup-link.txt", diagnostic: "notify link: public/standup-link.txt does not start with an absolute http(s) URL"}, + {name: "scheme", link: "standup-link.txt", files: map[string]string{"standup-link.txt": "javascript:alert(1)"}, artifact: "standup-link.txt", diagnostic: "does not start with an absolute http(s) URL"}, + {name: "fragment", link: "standup-link.txt", files: map[string]string{"standup-link.txt": doc + "#top"}, artifact: "standup-link.txt", diagnostic: "does not start with an absolute http(s) URL"}, + {name: "empty", link: "standup-link.txt", files: map[string]string{"standup-link.txt": " \n\n"}, artifact: "standup-link.txt", diagnostic: "notify link: public/standup-link.txt is empty"}, + {name: "large", link: "standup-link.txt", files: map[string]string{"standup-link.txt": doc + "\n" + strings.Repeat("x", 4<<10)}, artifact: "standup-link.txt", diagnostic: "at most 4 KiB"}, + {name: "absent", files: map[string]string{"standup-link.txt": doc, "notes.txt": "n"}}, + {name: "absent-only-file", files: map[string]string{"standup-link.txt": doc}, artifact: "standup-link.txt"}, + {name: "with-open", link: "*-link.txt", open: "*.md", files: map[string]string{"standup-link.txt": doc, "standup.md": "# Standup", "notes.txt": "n"}, click: true, artifact: "standup.md"}, + } { + t.Run(test.name, func(t *testing.T) { + id, _, err := store.CreateRun(ctx, d, test.name, t.TempDir(), false, nil, map[string]any{"prompt": "task"}) + if err != nil { + t.Fatal(err) + } + public := filepath.Join(artifacts, fmt.Sprint(id), "public") + if err := os.MkdirAll(public, 0700); err != nil { + t.Fatal(err) + } + for name, content := range test.files { + if err := os.WriteFile(filepath.Join(public, name), []byte(content), 0600); err != nil { + t.Fatal(err) + } + } + if err := store.BeginStep(ctx, id, 1, "one", nil); err != nil { + t.Fatal(err) + } + step := protocol.RunStep{Sequence: 1, Stage: "one", Status: "completed", Outcome: "success", Target: "two", Output: map[string]any{}} + if err := store.FinishStep(ctx, id, step); err != nil { + t.Fatal(err) + } + before := len(captured()) + policy := &protocol.NotificationPolicy{On: []string{"success"}, Destination: "system", Link: test.link, Open: test.open} + r.notifyStep(id, d.Name, t.TempDir(), policy, step) + + // Without a usable link everything is as before: ntfy taps open the + // run, the app opens the attached artifact (else the run). + runClick := fmt.Sprintf("pipelines://run/%d", id) + wantNtfy, wantClick, wantRunClick := runClick, runClick, "" + if test.artifact != "" { + wantClick, wantRunClick = fmt.Sprintf("pipelines://artifact/%d/1/%s", id, test.artifact), runClick + } + if test.click { + wantNtfy, wantClick, wantRunClick = doc, doc, runClick + } + got := captured() + if len(got) != before+1 { + t.Fatalf("ntfy publications = %+v", got[before:]) + } + if got[before].Click != wantNtfy || got[before].Actions != fmt.Sprintf("view, Open in browser, https://pipelines.example.com/runs/%d", id) { + t.Fatalf("ntfy click/actions = %q %q, want %q", got[before].Click, got[before].Actions, wantNtfy) + } + active, _, err := store.ActiveAppNotifications(ctx, "", time.Now()) + if err != nil { + t.Fatal(err) + } + var n *protocol.AppNotification + for i := range active { + if active[i].ID == fmt.Sprintf("run:%d:1:success", id) { + n = &active[i] + } + } + if n == nil || n.Click != wantClick || n.RunClick != wantRunClick { + t.Fatalf("app notification = %+v, want click %q run %q", n, wantClick, wantRunClick) + } + if (n.Artifact == nil) != (test.artifact == "") || (n.Artifact != nil && n.Artifact.Path != test.artifact) { + t.Fatalf("app artifact = %+v, want %q", n.Artifact, test.artifact) + } + detail, err := store.GetRun(ctx, id) + if err != nil { + t.Fatal(err) + } + receipts := detail.Steps[0].Notifications + if len(receipts) != 1 || receipts[0].Status != "sent" || !strings.Contains(receipts[0].Diagnostic, test.diagnostic) || (test.diagnostic == "") != (receipts[0].Diagnostic == "") { + t.Fatalf("receipts = %+v, want diagnostic %q", receipts, test.diagnostic) + } + }) + } +} diff --git a/internal/stage/ntfy.go b/internal/stage/ntfy.go index e02bbced..aa043864 100644 --- a/internal/stage/ntfy.go +++ b/internal/stage/ntfy.go @@ -115,7 +115,7 @@ func PublishNtfy(ctx context.Context, destination, title, summary, filename stri 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) { + if !ValidNtfyClick(click) { return nil, fmt.Errorf("invalid ntfy click action") } actions, err := ntfyViewActions(views) @@ -227,11 +227,11 @@ func PublishNtfy(ctx context.Context, destination, title, summary, filename stri 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 +// 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 { +func ValidNtfyClick(click string) bool { if click == "" { return true } @@ -262,7 +262,7 @@ func ntfyViewActions(views []NtfyView) (string, error) { 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) { + 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() == "" {