You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

83 lines
2.2 KiB

  1. # frozen_string_literal: true
  2. class Sanitize
  3. module Config
  4. HTTP_PROTOCOLS ||= ['http', 'https', 'dat', 'dweb', 'ipfs', 'ipns', 'ssb', 'gopher', :relative].freeze
  5. CLASS_WHITELIST_TRANSFORMER = lambda do |env|
  6. node = env[:node]
  7. class_list = node['class']&.split(/[\t\n\f\r ]/)
  8. return unless class_list
  9. class_list.keep_if do |e|
  10. next true if e =~ /^(h|p|u|dt|e)-/ # microformats classes
  11. next true if e =~ /^(mention|hashtag)$/ # semantic classes
  12. next true if e =~ /^(ellipsis|invisible)$/ # link formatting classes
  13. end
  14. node['class'] = class_list.join(' ')
  15. end
  16. UNSUPPORTED_ELEMENTS_TRANSFORMER = lambda do |env|
  17. return unless %w(h1 h2 h3 h4 h5 h6 blockquote pre ul ol li).include?(env[:node_name])
  18. case env[:node_name]
  19. when 'li'
  20. env[:node].traverse do |node|
  21. node.add_next_sibling('<br>') if node.next_sibling
  22. node.replace(node.children) unless node.text?
  23. end
  24. else
  25. env[:node].name = 'p'
  26. end
  27. end
  28. MASTODON_STRICT ||= freeze_config(
  29. elements: %w(p br span a),
  30. attributes: {
  31. 'a' => %w(href rel class),
  32. 'span' => %w(class),
  33. },
  34. add_attributes: {
  35. 'a' => {
  36. 'rel' => 'nofollow noopener',
  37. 'target' => '_blank',
  38. },
  39. },
  40. protocols: {
  41. 'a' => { 'href' => HTTP_PROTOCOLS },
  42. },
  43. transformers: [
  44. CLASS_WHITELIST_TRANSFORMER,
  45. UNSUPPORTED_ELEMENTS_TRANSFORMER,
  46. ]
  47. )
  48. MASTODON_OEMBED ||= freeze_config merge(
  49. RELAXED,
  50. elements: RELAXED[:elements] + %w(audio embed iframe source video),
  51. attributes: merge(
  52. RELAXED[:attributes],
  53. 'audio' => %w(controls),
  54. 'embed' => %w(height src type width),
  55. 'iframe' => %w(allowfullscreen frameborder height scrolling src width),
  56. 'source' => %w(src type),
  57. 'video' => %w(controls height loop width),
  58. 'div' => [:data]
  59. ),
  60. protocols: merge(
  61. RELAXED[:protocols],
  62. 'embed' => { 'src' => HTTP_PROTOCOLS },
  63. 'iframe' => { 'src' => HTTP_PROTOCOLS },
  64. 'source' => { 'src' => HTTP_PROTOCOLS }
  65. )
  66. )
  67. end
  68. end