import { shallowMount } from '@vue/test-utils'; import safeHtml from '~/vue_shared/directives/safe_html'; import { defaultConfig } from '~/lib/dompurify'; /* eslint-disable no-script-url */ const invalidProtocolUrls = [ 'javascript:alert(1)', 'jAvascript:alert(1)', 'data:text/html,', ' javascript:', 'javascript :', ]; /* eslint-enable no-script-url */ const validProtocolUrls = ['slack://open', 'x-devonthink-item://90909', 'x-devonthink-item:90909']; describe('safe html directive', () => { let wrapper; const createComponent = ({ template, html, config } = {}) => { const defaultTemplate = `
`; const defaultHtml = 'hello world'; const component = { directives: { safeHtml, }, data() { return { rawHtml: html || defaultHtml, config: config || {}, }; }, template: template || defaultTemplate, }; wrapper = shallowMount(component); }; describe('default', () => { it('should remove the script tag', () => { createComponent(); expect(wrapper.html()).toEqual('
hello world
'); }); it('should remove javascript hrefs', () => { createComponent({ html: 'click here' }); expect(wrapper.html()).toEqual('
click here
'); }); it('should remove any existing children', () => { createComponent({ template: `
foo bar
`, }); expect(wrapper.html()).toEqual('
hello world
'); }); describe('with non-http links', () => { it.each(validProtocolUrls)('should allow %s', (url) => { createComponent({ html: `internal link`, }); expect(wrapper.html()).toContain(`internal link`); }); it.each(invalidProtocolUrls)('should not allow %s', (url) => { createComponent({ html: `internal link`, }); expect(wrapper.html()).toContain(`internal link`); }); }); describe('handles data attributes correctly', () => { const allowedDataAttrs = ['data-safe', 'data-random']; it.each(defaultConfig.FORBID_ATTR)('removes dangerous `%s` attribute', (attr) => { const html = ``; createComponent({ html }); expect(wrapper.html()).not.toContain(html); }); it.each(allowedDataAttrs)('does not remove allowed `%s` attribute', (attr) => { const html = ``; createComponent({ html }); expect(wrapper.html()).toContain(html); }); }); }); describe('advance config', () => { const template = '
'; it('should only allow tags', () => { createComponent({ template, html: 'click here', config: { ALLOWED_TAGS: ['b'] }, }); expect(wrapper.html()).toEqual('
click here
'); }); it('should strip all html tags', () => { createComponent({ template, html: 'click here', config: { ALLOWED_TAGS: [] }, }); expect(wrapper.html()).toEqual('
click here
'); }); }); });