From bc4a29ce3e0bf564ad23a2e543023468284e98b1 Mon Sep 17 00:00:00 2001 From: Evgeny Biriulin Date: Tue, 8 Aug 2023 07:56:05 +0400 Subject: [PATCH] feat: transform should sanitize html by default PR where sanitizer was added: https://github.com/yandex-cloud/yfm-transform/pull/177 --- src/transform/md.ts | 2 +- src/transform/sanitize.ts | 1 + test/sanitize-html.test.ts | 43 ++++++++++++++++++++++++++++++++------ 3 files changed, 39 insertions(+), 7 deletions(-) diff --git a/src/transform/md.ts b/src/transform/md.ts index 245d17c6..c46568be 100644 --- a/src/transform/md.ts +++ b/src/transform/md.ts @@ -111,7 +111,7 @@ function initParser(md: MarkdownIt, options: OptionsType, env: EnvType) { } function initCompiler(md: MarkdownIt, options: OptionsType, env: EnvType) { - const {needToSanitizeHtml = false, sanitizeOptions} = options; + const {needToSanitizeHtml = true, sanitizeOptions} = options; return (tokens: Token[]) => { const html = md.renderer.render(tokens, md.options, env); diff --git a/src/transform/sanitize.ts b/src/transform/sanitize.ts index 292eac92..ac5b4e8e 100644 --- a/src/transform/sanitize.ts +++ b/src/transform/sanitize.ts @@ -118,6 +118,7 @@ const htmlTags = [ 'video', 'wbr', 'iframe', + 'style' ]; const svgTags = [ diff --git a/test/sanitize-html.test.ts b/test/sanitize-html.test.ts index 997e392c..90406a57 100644 --- a/test/sanitize-html.test.ts +++ b/test/sanitize-html.test.ts @@ -16,13 +16,44 @@ describe('Sanitize HTML utility', () => { expect(sanitizeHtml('')).toBe(''); }); - it('transform should sanitize html', () => { - expect(transformYfm('', {needToSanitizeHtml: true})).toBe( - '', - ); + describe('by default transform should sanitize html', () => { + + describe('html in markdown', () => { + it('should sanitize danger attributes', () => { + expect(transformYfm('')).toBe( + '', + ); + }) + + it('should not sanitize style tag', () => { + expect(transformYfm('')).toBe( + '', + ); + }); + }) + + describe('plugin markdown-it-attrs', () => { + it('should sanitize danger attributes', () => { + expect(transformYfm('Click {onfocus="alert(1)" onclick="alert(1)"}')).toBe( + '

Click

\n', + ); + }); + + it('should not sanitize safe attributes', () => { + expect(transformYfm('Click {.style-me data-toggle=modal}')).toBe( + '

Click

\n', + ); + }); + + it('should not sanitize style attribute', () => { + expect(transformYfm('[example.com](https://example.com){style="position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color: red; opacity: 0.5"}')).toBe( + '

example.com

\n', + ); + }); + }) }); - it('by default transform should not sanitize html', () => { - expect(transformYfm('')).toBe(''); + it('transform should not sanitize html', () => { + expect(transformYfm('', {needToSanitizeHtml: false})).toBe(''); }); });