Notify link=: a stage's public/ file sets the phone tap target
A stage's notify block may name `link=<pattern>` (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.
This commit is contained in:
@@ -1,6 +1,8 @@
|
|||||||
package net.awan.pipelines_app
|
package net.awan.pipelines_app
|
||||||
|
|
||||||
|
import android.content.ActivityNotFoundException
|
||||||
import android.content.Intent
|
import android.content.Intent
|
||||||
|
import android.net.Uri
|
||||||
import android.os.Bundle
|
import android.os.Bundle
|
||||||
import io.flutter.embedding.android.FlutterActivity
|
import io.flutter.embedding.android.FlutterActivity
|
||||||
import io.flutter.embedding.engine.FlutterEngine
|
import io.flutter.embedding.engine.FlutterEngine
|
||||||
@@ -24,12 +26,16 @@ class MainActivity : FlutterActivity() {
|
|||||||
|
|
||||||
override fun onCreate(savedInstanceState: Bundle?) {
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
super.onCreate(savedInstanceState)
|
super.onCreate(savedInstanceState)
|
||||||
if (savedInstanceState == null) clearOpenedNotification(intent)
|
if (savedInstanceState == null) {
|
||||||
|
clearOpenedNotification(intent)
|
||||||
|
openExternalLink(intent)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onNewIntent(intent: Intent) {
|
override fun onNewIntent(intent: Intent) {
|
||||||
super.onNewIntent(intent)
|
super.onNewIntent(intent)
|
||||||
clearOpenedNotification(intent)
|
clearOpenedNotification(intent)
|
||||||
|
openExternalLink(intent)
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -41,4 +47,18 @@ class MainActivity : FlutterActivity() {
|
|||||||
intent.removeExtra(NotificationPresenter.EXTRA_NOTIFICATION_ID)
|
intent.removeExtra(NotificationPresenter.EXTRA_NOTIFICATION_ID)
|
||||||
NotificationDismissReceiver.queueClear(this, 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.
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+13
-3
@@ -17,6 +17,8 @@ data class NotificationIntentSpec(
|
|||||||
val ids: String,
|
val ids: String,
|
||||||
val action: String?,
|
val action: String?,
|
||||||
val data: 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,
|
* conversation notification with the latest artifact preview and unread count,
|
||||||
* keyed by its server group. Thread notifications share a
|
* keyed by its server group. Thread notifications share a
|
||||||
* group per namespace, so Android bundles them under a summary ("N chats",
|
* 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
|
* "N runs"). A tap opens the app at the `click` deep link (or an http(s)
|
||||||
* thread; a dismissal is reported back so the server clears it everywhere.
|
* 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) {
|
class NotificationPresenter(private val context: Context) {
|
||||||
private val manager = context.getSystemService(NotificationManager::class.java)
|
private val manager = context.getSystemService(NotificationManager::class.java)
|
||||||
@@ -219,6 +222,8 @@ class NotificationPresenter(private val context: Context) {
|
|||||||
Intent.FLAG_ACTIVITY_CLEAR_TOP,
|
Intent.FLAG_ACTIVITY_CLEAR_TOP,
|
||||||
)
|
)
|
||||||
if (spec.action != null) intent.setAction(spec.action).setData(Uri.parse(spec.data))
|
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(
|
return PendingIntent.getActivity(
|
||||||
context,
|
context,
|
||||||
requestCode,
|
requestCode,
|
||||||
@@ -280,11 +285,14 @@ class NotificationPresenter(private val context: Context) {
|
|||||||
/** Builds the deep-link portion of a tray tap without requiring Android Context. */
|
/** Builds the deep-link portion of a tray tap without requiring Android Context. */
|
||||||
fun notificationIntent(ids: List<String>, click: String): NotificationIntentSpec {
|
fun notificationIntent(ids: List<String>, click: String): NotificationIntentSpec {
|
||||||
val link = notificationLink(click)
|
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(
|
return NotificationIntentSpec(
|
||||||
ids = ids.joinToString("\n"),
|
ids = ids.joinToString("\n"),
|
||||||
action = if (appLink) Intent.ACTION_VIEW else null,
|
action = if (appLink) Intent.ACTION_VIEW else null,
|
||||||
data = if (appLink) link 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"
|
const val ACCOUNT_CHANNEL = "pipelines.account"
|
||||||
/** Holds the server id(s) a tap or dismissal clears, newline-separated. */
|
/** Holds the server id(s) a tap or dismissal clears, newline-separated. */
|
||||||
const val EXTRA_NOTIFICATION_ID = "net.awan.pipelines.notification_id"
|
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(
|
private val KIND_LABELS = mapOf(
|
||||||
"run_waiting" to "Run waiting for you",
|
"run_waiting" to "Run waiting for you",
|
||||||
"run_failed" to "Run failed",
|
"run_failed" to "Run failed",
|
||||||
|
|||||||
+14
@@ -45,6 +45,20 @@ class NotificationProtocolTest {
|
|||||||
val intent = NotificationPresenter.notificationIntent(listOf("n-1"), "")
|
val intent = NotificationPresenter.notificationIntent(listOf("n-1"), "")
|
||||||
assertNull(intent.action)
|
assertNull(intent.action)
|
||||||
assertNull(intent.data)
|
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
|
@Test
|
||||||
|
|||||||
@@ -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.
|
else (a failed run, unlanded commits, stray files) is kept for recovery.
|
||||||
|
|
||||||
The `notify` block accepts `on`, optional legacy `destination`, optional
|
The `notify` block accepts `on`, optional legacy `destination`, optional
|
||||||
`artifacts=markdown|files`, and optional `open=<relative-glob>`. `open` selects
|
`artifacts=markdown|files`, optional `open=<relative-glob>` and optional
|
||||||
an artifact in the run's shared `public/`; without it, one and only one regular
|
`link=<relative-glob>`. `open` selects an artifact in the run's shared `public/`;
|
||||||
file there is selected automatically.
|
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.
|
||||||
|
|||||||
@@ -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
|
regular file in `public/` is attached automatically. Zero or multiple files
|
||||||
produce no attached artifact. This is separate from ntfy's `artifacts=` keys.
|
produce no attached artifact. This is separate from ntfy's `artifacts=` keys.
|
||||||
|
|
||||||
|
`link=<pattern>` 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
|
## Optional explicit delivery stage
|
||||||
|
|
||||||
Use native delivery only when the user needs delivery as an explicit routed stage
|
Use native delivery only when the user needs delivery as an explicit routed stage
|
||||||
|
|||||||
+26
-14
@@ -24,7 +24,7 @@ func parseNotify(text string) (*protocol.NotificationPolicy, error) {
|
|||||||
return nil, fmt.Errorf("duplicate notify setting %s", key)
|
return nil, fmt.Errorf("duplicate notify setting %s", key)
|
||||||
}
|
}
|
||||||
switch key {
|
switch key {
|
||||||
case "on", "destination", "artifacts", "open":
|
case "on", "destination", "artifacts", "open", "link":
|
||||||
default:
|
default:
|
||||||
return nil, fmt.Errorf("unknown notify setting %s", key)
|
return nil, fmt.Errorf("unknown notify setting %s", key)
|
||||||
}
|
}
|
||||||
@@ -60,19 +60,31 @@ func parseNotify(text string) (*protocol.NotificationPolicy, error) {
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if open := values["open"]; open != "" {
|
if p.Open, err = notifyPattern("open", values["open"]); err != nil {
|
||||||
if strings.ContainsAny(open, "\\\x00\r\n") || strings.HasPrefix(open, "/") || path.IsAbs(open) || path.Clean(open) != open {
|
return nil, err
|
||||||
return nil, fmt.Errorf("invalid notify open pattern")
|
}
|
||||||
}
|
if p.Link, err = notifyPattern("link", values["link"]); err != nil {
|
||||||
for _, part := range strings.Split(open, "/") {
|
return nil, err
|
||||||
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
|
|
||||||
}
|
}
|
||||||
return p, nil
|
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
|
||||||
|
}
|
||||||
|
|||||||
@@ -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\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\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},
|
{"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)
|
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 {
|
if _, err := Parse(source); err != nil {
|
||||||
t.Fatal("notify not supported on native stage", err)
|
t.Fatal("notify not supported on native stage", err)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -57,6 +57,8 @@ type NotificationPolicy struct {
|
|||||||
Destination string `json:"destination"`
|
Destination string `json:"destination"`
|
||||||
Artifacts []string `json:"artifacts,omitempty"`
|
Artifacts []string `json:"artifacts,omitempty"`
|
||||||
Open string `json:"open,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.
|
// Public phone setup only. Never include publishing endpoints or credentials.
|
||||||
|
|||||||
+55
-29
@@ -76,6 +76,19 @@ func (r *runner) notifyStep(id int64, name, workspace string, policy *protocol.N
|
|||||||
// the first ntfy publication; artifacts stay ntfy attachments.
|
// the first ntfy publication; artifacts stay ntfy attachments.
|
||||||
appEvent, appKind := stageNotification(event, step.Target)
|
appEvent, appKind := stageNotification(event, step.Target)
|
||||||
appArtifact, appPreview := r.resolveNotificationArtifact(id, step.Sequence, policy.Open)
|
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
|
recorded := false
|
||||||
ntfyOn := ntfyEnabled(ctx, r.settingsStore())
|
ntfyOn := ntfyEnabled(ctx, r.settingsStore())
|
||||||
send := func(filename string, data []byte) {
|
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]
|
receipt := &receipts[len(receipts)-1]
|
||||||
if !recorded {
|
if !recorded {
|
||||||
recorded = true
|
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 {
|
if !ntfyOn {
|
||||||
receipt.Status = "sent"
|
receipt.Status = "sent"
|
||||||
receipt.Diagnostic = "ntfy disabled; delivered to app clients only"
|
receipt.Diagnostic = note("ntfy disabled; delivered to app clients only")
|
||||||
persist()
|
persist()
|
||||||
return
|
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 {
|
if err != nil {
|
||||||
receipt.Status = "failed"
|
receipt.Status = "failed"
|
||||||
receipt.Diagnostic = err.Error()
|
receipt.Diagnostic = note(err.Error())
|
||||||
} else {
|
} else {
|
||||||
receipt.Status = "sent"
|
receipt.Status = "sent"
|
||||||
|
receipt.Diagnostic = note("")
|
||||||
receipt.MessageID, _ = result["message_id"].(string)
|
receipt.MessageID, _ = result["message_id"].(string)
|
||||||
receipt.AttachmentURL, _ = result["attachment_url"].(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/.
|
// resolveNotificationArtifact selects only files in the run's shared public/.
|
||||||
// It is deliberately independent of the ntfy attachment policy.
|
// It is deliberately independent of the ntfy attachment policy.
|
||||||
func (r *runner) resolveNotificationArtifact(runID int64, sequence int, pattern string) (*protocol.NotificationArtifact, string) {
|
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")
|
root := filepath.Join(r.artifactsRoot, fmt.Sprint(runID), "public")
|
||||||
type candidate struct {
|
type candidate struct {
|
||||||
path string
|
path string
|
||||||
@@ -602,11 +650,8 @@ func (r *runner) resolveNotificationArtifact(runID int64, sequence int, pattern
|
|||||||
candidates = append(candidates, candidate{rel, info})
|
candidates = append(candidates, candidate{rel, info})
|
||||||
return nil
|
return nil
|
||||||
})
|
})
|
||||||
if pattern == "" && len(candidates) != 1 {
|
if (pattern == "" && len(candidates) != 1) || len(candidates) == 0 {
|
||||||
return nil, ""
|
return ""
|
||||||
}
|
|
||||||
if len(candidates) == 0 {
|
|
||||||
return nil, ""
|
|
||||||
}
|
}
|
||||||
selected := candidates[0]
|
selected := candidates[0]
|
||||||
for _, c := range candidates[1:] {
|
for _, c := range candidates[1:] {
|
||||||
@@ -614,26 +659,7 @@ func (r *runner) resolveNotificationArtifact(runID int64, sequence int, pattern
|
|||||||
selected = c
|
selected = c
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
full := filepath.Join(root, filepath.FromSlash(selected.path))
|
return 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))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
var markdownSyntax = regexp.MustCompile(`[*_` + "`" + `>#\[\]()]`)
|
var markdownSyntax = regexp.MustCompile(`[*_` + "`" + `>#\[\]()]`)
|
||||||
|
|||||||
@@ -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)
|
||||||
|
}
|
||||||
@@ -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)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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") {
|
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")
|
return nil, fmt.Errorf("invalid ntfy notification metadata")
|
||||||
}
|
}
|
||||||
if !validNtfyClick(click) {
|
if !ValidNtfyClick(click) {
|
||||||
return nil, fmt.Errorf("invalid ntfy click action")
|
return nil, fmt.Errorf("invalid ntfy click action")
|
||||||
}
|
}
|
||||||
actions, err := ntfyViewActions(views)
|
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
|
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,
|
// 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
|
// no control characters and a bounded length. The value is an operator-visible
|
||||||
// deep link, never a place to smuggle a token.
|
// deep link, never a place to smuggle a token.
|
||||||
func validNtfyClick(click string) bool {
|
func ValidNtfyClick(click string) bool {
|
||||||
if click == "" {
|
if click == "" {
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
@@ -262,7 +262,7 @@ func ntfyViewActions(views []NtfyView) (string, error) {
|
|||||||
if label == "" || len(label) > 64 || strings.ContainsAny(label, ",;\"'\\=") || !printableASCII(label) {
|
if label == "" || len(label) > 64 || strings.ContainsAny(label, ",;\"'\\=") || !printableASCII(label) {
|
||||||
return "", fmt.Errorf("invalid ntfy action 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")
|
return "", fmt.Errorf("invalid ntfy action URL")
|
||||||
}
|
}
|
||||||
if u, err := url.Parse(view.URL); err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Hostname() == "" {
|
if u, err := url.Parse(view.URL); err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Hostname() == "" {
|
||||||
|
|||||||
Reference in New Issue
Block a user