Skip to content

Commit b206e73

Browse files
authored
Merge pull request #203 from jayhemnani9910/fix/to-html-escape-text
Escape text and attribute values in to_html
2 parents b101ffd + 461e614 commit b206e73

3 files changed

Lines changed: 10 additions & 2 deletions

File tree

‎lib/docx/containers/text_run.rb‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -105,7 +105,7 @@ def to_s
105105

106106
# Return text as a HTML fragment with formatting based on properties.
107107
def to_html
108-
html = @text
108+
html = CGI.escapeHTML(@text.to_s)
109109
html = html_tag(:em, content: html) if italicized?
110110
html = html_tag(:strong, content: html) if bolded?
111111
html = html_tag(:s, content: html) if striked?

‎lib/docx/elements/element.rb‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
require 'cgi'
12
require 'nokogiri'
23
require 'docx/elements'
34
require 'docx/containers'
@@ -87,7 +88,7 @@ def html_tag(name, options = {})
8788

8889
unless attributes.nil? || attributes.empty?
8990
attributes.each do |attr_name, attr_value|
90-
html << " #{attr_name}=\"#{attr_value}\""
91+
html << " #{attr_name}=\"#{CGI.escapeHTML(attr_value.to_s)}\""
9192
end
9293
end
9394

‎spec/docx/document_spec.rb‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -228,6 +228,13 @@
228228
it 'handles internal (anchor) links' do
229229
expect { described_class.open(fixture_path('internal-links.docx')).to_html }.not_to raise_error
230230
end
231+
232+
it 'escapes the document text' do
233+
doc = described_class.open(fixture_path('basic.docx'))
234+
doc.paragraphs.first.text = 'a <img src=x onerror=alert(1)> & c'
235+
236+
expect(doc.paragraphs.first.to_html).to include('a &lt;img src=x onerror=alert(1)&gt; &amp; c')
237+
end
231238
end
232239

233240
describe '#to_xml' do

0 commit comments

Comments
 (0)