diff --git a/webapp/packages/core-utils/src/index.ts b/webapp/packages/core-utils/src/index.ts index e16378ab72..e4275bfaac 100644 --- a/webapp/packages/core-utils/src/index.ts +++ b/webapp/packages/core-utils/src/index.ts @@ -77,3 +77,4 @@ export * from './removeLineBreak'; export * from './replaceSubstring'; export * from './formatNumber'; export * from './withTimestamp'; +export * from './toSafeHtmlString'; diff --git a/webapp/packages/core-utils/src/toSafeHtmlString.test.tsx b/webapp/packages/core-utils/src/toSafeHtmlString.test.tsx new file mode 100644 index 0000000000..147716b8e2 --- /dev/null +++ b/webapp/packages/core-utils/src/toSafeHtmlString.test.tsx @@ -0,0 +1,28 @@ +/* + * CloudBeaver - Cloud Database Manager + * Copyright (C) 2020-2024 DBeaver Corp and others + * + * Licensed under the Apache License, Version 2.0. + * you may not use this file except in compliance with the License. + */ +import { toSafeHtmlString } from './toSafeHtmlString'; + +describe('toSafeHtmlString', () => { + it('should make html string safe', () => { + const input = ''; + const output = toSafeHtmlString(input); + expect(output).toBe('<script>alert("some unsafe action")</script>'); + }); + + it('should return empty string', () => { + const input = ''; + const output = toSafeHtmlString(input); + expect(output).toBe(''); + }); + + it('should return the same string', () => { + const input = 'some safe string'; + const output = toSafeHtmlString(input); + expect(output).toBe(input); + }); +}); diff --git a/webapp/packages/core-utils/src/toSafeHtmlString.ts b/webapp/packages/core-utils/src/toSafeHtmlString.ts new file mode 100644 index 0000000000..783869079c --- /dev/null +++ b/webapp/packages/core-utils/src/toSafeHtmlString.ts @@ -0,0 +1,14 @@ +/* + * CloudBeaver - Cloud Database Manager + * Copyright (C) 2020-2024 DBeaver Corp and others + * + * Licensed under the Apache License, Version 2.0. + * you may not use this file except in compliance with the License. + */ +export function toSafeHtmlString(dirty: string): string { + const el = document.createElement('div'); + el.innerText = el.textContent = dirty; + dirty = el.innerHTML; + + return dirty; +}