闭社主体 forked from https://github.com/tootsuite/mastodon
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.

85 lines
2.3 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. next unless %w(p ul ol li).include?(node.name)
  22. node.add_next_sibling('<br>') if node.next_sibling
  23. node.replace(node.children) unless node.text?
  24. end
  25. else
  26. env[:node].name = 'p'
  27. end
  28. end
  29. MASTODON_STRICT ||= freeze_config(
  30. elements: %w(p br span a),
  31. attributes: {
  32. 'a' => %w(href rel class),
  33. 'span' => %w(class),
  34. },
  35. add_attributes: {
  36. 'a' => {
  37. 'rel' => 'nofollow noopener',
  38. 'target' => '_blank',
  39. },
  40. },
  41. protocols: {
  42. 'a' => { 'href' => HTTP_PROTOCOLS },
  43. },
  44. transformers: [
  45. CLASS_WHITELIST_TRANSFORMER,
  46. UNSUPPORTED_ELEMENTS_TRANSFORMER,
  47. ]
  48. )
  49. MASTODON_OEMBED ||= freeze_config merge(
  50. RELAXED,
  51. elements: RELAXED[:elements] + %w(audio embed iframe source video),
  52. attributes: merge(
  53. RELAXED[:attributes],
  54. 'audio' => %w(controls),
  55. 'embed' => %w(height src type width),
  56. 'iframe' => %w(allowfullscreen frameborder height scrolling src width),
  57. 'source' => %w(src type),
  58. 'video' => %w(controls height loop width),
  59. 'div' => [:data]
  60. ),
  61. protocols: merge(
  62. RELAXED[:protocols],
  63. 'embed' => { 'src' => HTTP_PROTOCOLS },
  64. 'iframe' => { 'src' => HTTP_PROTOCOLS },
  65. 'source' => { 'src' => HTTP_PROTOCOLS }
  66. )
  67. )
  68. end
  69. end