feat: clean plugin READMEs before they reach the page
A README is third-party HTML that can change after review. It is sanitized against a closed allowlist on every build, and its relative links are pointed at the published version so images and docs resolve without knowing the author's branch. Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
4 files changed
+261
-2
No files matched your search
@@ -0,0 +1,46 @@
|
||||
// A plugin's README is somebody else's HTML. Review reads the yaml once; the README can change on
|
||||
// any later publish and reach the site at the next Friday cut. So it is cleaned against a closed
|
||||
// allowlist every build, and never trusted because the entry was.
|
||||
import sanitizeHtml from 'sanitize-html';
|
||||
|
||||
const HEX = /^#[0-9a-f]{3,8}$/i;
|
||||
|
||||
/** Relative URLs resolve against the published package; anchors and absolute URLs stay. */
|
||||
function absolute(url, base) {
|
||||
if (!url || url.startsWith('#')) return url;
|
||||
try {
|
||||
return new URL(url, base).href;
|
||||
} catch {
|
||||
return url;
|
||||
}
|
||||
}
|
||||
|
||||
/** Only touch the attribute when it is there — setting it to `undefined` renders a bare `href`. */
|
||||
function rebase(attribs, key, base) {
|
||||
return key in attribs ? { ...attribs, [key]: absolute(attribs[key], base) } : attribs;
|
||||
}
|
||||
|
||||
export function cleanReadme(html, base) {
|
||||
return sanitizeHtml(html, {
|
||||
allowedTags: sanitizeHtml.defaults.allowedTags.concat(['img', 'h1', 'h2', 'details', 'summary', 'picture', 'source']),
|
||||
allowedAttributes: {
|
||||
'*': ['id', 'align'],
|
||||
a: ['href', 'title'],
|
||||
img: ['src', 'alt', 'title', 'width', 'height'],
|
||||
source: ['srcset', 'media'],
|
||||
pre: ['class', 'style', 'tabindex', 'data-language'],
|
||||
span: ['class', 'style'],
|
||||
code: ['class'],
|
||||
},
|
||||
// Only what shiki writes. Anything else (position, inset, z-index…) would let a README draw
|
||||
// over the page around it.
|
||||
allowedStyles: {
|
||||
'*': { color: [HEX], 'background-color': [HEX], 'overflow-x': [/^auto$/] },
|
||||
},
|
||||
allowedSchemes: ['http', 'https', 'mailto'],
|
||||
transformTags: {
|
||||
a: (tagName, attribs) => ({ tagName, attribs: rebase(attribs, 'href', base) }),
|
||||
img: (tagName, attribs) => ({ tagName, attribs: rebase(attribs, 'src', base) }),
|
||||
},
|
||||
});
|
||||
}
|
||||
Reference in new issue
Block a user