Spaces:
Running
Running
Use per-request CSP nonce instead of script-src unsafe-inline
Browse filesFiles changed (3)
8 unmodified lines9101112131415161718104 unmodified lines12312412512612712815 unmodified lines1441451461471481491501511521531541551561571581597 unmodified lines16716816917017117217317423 unmodified lines1981992002012022034 unmodified lines2082092102112122132142152162172182192202213 unmodified lines2252262272282292308 unmodified lines"regexp""strings""panelthtuanit/internal/services")var jsonLDScriptRe = regexp.MustCompile(`(?is)(<script\b[^>]*type=["']application/ld\+json["'][^>]*>)(.*?)(</script>)`)// InjectReviewsIntoHTML attaches real aggregateRating and top-5 reviews to SoftwareApplication JSON-LD.func InjectReviewsIntoHTML(html string, summary services.ReviewsSummary) string {104 unmodified linesreturn false}// RegisterSPARoutes serves frontend/out (Next.js export) or legacy static/index.html.func RegisterSPARoutes(mux *http.ServeMux) {nextjsOut := "frontend/out"15 unmodified lines}mux.HandleFunc("GET /{$}", func(w http.ResponseWriter, r *http.Request) {summary := services.GetReviewsSummary()if summary.ReviewCount > 0 {if raw, err := os.ReadFile(indexPath); err == nil {injected := InjectReviewsIntoHTML(string(raw), summary)w.Header().Set("Content-Type", "text/html; charset=utf-8")w.Header().Set("Cache-Control", "no-cache")w.WriteHeader(http.StatusOK)_, _ = w.Write([]byte(injected))return}}w.Header().Set("Cache-Control", "no-cache")http.ServeFile(w, r, indexPath)7 unmodified lineshttp.ServeFile(w, r, iconSVG)return}w.Header().Set("Cache-Control", "no-cache")http.ServeFile(w, r, indexPath)})mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {23 unmodified linestargetAbs, _ := filepath.Abs(target)if rel, err := filepath.Rel(outAbs, targetAbs); err == nil && rel != ".." && !strings.HasPrefix(rel, ".."+string(os.PathSeparator)) {if isRegularFile(targetAbs) {if isImmutableAsset(fullPath) {w.Header().Set("Cache-Control", "public, max-age=31536000, immutable")} else {4 unmodified lines}subIndex := filepath.Join(targetAbs, "index.html")if isRegularFile(subIndex) {w.Header().Set("Cache-Control", "no-cache")http.ServeFile(w, r, subIndex)return}}w.Header().Set("Cache-Control", "no-cache")http.ServeFile(w, r, indexPath)})return}3 unmodified linesmux.Handle("GET /static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))}mux.HandleFunc("GET /{$}", func(w http.ResponseWriter, r *http.Request) {http.ServeFile(w, r, filepath.Join("static", "index.html"))})}8 unmodified lines910111213141516171819202122104 unmodified lines12712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222315 unmodified lines2392402412422432442452462472482492502512527 unmodified lines26026126226326426526623 unmodified lines2902912922932942952962972982994 unmodified lines3043053063073083093103113123133143153 unmodified lines3193203213223233248 unmodified lines"regexp""strings""panelthtuanit/internal/httpx""panelthtuanit/internal/services")var (jsonLDScriptRe = regexp.MustCompile(`(?is)(<script\b[^>]*type=["']application/ld\+json["'][^>]*>)(.*?)(</script>)`)scriptNonceAttrRe = regexp.MustCompile(`(?is)\s+nonce=(?:"[^"]*"|'[^']*'|[^\s>]+)`))// InjectReviewsIntoHTML attaches real aggregateRating and top-5 reviews to SoftwareApplication JSON-LD.func InjectReviewsIntoHTML(html string, summary services.ReviewsSummary) string {104 unmodified linesreturn false}func injectNonceIntoHTML(html, nonce string) string {if nonce == "" {return html}lower := strings.ToLower(html)var b strings.Builderb.Grow(len(html) + 256)pos := 0for pos < len(html) {rel := strings.Index(lower[pos:], "<script")if rel < 0 {b.WriteString(html[pos:])break}start := pos + relafter := start + len("<script")if after < len(html) {ch := html[after]if ch != '>' && ch != ' ' && ch != '\t' && ch != '\r' && ch != '\n' && ch != '/' {b.WriteString(html[pos:after])pos = aftercontinue}}quote := byte(0)endTag := -1for i := after; i < len(html); i++ {c := html[i]if quote != 0 {if c == quote {quote = 0}continue}if c == '"' || c == '\'' {quote = ccontinue}if c == '>' {endTag = ibreak}}if endTag < 0 {b.WriteString(html[pos:])break}b.WriteString(html[pos:start])attrs := scriptNonceAttrRe.ReplaceAllString(html[after:endTag], "")b.WriteString("<script")b.WriteString(attrs)b.WriteString(` nonce="`)b.WriteString(nonce)b.WriteString(`">`)bodyStart := endTag + 1if endRel := strings.Index(lower[bodyStart:], "</script>"); endRel >= 0 {endScript := bodyStart + endRel + len("</script>")b.WriteString(html[bodyStart:endScript])pos = endScript} else {pos = bodyStart}}return b.String()}func serveHTMLWithCSPNonce(w http.ResponseWriter, r *http.Request, htmlBytes []byte) {nonce := httpx.GenerateCSPNonce()rendered := injectNonceIntoHTML(string(htmlBytes), nonce)w.Header().Set("Content-Type", "text/html; charset=utf-8")w.Header().Set("Cache-Control", "no-cache")w.Header().Set("Content-Security-Policy", httpx.BuildPanelCSPWithNonce(nonce))w.WriteHeader(http.StatusOK)if r.Method != http.MethodHead {_, _ = w.Write([]byte(rendered))}}func serveHTMLFileWithCSPNonce(w http.ResponseWriter, r *http.Request, filePath string) {raw, err := os.ReadFile(filePath)if err != nil {w.Header().Set("Cache-Control", "no-cache")http.ServeFile(w, r, filePath)return}serveHTMLWithCSPNonce(w, r, raw)}// RegisterSPARoutes serves frontend/out (Next.js export) or legacy static/index.html.func RegisterSPARoutes(mux *http.ServeMux) {nextjsOut := "frontend/out"15 unmodified lines}mux.HandleFunc("GET /{$}", func(w http.ResponseWriter, r *http.Request) {if raw, err := os.ReadFile(indexPath); err == nil {content := string(raw)summary := services.GetReviewsSummary()if summary.ReviewCount > 0 {content = InjectReviewsIntoHTML(content, summary)}serveHTMLWithCSPNonce(w, r, []byte(content))return}w.Header().Set("Cache-Control", "no-cache")http.ServeFile(w, r, indexPath)7 unmodified lineshttp.ServeFile(w, r, iconSVG)return}serveHTMLFileWithCSPNonce(w, r, indexPath)})mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {23 unmodified linestargetAbs, _ := filepath.Abs(target)if rel, err := filepath.Rel(outAbs, targetAbs); err == nil && rel != ".." && !strings.HasPrefix(rel, ".."+string(os.PathSeparator)) {if isRegularFile(targetAbs) {if strings.HasSuffix(strings.ToLower(targetAbs), ".html") {serveHTMLFileWithCSPNonce(w, r, targetAbs)return}if isImmutableAsset(fullPath) {w.Header().Set("Cache-Control", "public, max-age=31536000, immutable")} else {4 unmodified lines}subIndex := filepath.Join(targetAbs, "index.html")if isRegularFile(subIndex) {serveHTMLFileWithCSPNonce(w, r, subIndex)return}}serveHTMLFileWithCSPNonce(w, r, indexPath)})return}3 unmodified linesmux.Handle("GET /static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))}mux.HandleFunc("GET /{$}", func(w http.ResponseWriter, r *http.Request) {serveHTMLFileWithCSPNonce(w, r, filepath.Join("static", "index.html"))})}
3 unmodified lines45678942 unmodified lines52535455565758593 unmodified lines"bufio""bytes""compress/gzip""encoding/json""errors""io"42 unmodified linesconst defaultCanonicalPanelURL = "https://panel.thtuanit.com"// PanelContentSecurityPolicy sets baseline XSS and framing protection for the Panel UI without breaking inline hydration scripts or PTY WebSockets.const PanelContentSecurityPolicy = "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self' data:; connect-src 'self' ws: wss:; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'self'; upgrade-insecure-requests"var panelSecurityHeaders = [][2]string{{"Content-Security-Policy", PanelContentSecurityPolicy},3 unmodified lines456789101142 unmodified lines54555657585960616263646566676869707172737475763 unmodified lines"bufio""bytes""compress/gzip""crypto/rand""encoding/base64""encoding/json""errors""io"42 unmodified linesconst defaultCanonicalPanelURL = "https://panel.thtuanit.com"// PanelContentSecurityPolicy sets baseline XSS and framing protection for the Panel UI; HTML responses inject a per-request script nonce.const PanelContentSecurityPolicy = "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self' data:; connect-src 'self' ws: wss:; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'self'; upgrade-insecure-requests"// GenerateCSPNonce generates a fresh 128-bit cryptographic base64 nonce per HTML response.func GenerateCSPNonce() string {var b [16]byte_, _ = rand.Read(b[:])return base64.StdEncoding.EncodeToString(b[:])}// BuildPanelCSPWithNonce inserts 'nonce-<nonce>' into script-src of PanelContentSecurityPolicy.func BuildPanelCSPWithNonce(nonce string) string {if nonce == "" {return PanelContentSecurityPolicy}return strings.Replace(PanelContentSecurityPolicy, "script-src 'self'", "script-src 'self' 'nonce-"+nonce+"'", 1)}var panelSecurityHeaders = [][2]string{{"Content-Security-Policy", PanelContentSecurityPolicy},
680 unmodified lines68168268368468568668721 unmodified lines709710711712713714680 unmodified linesif err := os.MkdirAll(filepath.Join(outDir, "_next"), 0o755); err != nil {t.Fatal(err)}if err := os.WriteFile(filepath.Join(outDir, "index.html"), []byte("<html><body>SPA_INDEX</body></html>"), 0o644); err != nil {t.Fatal(err)}if err := os.Chdir(tmp); err != nil {21 unmodified linesif !strings.Contains(csp, "default-src 'self'") || !strings.Contains(csp, "frame-ancestors 'self'") {t.Fatalf("expected Content-Security-Policy on GET /, got %q", csp)}respAbout, err := http.Get(srv.URL + "/about")if err != nil {680 unmodified lines68168268368468568668721 unmodified lines709710711712713714715716717718719720721722723724725726727728729730731732733734735736737680 unmodified linesif err := os.MkdirAll(filepath.Join(outDir, "_next"), 0o755); err != nil {t.Fatal(err)}if err := os.WriteFile(filepath.Join(outDir, "index.html"), []byte("<html><body><script>window.__ok=1</script>SPA_INDEX</body></html>"), 0o644); err != nil {t.Fatal(err)}if err := os.Chdir(tmp); err != nil {21 unmodified linesif !strings.Contains(csp, "default-src 'self'") || !strings.Contains(csp, "frame-ancestors 'self'") {t.Fatalf("expected Content-Security-Policy on GET /, got %q", csp)}if strings.Contains(csp, "script-src 'self' 'unsafe-inline'") || !strings.Contains(csp, "script-src 'self' 'nonce-") {t.Fatalf("expected script-src with nonce and without unsafe-inline, got %q", csp)}const marker = "script-src 'self' 'nonce-"idx := strings.Index(csp, marker)rest := csp[idx+len(marker):]endQ := strings.IndexByte(rest, '\'')if endQ <= 0 {t.Fatalf("malformed nonce in CSP: %q", csp)}nonce1 := rest[:endQ]if !strings.Contains(string(body), `<script nonce="`+nonce1+`">window.__ok=1</script>`) {t.Fatalf("expected HTML inline script to carry nonce=%q, got %q", nonce1, string(body))}resp2, err := http.Get(srv.URL + "/")if err != nil {t.Fatalf("second GET /: %v", err)}_ = resp2.Body.Close()if resp2.Header.Get("Content-Security-Policy") == csp {t.Fatalf("expected fresh CSP nonce per request, got identical header %q", csp)}respAbout, err := http.Get(srv.URL + "/about")if err != nil {
backend/internal/handlers/spa.go+111-17
backend/internal/httpx/httpx.go+19-2
backend/main_test.go+24-1