text.ts 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. import xss from 'xss';
  2. const XSSWL = Object.keys(xss.whiteList).reduce((acc, element) => {
  3. // @ts-ignore
  4. acc[element] = xss.whiteList[element].concat(['class', 'style']);
  5. return acc;
  6. }, {});
  7. const sanitizeXSS = new xss.FilterXSS({
  8. whiteList: XSSWL,
  9. });
  10. /**
  11. * Returns string safe from XSS attacks.
  12. *
  13. * Even though we allow the style-attribute, there's still default filtering applied to it
  14. * Info: https://github.com/leizongmin/js-xss#customize-css-filter
  15. * Whitelist: https://github.com/leizongmin/js-css-filter/blob/master/lib/default.js
  16. */
  17. export function sanitize(unsanitizedString: string): string {
  18. try {
  19. return sanitizeXSS.process(unsanitizedString);
  20. } catch (error) {
  21. console.log('String could not be sanitized', unsanitizedString);
  22. return unsanitizedString;
  23. }
  24. }
  25. export function hasAnsiCodes(input: string): boolean {
  26. return /\u001b\[\d{1,2}m/.test(input);
  27. }
  28. export function escapeHtml(str: string): string {
  29. return String(str)
  30. .replace(/&/g, '&')
  31. .replace(/</g, '&lt;')
  32. .replace(/>/g, '&gt;')
  33. .replace(/"/g, '&quot;');
  34. }