Files
pipelines/internal/server/chat_tools_files.go
T
alan fc7dbb0ac0 Remove ntfy: notifications go only through the app notification stream
Server: drop ntfy publishing (stage hooks, run outbox, chat attention, chat
tool notify, auto-switch and schedule notices), the chat push outbox (its
table is dropped at startup), ntfy status/endpoints and PIPELINES_NTFY_*.
The app_notifications stream, subscribe/clear and kinds are unchanged.
Notification settings keep run_finished/chat_needs_you/chat_reply_finished;
ntfy_enabled is accepted and ignored and its stored row is never read.

Stage type=ntfy is rejected: "ntfy stages were removed; notifications go to
the Pipelines apps — use the stage notify hook". The notify hook remains.

Installer: no ntfy build, accounts, config or supervisor child; manifest
gets top-level "mode" (legacy ntfy.mode still read). Reinstall retires an
old ntfy (safe PID-file stop, deletes binary, config, data dir, token, log,
with a note in logs/install.log); uninstall cleans leftovers.

App: ntfy settings section replaced by "Notification events"; texts updated.
Docs: docs/ntfy.md folded into docs/notifications.md; install, docker, cli,
author skill references updated; security review M1 marked resolved.

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

190 lines
6.2 KiB
Go

package server
import (
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"io"
"mime"
"net/http"
"net/url"
"os"
"path/filepath"
"strings"
"git.a-wan.net/alan/pipelines/internal/pipeline"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// shownFile is a resolved file inside the operator's home.
type shownFile struct {
path string
name string
size int64
mime string
}
func (f shownFile) item(kind, title string) protocol.ChatShownItem {
return protocol.ChatShownItem{Kind: kind, Title: title, Path: f.path, Name: f.name, Size: f.size, Mime: f.mime}
}
// resolveShownFile applies the /files endpoint's containment rules to a model
// supplied path: it must name an existing regular file whose real path (every
// symlink resolved) is inside the operator's home and not on a special
// filesystem. A relative path is taken from the chat's working directory.
func (s *chatToolService) resolveShownFile(ctx context.Context, sessionID, requested string) (shownFile, error) {
requested = strings.TrimSpace(requested)
if requested == "" {
return shownFile{}, errors.New("a path is required")
}
home, err := s.home()
if err != nil {
return shownFile{}, err
}
home = filepath.Clean(home)
realHome, err := filepath.EvalSymlinks(home)
if err != nil {
return shownFile{}, errors.New("the operator's home directory is not available")
}
if !filepath.IsAbs(requested) && !strings.HasPrefix(requested, "~") {
directory := s.chatSessionDirectory(ctx, sessionID)
if directory == "" {
return shownFile{}, errors.New("path " + requested + " is relative and this chat has no recorded working directory; pass an absolute path")
}
requested = filepath.Join(directory, requested)
}
target, err := expandHomePath(home, requested)
if err != nil {
return shownFile{}, err
}
_, realTarget, err := resolveInsideHome(realHome, target)
if err != nil {
if strings.Contains(err.Error(), "outside the home directory") {
return shownFile{}, errors.New("path " + requested + " is outside the operator's home directory; only files inside home can be shown")
}
return shownFile{}, err
}
info, err := os.Stat(realTarget)
if err != nil {
return shownFile{}, describePathError(requested, err)
}
if info.IsDir() {
return shownFile{}, errors.New(requested + " is a directory; show one file")
}
if !info.Mode().IsRegular() || specialFilesystem(realTarget) {
return shownFile{}, errors.New(requested + " is not a regular file")
}
return shownFile{path: realTarget, name: filepath.Base(realTarget), size: info.Size(), mime: shownFileMime(realTarget)}, nil
}
// shownFileMime is the type the /files endpoint will serve: by extension, else
// sniffed from the first bytes.
func shownFileMime(path string) string {
if byExtension := mime.TypeByExtension(filepath.Ext(path)); byExtension != "" {
media, _, err := mime.ParseMediaType(byExtension)
if err == nil {
return media
}
}
file, err := os.Open(path)
if err != nil {
return "application/octet-stream"
}
defer file.Close()
var sample [512]byte
n, err := file.Read(sample[:])
if err != nil && !errors.Is(err, io.EOF) {
return "application/octet-stream"
}
media, _, _ := mime.ParseMediaType(http.DetectContentType(sample[:n]))
if media == "" {
return "application/octet-stream"
}
return media
}
// shownImageURL accepts only an absolute https URL without credentials.
func shownImageURL(raw string) (string, error) {
if len(raw) > 2048 {
return "", errors.New("the image URL is longer than 2048 characters")
}
parsed, err := url.Parse(raw)
if err != nil || parsed.Host == "" {
return "", errors.New("the image URL is not a valid absolute URL")
}
if parsed.Scheme != "https" {
return "", errors.New("only https:// image URLs can be shown")
}
if parsed.User != nil {
return "", errors.New("the image URL must not carry credentials")
}
return parsed.String(), nil
}
// chatToolNotice is one model-requested notification. ID is the chat's shown
// item id, so every call is its own notification even with repeated words.
type chatToolNotice struct {
ID string
Title string
Message string
Priority string // low, default or high
}
// chatToolDelivery reports where a chat tool notification went: App when it
// was recorded on the app notification stream (every connected Pipelines app
// receives it and a reconnecting one replays it). Detail explains a failure.
type chatToolDelivery struct {
App bool
Detail string
}
// chatToolNotifier delivers one model-requested notification for a chat.
type chatToolNotifier func(ctx context.Context, sessionID string, notice chatToolNotice) chatToolDelivery
// chatNotifyPriority maps the tool's priority word to the app stream's 1-5
// priority (3 is the default).
func chatNotifyPriority(priority string) int {
switch priority {
case "low":
return 2
case "high":
return 4
}
return protocol.DefaultNotificationPriority
}
// publishToolNotification records the notification on the app notification
// stream (kind chat_notify), which is pushed to every subscribed client and
// replayed to one that reconnects while it is still active. Tapping it opens
// the chat (pipelines://chat/<id>).
func (h *chatHub) publishToolNotification(ctx context.Context, sessionID string, notice chatToolNotice) chatToolDelivery {
title := truncateUTF8(notice.Title, 256)
message := truncateUTF8(notice.Message, 2000)
click := chatAttentionClick(sessionID)
id := notice.ID
if id == "" {
digest := sha256.Sum256([]byte(title + "\x00" + message))
id = hex.EncodeToString(digest[:8])
}
appID := chatNotificationID(sessionID, "notify", id)
var delivery chatToolDelivery
if h.notes != nil {
delivery.App = h.notes.record(ctx, pipeline.AppNotificationRecord{
AppNotification: protocol.AppNotification{ID: appID, Kind: protocol.NotificationChatNotify, Title: title, Message: message, Click: click, Priority: chatNotifyPriority(notice.Priority), Tags: []string{}, Group: "chat:" + sessionID},
SessionID: sessionID,
})
}
switch {
case h.notes == nil:
delivery.Detail = "the app notification stream is not available"
case !delivery.App:
delivery.Detail = "the notification could not be recorded"
}
if delivery.App {
// This turn has pinged the operator; its end is not announced again.
h.markTurnNotified(sessionID)
}
return delivery
}