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.

58 lines
1.8 KiB

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