Files
bookhoard/internal/middleware/security_headers.go
T
John O'Keefe 71b171bf72 fix(csp): allow blob: stylesheets in style-src for the reader
Every /readers load logged a CSP violation: foliate-js injects its
reader-generated stylesheets as blob: URLs, and style-src only allowed
'self' 'unsafe-inline' — so the sheet was refused and selection/
highlight styling inside the reader rode on nothing.

blob: was already granted for img-src, font-src, and frame-src for
exactly this reader content; style-src now matches. The content is
app-generated at runtime (no cross-origin input), script-src is
untouched, and the strict script hash allow-list keeps its guarantee.

Pinned by TestThemeFlashGuardHashMatchesCSP (script-src only — the
style-src addition doesn't interact) and TestGoSourcesAreCSPSafe.
2026-11-02 09:31:58 -05:00

71 lines
3.3 KiB
Go

package middleware
import (
"strings"
"github.com/labstack/echo/v5"
)
// ScriptHashThemeFlashGuard is the CSP script-src hash of the theme flash
// guard's inline script (the app's only inline script). Enforced against
// the rendered component by security_headers_test.go.
const ScriptHashThemeFlashGuard = "'sha256-JYIVpFyKdLUtWizMha0v69f6yHds+GbJRBWjvpuECBY='"
// SecurityHeadersMiddleware adds security headers to all responses.
// It also forces HTML pages to revalidate (Cache-Control: no-cache):
// SSR pages are dynamic, and heuristic browser caching of a PAGE let a
// stale page reference a stale main.js stamp long after the bundle was
// fixed — the "search dropdown still broken" report was exactly that.
// /api, /static and /uploads keep their own (or absent) caching: the
// stamped bundles are content-frozen by URL, media files are immutable
// by path.
func SecurityHeadersMiddleware() echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c *echo.Context) error {
// Add security headers
c.Response().Header().Set("X-Content-Type-Options", "nosniff")
c.Response().Header().Set("X-Frame-Options", "DENY")
c.Response().Header().Set("X-XSS-Protection", "1; mode=block")
c.Response().Header().Set("Strict-Transport-Security", "max-age=31536000; includeSubDomains; preload")
// script-src notes: 'unsafe-inline' is required by the pre-paint
// CSP-safe Alpine build (@alpinejs/csp) needs no eval — do NOT
// add 'unsafe-eval' here without removing that build.
//
// The inline script allow-list: the theme flash guard is the
// ONLY inline script in the app, and its byte-stable content is
// hashed into script-src (sha256 of the bytes between the
// script tags as rendered by
// templates.ThemeFlashGuard()). Editing the guard requires
// recomputing the hash — enforced by
// internal/middleware/security_headers_test.go, which renders
// the component and asserts the hash matches.
//
// style-src keeps 'unsafe-inline' for htmx-injected styles and
// Alpine :style attribute writes, plus blob: for the
// reader-generated stylesheets foliate injects at open time
// (blocked since the CSP migration — every /readers load
// logged a violation; selection/highlight styling rode on it).
// font/img blob: — the reader renders EPUB-embedded fonts and
// images from blob: URLs inside the foliate content frame.
c.Response().Header().Set("Content-Security-Policy", "default-src 'self'; script-src 'self' "+ScriptHashThemeFlashGuard+"; style-src 'self' 'unsafe-inline' blob:; img-src 'self' data: https: blob:; font-src 'self' data: blob:; frame-src 'self' blob:")
c.Response().Header().Set("Referrer-Policy", "strict-origin-when-cross-origin")
c.Response().Header().Set("Permissions-Policy", "geolocation=(), microphone=(), camera=()")
// Pages must always revalidate (see doc comment). The check
// runs BEFORE next(): once a templ handler writes the body,
// response headers are already on the wire.
switch p := c.Request().URL.Path; {
case strings.HasPrefix(p, "/api/"),
strings.HasPrefix(p, "/static/"),
strings.HasPrefix(p, "/uploads/"),
p == "/health":
// Not a page: keep native caching behavior.
default:
c.Response().Header().Set("Cache-Control", "no-cache")
}
return next(c)
}
}
}