diff --git a/CLAUDE.md b/CLAUDE.md index 04a274a..53f0139 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -2,7 +2,7 @@ ## Project Overview -**Glimmer** is a single-binary Go URL shortener + pastebin with image upload support. It runs on a Raspberry Pi Zero (512 MB RAM, ARMv5) and compiles to a fully self-contained binary — no CGo, no external runtime, no system SQLite. +**Glimmer** is a single-binary Go URL shortener + pastebin with image and file upload support. It runs on a Raspberry Pi Zero (512 MB RAM, ARMv5) and compiles to a fully self-contained binary — no CGo, no external runtime, no system SQLite. Live at [luci.ooo](https://luci.ooo). @@ -33,25 +33,27 @@ glimmer/ ├── Makefile ├── data/ │ ├── urls.db # SQLite DB (auto-created) -│ └── uploads/ # Uploaded images (auto-created) +│ └── uploads/ # Uploaded images & files (auto-created) └── internal/ ├── config/config.go # TOML config structs + loader - ├── db/db.go # DB open/migrate; Link + Paste CRUD + ├── db/db.go # DB open/migrate; Link + Paste + Upload CRUD ├── slug/slug.go # Base-36 slug generation + validation └── server/ ├── server.go # Mux, middleware wiring, server start ├── handlers.go # All HTTP handlers + rendering helpers ├── middleware.go # Auth, CSRF, sessions, rate limiter ├── templates.go # embed.FS for templates + static; initTemplates() - ├── static/style.css # Custom styles on top of Pico CSS 2 + ├── static/ + │ ├── style.css # Custom styles on top of Pico CSS 2 + │ └── upload.js # Shared client-side upload helper (window.GlimmerUpload) └── templates/ ├── index.html # Public: URL shortener form ├── admin_login.html # Login (dark, centered) ├── admin.html # Dashboard: stats, tiles, links tables ├── admin_edit.html # Edit a single link ├── admin_bin.html # Pastes list - ├── admin_bin_edit.html # Create / edit paste (with image upload JS) - ├── admin_uploads.html # Image upload management + ├── admin_bin_edit.html # Create / edit paste (uses /static/upload.js) + ├── admin_uploads.html # Image + file upload management ├── bin_view.html # Public paste viewer ├── bin_token.html # Token prompt for protected pastes └── 404.html @@ -84,7 +86,7 @@ All templates receive a `pageData` struct. Add new fields there when templates n Templates and static files are embedded into the binary via `//go:embed` in `templates.go`. Changes to templates are compiled in; they are **not** reloaded at runtime. Always rebuild after template changes. ### No JS frameworks -All JavaScript is vanilla ES5-style (`var`, not `const`/`let`) written inline in templates. No build step, no npm, no bundler. +All JavaScript is vanilla ES5-style (`var`, not `const`/`let`). Most JS is inline in templates; shared upload logic lives in `static/upload.js` and is exposed as `window.GlimmerUpload`. No build step, no npm, no bundler. ### CSS framework [Pico CSS 2](https://picocss.com/) loaded from CDN. Custom overrides in `static/style.css`. Admin pages use `data-theme="dark"`. @@ -104,10 +106,20 @@ All JavaScript is vanilla ES5-style (`var`, not `const`/`let`) written inline in All state-changing POSTs must include `` in the form. Handlers must be wrapped with `requireCSRF`. For multipart form handlers (file uploads), verify CSRF manually inside the handler *after* calling `r.ParseMultipartForm` — do not use the `requireCSRF` wrapper as it will parse with Go's default 32 MB limit before `MaxBytesReader` takes effect. ### File uploads +Two endpoints, both admin-only and CSRF-protected: +- `POST /admin/upload` — images only (PNG/JPEG/GIF/WebP), up to `upload.max_size_mb` from config (default 50 MB). MIME type validated by magic bytes via `http.DetectContentType`. +- `POST /admin/upload-file` — any file type, hard-coded 5 MB cap. Validates only that the extension is `[a-z0-9]{1,10}`. + +Shared upload rules: - Max size enforced via `http.MaxBytesReader(w, r.Body, maxBytes)` at handler start -- MIME type validated via `http.DetectContentType` (magic bytes), not the client-supplied `Content-Type` -- Filenames are always `[32 hex chars].[ext]` — validated by `validUploadRe` regexp before any file operation +- Filenames written to disk are always `[32 hex chars].[ext]` — validated by `validUploadRe` regexp before any file operation. Original filenames are stored in the `uploads` table (filename → original_name) and used for `Content-Disposition` and the admin listing. - Per-request timeouts extended to 120s via `http.NewResponseController` — global timeouts stay at 5s/10s +- `sanitizeDisplayFilename()` strips control chars and markdown-significant chars (`[ ] ( ) \ \` * < > " '`) before the original name is embedded in JSON responses or stored. + +### Serving uploads (`/uploads/{filename}`) +`handleUploadsServe` validates the filename against `validUploadRe`, then: +- **Images** (`.png`/`.jpg`/`.gif`/`.webp`) — served inline by `http.ServeFile` so they can embed in public pastes. +- **Everything else** — forced to download with `Content-Type: application/octet-stream` + `Content-Disposition: attachment` (with both ASCII `filename=` and RFC 5987 `filename*=UTF-8''…`). This prevents same-origin XSS from uploaded HTML/SVG/JS being rendered by the browser. ### Image resize Only PNG (`.png`) and JPEG (`.jpg`) are resizable. Resize uses a nearest-neighbour scale implemented in stdlib (`image`, `image/color`, `image/jpeg`, `image/png`) — no external image library. GIF and WebP are served and deletable but not resizable. diff --git a/README.md b/README.md index 61e1c1a..74d7da0 100644 --- a/README.md +++ b/README.md @@ -33,16 +33,19 @@ A lightweight, single-binary URL shortener and pastebin built in Go. Hosted on [ - **Raw view:** Append `?raw=1` to any paste URL for `text/plain` output - **Copy button:** One-click clipboard copy in the paste viewer - **Image embedding:** Paste an image from clipboard or use the Upload Image button in the paste editor — image is uploaded and a markdown link is inserted at the cursor automatically +- **File attachments:** Use the Upload File button to attach any file type (up to 5 MB); a markdown download link is inserted at the cursor -### Image Uploads -- **Admin-only upload:** Images up to 50 MB via file picker or clipboard paste in the paste editor -- **Supported formats:** PNG, JPEG, GIF, WebP (validated by magic bytes, not file extension) -- **Uploads management tab:** View all uploaded images with thumbnails, file size, and dimensions -- **Resize:** Downscale PNG or JPEG images in-place by setting a max dimension — re-encodes JPEG at 85% quality; no additional dependencies -- **Delete:** Remove individual images from the admin uploads tab -- **Copy markdown:** One-click copy of the `` link for use in any paste -- **Public serving:** Uploaded images are served at `/uploads/{filename}` and render in public paste views -- **Per-upload timeout:** Upload requests get a 120-second read/write deadline via `http.NewResponseController`; all other routes keep the 5s/10s defaults +### Image & File Uploads +- **Two upload modes:** + - **Images** — PNG, JPEG, GIF, WebP up to 50 MB (configurable). Validated by magic bytes, not file extension. + - **Files** — any file type up to 5 MB (hard-coded). Validated by extension regex only. +- **Original filenames preserved:** Stored on disk as `[32 hex chars].[ext]` but the user's original filename is recorded in a SQLite `uploads` table and used in the admin listing and the `Content-Disposition` header when the file is downloaded. +- **Uploads management tab:** View all uploaded files with thumbnails (images) or document icons (files), extension chip, original name, file size, and image dimensions. +- **Resize:** Downscale PNG or JPEG images in-place by setting a max dimension — re-encodes JPEG at 85% quality; no additional dependencies. +- **Delete:** Remove individual uploads from the admin uploads tab. +- **Copy markdown:** One-click copy of the `` (images) or `[name](/uploads/...)` (files) link for use in any paste. +- **Public serving:** Uploaded images are served inline at `/uploads/{filename}` and render in public paste views. **Non-image files are forced to download** with `Content-Disposition: attachment` to prevent same-origin XSS via uploaded HTML/SVG/JS. +- **Per-upload timeout:** Upload requests get a 120-second read/write deadline via `http.NewResponseController`; all other routes keep the 5s/10s defaults. ### Security - CSRF protection on every state-changing POST (double-submit cookie pattern) @@ -69,12 +72,12 @@ glimmer/ │ └── glimmer.init # SysV init script (Ubuntu 14.04 and older) ├── data/ │ ├── urls.db # SQLite database (auto-created on first run) -│ └── uploads/ # Uploaded images (auto-created on first run) +│ └── uploads/ # Uploaded images & files (auto-created on first run) └── internal/ ├── config/ │ └── config.go # TOML config loader; Config struct (incl. UploadConfig) ├── db/ - │ └── db.go # SQLite open/migrate; Link & Paste CRUD + │ └── db.go # SQLite open/migrate; Link & Paste & Upload CRUD ├── slug/ │ └── slug.go # Base-36 slug generation and validation └── server/ @@ -82,14 +85,15 @@ glimmer/ ├── handlers.go # All request handlers; template rendering helpers ├── middleware.go # requireAuth, requireCSRF, rateLimiter, sessionStore, clientIP ├── static/ - │ └── style.css # Custom styles on top of Pico CSS (no JS) + │ ├── style.css # Custom styles on top of Pico CSS + │ └── upload.js # Shared client-side upload helper (window.GlimmerUpload) └── templates/ ├── index.html # Public home: shorten form + QR result ├── admin_login.html # Login form (dark, centered card) ├── admin.html # Admin dashboard: stats bar, tiles, links tables ├── admin_edit.html # Edit a single link ├── admin_bin.html # Pastes list with format/token badges - ├── admin_bin_edit.html # Create / edit a paste (with image upload) + ├── admin_bin_edit.html # Create / edit a paste (with image + file upload) ├── admin_uploads.html # Upload management: list, resize, delete ├── bin_view.html # Public paste viewer (GitHub Gist style) └── 404.html # Not found page @@ -154,8 +158,8 @@ path = "./data/urls.db" length = 3 # Auto-generated slug length (characters) [upload] -dir = "./data/uploads" # Where uploaded images are stored (auto-created) -max_size_mb = 50 # Max image upload size in MB +dir = "./data/uploads" # Where uploaded images & files are stored (auto-created) +max_size_mb = 50 # Max image upload size in MB (file uploads are hard-capped at 5 MB) ``` ### 3. Set your admin password @@ -402,7 +406,7 @@ If proxying through Cloudflare, `X-Forwarded-For` is safe to trust for rate limi | `GET` | `/{slug}` | Public | Redirect to destination | | `GET` | `/bin/{name}` | Public | View paste | | `GET` | `/bin/{name}/{token}` | Public | View token-protected paste | -| `GET` | `/uploads/{filename}` | Public | Serve uploaded image | +| `GET` | `/uploads/{filename}` | Public | Serve uploaded image inline; non-images forced as `attachment` | | `GET` | `/admin/login` | Public | Login form | | `POST` | `/admin/login` | Public | Submit login | | `POST` | `/admin/logout` | Admin | Logout (CSRF protected) | @@ -418,8 +422,9 @@ If proxying through Cloudflare, `X-Forwarded-For` is safe to trust for rate limi | `POST` | `/admin/bin/edit/{id}` | Admin | Save paste edit (CSRF) | | `POST` | `/admin/bin/delete/{id}` | Admin | Delete paste (CSRF) | | `GET` | `/admin/uploads` | Admin | Uploads management list | -| `POST` | `/admin/upload` | Admin | Upload an image (returns JSON) | -| `POST` | `/admin/uploads/delete/{filename}` | Admin | Delete an uploaded image (CSRF) | +| `POST` | `/admin/upload` | Admin | Upload an image — PNG/JPEG/GIF/WebP, up to 50 MB (returns JSON) | +| `POST` | `/admin/upload-file` | Admin | Upload any file — up to 5 MB (returns JSON) | +| `POST` | `/admin/uploads/delete/{filename}` | Admin | Delete an uploaded file (CSRF) | | `POST` | `/admin/uploads/resize/{filename}` | Admin | Resize a PNG/JPEG in-place (returns JSON) | | `GET` | `/static/*` | Public | CSS / static assets | @@ -446,9 +451,16 @@ CREATE TABLE pastes ( content TEXT NOT NULL DEFAULT '', format TEXT NOT NULL DEFAULT 'markdown', -- 'markdown' | 'text' token TEXT, -- NULL = public; non-null = token required + hidden INTEGER NOT NULL DEFAULT 0, -- 1 = return 404 instead of token prompt created_at TEXT NOT NULL DEFAULT (datetime('now')), updated_at TEXT NOT NULL DEFAULT (datetime('now')) ); + +CREATE TABLE uploads ( + filename TEXT PRIMARY KEY, -- on-disk name, e.g. "abc123…def.pdf" + original_name TEXT NOT NULL DEFAULT '', -- sanitised original from the upload form + created_at TEXT NOT NULL DEFAULT (datetime('now')) +); ``` To reset the database (e.g. during development): @@ -481,8 +493,8 @@ path = "./data/urls.db" # Path to SQLite file (directory auto-created) length = 3 # Length of auto-generated slugs (recommended: 3–6) [upload] -dir = "./data/uploads" # Directory for uploaded images (auto-created) -max_size_mb = 50 # Max upload size in MB +dir = "./data/uploads" # Directory for uploaded images & files (auto-created) +max_size_mb = 50 # Max image upload size in MB; file uploads are hard-capped at 5 MB ``` --- diff --git a/internal/db/db.go b/internal/db/db.go index 43e7286..a77de3b 100644 --- a/internal/db/db.go +++ b/internal/db/db.go @@ -31,6 +31,12 @@ type Link struct { CreatedAt time.Time } +type Upload struct { + Filename string + OriginalName string + CreatedAt time.Time +} + type DB struct { conn *sql.DB } @@ -76,6 +82,11 @@ func migrate(conn *sql.DB) error { created_at TEXT NOT NULL DEFAULT (datetime('now')), updated_at TEXT NOT NULL DEFAULT (datetime('now')) ); + CREATE TABLE IF NOT EXISTS uploads ( + filename TEXT PRIMARY KEY, + original_name TEXT NOT NULL DEFAULT '', + created_at TEXT NOT NULL DEFAULT (datetime('now')) + ); `) if err != nil { return fmt.Errorf("running migrations: %w", err) @@ -277,6 +288,47 @@ func scanPaste(row *sql.Row) (*Paste, error) { return &p, nil } +// ---- Upload metadata ---- + +func (d *DB) RecordUpload(filename, originalName string) error { + _, err := d.conn.Exec( + "INSERT OR REPLACE INTO uploads (filename, original_name) VALUES (?, ?)", + filename, originalName, + ) + return err +} + +func (d *DB) GetUploadName(filename string) (string, error) { + var name string + err := d.conn.QueryRow("SELECT original_name FROM uploads WHERE filename = ?", filename).Scan(&name) + if err == sql.ErrNoRows { + return "", nil + } + return name, err +} + +func (d *DB) ListUploadNames() (map[string]string, error) { + rows, err := d.conn.Query("SELECT filename, original_name FROM uploads") + if err != nil { + return nil, err + } + defer rows.Close() + names := make(map[string]string) + for rows.Next() { + var f, n string + if err := rows.Scan(&f, &n); err != nil { + return nil, err + } + names[f] = n + } + return names, rows.Err() +} + +func (d *DB) DeleteUpload(filename string) error { + _, err := d.conn.Exec("DELETE FROM uploads WHERE filename = ?", filename) + return err +} + func scanLink(row *sql.Row) (*Link, error) { var l Link var ts string diff --git a/internal/server/handlers.go b/internal/server/handlers.go index 0fb522d..cc3cdde 100644 --- a/internal/server/handlers.go +++ b/internal/server/handlers.go @@ -56,15 +56,17 @@ type pageData struct { } type UploadInfo struct { - Filename string - SizeHuman string - Size int64 - URL string - Width int - Height int - CanResize bool - IsImage bool - ModTime time.Time + Filename string + OriginalName string + SizeHuman string + Size int64 + URL string + Ext string + Width int + Height int + CanResize bool + IsImage bool + ModTime time.Time } var mdRenderer = goldmark.New( @@ -770,12 +772,38 @@ func (s *Server) handleUploadsServe(w http.ResponseWriter, r *http.Request) { } path := filepath.Join(s.cfg.Upload.Dir, name) if !isImageFile(name) { + download := name + if orig, _ := s.db.GetUploadName(name); orig != "" { + download = orig + } w.Header().Set("Content-Type", "application/octet-stream") - w.Header().Set("Content-Disposition", `attachment; filename="`+name+`"`) + w.Header().Set("Content-Disposition", contentDispositionAttachment(download)) } http.ServeFile(w, r, path) } +// contentDispositionAttachment builds a safe attachment header. The ASCII +// filename strips characters that would break header parsing; the RFC 5987 +// filename* preserves any UTF-8 chars for clients that understand it. +func contentDispositionAttachment(name string) string { + var ascii strings.Builder + for _, r := range name { + if r < 32 || r == 127 || r == '"' || r == '\\' { + continue + } + if r > 127 { + ascii.WriteByte('_') + continue + } + ascii.WriteRune(r) + } + a := ascii.String() + if a == "" { + a = "download" + } + return fmt.Sprintf(`attachment; filename="%s"; filename*=UTF-8''%s`, a, url.PathEscape(name)) +} + // ---- Upload management handlers ---- func (s *Server) handleAdminUploads(w http.ResponseWriter, r *http.Request) { @@ -785,6 +813,8 @@ func (s *Server) handleAdminUploads(w http.ResponseWriter, r *http.Request) { return } + names, _ := s.db.ListUploadNames() + var uploads []UploadInfo for _, entry := range entries { if entry.IsDir() { @@ -798,15 +828,17 @@ func (s *Server) handleAdminUploads(w http.ResponseWriter, r *http.Request) { if err != nil { continue } - ui := UploadInfo{ - Filename: name, - Size: info.Size(), - SizeHuman: formatBytes(info.Size()), - URL: "/uploads/" + name, - IsImage: isImageFile(name), - ModTime: info.ModTime(), - } ext := strings.ToLower(filepath.Ext(name)) + ui := UploadInfo{ + Filename: name, + OriginalName: names[name], + Size: info.Size(), + SizeHuman: formatBytes(info.Size()), + URL: "/uploads/" + name, + Ext: strings.TrimPrefix(ext, "."), + IsImage: isImageFile(name), + ModTime: info.ModTime(), + } if ui.IsImage { if f, err := os.Open(filepath.Join(s.cfg.Upload.Dir, name)); err == nil { if cfg, _, err := image.DecodeConfig(f); err == nil { @@ -838,6 +870,7 @@ func (s *Server) handleAdminUploadDelete(w http.ResponseWriter, r *http.Request) return } os.Remove(filepath.Join(s.cfg.Upload.Dir, filename)) + s.db.DeleteUpload(filename) http.Redirect(w, r, "/admin/uploads", http.StatusSeeOther) } @@ -937,7 +970,7 @@ func (s *Server) handleUpload(w http.ResponseWriter, r *http.Request) { return } - file, _, err := r.FormFile("file") + file, header, err := r.FormFile("file") if err != nil { w.Header().Set("Content-Type", "application/json") if err.Error() == "http: request body too large" { @@ -1003,10 +1036,14 @@ func (s *Server) handleUpload(w http.ResponseWriter, r *http.Request) { return } + displayName := sanitizeDisplayFilename(header.Filename) + s.db.RecordUpload(filename, displayName) + imgURL := "/uploads/" + filename w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(map[string]string{ "url": imgURL, + "filename": displayName, "markdown": "", }) } @@ -1074,6 +1111,8 @@ func (s *Server) handleFileUpload(w http.ResponseWriter, r *http.Request) { if displayName == "" { displayName = filename } + s.db.RecordUpload(filename, displayName) + w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(map[string]string{ "url": fileURL, diff --git a/internal/server/static/style.css b/internal/server/static/style.css index f4ded16..c95db3d 100644 --- a/internal/server/static/style.css +++ b/internal/server/static/style.css @@ -402,3 +402,18 @@ mark.badge-hidden { color: var(--pico-muted-color); font-size: 0.8rem; } + +.ext-chip { + display: inline-block; + font-family: var(--pico-font-family-monospace); + font-size: 0.7rem; + font-weight: 600; + text-transform: uppercase; + letter-spacing: 0.03em; + padding: 0.1rem 0.4rem; + border-radius: 4px; + background: var(--pico-primary-background); + color: var(--pico-primary-inverse); + min-width: 2.5rem; + text-align: center; +} diff --git a/internal/server/static/upload.js b/internal/server/static/upload.js new file mode 100644 index 0000000..592b053 --- /dev/null +++ b/internal/server/static/upload.js @@ -0,0 +1,96 @@ +// Shared upload helper for the admin uploads page and the paste editor. +// Wires up an "Upload Image" and "Upload File" button pair to their hidden +// file inputs and posts to /admin/upload (images, 50 MB) or +// /admin/upload-file (any file, 5 MB). +// +// Usage: call window.GlimmerUpload.init({ +// imgBtn, fileBtn, imgInput, fileInput, statusEl, +// onUploaded: function(data, isImage) { ... } // required +// }); + +(function(window) { + var IMG_MAX = 50 * 1024 * 1024; + var FILE_MAX = 5 * 1024 * 1024; + + function getCsrfToken() { + var match = document.cookie.match(/(?:^|;\s*)csrf=([^;]+)/); + return match ? match[1] : ''; + } + + function init(opts) { + var imgBtn = opts.imgBtn; + var fileBtn = opts.fileBtn; + var imgInput = opts.imgInput; + var fileInput = opts.fileInput; + var statusEl = opts.statusEl; + var onUploaded = opts.onUploaded; + + function setDisabled(v) { + if (imgBtn) imgBtn.disabled = v; + if (fileBtn) fileBtn.disabled = v; + } + + function setStatus(msg) { + if (statusEl) statusEl.textContent = msg; + } + + function doUpload(file, isImage) { + if (isImage) { + if (!file || !file.type || file.type.indexOf('image/') !== 0) { + setStatus('Not an image file'); + return; + } + if (file.size > IMG_MAX) { + setStatus('File too large (max 50 MB)'); + return; + } + } else { + if (file.size > FILE_MAX) { + setStatus('File too large (max 5 MB)'); + return; + } + } + setStatus('Uploading…'); + setDisabled(true); + + var fd = new FormData(); + fd.append('file', file); + fd.append('csrf_token', getCsrfToken()); + var endpoint = isImage ? '/admin/upload' : '/admin/upload-file'; + + fetch(endpoint, { method: 'POST', body: fd, credentials: 'same-origin' }) + .then(function(r) { return r.json(); }) + .then(function(data) { + setDisabled(false); + if (data.error) { + setStatus('Error: ' + data.error); + return; + } + onUploaded(data, isImage); + }) + .catch(function() { + setDisabled(false); + setStatus('Upload failed'); + }); + } + + if (imgBtn && imgInput) { + imgBtn.addEventListener('click', function() { imgInput.click(); }); + imgInput.addEventListener('change', function() { + if (imgInput.files.length > 0) doUpload(imgInput.files[0], true); + imgInput.value = ''; + }); + } + if (fileBtn && fileInput) { + fileBtn.addEventListener('click', function() { fileInput.click(); }); + fileInput.addEventListener('change', function() { + if (fileInput.files.length > 0) doUpload(fileInput.files[0], false); + fileInput.value = ''; + }); + } + + return { doUpload: doUpload, setStatus: setStatus }; + } + + window.GlimmerUpload = { init: init, getCsrfToken: getCsrfToken }; +})(window); diff --git a/internal/server/templates/admin_bin_edit.html b/internal/server/templates/admin_bin_edit.html index 5ee2954..476ed43 100644 --- a/internal/server/templates/admin_bin_edit.html +++ b/internal/server/templates/admin_bin_edit.html @@ -80,8 +80,8 @@