Skip to content

Commit

Permalink
fix: update function to take better care of quotes as some of them ar…
Browse files Browse the repository at this point in the history
…e okay
  • Loading branch information
iOvergaard committed Jan 20, 2025
1 parent 94f6b03 commit 6833f95
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 12 deletions.
2 changes: 1 addition & 1 deletion src/libs/localization-api/localization.controller.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,7 @@ describe('UmbLocalizeController', () => {

it('should encode HTML entities', () => {
expect(controller.term('withInlineToken', 'Hello', '<script>alert("XSS")</script>'), 'XSS detected').to.equal(
'Hello &lt;script&gt;alert(&quot;XSS&quot;)&lt;/script&gt;',
'Hello &lt;script&gt;alert(&#34;XSS&#34;)&lt;/script&gt;',
);
});

Expand Down
10 changes: 1 addition & 9 deletions src/packages/core/utils/sanitize/escape-html.function.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,6 @@ import { escapeHTML } from './escape-html.function.js';

describe('escapeHtml', () => {
it('should escape html', () => {
expect(escapeHTML('<script>alert("XSS")</script>')).to.equal('&lt;script&gt;alert(&quot;XSS&quot;)&lt;/script&gt;');
});

it('should escape html with single quotes', () => {
expect(escapeHTML("<script>alert('XSS')</script>")).to.equal('&lt;script&gt;alert(&#39;XSS&#39;)&lt;/script&gt;');
});

it('should escape html with mixed quotes', () => {
expect(escapeHTML("<script>alert('XSS')</script>")).to.equal('&lt;script&gt;alert(&#39;XSS&#39;)&lt;/script&gt;');
expect(escapeHTML('<script>alert("XSS")</script>')).to.equal('&lt;script&gt;alert(&#34;XSS&#34;)&lt;/script&gt;');
});
});
14 changes: 12 additions & 2 deletions src/packages/core/utils/sanitize/escape-html.function.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
const SURROGATE_PAIR_REGEXP = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
// Match everything outside of normal chars and " (quote character)
const NON_ALPHANUMERIC_REGEXP = /([^#-~| |!])/g;

/**
* Escapes HTML entities in a string.
* @example escapeHTML('<script>alert("XSS")</script>'), // "&lt;script&gt;alert(&quot;XSS&quot;)&lt;/script&gt;"
Expand All @@ -12,8 +16,14 @@ export function escapeHTML(html: unknown): string {
return html
.toString()
.replace(/&/g, '&amp;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#39;')
.replace(SURROGATE_PAIR_REGEXP, function (value) {
const hi = value.charCodeAt(0);
const low = value.charCodeAt(1);
return '&#' + ((hi - 0xd800) * 0x400 + (low - 0xdc00) + 0x10000) + ';';
})
.replace(NON_ALPHANUMERIC_REGEXP, function (value) {
return '&#' + value.charCodeAt(0) + ';';
})
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;');
}

0 comments on commit 6833f95

Please sign in to comment.