Skip to content

Commit

Permalink
do not double-escape contents of <script> tags (#48)
Browse files Browse the repository at this point in the history
  • Loading branch information
sqs authored Jul 15, 2020
1 parent c5500fb commit 7c8864e
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 2 deletions.
2 changes: 1 addition & 1 deletion markdown/func.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ func EvalMarkdownFuncs(ctx context.Context, htmlFragment []byte, opt Options) ([
}

if !invokedFunc {
buf.WriteString(tok.String())
buf.WriteString(tokenStringWithUnescapedText(tok))
}
}
return buf.Bytes(), nil
Expand Down
14 changes: 13 additions & 1 deletion markdown/html.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,11 +52,23 @@ func rewriteRelativeURLsInHTML(htmlFragment []byte, opt Options) ([]byte, error)
}
}
}
buf.WriteString(tok.String())

buf.WriteString(tokenStringWithUnescapedText(tok))
}
return buf.Bytes(), nil
}

// tokenStringWithUnescapedText returns the HTML token string, except that if it is a text node, it
// is not escaped. For example, a text node containing "&" will not have that character escaped to
// "&amp;". This prevents double-escaping of tokens when multiple HTML tokenizers run on the
// content.
func tokenStringWithUnescapedText(tok html.Token) string {
if tok.Type == html.TextToken {
return tok.Data
}
return tok.String()
}

// isOnlyHTMLComment reports whether htmlFragment consists only of zero or more HTML comments and whitespace.
func isOnlyHTMLComment(htmlFragment []byte) bool {
z := html.NewTokenizer(bytes.NewReader(htmlFragment))
Expand Down
10 changes: 10 additions & 0 deletions markdown/markdown_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -240,6 +240,16 @@ func TestRenderer(t *testing.T) {
t.Errorf("got %q, want %q", string(doc.HTML), want)
}
})
t.Run("inline javascript script tag", func(t *testing.T) {
doc, err := Run(ctx, []byte("<script>'a'</script>\n\na"), Options{Base: &url.URL{Path: "/"}})
if err != nil {
t.Fatal(err)
}
want := "<script>'a'</script>\n\n<p>a</p>\n"
if string(doc.HTML) != want {
t.Errorf("got %q, want %q", string(doc.HTML), want)
}
})
t.Run("list", func(t *testing.T) {
t.Run("bare items", func(t *testing.T) {
doc, err := Run(ctx, []byte(`
Expand Down

0 comments on commit 7c8864e

Please sign in to comment.