Files
lucioandClaude Opus 5.5 e48a1eacf4 Keep hotlink 403s out of CDN and browser caches
The tile hotlink refusal is sent with Cache-Control: no-store from
LuPhoto, Caddy and nginx instead of inheriting the one-year immutable
header. cloudflare.md explains that edge-cached tiles bypass the
origin Referer check, recommends a WAF rule for /t/, and notes that
tile URLs depend only on the photo, the settings and the site key.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 22:49:45 -08:00

306 lines
7.5 KiB
Go

package server
import (
"context"
"errors"
"fmt"
"io/fs"
"log"
"mime"
"net"
"net/http"
"net/url"
"os"
"path"
"path/filepath"
"strconv"
"strings"
"sync/atomic"
"time"
)
const (
contentSecurityPolicy = "default-src 'self'; img-src 'self' blob: data:; font-src 'self'; worker-src 'self'; frame-ancestors 'none'"
cacheImmutable = "public, max-age=31536000, immutable"
cacheShort = "public, max-age=60"
)
var contentTypes = map[string]string{
".html": "text/html; charset=utf-8",
".json": "application/json",
".js": "text/javascript; charset=utf-8",
".css": "text/css; charset=utf-8",
".svg": "image/svg+xml",
".webp": "image/webp",
".avif": "image/avif",
".jpg": "image/jpeg",
".jpeg": "image/jpeg",
".png": "image/png",
".woff2": "font/woff2",
".ico": "image/x-icon",
".txt": "text/plain; charset=utf-8",
}
var compressible = map[string]bool{".html": true, ".json": true, ".js": true, ".css": true, ".svg": true}
type Settings struct {
Output string
HotlinkAllow []string
}
type Handler struct {
settings atomic.Pointer[Settings]
keys http.Handler
}
func NewHandler(settings Settings, keys http.Handler) *Handler {
h := &Handler{keys: keys}
h.Update(settings)
return h
}
func (h *Handler) Update(settings Settings) {
allow := make([]string, 0, len(settings.HotlinkAllow))
for _, host := range settings.HotlinkAllow {
allow = append(allow, strings.ToLower(strings.TrimSpace(host)))
}
settings.HotlinkAllow = allow
h.settings.Store(&settings)
}
func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
header := w.Header()
header.Set("Content-Security-Policy", contentSecurityPolicy)
header.Set("X-Content-Type-Options", "nosniff")
header.Set("Referrer-Policy", "strict-origin-when-cross-origin")
if r.URL.Path == "/k" && h.keys != nil {
h.keys.ServeHTTP(w, r)
return
}
if r.Method != http.MethodGet && r.Method != http.MethodHead {
header.Set("Allow", "GET, HEAD")
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
settings := h.settings.Load()
clean := path.Clean("/" + r.URL.Path)
if strings.HasPrefix(clean, "/t/") && hotlinked(r, settings.HotlinkAllow) {
header.Set("Cache-Control", "no-store")
http.Error(w, "forbidden", http.StatusForbidden)
return
}
root, err := currentRoot(settings.Output)
if err != nil {
http.Error(w, "no build published yet", http.StatusServiceUnavailable)
return
}
if !visible(clean) {
notFound(w, r, root)
return
}
name := filepath.Join(root, filepath.FromSlash(clean))
info, err := os.Stat(name)
if err != nil {
notFound(w, r, root)
return
}
if info.IsDir() {
index := filepath.Join(name, "index.html")
indexInfo, err := os.Stat(index)
if err != nil || !indexInfo.Mode().IsRegular() {
notFound(w, r, root)
return
}
if !strings.HasSuffix(r.URL.Path, "/") {
target := clean + "/"
if clean == "/" {
target = "/"
}
if r.URL.RawQuery != "" {
target += "?" + r.URL.RawQuery
}
http.Redirect(w, r, target, http.StatusMovedPermanently)
return
}
name, info, clean = index, indexInfo, path.Join(clean, "index.html")
}
if !info.Mode().IsRegular() {
notFound(w, r, root)
return
}
serveFile(w, r, clean, name, info)
}
func notFound(w http.ResponseWriter, r *http.Request, root string) {
page, err := os.ReadFile(filepath.Join(root, "404.html"))
if err != nil {
http.NotFound(w, r)
return
}
header := w.Header()
header.Set("Content-Type", contentTypes[".html"])
header.Set("Cache-Control", cacheShort)
header.Set("Content-Length", strconv.Itoa(len(page)))
w.WriteHeader(http.StatusNotFound)
if r.Method != http.MethodHead {
_, _ = w.Write(page)
}
}
func visible(clean string) bool {
for _, part := range strings.Split(clean, "/") {
if strings.HasPrefix(part, ".") {
return false
}
}
return !strings.HasSuffix(clean, ".gz")
}
func hotlinked(r *http.Request, allow []string) bool {
referer := r.Header.Get("Referer")
if referer == "" {
return false
}
u, err := url.Parse(referer)
if err != nil || u.Host == "" {
return true
}
host := strings.ToLower(u.Hostname())
own := r.Host
if split, _, err := net.SplitHostPort(r.Host); err == nil {
own = split
}
if strings.EqualFold(own, host) {
return false
}
for _, allowed := range allow {
if host == allowed {
return false
}
}
return true
}
func currentRoot(output string) (string, error) {
link := filepath.Join(output, "current")
target, err := os.Readlink(link)
if err != nil {
return "", err
}
if !filepath.IsAbs(target) {
target = filepath.Join(output, target)
}
info, err := os.Stat(target)
if err != nil {
return "", err
}
if !info.IsDir() {
return "", fs.ErrNotExist
}
return target, nil
}
func cacheControl(clean string) string {
for _, prefix := range []string{"/t/", "/og/", "/assets/"} {
if strings.HasPrefix(clean, prefix) {
return cacheImmutable
}
}
return cacheShort
}
func acceptsGzip(r *http.Request) bool {
for _, part := range strings.Split(r.Header.Get("Accept-Encoding"), ",") {
coding, params, _ := strings.Cut(strings.TrimSpace(part), ";")
coding = strings.ToLower(strings.TrimSpace(coding))
if coding != "gzip" && coding != "*" {
continue
}
params = strings.ReplaceAll(strings.TrimSpace(params), " ", "")
if q, ok := strings.CutPrefix(params, "q="); ok {
if value, err := strconv.ParseFloat(q, 64); err == nil && value <= 0 {
continue
}
}
return true
}
return false
}
func serveFile(w http.ResponseWriter, r *http.Request, clean, name string, info fs.FileInfo) {
header := w.Header()
ext := strings.ToLower(path.Ext(clean))
contentType, ok := contentTypes[ext]
if !ok {
contentType = mime.TypeByExtension(ext)
}
if contentType == "" {
contentType = "application/octet-stream"
}
header.Set("Content-Type", contentType)
header.Set("Cache-Control", cacheControl(clean))
variant := ""
if compressible[ext] {
header.Add("Vary", "Accept-Encoding")
if acceptsGzip(r) {
if gzInfo, err := os.Stat(name + ".gz"); err == nil && gzInfo.Mode().IsRegular() && gzInfo.ModTime().After(info.ModTime().Add(-time.Second)) {
name, info, variant = name+".gz", gzInfo, "-gz"
header.Set("Content-Encoding", "gzip")
}
}
}
f, err := os.Open(name)
if err != nil {
header.Del("Content-Encoding")
http.NotFound(w, r)
return
}
defer f.Close()
header.Set("ETag", fmt.Sprintf("\"%x-%x%s\"", info.ModTime().UnixNano(), info.Size(), variant))
http.ServeContent(w, r, "", info.ModTime(), f)
}
type Server struct {
http *http.Server
done chan error
}
func Start(listen string, handler http.Handler, logger *log.Logger) (*Server, error) {
listener, err := net.Listen("tcp", listen)
if err != nil {
return nil, err
}
srv := &http.Server{
Handler: handler,
ReadHeaderTimeout: 10 * time.Second,
ReadTimeout: 30 * time.Second,
WriteTimeout: 2 * time.Minute,
IdleTimeout: 2 * time.Minute,
MaxHeaderBytes: 64 << 10,
ErrorLog: logger,
}
s := &Server{http: srv, done: make(chan error, 1)}
go func() {
err := srv.Serve(listener)
if errors.Is(err, http.ErrServerClosed) {
err = nil
}
s.done <- err
}()
logger.Printf("serve: listening on http://%s", listener.Addr())
return s, nil
}
func (s *Server) Shutdown(timeout time.Duration) error {
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
err := s.http.Shutdown(ctx)
if errors.Is(err, context.DeadlineExceeded) {
err = s.http.Close()
}
if serveErr := <-s.done; serveErr != nil && err == nil {
err = serveErr
}
return err
}