Editors upload files to a page (attach button, paste or drop); images go into the document as images and other files as download cards. Files are stored in a new attachments collection, so PocketBase's local or S3 storage applies, and docwell-server streams them after checking the reader's page access. Documents keep the file's API path. Because <img> tags cannot send the Authorization header, clients load files with a short-lived signed file token (?token=) instead of the session token. Uploads are limited by DOCWELL_MAX_UPLOAD_MB (default 50), their type is sniffed from the content, and only images, PDFs and media are served inline, so an uploaded HTML or SVG file never runs on the API's origin. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
121 lines
4.3 KiB
Go
121 lines
4.3 KiB
Go
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
|
|
package httpapi
|
|
|
|
import (
|
|
"context"
|
|
"io"
|
|
"mime"
|
|
"net/http"
|
|
"time"
|
|
|
|
"docwell/server/internal/access"
|
|
"docwell/server/internal/auth"
|
|
"docwell/server/internal/directory"
|
|
)
|
|
|
|
// AttachmentService is the part of directory.Service that handles page files.
|
|
type AttachmentService interface {
|
|
UploadAttachment(ctx context.Context, c access.Caller, pageID, filename string, file io.Reader) (directory.Attachment, error)
|
|
ListAttachments(ctx context.Context, c access.Caller, pageID string) ([]directory.Attachment, error)
|
|
DeleteAttachment(ctx context.Context, c access.Caller, id string) error
|
|
OpenAttachment(ctx context.Context, c access.Caller, id string, header http.Header) (directory.FileDownload, error)
|
|
}
|
|
|
|
// inlineTypes are shown in the browser; everything else downloads, so a
|
|
// stored HTML or SVG file can never run script on the API's origin.
|
|
var inlineTypes = map[string]bool{
|
|
"image/png": true, "image/jpeg": true, "image/gif": true, "image/webp": true, "image/avif": true,
|
|
"application/pdf": true, "video/mp4": true, "video/webm": true, "audio/mpeg": true, "audio/ogg": true,
|
|
}
|
|
|
|
func (a *api) fileRoutes(mux *routeMux, maxUpload int64) {
|
|
mux.HandleFunc("GET /api/v1/pages/{id}/attachments", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
|
|
list, err := a.dir.ListAttachments(r.Context(), caller(r), r.PathValue("id"))
|
|
a.respond(w, list, err)
|
|
}))
|
|
mux.HandleFunc("POST /api/v1/pages/{id}/attachments", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
|
|
r.Body = http.MaxBytesReader(w, r.Body, maxUpload+1<<20)
|
|
mr, err := r.MultipartReader()
|
|
if err != nil {
|
|
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid", "message": "expected multipart/form-data"})
|
|
return
|
|
}
|
|
for {
|
|
part, err := mr.NextPart()
|
|
if err != nil {
|
|
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid", "message": "no file part"})
|
|
return
|
|
}
|
|
if part.FormName() != "file" {
|
|
_ = part.Close()
|
|
continue
|
|
}
|
|
att, err := a.dir.UploadAttachment(r.Context(), caller(r), r.PathValue("id"), part.FileName(), part)
|
|
_ = part.Close()
|
|
a.respondStatus(w, http.StatusCreated, att, err)
|
|
return
|
|
}
|
|
}))
|
|
mux.HandleFunc("DELETE /api/v1/attachments/{id}", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
|
|
a.respondNoContent(w, a.dir.DeleteAttachment(r.Context(), caller(r), r.PathValue("id")))
|
|
}))
|
|
|
|
mux.HandleFunc("POST /api/v1/files/token", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
|
|
u, _ := CurrentUser(r.Context())
|
|
token, exp := a.files.Issue(u.ID)
|
|
writeJSON(w, http.StatusOK, map[string]string{"token": token, "expires": exp.UTC().Format(time.RFC3339)})
|
|
}))
|
|
// Files load with the session token or, for <img> tags and links, ?token=<file token>.
|
|
mux.HandleFunc("GET /api/v1/files/{id}", func(w http.ResponseWriter, r *http.Request) {
|
|
u, err := a.fileUser(r)
|
|
if err != nil {
|
|
a.writeError(w, err)
|
|
return
|
|
}
|
|
f, err := a.dir.OpenAttachment(r.Context(), u.Caller(), r.PathValue("id"), r.Header)
|
|
if err != nil {
|
|
a.writeError(w, err)
|
|
return
|
|
}
|
|
serveFile(w, f)
|
|
})
|
|
}
|
|
|
|
// fileUser identifies a download's user from the bearer token or a file token.
|
|
func (a *api) fileUser(r *http.Request) (auth.User, error) {
|
|
if t := auth.BearerToken(r); t != "" {
|
|
return a.auth.Verify(r.Context(), t)
|
|
}
|
|
if a.files == nil {
|
|
return auth.User{}, auth.ErrUnauthorized
|
|
}
|
|
id, err := a.files.Parse(r.URL.Query().Get("token"))
|
|
if err != nil {
|
|
return auth.User{}, err
|
|
}
|
|
return a.auth.UserByID(r.Context(), id)
|
|
}
|
|
|
|
func serveFile(w http.ResponseWriter, f directory.FileDownload) {
|
|
defer f.Body.Close()
|
|
h := w.Header()
|
|
for _, k := range []string{"Content-Length", "Content-Range", "Accept-Ranges", "ETag", "Last-Modified"} {
|
|
if v := f.Header.Get(k); v != "" {
|
|
h.Set(k, v)
|
|
}
|
|
}
|
|
disposition := "attachment"
|
|
contentType := "application/octet-stream"
|
|
if inlineTypes[f.Mime] {
|
|
disposition, contentType = "inline", f.Mime
|
|
}
|
|
h.Set("Content-Type", contentType)
|
|
h.Set("Content-Disposition", mime.FormatMediaType(disposition, map[string]string{"filename": f.Name}))
|
|
h.Set("X-Content-Type-Options", "nosniff")
|
|
h.Set("Content-Security-Policy", "default-src 'none'; img-src 'self'; media-src 'self'; style-src 'unsafe-inline'; sandbox")
|
|
h.Set("Cache-Control", "private, max-age=3600")
|
|
w.WriteHeader(f.StatusCode)
|
|
_, _ = io.Copy(w, f.Body)
|
|
}
|