Files
pipelines/internal/server/chat_attachment_image.go
alan 8c421952db feat(chat): show sent images as thumbnails with a full-screen viewer
Operator-attached images render as rounded thumbnails above the user
bubble and open a zoomable Material/Cupertino viewer. Inline data: URIs
decode locally; file:// attachment-store URIs load through the new
chat_attachment_image websocket request, which serves only regular image
files directly inside the private attachment store (os.Root, <= 4 MiB,
sniffed raster types). Missing files show an 'Image no longer available'
placeholder; other files keep the file row.
2026-10-30 20:53:03 +00:00

137 lines
4.5 KiB
Go

package server
import (
"encoding/base64"
"errors"
"fmt"
"io"
"io/fs"
"net/http"
"net/url"
"os"
"path/filepath"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// maxChatAttachmentImageBytes bounds one chat_attachment_image reply. The
// bytes travel base64-encoded in a single websocket frame that the server must
// write within its per-frame deadline, and clients serialize requests, so a
// preview stays well below the 100 MiB upload limit.
const maxChatAttachmentImageBytes = 4 << 20
// errChatAttachmentGone is the reply for a stored file that was collected by
// retention or never existed; clients show it as "no longer available".
var errChatAttachmentGone = errors.New("image is no longer available")
// chatAttachmentImageTypes are the sniffed types a client can draw. SVG and
// anything unrecognised stay a plain file row.
var chatAttachmentImageTypes = map[string]bool{
"image/png": true,
"image/jpeg": true,
"image/gif": true,
"image/webp": true,
"image/bmp": true,
}
// handleChatAttachmentImage returns one image file the operator attached, so a
// transcript can draw it after a reload. Only regular files directly inside the
// private attachment store are readable; anything else is refused before it is
// opened.
func handleChatAttachmentImage(request protocol.Message, broker chatBroker, write func(protocol.Message) error) {
fail := func(message string) {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: message})
}
if broker == nil {
fail("chat is not configured on this server")
return
}
query := request.ChatAttachmentImageRequest
if query == nil || query.URI == "" {
fail("a chat_attachment_image_request with a uri is required")
return
}
data, mime, err := readChatAttachmentImage(query.URI)
if err != nil {
fail(err.Error())
return
}
_ = write(protocol.Message{Type: protocol.ChatAttachmentImage, ID: request.ID, ChatAttachmentImage: &protocol.ChatAttachmentImageContent{
URI: query.URI,
Mime: mime,
Size: int64(len(data)),
Data: base64.StdEncoding.EncodeToString(data),
}})
}
// readChatAttachmentImage resolves a file:// URI to one regular file in the
// attachment store and returns its bytes and sniffed image type.
func readChatAttachmentImage(uri string) ([]byte, string, error) {
notStored := errors.New("not a stored chat attachment")
u, err := url.Parse(uri)
if err != nil || u.Scheme != "file" || u.Host != "" || u.User != nil || u.Opaque != "" || u.RawQuery != "" || u.ForceQuery || u.Fragment != "" {
return nil, "", notStored
}
path := u.Path
if !filepath.IsAbs(path) || filepath.Clean(path) != path {
return nil, "", notStored
}
dir, err := chatAttachmentDir()
if err != nil {
return nil, "", err
}
name := filepath.Base(path)
if filepath.Dir(path) != dir || name == "." || name == ".." || name == string(filepath.Separator) {
return nil, "", notStored
}
dirInfo, err := os.Lstat(dir)
if errors.Is(err, fs.ErrNotExist) {
return nil, "", errChatAttachmentGone
}
if err != nil || !dirInfo.IsDir() {
return nil, "", errors.New("attachment storage must be a directory, not a symlink")
}
root, err := os.OpenRoot(dir)
if err != nil {
return nil, "", err
}
defer root.Close()
if actual, err := root.Stat("."); err != nil || !os.SameFile(dirInfo, actual) {
return nil, "", errors.New("chat attachment storage changed while opening")
}
info, err := root.Lstat(name)
if errors.Is(err, fs.ErrNotExist) {
return nil, "", errChatAttachmentGone
}
if err != nil || !info.Mode().IsRegular() {
return nil, "", notStored
}
if info.Size() > maxChatAttachmentImageBytes {
return nil, "", fmt.Errorf("image is too large to preview (over %d MiB)", maxChatAttachmentImageBytes>>20)
}
file, err := root.Open(name)
if errors.Is(err, fs.ErrNotExist) {
return nil, "", errChatAttachmentGone
}
if err != nil {
return nil, "", notStored
}
defer file.Close()
opened, err := file.Stat()
if err != nil || !os.SameFile(info, opened) || !opened.Mode().IsRegular() {
return nil, "", errors.New("attachment changed while opening")
}
data, err := io.ReadAll(io.LimitReader(file, maxChatAttachmentImageBytes+1))
if err != nil {
return nil, "", fmt.Errorf("read attachment: %w", err)
}
if len(data) > maxChatAttachmentImageBytes {
return nil, "", fmt.Errorf("image is too large to preview (over %d MiB)", maxChatAttachmentImageBytes>>20)
}
mime := http.DetectContentType(data)
if !chatAttachmentImageTypes[mime] {
return nil, "", errors.New("attachment is not a previewable image")
}
return data, mime, nil
}