sanitizer.ts 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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', 'audio', 'video'),
  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. // Allow the "src" attribute for <audio> tags.
  34. 'audio': ['src', 'autoplay', 'loop', 'muted', 'controls'],
  35. // Allow the "src" attribute for <video> tags.
  36. 'video': ['src', 'height', 'width', 'autoplay',
  37. 'loop', 'muted', 'controls']
  38. },
  39. transformTags: {
  40. // Set the "rel" attribute for <a> tags to "nofollow".
  41. 'a': sanitize.simpleTransform('a', { 'rel': 'nofollow' })
  42. }
  43. };
  44. }
  45. /**
  46. * The default instance of an `ISanitizer` meant for use by user code.
  47. */
  48. export
  49. const defaultSanitizer: ISanitizer = new Sanitizer();