fix(techdocs-plugin): do not sanitize safe head links

Signed-off-by: Camila Belo <camilaibs@gmail.com>
This commit is contained in:
Camila Belo
2021-07-30 18:30:01 +02:00
parent 29d616592b
commit b24a18e406
3 changed files with 61 additions and 0 deletions
+5
View File
@@ -0,0 +1,5 @@
---
'@backstage/plugin-techdocs': patch
---
Avoid sanitize safe links in the header of document pages.
@@ -110,4 +110,39 @@ describe('sanitizeDOM', () => {
expect(shadowDom.querySelectorAll('link').length).toEqual(1);
});
describe('safe head links', () => {
let shadowDom: ShadowRoot;
beforeEach(async () => {
shadowDom = await createTestShadowDom(FIXTURES.FIXTURE_STANDARD_PAGE, {
preTransformers: [sanitizeDOM()],
postTransformers: [],
});
});
it('should not sanitize the techdocs css', async () => {
const techdocsCss = shadowDom.querySelector(
'link[href$="main.fe0cca5b.min.css"]',
);
const rel = techdocsCss!.getAttribute('rel');
expect(rel).toBe('stylesheet');
});
it('should not sanitize google fonts', async () => {
const googleFonts = shadowDom.querySelector(
'link[href^="https://fonts.googleapis.com"]',
);
const rel = googleFonts!.getAttribute('rel');
expect(rel).toBe('stylesheet');
});
it('should not sanitize gstatic fonts', async () => {
const gstaticFonts = shadowDom.querySelector(
'link[href^="https://fonts.gstatic.com"]',
);
const rel = gstaticFonts!.getAttribute('rel');
expect(rel).toBe('preconnect');
});
});
});
@@ -14,11 +14,32 @@
* limitations under the License.
*/
const TECHDOCS_CSS = /main\.[A-Fa-f0-9]{8}\.min\.css/;
const GOOGLE_FONTS = /fonts\.googleapis\.com/;
const GSTATIC_FONTS = /fonts\.gstatic\.com/;
export const safeLinksHook = (node: Element) => {
if (node.nodeName && node.nodeName === 'LINK') {
const href = node.getAttribute('href') || '';
if (href.match(TECHDOCS_CSS)) {
node.setAttribute('rel', 'stylesheet');
}
if (href.match(GOOGLE_FONTS)) {
node.setAttribute('rel', 'stylesheet');
}
if (href.match(GSTATIC_FONTS)) {
node.setAttribute('rel', 'preconnect');
}
}
return node;
};
import DOMPurify from 'dompurify';
import type { Transformer } from './transformer';
export const sanitizeDOM = (): Transformer => {
return dom => {
DOMPurify.addHook('afterSanitizeAttributes', safeLinksHook);
return DOMPurify.sanitize(dom.innerHTML, {
ADD_TAGS: ['link'],
FORBID_TAGS: ['style'],