about summary refs log tree commit diff stats
path: root/internal/server/server.go
diff options
context:
space:
mode:
authorAlan Pearce2024-06-13 20:51:49 +0200
committerAlan Pearce2024-06-13 20:52:16 +0200
commitf690e8cb7a820b0685b98f83a6761cfc169487e4 (patch)
tree3102375c3c3c9461776a79082f4db9898c1eee5e /internal/server/server.go
parent6b1697144e6261c09f1d2c254cf33d39f02ce92e (diff)
downloadwebsite-f690e8cb7a820b0685b98f83a6761cfc169487e4.tar.lz
website-f690e8cb7a820b0685b98f83a6761cfc169487e4.tar.zst
website-f690e8cb7a820b0685b98f83a6761cfc169487e4.zip
hash style elements during build step
Diffstat (limited to 'internal/server/server.go')
-rw-r--r--internal/server/server.go20
1 files changed, 17 insertions, 3 deletions
diff --git a/internal/server/server.go b/internal/server/server.go
index 77905f8..d2939ca 100644
--- a/internal/server/server.go
+++ b/internal/server/server.go
@@ -39,7 +39,6 @@ type Server struct {
 }
 
 func applyDevModeOverrides(config *cfg.Config, listenAddress string) {
-	config.CSP.StyleSrc = slices.Insert(config.CSP.StyleSrc, 0, "'unsafe-inline'")
 	config.CSP.ScriptSrc = slices.Insert(config.CSP.ScriptSrc, 0, "'unsafe-inline'")
 	config.CSP.ConnectSrc = slices.Insert(config.CSP.ConnectSrc, 0, "'self'")
 	config.BaseURL = cfg.URL{
@@ -50,6 +49,13 @@ func applyDevModeOverrides(config *cfg.Config, listenAddress string) {
 	}
 }
 
+func updateCSPHashes(config *cfg.Config, r *builder.Result) {
+	clear(config.CSP.StyleSrc)
+	for i, h := range r.Hashes {
+		config.CSP.StyleSrc[i] = fmt.Sprintf("'%s'", h)
+	}
+}
+
 func serverHeaderHandler(wrappedHandler http.Handler) http.Handler {
 	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
 		if r.ProtoMajor >= 2 && r.Header.Get("Host") != "" {
@@ -81,7 +87,11 @@ func New(runtimeConfig *Config) (*Server, error) {
 			BaseURL:     config.BaseURL,
 			Development: true,
 		}
-		builder.BuildSite(builderConfig)
+		r, err := builder.BuildSite(builderConfig)
+		if err != nil {
+			return nil, errors.WithMessage(err, "could not build site")
+		}
+		updateCSPHashes(config, r)
 
 		liveReload := livereload.New()
 		top.Handle("/_/reload", liveReload)
@@ -102,7 +112,11 @@ func New(runtimeConfig *Config) (*Server, error) {
 		}
 		go fw.Start(func(filename string) {
 			log.Debug("file updated", "filename", filename)
-			builder.BuildSite(builderConfig)
+			r, err := builder.BuildSite(builderConfig)
+			if err != nil {
+				log.Error("could not build site", "error", err)
+			}
+			updateCSPHashes(config, r)
 			liveReload.Reload()
 		})
 	}