sanitizer.ts 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. // Copyright (c) Jupyter Development Team.
  2. // Distributed under the terms of the Modified BSD License.
  3. import * as sanitize from 'sanitize-html';
  4. export
  5. interface ISanitizer {
  6. /**
  7. * Sanitize an HTML string.
  8. */
  9. sanitize(dirty: string): string;
  10. }
  11. /**
  12. * A class to sanitize HTML strings.
  13. */
  14. class Sanitizer implements ISanitizer {
  15. /**
  16. * Sanitize an HTML string.
  17. */
  18. sanitize(dirty: string): string {
  19. return sanitize(dirty, this._options);
  20. }
  21. private _options: sanitize.IOptions = {
  22. allowedTags: sanitize.defaults.allowedTags
  23. .concat('h1', 'h2', 'img', 'span'),
  24. allowedAttributes: {
  25. // Allow the "rel" attribute for <a> tags.
  26. 'a': sanitize.defaults.allowedAttributes['a'].concat('rel'),
  27. // Allow the "src" attribute for <img> tags.
  28. 'img': ['src', 'height', 'width', 'alt'],
  29. // Allow "class" attribute for <code> tags.
  30. 'code': ['class'],
  31. // Allow "class" attribute for <span> tags.
  32. 'span': ['class']
  33. },
  34. transformTags: {
  35. // Set the "rel" attribute for <a> tags to "nofollow".
  36. 'a': sanitize.simpleTransform('a', { 'rel': 'nofollow' })
  37. }
  38. };
  39. }
  40. /**
  41. * The default instance of an `ISanitizer` meant for use by user code.
  42. */
  43. export
  44. const defaultSanitizer: ISanitizer = new Sanitizer();