debian-mirror-gitlab/lib/banzai/filter/sanitization_filter.rb

67 lines
2.2 KiB
Ruby
Raw Normal View History

2018-11-18 11:00:15 +05:30
# frozen_string_literal: true
2015-12-23 02:04:40 +05:30
module Banzai
module Filter
2019-09-30 21:07:59 +05:30
# Sanitize HTML produced by Markdown.
2015-09-11 14:41:01 +05:30
#
2019-09-30 21:07:59 +05:30
# Extends Banzai::Filter::BaseSanitizationFilter with specific rules.
class SanitizationFilter < Banzai::Filter::BaseSanitizationFilter
# Styles used by Markdown for table alignment
2019-03-02 22:35:43 +05:30
TABLE_ALIGNMENT_PATTERN = /text-align: (?<alignment>center|left|right)/.freeze
2016-06-02 11:05:42 +05:30
2015-09-11 14:41:01 +05:30
def customize_whitelist(whitelist)
2018-06-27 16:04:02 +05:30
# Allow table alignment; we whitelist specific text-align values in a
2017-09-10 17:25:29 +05:30
# transformer below
2015-09-11 14:41:01 +05:30
whitelist[:attributes]['th'] = %w(style)
whitelist[:attributes]['td'] = %w(style)
2018-06-27 16:04:02 +05:30
whitelist[:css] = { properties: ['text-align'] }
2015-09-11 14:41:01 +05:30
2019-03-02 22:35:43 +05:30
# Allow the 'data-sourcepos' from CommonMark on all elements
whitelist[:attributes][:all].push('data-sourcepos')
2017-09-10 17:25:29 +05:30
# Remove any `style` properties not required for table alignment
whitelist[:transformers].push(self.class.remove_unsafe_table_style)
2019-03-02 22:35:43 +05:30
# Allow `id` in a and li elements for footnotes
# and remove any `id` properties not matching for footnotes
whitelist[:attributes]['a'].push('id')
whitelist[:attributes]['li'] = %w(id)
whitelist[:transformers].push(self.class.remove_non_footnote_ids)
2015-09-11 14:41:01 +05:30
whitelist
end
2016-09-29 09:46:39 +05:30
class << self
2017-09-10 17:25:29 +05:30
def remove_unsafe_table_style
lambda do |env|
node = env[:node]
return unless node.name == 'th' || node.name == 'td'
return unless node.has_attribute?('style')
if node['style'] =~ TABLE_ALIGNMENT_PATTERN
node['style'] = "text-align: #{$~[:alignment]}"
else
node.remove_attribute('style')
end
end
end
2019-03-02 22:35:43 +05:30
def remove_non_footnote_ids
lambda do |env|
node = env[:node]
return unless node.name == 'a' || node.name == 'li'
return unless node.has_attribute?('id')
return if node.name == 'a' && node['id'] =~ Banzai::Filter::FootnoteFilter::FOOTNOTE_LINK_REFERENCE_PATTERN
return if node.name == 'li' && node['id'] =~ Banzai::Filter::FootnoteFilter::FOOTNOTE_LI_REFERENCE_PATTERN
node.remove_attribute('id')
end
end
2015-09-11 14:41:01 +05:30
end
end
end
end