security.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. // Package security — headers de seguridad obligatorios (middleware global).
  2. // Literales de src/security.js:6-19 (SPEC §10.1), en TODAS las respuestas.
  3. package security
  4. import "net/http"
  5. // Headers es la lista literal de headers (orden de security.js).
  6. var Headers = []struct{ K, V string }{
  7. {"X-Content-Type-Options", "nosniff"},
  8. {"X-Frame-Options", "DENY"},
  9. {"Referrer-Policy", "strict-origin-when-cross-origin"},
  10. {"Permissions-Policy", "geolocation=(), microphone=(), camera=()"},
  11. // style-src lleva 'unsafe-inline' a propósito (#485): Radix (posicionado
  12. // popper) y framer-motion (transform/opacity) escriben atributos style
  13. // CON VALORES DINÁMICOS (píxeles calculados), imposibles de hashear con
  14. // 'unsafe-hashes'. Sin 'unsafe-inline' cada apertura de diálogo loguea
  15. // una violación CSP y las transiciones no corren. El riesgo de CSS
  16. // inline es muy inferior al de script inline (la app no renderiza HTML
  17. // controlado por el usuario), y script-src sigue sin 'unsafe-inline'.
  18. {"Content-Security-Policy", "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; font-src 'self'; img-src 'self' data:; connect-src 'self'"},
  19. }
  20. // HSTS is the Strict-Transport-Security value for a server whose every
  21. // port speaks TLS.
  22. //
  23. // includeSubDomains is left out: nothing lives under the server's own name,
  24. // and the flag would pin every host below it to HTTPS for a year, which
  25. // makes turning HTTPS off again much harder to undo.
  26. const HSTS = "max-age=31536000"
  27. // Middleware applies the headers to every response, and the HSTS value hsts
  28. // returns for it, if any.
  29. //
  30. // HSTS is per host, not per port (RFC 6797 section 8.3): a policy received on
  31. // one port makes the browser rewrite http://host:ANY to https://host:ANY. So
  32. // it may only be sent where no port of the host still serves plain HTTP that
  33. // people need - the caller decides that, not this package.
  34. func Middleware(hsts func(*http.Request) string, next http.Handler) http.Handler {
  35. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  36. for _, h := range Headers {
  37. w.Header().Set(h.K, h.V)
  38. }
  39. if hsts != nil {
  40. if v := hsts(r); v != "" {
  41. w.Header().Set("Strict-Transport-Security", v)
  42. }
  43. }
  44. next.ServeHTTP(w, r)
  45. })
  46. }