From 461e61495349e5613dd1112fe9cf4a02d6235c87 Mon Sep 17 00:00:00 2001 From: Jay Hemnani <193022578+jayhemnani9910@users.noreply.github.com> Date: Wed, 18 Nov 2026 20:45:29 +0530 Subject: [PATCH] Escape text and attribute values in to_html TextRun#to_html and html_tag wrote document text and attribute values (link hrefs) into the HTML as is, so text such as "" disappeared from the output and markup in a document came out as markup. --- lib/docx/containers/text_run.rb | 2 +- lib/docx/elements/element.rb | 3 ++- spec/docx/document_spec.rb | 7 +++++++ 3 files changed, 10 insertions(+), 2 deletions(-) diff --git a/lib/docx/containers/text_run.rb b/lib/docx/containers/text_run.rb index 0597bfa..019c9a2 100755 --- a/lib/docx/containers/text_run.rb +++ b/lib/docx/containers/text_run.rb @@ -105,7 +105,7 @@ def to_s # Return text as a HTML fragment with formatting based on properties. def to_html - html = @text + html = CGI.escapeHTML(@text.to_s) html = html_tag(:em, content: html) if italicized? html = html_tag(:strong, content: html) if bolded? html = html_tag(:s, content: html) if striked? diff --git a/lib/docx/elements/element.rb b/lib/docx/elements/element.rb index 039dda6..df3666f 100755 --- a/lib/docx/elements/element.rb +++ b/lib/docx/elements/element.rb @@ -1,3 +1,4 @@ +require 'cgi' require 'nokogiri' require 'docx/elements' require 'docx/containers' @@ -87,7 +88,7 @@ def html_tag(name, options = {}) unless attributes.nil? || attributes.empty? attributes.each do |attr_name, attr_value| - html << " #{attr_name}=\"#{attr_value}\"" + html << " #{attr_name}=\"#{CGI.escapeHTML(attr_value.to_s)}\"" end end diff --git a/spec/docx/document_spec.rb b/spec/docx/document_spec.rb index 007cf02..1e9972a 100755 --- a/spec/docx/document_spec.rb +++ b/spec/docx/document_spec.rb @@ -228,6 +228,13 @@ it 'handles internal (anchor) links' do expect { described_class.open(fixture_path('internal-links.docx')).to_html }.not_to raise_error end + + it 'escapes the document text' do + doc = described_class.open(fixture_path('basic.docx')) + doc.paragraphs.first.text = 'a & c' + + expect(doc.paragraphs.first.to_html).to include('a <img src=x onerror=alert(1)> & c') + end end describe '#to_xml' do