diff --git a/src/main.go b/src/main.go index 51a68b6..4dae346 100644 --- a/src/main.go +++ b/src/main.go @@ -32,12 +32,14 @@ func NewTemplates() *Templates { type Page struct { Boxes []boxes.Box BuildNumber string + Integrity *util.AssetIntegrity } func newPage(boxes []boxes.Box) Page { return Page{ Boxes: boxes, BuildNumber: util.GetBuildNumber(), + Integrity: util.CalculateAssetIntegrities(), } } @@ -58,6 +60,7 @@ func main() { e.GET("/health", func(c echo.Context) error { return c.Render(200, "health", Page{ BuildNumber: util.GetBuildNumber(), + Integrity: util.CalculateAssetIntegrities(), }) }) diff --git a/src/util/util.go b/src/util/util.go index ded0923..6c22189 100644 --- a/src/util/util.go +++ b/src/util/util.go @@ -1,6 +1,10 @@ package util import ( + "crypto/sha256" + "encoding/base64" + "fmt" + "io" "os" ) @@ -11,3 +15,52 @@ func GetBuildNumber() string { func IsProd() bool { return len(GetBuildNumber()) > 0 } + +// CalculateFileIntegrity calculates SHA256 hash for SRI +func CalculateFileIntegrity(filePath string) (string, error) { + file, err := os.Open(filePath) + if err != nil { + return "", err + } + defer file.Close() + + hasher := sha256.New() + if _, err := io.Copy(hasher, file); err != nil { + return "", err + } + + hash := hasher.Sum(nil) + return fmt.Sprintf("sha256-%s", base64.StdEncoding.EncodeToString(hash)), nil +} + +// AssetIntegrity holds file integrity information +type AssetIntegrity struct { + CSS map[string]string + JS map[string]string +} + +// CalculateAssetIntegrities calculates hashes for all assets +func CalculateAssetIntegrities() *AssetIntegrity { + integrity := &AssetIntegrity{ + CSS: make(map[string]string), + JS: make(map[string]string), + } + + // CSS files + cssFiles := []string{"main.css", "boxes.css"} + for _, file := range cssFiles { + if hash, err := CalculateFileIntegrity("css/" + file); err == nil { + integrity.CSS[file] = hash + } + } + + // JS files + jsFiles := []string{"ws.js", "boxes.js", "draw.js"} + for _, file := range jsFiles { + if hash, err := CalculateFileIntegrity("js/" + file); err == nil { + integrity.JS[file] = hash + } + } + + return integrity +} diff --git a/views/boxes.html b/views/boxes.html index 1432c29..b90d4c1 100644 --- a/views/boxes.html +++ b/views/boxes.html @@ -1,5 +1,5 @@ {{block "boxes" .}} - +
Currently Online:
@@ -21,6 +21,6 @@
- - + + {{end}} diff --git a/views/index.html b/views/index.html index 39eff3f..4b295d8 100644 --- a/views/index.html +++ b/views/index.html @@ -5,7 +5,7 @@ Home - +