sanitizer.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. // Copyright 2015 - Present, The Gogs Authors. All rights reserved.
  2. // Copyright 2018 - Present, Gitote. All rights reserved.
  3. //
  4. // This source code is licensed under the MIT license found in the
  5. // LICENSE file in the root directory of this source tree.
  6. package markup
  7. import (
  8. "gitote/gitote/pkg/setting"
  9. "regexp"
  10. "sync"
  11. "github.com/microcosm-cc/bluemonday"
  12. )
  13. // Sanitizer is a protection wrapper of *bluemonday.Policy which does not allow
  14. // any modification to the underlying policies once it's been created.
  15. type Sanitizer struct {
  16. policy *bluemonday.Policy
  17. init sync.Once
  18. }
  19. var sanitizer = &Sanitizer{
  20. policy: bluemonday.UGCPolicy(),
  21. }
  22. // NewSanitizer initializes sanitizer with allowed attributes based on settings.
  23. // Multiple calls to this function will only create one instance of Sanitizer during
  24. // entire application lifecycle.
  25. func NewSanitizer() {
  26. sanitizer.init.Do(func() {
  27. // We only want to allow HighlightJS specific classes for code blocks
  28. sanitizer.policy.AllowAttrs("class").Matching(regexp.MustCompile(`^language-\w+$`)).OnElements("code")
  29. // Checkboxes
  30. sanitizer.policy.AllowAttrs("type").Matching(regexp.MustCompile(`^checkbox$`)).OnElements("input")
  31. sanitizer.policy.AllowAttrs("checked", "disabled").OnElements("input")
  32. // Data URLs
  33. sanitizer.policy.AllowURLSchemes("data")
  34. // Custom URL-Schemes
  35. sanitizer.policy.AllowURLSchemes(setting.Markdown.CustomURLSchemes...)
  36. })
  37. }
  38. // Sanitize takes a string that contains a HTML fragment or document and applies policy whitelist.
  39. func Sanitize(s string) string {
  40. return sanitizer.policy.Sanitize(s)
  41. }
  42. // SanitizeBytes takes a []byte slice that contains a HTML fragment or document and applies policy whitelist.
  43. func SanitizeBytes(b []byte) []byte {
  44. return sanitizer.policy.SanitizeBytes(b)
  45. }