diff --git a/README.md b/README.md index 81f2519..3db0543 100644 --- a/README.md +++ b/README.md @@ -423,6 +423,7 @@ If proxying through Cloudflare, `X-Forwarded-For` is safe to trust for rate limi | `GET` | `/bin/{name}` | Public | View paste | | `GET` | `/bin/{name}/{token}` | Public | View token-protected paste | | `GET` | `/uploads/{filename}` | Public | Serve uploaded image inline; non-images forced as `attachment` | +| `GET` | `/uploads/thumb/{filename}` | Public | Serve a 512px (long side) JPEG thumbnail of an uploaded image, generated and cached on first request | | `GET` | `/admin/login` | Public | Login form | | `POST` | `/admin/login` | Public | Submit login | | `POST` | `/admin/logout` | Admin | Logout (CSRF protected) | diff --git a/internal/server/handlers.go b/internal/server/handlers.go index f718a37..c0f6db6 100644 --- a/internal/server/handlers.go +++ b/internal/server/handlers.go @@ -27,6 +27,7 @@ import ( "strings" "time" + "glimmer/internal/db" "glimmer/internal/slug" "github.com/yuin/goldmark" @@ -544,8 +545,16 @@ func (s *Server) handleAdminBin(w http.ResponseWriter, r *http.Request) { http.Error(w, "Database error", http.StatusInternalServerError) return } + cards := make([]pasteCard, 0, len(pastes)) + for _, p := range pastes { + cards = append(cards, pasteCard{ + Paste: p, + Summary: pasteSummary(p.Content, 140), + ThumbURL: thumbURLFor(firstPasteImage(p.Content)), + }) + } d := s.adminPage(w, r) - d.Pastes = pastes + d.Pastes = cards renderTemplate(w, "admin_bin.html", d) } @@ -776,6 +785,158 @@ func scaleImage(src image.Image, maxDim int) image.Image { return dst } +// ---- Thumbnails ---- + +const thumbMaxDim = 512 // long-side size of generated thumbnails, in pixels + +// thumbDir is the directory thumbnails are cached in (a subdir of uploads). +func (s *Server) thumbDir() string { + return filepath.Join(s.cfg.Upload.Dir, "thumbs") +} + +// thumbPath returns the on-disk path of the thumbnail for an upload filename. +// Thumbnails are always JPEG, named after the original's hash. +func (s *Server) thumbPath(filename string) string { + base := strings.TrimSuffix(filename, filepath.Ext(filename)) + return filepath.Join(s.thumbDir(), base+".jpg") +} + +// generateThumbnail decodes an uploaded image, scales it so its long side is at +// most thumbMaxDim px, and writes a cached JPEG thumbnail. Best-effort: returns +// an error for formats it can't decode (e.g. WebP), leaving callers to fall +// back to the original file. +func (s *Server) generateThumbnail(filename string) error { + if !isImageFile(filename) { + return fmt.Errorf("not an image") + } + f, err := os.Open(filepath.Join(s.cfg.Upload.Dir, filename)) + if err != nil { + return err + } + src, _, err := image.Decode(f) + f.Close() + if err != nil { + return err + } + dst := scaleImage(src, thumbMaxDim) + if err := os.MkdirAll(s.thumbDir(), 0755); err != nil { + return err + } + tp := s.thumbPath(filename) + tmp := tp + ".tmp" + out, err := os.Create(tmp) + if err != nil { + return err + } + if err := jpeg.Encode(out, dst, &jpeg.Options{Quality: 82}); err != nil { + out.Close() + os.Remove(tmp) + return err + } + out.Close() + return os.Rename(tmp, tp) +} + +// handleThumb serves a cached 512px (long side) JPEG thumbnail for an uploaded +// image, generating it on first request. Falls back to serving the original +// inline for images it can't decode (e.g. WebP). +func (s *Server) handleThumb(w http.ResponseWriter, r *http.Request) { + name := r.PathValue("filename") + if !validUploadFilename(name) || !isImageFile(name) { + http.NotFound(w, r) + return + } + orig := filepath.Join(s.cfg.Upload.Dir, name) + if _, err := os.Stat(orig); err != nil { + http.NotFound(w, r) + return + } + tp := s.thumbPath(name) + if _, err := os.Stat(tp); err != nil { + if err := s.generateThumbnail(name); err != nil { + // Can't thumbnail this format — serve the original inline. + http.ServeFile(w, r, orig) + return + } + } + w.Header().Set("Content-Type", "image/jpeg") + w.Header().Set("Cache-Control", "public, max-age=86400") + http.ServeFile(w, r, tp) +} + +// ---- Paste card helpers (admin Pastes grid) ---- + +type pasteCard struct { + db.Paste + Summary string + ThumbURL string // thumbnail URL for the first image, or "" if none +} + +var ( + pasteImgMDRe = regexp.MustCompile(`!\[[^\]]*\]\(\s*(\S+?)\s*\)`) + pasteImgHTMLRe = regexp.MustCompile(`(?i)]+src=["']?([^"'>\s]+)`) + fencedCodeRe = regexp.MustCompile("(?s)```.*?```") + mdLinkRe = regexp.MustCompile(`\[([^\]]*)\]\([^)]*\)`) + mdStripRe = regexp.MustCompile("[#>*_`~|<>\\-]+") +) + +// firstPasteImage returns the URL of the first image referenced in paste +// content (markdown or HTML), or "" if there is none. +func firstPasteImage(content string) string { + idxMD, idxHTML := -1, -1 + var urlMD, urlHTML string + if m := pasteImgMDRe.FindStringSubmatchIndex(content); m != nil { + idxMD, urlMD = m[0], content[m[2]:m[3]] + } + if m := pasteImgHTMLRe.FindStringSubmatchIndex(content); m != nil { + idxHTML, urlHTML = m[0], content[m[2]:m[3]] + } + switch { + case idxMD == -1 && idxHTML == -1: + return "" + case idxHTML == -1: + return urlMD + case idxMD == -1: + return urlHTML + case idxMD <= idxHTML: + return urlMD + default: + return urlHTML + } +} + +// thumbURLFor maps a paste's first image URL to a card thumbnail URL. Local +// uploads use the on-the-fly thumbnail route; remote https images are used +// as-is (allowed by CSP img-src); anything else yields no thumbnail. +func thumbURLFor(rawURL string) string { + if strings.HasPrefix(rawURL, "/uploads/") { + name := strings.TrimPrefix(rawURL, "/uploads/") + if validUploadFilename(name) && isImageFile(name) { + return "/uploads/thumb/" + name + } + return "" + } + if strings.HasPrefix(rawURL, "https://") { + return rawURL + } + return "" +} + +// pasteSummary produces a short plain-text excerpt from paste content by +// stripping code fences, images, link targets, and markdown punctuation. +func pasteSummary(content string, max int) string { + t := fencedCodeRe.ReplaceAllString(content, " ") + t = pasteImgMDRe.ReplaceAllString(t, " ") + t = mdLinkRe.ReplaceAllString(t, "$1") + t = mdStripRe.ReplaceAllString(t, " ") + t = strings.Join(strings.Fields(t), " ") + r := []rune(t) + if len(r) > max { + return strings.TrimSpace(string(r[:max])) + "…" + } + return t +} + // handleUploadsServe serves files from the upload directory. For non-image // files it forces Content-Disposition: attachment with an octet-stream type so // that arbitrary uploads (e.g. HTML, SVG, JS) cannot be rendered in-browser @@ -886,6 +1047,7 @@ func (s *Server) handleAdminUploadDelete(w http.ResponseWriter, r *http.Request) return } os.Remove(filepath.Join(s.cfg.Upload.Dir, filename)) + os.Remove(s.thumbPath(filename)) s.db.DeleteUpload(filename) http.Redirect(w, r, "/admin/uploads", http.StatusSeeOther) } @@ -945,6 +1107,7 @@ func (s *Server) handleAdminUploadResize(w http.ResponseWriter, r *http.Request) jsonError(w, "Failed to save resized image", http.StatusInternalServerError) return } + os.Remove(s.thumbPath(filename)) // invalidate cached thumbnail; regenerated on next view info, _ := os.Stat(path) var newSize int64 @@ -1067,6 +1230,7 @@ func (s *Server) handleUpload(w http.ResponseWriter, r *http.Request) { displayName := sanitizeDisplayFilename(header.Filename) s.db.RecordUpload(filename, displayName) + _ = s.generateThumbnail(filename) // best-effort; lazily regenerated on first view otherwise imgURL := "/uploads/" + filename w.Header().Set("Content-Type", "application/json") diff --git a/internal/server/server.go b/internal/server/server.go index d54de73..261c914 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -43,7 +43,9 @@ func New(cfg *config.Config, database *db.DB) *Server { func securityHeaders(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("X-Frame-Options", "DENY") + // SAMEORIGIN (not DENY) so the admin Pastes page can preview a paste in + // an in-page iframe; cross-site framing is still blocked. + w.Header().Set("X-Frame-Options", "SAMEORIGIN") w.Header().Set("X-Content-Type-Options", "nosniff") w.Header().Set("Referrer-Policy", "strict-origin-when-cross-origin") // All assets are served from the same origin (Pico CSS is vendored @@ -51,8 +53,9 @@ func securityHeaders(next http.Handler) http.Handler { // down. img-src allows data: and https: so uploaded/remote images and // 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. + // scripts/styles in the templates; object-src/base-uri are pinned to + // blunt injection; frame-ancestors 'self' permits the same-origin paste + // preview iframe while blocking cross-site clickjacking. w.Header().Set("Content-Security-Policy", "default-src 'self'; "+ "img-src 'self' data: https: blob:; "+ @@ -60,7 +63,7 @@ func securityHeaders(next http.Handler) http.Handler { "script-src 'self' 'unsafe-inline'; "+ "object-src 'none'; "+ "base-uri 'none'; "+ - "frame-ancestors 'none'") + "frame-ancestors 'self'") next.ServeHTTP(w, r) }) } @@ -96,6 +99,8 @@ func (s *Server) Start() error { // Uploaded files (public — appear in public pastes). Non-image files are // served as attachments to prevent same-origin XSS via HTML/SVG/JS uploads. + // The more specific /uploads/thumb/ route wins for thumbnails. + mux.HandleFunc("GET /uploads/thumb/{filename}", s.handleThumb) mux.HandleFunc("GET /uploads/", s.handleUploadsServe) // Public routes diff --git a/internal/server/static/style.css b/internal/server/static/style.css index c95db3d..6864b90 100644 --- a/internal/server/static/style.css +++ b/internal/server/static/style.css @@ -417,3 +417,228 @@ mark.badge-hidden { min-width: 2.5rem; text-align: center; } + +/* ── Pastes masonry cards (Xiaohongshu style) ───────────────────────── */ +.pcard-grid { + columns: 240px; + column-gap: 1rem; + margin-top: 1rem; +} + +.pcard { + break-inside: avoid; + display: inline-block; + width: 100%; + margin: 0 0 1rem; + padding: 0; + background: var(--pico-card-background-color); + border: 1px solid var(--pico-muted-border-color); + border-radius: var(--pico-border-radius); + overflow: hidden; + cursor: pointer; + transition: border-color 0.15s, box-shadow 0.15s, transform 0.15s; +} + +.pcard:hover { + transform: translateY(-2px); +} + +.pcard:focus-visible { + outline: 2px solid var(--pico-primary); + outline-offset: 2px; +} + +.pcard:hover .pcard-img { + opacity: 0.92; +} + +.pcard:hover { + border-color: var(--pico-primary); + box-shadow: 0 6px 20px rgba(0, 0, 0, 0.25); +} + +.pcard-imgwrap { + display: block; + width: 100%; + margin: 0; + padding: 0; + border: 0; + background: none; + cursor: pointer; + line-height: 0; +} + +.pcard-img { + width: 100%; + height: auto; + display: block; + transition: opacity 0.15s; +} + +.pcard-imgwrap:hover .pcard-img { + opacity: 0.9; +} + +.pcard-body { + padding: 0.75rem; +} + +.pcard-title { + display: block; + width: 100%; + margin: 0 0 0.35rem; + padding: 0; + border: 0; + background: none; + text-align: left; + font-weight: 600; + font-size: 1rem; + line-height: 1.3; + color: var(--pico-color); + cursor: pointer; +} + +.pcard-title:hover { + color: var(--pico-primary); +} + +.pcard-summary { + margin: 0 0 0.5rem; + font-size: 0.85rem; + line-height: 1.45; + color: var(--pico-muted-color); + display: -webkit-box; + -webkit-line-clamp: 3; + -webkit-box-orient: vertical; + overflow: hidden; +} + +.pcard-meta { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 0.3rem; + margin-bottom: 0.6rem; + font-size: 0.72rem; + color: var(--pico-muted-color); +} + +.pcard-date { + margin-left: auto; + font-variant-numeric: tabular-nums; +} + +.pcard-actions { + display: flex; + flex-wrap: wrap; + gap: 0.25rem; + cursor: default; +} + +.pcard-actions form { + margin: 0; + display: flex; +} + +.pcard-actions a[role="button"], +.pcard-actions button { + margin: 0; + padding: 0.2rem 0.5rem; + font-size: 0.78rem; + white-space: nowrap; +} + +/* ── In-page paste preview modal ────────────────────────────────────── */ +.preview-dialog { + width: min(820px, 94vw); + height: min(80vh, 920px); + max-width: none; + max-height: none; + padding: 0; + border: 1px solid var(--pico-muted-border-color); + border-radius: 16px; + background: var(--pico-card-background-color); + box-shadow: 0 24px 70px rgba(0, 0, 0, 0.55); + overflow: hidden; + transition: width 0.22s ease, height 0.22s ease; +} + +/* dialog is only laid out when open; scope flex so closed state stays hidden */ +.preview-dialog[open] { + display: flex; + flex-direction: column; +} + +/* Expanded fills the main content area, not the whole viewport. */ +.preview-dialog.expanded { + width: min(1180px, 94vw); + height: 88vh; +} + +.preview-dialog::backdrop { + background: rgba(0, 0, 0, 0.55); + backdrop-filter: blur(3px); +} + +.preview-head { + flex: 0 0 auto; + display: flex; + align-items: center; + gap: 0.75rem; + padding: 0.55rem 0.6rem 0.55rem 1rem; + background: var(--pico-card-background-color); + border-bottom: 1px solid var(--pico-muted-border-color); +} + +.preview-title { + flex: 1; + min-width: 0; + font-weight: 600; + font-size: 0.95rem; + color: var(--pico-color); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +.preview-actions { + flex: 0 0 auto; + display: flex; + gap: 0.4rem; + align-items: center; +} + +.preview-actions a, +.preview-actions button { + margin: 0; + border-radius: 8px; +} + +/* square icon buttons for expand / close */ +#preview-expand, +.preview-close { + width: 2rem; + padding: 0.25rem 0; + text-align: center; + line-height: 1; + font-size: 0.95rem; +} + +.preview-close { + background: transparent; + border: 1px solid var(--pico-muted-border-color); + color: var(--pico-muted-color); +} + +.preview-close:hover { + background: var(--pico-del-color); + border-color: var(--pico-del-color); + color: #fff; +} + +.preview-frame { + flex: 1 1 auto; + width: 100%; + border: 0; + background: var(--pico-background-color); +} diff --git a/internal/server/templates/admin_bin.html b/internal/server/templates/admin_bin.html index fbeef19..616bc1e 100644 --- a/internal/server/templates/admin_bin.html +++ b/internal/server/templates/admin_bin.html @@ -26,67 +26,70 @@ Pastes Uploads -
+
{{if .Error}}
{{.Error}}
{{end}} -
-
-
-

Pastes

-

{{len .Pastes}} pastes

-
- + New Paste -
-
- - - - - - - - - - - - - {{range .Pastes}} - - - - - - - - - {{else}} - - - - {{end}} - -
NameTitleFormatTokenUpdatedActions
{{.Name}}{{.Title}}{{.Format}}{{if .Token}}🔒 token{{else}}public{{end}}{{if .Hidden}} hidden{{end}}{{.UpdatedAt.Format "2006-01-02 15:04"}} -
- Edit - - {{if .Token}}{{end}} -
- - -
-
-
-
- 📄 -

No pastes yet.

- Create your first paste -
-
-
-
+
+
+

Pastes

+

{{len .Pastes}} pastes

+
+ + New Paste +
+ + {{if .Pastes}} +
+ {{range .Pastes}} +
+ {{if .ThumbURL}} +
+ +
+ {{end}} +
+

{{if .Title}}{{.Title}}{{else}}{{.Name}}{{end}}

+ {{if .Summary}}

{{.Summary}}

{{end}} +
+ {{.Format}} + {{if .Token}}🔒{{else}}public{{end}} + {{if .Hidden}}hidden{{end}} + {{.UpdatedAt.Format "01-02 15:04"}} +
+
+ + Edit + +
+ + +
+
+
+
+ {{end}} +
+ {{else}} +
+ 📄 +

No pastes yet.

+ Create your first paste +
+ {{end}}
+ + +
+ Preview +
+ Open ↗ + + +
+
+ +
@@ -97,6 +100,65 @@