-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsanitize.go
More file actions
51 lines (42 loc) · 1.1 KB
/
sanitize.go
File metadata and controls
51 lines (42 loc) · 1.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package sanitize
import (
"io"
"slices"
"golang.org/x/net/html"
)
func sanitizeNode(node *html.Node, policies ...Policy) {
if node.Type != html.ElementNode {
for _, node := range slices.Collect(node.ChildNodes()) {
sanitizeNode(node, policies...)
}
return
}
tag := &Tag{
atom: node.DataAtom,
data: node.Data,
attributes: fromAttrs(node.Attr),
}
for _, policy := range policies {
policy.Apply(tag)
}
if tag.blocked {
node.Parent.RemoveChild(node)
return
}
node.Data = tag.data
node.Attr = toAttrs(tag.attributes)
for _, node := range slices.Collect(node.ChildNodes()) {
sanitizeNode(node, policies...)
}
}
// HTML will sanitize the HTML content for the given policies.
// By default, this function will correct the HTML tree, adding html, body and header tags.
// It's extremelly recommended to start a secure policy from a Blacklist, and allow individual policies.
func HTML(r io.Reader, w io.Writer, policies ...Policy) error {
node, err := html.ParseWithOptions(r)
if err != nil {
return err
}
sanitizeNode(node, policies...)
return html.Render(w, node)
}