fix: sanitize app status summary (#19075)

Fixes https://github.com/coder/coder/issues/18875
This commit is contained in:
Cian Johnston
2025-07-29 15:24:11 +01:00
committed by GitHub
parent 29486f9d4e
commit 812d72c5bb
5 changed files with 86 additions and 3 deletions
+40
View File
@@ -2,7 +2,12 @@ package strings
import (
"fmt"
"strconv"
"strings"
"unicode"
"github.com/acarl005/stripansi"
"github.com/microcosm-cc/bluemonday"
)
// JoinWithConjunction joins a slice of strings with commas except for the last
@@ -28,3 +33,38 @@ func Truncate(s string, n int) string {
}
return s[:n]
}
var bmPolicy = bluemonday.StrictPolicy()
// UISanitize sanitizes a string for display in the UI.
// The following transformations are applied, in order:
// - HTML tags are removed using bluemonday's strict policy.
// - ANSI escape codes are stripped using stripansi.
// - Consecutive backslashes are replaced with a single backslash.
// - Non-printable characters are removed.
// - Whitespace characters are replaced with spaces.
// - Multiple spaces are collapsed into a single space.
// - Leading and trailing whitespace is trimmed.
func UISanitize(in string) string {
if unq, err := strconv.Unquote(`"` + in + `"`); err == nil {
in = unq
}
in = bmPolicy.Sanitize(in)
in = stripansi.Strip(in)
var b strings.Builder
var spaceSeen bool
for _, r := range in {
if unicode.IsSpace(r) {
if !spaceSeen {
_, _ = b.WriteRune(' ')
spaceSeen = true
}
continue
}
spaceSeen = false
if unicode.IsPrint(r) {
_, _ = b.WriteRune(r)
}
}
return strings.TrimSpace(b.String())
}