Allow more text mutation for safe HTML

This commit is contained in:
Alexander Olofsson 2024-12-17 15:57:59 +01:00
parent 2256adae26
commit 2a2a916ac1
Signed by: ace
GPG key ID: D439C9470CB04C73

View file

@ -8,19 +8,23 @@ module Kramdown::Converter
class SafeHtml < Base class SafeHtml < Base
def initialize(root, options) def initialize(root, options)
super super
@options[:remove_block_html_tags] = true @options[:remove_block_html_tags] = true
@options[:remove_span_html_tags] = false @options[:remove_span_html_tags] = false
@options[:template] = 'string://<%= Html.convert(@body).first %>' @options[:template] = 'string://<%= Html.convert(@body).first %>'
end end
SUPERFLUOUS_TAGS = %w[align class justify] ALLOWED_ATTRS = %w[alt dir hidden inert lang title translate]
def convert(el) def convert(el)
real_el, el = el, el.value if el.type == :footnote real_el, el = el, el.value if el.type == :footnote
# Strip out unnecessary HTML tags # Strip out superfluous and invalid HTML 5 tags
SUPERFLUOUS_TAGS.each { |tag| el.attr.delete tag if el.attr.key? tag } style = el.attr['style'] || ""
style += ";text-align:#{el.attr['align']}" if el.attr.key? 'align'
style = strip_style(style) if style.include? ':'
el.attr.delete_if { |key, _| !ALLOWED_ATTRS.include?(key) }
el.attr['style'] = style if style.include? ':'
children = el.children.dup children = el.children.dup
index = 0 index = 0
@ -43,5 +47,19 @@ module Kramdown::Converter
real_el || el real_el || el
end end
private
ALLOWED_STYLE_ASSIGNMENTS = %w[font-size font-style font-weight text-align]
def strip_style(style)
parts = style.split(';').select { |p| p.include? ':' }.to_h do |assign|
parts = assign.split(':')
[parts.first.strip, parts.last.strip]
end
parts.delete_if { |key, _| !ALLOWED_STYLE_ASSIGNMENTS.include?(key) }
parts.map { |key, val| "#{key}:#{val}" }.join(';')
end
end end
end end