diff --git a/internal/server/handlers.go b/internal/server/handlers.go index 3c5e7ed..85b3a16 100644 --- a/internal/server/handlers.go +++ b/internal/server/handlers.go @@ -7,6 +7,7 @@ import ( "database/sql" "encoding/hex" "encoding/json" + "errors" "fmt" "html/template" "image" @@ -975,7 +976,25 @@ func (s *Server) handleUpload(w http.ResponseWriter, r *http.Request) { rc.SetReadDeadline(time.Now().Add(120 * time.Second)) rc.SetWriteDeadline(time.Now().Add(120 * time.Second)) - // Verify CSRF manually (must happen after MaxBytesReader is set) + // Parse the multipart body explicitly BEFORE checking CSRF. verifyCSRF reads + // a form value, which would otherwise trigger an implicit ParseMultipartForm + // and surface an oversized body (tripping MaxBytesReader above) as a bogus + // "Invalid CSRF token" 403. Parsing here lets us report the real cause (413). + // A small maxMemory keeps large uploads spilling to temp files, not RAM (RPi Zero). + if err := r.ParseMultipartForm(4 << 20); err != nil { + w.Header().Set("Content-Type", "application/json") + var maxErr *http.MaxBytesError + if errors.As(err, &maxErr) { + w.WriteHeader(http.StatusRequestEntityTooLarge) + json.NewEncoder(w).Encode(map[string]string{"error": fmt.Sprintf("File too large (max %d MB)", s.cfg.Upload.MaxSize)}) + } else { + w.WriteHeader(http.StatusBadRequest) + json.NewEncoder(w).Encode(map[string]string{"error": "Invalid upload"}) + } + return + } + + // Verify CSRF (form already parsed; no body re-read). if !verifyCSRF(r) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusForbidden) @@ -986,13 +1005,8 @@ func (s *Server) handleUpload(w http.ResponseWriter, r *http.Request) { file, header, err := r.FormFile("file") if err != nil { w.Header().Set("Content-Type", "application/json") - if err.Error() == "http: request body too large" { - w.WriteHeader(http.StatusRequestEntityTooLarge) - json.NewEncoder(w).Encode(map[string]string{"error": fmt.Sprintf("File too large (max %d MB)", s.cfg.Upload.MaxSize)}) - } else { - w.WriteHeader(http.StatusBadRequest) - json.NewEncoder(w).Encode(map[string]string{"error": "No file provided"}) - } + w.WriteHeader(http.StatusBadRequest) + json.NewEncoder(w).Encode(map[string]string{"error": "No file provided"}) return } defer file.Close() @@ -1073,6 +1087,17 @@ func (s *Server) handleFileUpload(w http.ResponseWriter, r *http.Request) { rc.SetReadDeadline(time.Now().Add(120 * time.Second)) rc.SetWriteDeadline(time.Now().Add(120 * time.Second)) + // Parse before CSRF so an oversized body is reported as 413, not a bogus 403. + if err := r.ParseMultipartForm(4 << 20); err != nil { + var maxErr *http.MaxBytesError + if errors.As(err, &maxErr) { + jsonError(w, "File too large (max 5 MB)", http.StatusRequestEntityTooLarge) + } else { + jsonError(w, "Invalid upload", http.StatusBadRequest) + } + return + } + if !verifyCSRF(r) { jsonError(w, "Invalid CSRF token", http.StatusForbidden) return @@ -1080,11 +1105,7 @@ func (s *Server) handleFileUpload(w http.ResponseWriter, r *http.Request) { file, header, err := r.FormFile("file") if err != nil { - if err.Error() == "http: request body too large" { - jsonError(w, "File too large (max 5 MB)", http.StatusRequestEntityTooLarge) - } else { - jsonError(w, "No file provided", http.StatusBadRequest) - } + jsonError(w, "No file provided", http.StatusBadRequest) return } defer file.Close() diff --git a/internal/server/server.go b/internal/server/server.go index c4c1aa4..d54de73 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -49,12 +49,13 @@ func securityHeaders(next http.Handler) http.Handler { // All assets are served from the same origin (Pico CSS is vendored // locally), so the app works fully offline and we can lock the origin // down. img-src allows data: and https: so uploaded/remote images and - // favicons still render. 'unsafe-inline' is required by the inline + // favicons still render, and blob: so the client-side image compressor + // (canvas) can load a selected file before upload. 'unsafe-inline' is required by the inline // scripts/styles in the templates; object-src/base-uri/frame-ancestors // are pinned to blunt injection and clickjacking. w.Header().Set("Content-Security-Policy", "default-src 'self'; "+ - "img-src 'self' data: https:; "+ + "img-src 'self' data: https: blob:; "+ "style-src 'self' 'unsafe-inline'; "+ "script-src 'self' 'unsafe-inline'; "+ "object-src 'none'; "+ diff --git a/internal/server/static/upload.js b/internal/server/static/upload.js index 592b053..da2ba1d 100644 --- a/internal/server/static/upload.js +++ b/internal/server/static/upload.js @@ -11,6 +11,54 @@ (function(window) { var IMG_MAX = 50 * 1024 * 1024; var FILE_MAX = 5 * 1024 * 1024; + // Images larger than this offer in-browser compression before upload. + var COMPRESS_THRESHOLD = 10 * 1024 * 1024; + // Downscale so the longest edge is at most this many pixels, then re-encode + // as JPEG at this quality. Done entirely client-side via . + var COMPRESS_MAX_DIMENSION = 3000; + var COMPRESS_QUALITY = 0.85; + + // renameToJpg replaces a filename's extension with .jpg (compression always + // outputs JPEG). Falls back to "image.jpg" if there's no usable base name. + function renameToJpg(name) { + if (!name) return 'image.jpg'; + var dot = name.lastIndexOf('.'); + var base = dot > 0 ? name.slice(0, dot) : name; + return base + '.jpg'; + } + + // compressImage downscales + re-encodes an image File to a JPEG Blob using a + // canvas. cb(blob, err): on any failure cb is called with a null blob and an + // error string so the caller can fall back to uploading the original. + function compressImage(file, cb) { + if (!window.URL || !window.URL.createObjectURL) { cb(null, 'no object URL support'); return; } + var url = window.URL.createObjectURL(file); + var img = new Image(); + img.onload = function() { + var w = img.naturalWidth || img.width; + var h = img.naturalHeight || img.height; + window.URL.revokeObjectURL(url); + if (!w || !h) { cb(null, 'bad image dimensions'); return; } + var scale = Math.min(1, COMPRESS_MAX_DIMENSION / Math.max(w, h)); + var cw = Math.max(1, Math.round(w * scale)); + var ch = Math.max(1, Math.round(h * scale)); + var canvas = document.createElement('canvas'); + canvas.width = cw; + canvas.height = ch; + var ctx = canvas.getContext('2d'); + if (!ctx) { cb(null, 'no canvas context'); return; } + ctx.drawImage(img, 0, 0, cw, ch); + if (!canvas.toBlob) { cb(null, 'no toBlob support'); return; } + canvas.toBlob(function(blob) { + cb(blob, blob ? null : 'compression produced no data'); + }, 'image/jpeg', COMPRESS_QUALITY); + }; + img.onerror = function() { + window.URL.revokeObjectURL(url); + cb(null, 'could not load image'); + }; + img.src = url; + } function getCsrfToken() { var match = document.cookie.match(/(?:^|;\s*)csrf=([^;]+)/); @@ -40,21 +88,53 @@ setStatus('Not an image file'); return; } + // Offer in-browser compression for large images before the size + // guard, so a >50 MB photo can still be uploaded once shrunk. + if (file.size > COMPRESS_THRESHOLD) { + var mb = (file.size / (1024 * 1024)).toFixed(1); + var ok = window.confirm('This image is ' + mb + ' MB. Compress it in your browser before uploading?\n\nRecommended — this resizes and re-encodes it as JPEG for a much faster upload. Cancel to upload the original.'); + if (ok) { + setStatus('Compressing…'); + setDisabled(true); + compressImage(file, function(blob, err) { + if (err || !blob) { + // Compression failed — fall back to the original. + proceedUpload(file, true, null); + return; + } + setStatus('Compressed ' + mb + ' MB → ' + (blob.size / (1024 * 1024)).toFixed(1) + ' MB'); + proceedUpload(blob, true, renameToJpg(file.name)); + }); + return; + } + } + } + proceedUpload(file, isImage, null); + } + + // proceedUpload performs the actual POST. filename, when set, is sent as + // the multipart part filename (used for compressed blobs that have none). + function proceedUpload(file, isImage, filename) { + if (isImage) { if (file.size > IMG_MAX) { + setDisabled(false); setStatus('File too large (max 50 MB)'); return; } - } else { - if (file.size > FILE_MAX) { - setStatus('File too large (max 5 MB)'); - return; - } + } else if (file.size > FILE_MAX) { + setDisabled(false); + setStatus('File too large (max 5 MB)'); + return; } setStatus('Uploading…'); setDisabled(true); var fd = new FormData(); - fd.append('file', file); + if (filename) { + fd.append('file', file, filename); + } else { + fd.append('file', file); + } fd.append('csrf_token', getCsrfToken()); var endpoint = isImage ? '/admin/upload' : '/admin/upload-file';