sanitize_config.rb 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. MASTODON_STRICT ||= freeze_config(
  17. elements: %w(p br span a),
  18. attributes: {
  19. 'a' => %w(href rel class),
  20. 'span' => %w(class),
  21. },
  22. add_attributes: {
  23. 'a' => {
  24. 'rel' => 'nofollow noopener',
  25. 'target' => '_blank',
  26. },
  27. },
  28. protocols: {
  29. 'a' => { 'href' => HTTP_PROTOCOLS },
  30. },
  31. transformers: [
  32. CLASS_WHITELIST_TRANSFORMER,
  33. ]
  34. )
  35. MASTODON_OEMBED ||= freeze_config merge(
  36. RELAXED,
  37. elements: RELAXED[:elements] + %w(audio embed iframe source video),
  38. attributes: merge(
  39. RELAXED[:attributes],
  40. 'audio' => %w(controls),
  41. 'embed' => %w(height src type width),
  42. 'iframe' => %w(allowfullscreen frameborder height scrolling src width),
  43. 'source' => %w(src type),
  44. 'video' => %w(controls height loop width),
  45. 'div' => [:data]
  46. ),
  47. protocols: merge(
  48. RELAXED[:protocols],
  49. 'embed' => { 'src' => HTTP_PROTOCOLS },
  50. 'iframe' => { 'src' => HTTP_PROTOCOLS },
  51. 'source' => { 'src' => HTTP_PROTOCOLS }
  52. )
  53. )
  54. end
  55. end