- Add PostgreSQL-backed backend and frontend tests to CI - Harden Android API logging and disable app backups - Update the performance report with resolved findings
52 lines
1.8 KiB
Go
52 lines
1.8 KiB
Go
package main
|
|
|
|
import (
|
|
"crypto/sha256"
|
|
"encoding/base64"
|
|
"regexp"
|
|
"strings"
|
|
)
|
|
|
|
var (
|
|
scriptElement = regexp.MustCompile(`(?is)<script\b([^>]*)>(.*?)</script\s*>`)
|
|
scriptSrcAttribute = regexp.MustCompile(`(?i)\bsrc\s*=`)
|
|
// A browser reads a CR or CRLF in the HTML source as LF, and hashes that.
|
|
htmlNewlines = strings.NewReplacer("\r\n", "\n", "\r", "\n")
|
|
)
|
|
|
|
// inlineScriptHashes returns a CSP hash source for every inline <script> in the
|
|
// page. SvelteKit's static build puts one bootstrap script in index.html, and its
|
|
// text changes with every build, so the hash is read from the page being served
|
|
// instead of being configured.
|
|
func inlineScriptHashes(page []byte) []string {
|
|
var hashes []string
|
|
for _, match := range scriptElement.FindAllSubmatch(page, -1) {
|
|
if scriptSrcAttribute.Match(match[1]) || len(match[2]) == 0 {
|
|
continue
|
|
}
|
|
sum := sha256.Sum256([]byte(htmlNewlines.Replace(string(match[2]))))
|
|
hashes = append(hashes, "'sha256-"+base64.StdEncoding.EncodeToString(sum[:])+"'")
|
|
}
|
|
return hashes
|
|
}
|
|
|
|
// dashboardCSP is the Content-Security-Policy for the dashboard page. Scripts may
|
|
// only come from this origin or be the page's own inline bootstrap script, so an
|
|
// injected script does not run. Styles keep 'unsafe-inline' because the page
|
|
// shell uses a style attribute; the bundle has no eval, workers or external URLs.
|
|
func dashboardCSP(page []byte) string {
|
|
scriptSrc := append([]string{"script-src 'self'"}, inlineScriptHashes(page)...)
|
|
return strings.Join([]string{
|
|
"default-src 'self'",
|
|
strings.Join(scriptSrc, " "),
|
|
"style-src 'self' 'unsafe-inline'",
|
|
"img-src 'self' data:",
|
|
"font-src 'self' data:",
|
|
"connect-src 'self'",
|
|
"object-src 'none'",
|
|
"base-uri 'self'",
|
|
"form-action 'self'",
|
|
"frame-ancestors 'none'",
|
|
}, "; ")
|
|
}
|