// Sanitises the HTML that third-party Markdown brings into the site.
//
// Three collections (payloads, internal, hacktricks) are mirrors of other
// people's repositories, re-imported on a schedule with no review in between.
// Markdown may carry raw HTML, Astro's renderer passes it through untouched
// (`allowDangerousHtml`), and so a `<script>` committed upstream would be
// served from this origin, where the decrypted report index lives. This pass
// is what stands in the way; scripts/csp-hashes.mjs is the second lock behind
// it and refuses to add a hash for any script this pass somehow let through.
//
// How it tells the two kinds of HTML apart
// ----------------------------------------
// By the time a rehype plugin runs, Markdown itself has already become real
// element nodes (paragraphs, tables, Shiki's highlighted code), while raw HTML
// is still a string in a `raw` node. Those two have very different trust: the
// first is structure this build produced, the second is whatever upstream
// typed. Parsing the raw strings (the only reliable way to sanitise HTML, as
// a tag may open in one node and close in another) erases that difference, so
// before parsing every existing element is stamped with a random, per-process
// token. After parsing, an element carrying the token is the build's own and
// keeps its attributes (Shiki's inline colours, heading ids, task-list
// checkboxes); anything without it came from upstream and is held to the
// allowlist below. Upstream cannot forge the stamp without guessing the token.
//
// What happens to upstream HTML
// -----------------------------
// * Elements on ALLOWED stay, with only their listed attributes.
// * Elements on DROPPED go, contents and all (script, style, iframe, form
// controls, svg, ...).
// * Anything else is unwrapped: the tag goes, its text stays readable.
// * Comments go.
// * `href`/`src` keep only http(s), mailto and relative URLs — on the build's
// own elements too, since `[x](javascript:...)` is plain Markdown.
//
// Fenced and inline code is untouched: it never was HTML, only text that looks
// like it, and Markdown has already escaped it.
//
// Order matters: this is the LAST pass in astro.config.mjs, so the passes
// before it see exactly the tree they always have.
import { randomBytes } from 'node:crypto';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { raw } from 'hast-util-raw';
// Fail closed: every collection is sanitised unless it is first-party, and
// first-party means exactly one thing: the file sits in the `sheets`
// collection directly under this project's own content root.
//
// The test is anchored to that root on purpose. Matching "/src/content/sheets/"
// anywhere in the path would let a mirror opt itself out: an upstream folder
// named `src/content/sheets` is imported as
// `src/content/payloads/<topic>/src/content/sheets/page.md`, which contains
// the same substring. Two spellings of the root are accepted (the working
// directory the build runs from, and this file's own location) so the check
// holds whichever way the config was loaded; a path under neither is treated
// as third-party.
const FIRST_PARTY_COLLECTIONS = new Set(['sheets']);
const posix = (p) => p.replace(/\\/g, '/');
const CONTENT_ROOTS = [
posix(path.join(process.cwd(), 'src', 'content')),
posix(fileURLToPath(new URL('../content', import.meta.url))),
];
/** True only for a file in a first-party collection directly under a content root. */
export function isFirstParty(source, roots = CONTENT_ROOTS) {
if (!source) return false;
const file = path.posix.normalize(posix(source));
return roots.some((root) => {
const rel = path.posix.relative(path.posix.normalize(posix(root)), file);
if (!rel || rel.startsWith('..') || path.posix.isAbsolute(rel)) return false;
const [collection, ...rest] = rel.split('/');
return rest.length > 0 && FIRST_PARTY_COLLECTIONS.has(collection);
});
}
const STAMP = 'dataDmnBuilt';
const TOKEN = randomBytes(18).toString('hex');
const GLOBAL_ATTRS = ['title', 'dir', 'lang', 'id'];
const ALIGN = ['align'];
const CELL = ['align', 'vAlign', 'colSpan', 'rowSpan'];
/** tag -> extra attributes kept (besides GLOBAL_ATTRS). */
const ALLOWED = new Map(Object.entries({
a: ['href'], abbr: [], b: [], bdi: [], bdo: [], blockquote: [], br: [], caption: ALIGN, center: [],
cite: [], code: [], col: ['span'], colgroup: ['span'], dd: [], del: [], details: ['open'], dfn: [],
div: ALIGN, dl: [], dt: [], em: [], figcaption: [], figure: [], h1: ALIGN, h2: ALIGN, h3: ALIGN,
h4: ALIGN, h5: ALIGN, h6: ALIGN, hr: [], i: [], img: ['src', 'alt', 'width', 'height', 'align', 'loading'],
ins: [], kbd: [], li: ['value'], mark: [], ol: ['start', 'type', 'reversed'], p: ALIGN, pre: [], q: [],
rp: [], rt: [], ruby: [], s: [], samp: [], small: [], span: [], strike: [], strong: [], sub: [],
summary: [], sup: [], table: ALIGN, tbody: [], td: CELL, tfoot: [], th: CELL, thead: [], time: ['dateTime'],
tr: ALIGN, tt: [], u: [], ul: [], var: [], wbr: [],
}));
/** Removed together with everything inside them. */
const DROPPED = new Set([
'script', 'style', 'template', 'iframe', 'frame', 'frameset', 'noframes', 'object', 'embed', 'applet',
'param', 'noscript', 'noembed', 'plaintext', 'xmp', 'listing', 'svg', 'math', 'audio', 'video', 'track',
'source', 'canvas', 'map', 'area', 'link', 'meta', 'base', 'title', 'head', 'dialog', 'portal', 'slot',
'input', 'button', 'select', 'textarea', 'option', 'optgroup', 'datalist', 'output', 'keygen',
]);
const SAFE_LINK = new Set(['http', 'https', 'mailto']);
const SAFE_MEDIA = new Set(['http', 'https']);
// No spaces, quotes or markup; HTML allows an id to start with a digit.
const SAFE_ID = /^\w[\w:.-]{0,127}$/;
/** True for a relative URL or one whose scheme is on the list. */
export function isSafeUrl(value, schemes) {
if (typeof value !== 'string') return false;
// Browsers drop tabs and newlines inside a URL and leading control
// characters before reading the scheme, so `java\nscript:` is a scheme too.
// eslint-disable-next-line no-control-regex
const url = value.replace(/[\t\n\r]/g, '').replace(/^[\u0000- ]+/, '');
const colon = url.indexOf(':');
if (colon === -1) return true;
const stop = url.search(/[/?#]/);
if (stop !== -1 && stop < colon) return true;
return schemes.has(url.slice(0, colon).toLowerCase());
}
function stamp(node) {
if (node.type === 'element') node.properties = { ...node.properties, [STAMP]: TOKEN };
if (node.children) for (const child of node.children) stamp(child);
}
function checkUrls(tag, properties) {
if ('href' in properties && !(tag === 'a' && isSafeUrl(properties.href, SAFE_LINK))) delete properties.href;
if ('src' in properties && !isSafeUrl(properties.src, SAFE_MEDIA)) delete properties.src;
for (const name of ['srcSet', 'srcDoc', 'formAction', 'action', 'xLinkHref', 'ping', 'background', 'poster']) {
delete properties[name];
}
}
function upstreamProperties(tag, properties) {
const kept = {};
const allow = ALLOWED.get(tag);
for (const name of [...GLOBAL_ATTRS, ...allow]) {
const value = properties[name];
if (value === undefined || value === null || value === false) continue;
kept[name] = value;
}
// `<a name="x">` is the old spelling of an anchor target; keep it as an id
// so in-page links still land, without the named-access side of `name`.
if (tag === 'a' && kept.id === undefined && typeof properties.name === 'string') kept.id = properties.name;
if (kept.id !== undefined && !SAFE_ID.test(String(kept.id))) delete kept.id;
checkUrls(tag, kept);
return kept;
}
/** Returns the nodes that replace `node`: itself, its children, or nothing. */
function clean(node) {
if (node.type === 'text') return [node];
if (node.type !== 'element') return []; // comments, doctypes, stray raw
const properties = { ...node.properties };
const built = properties[STAMP] === TOKEN;
delete properties[STAMP];
const tag = node.tagName;
if (built) {
checkUrls(tag, properties);
return [{ ...node, properties, children: node.children.flatMap(clean) }];
}
if (DROPPED.has(tag)) return [];
const children = node.children.flatMap(clean);
if (!ALLOWED.has(tag)) return children;
const kept = upstreamProperties(tag, properties);
if (tag === 'img' && kept.src === undefined) return []; // nothing left to show
return [{ type: 'element', tagName: tag, properties: kept, children }];
}
/** Sanitise one already-rendered Markdown tree. Exported for the tests. */
export function sanitizeTree(tree, file) {
stamp(tree);
const parsed = raw(tree, { file });
return { ...parsed, children: parsed.children.flatMap(clean) };
}
/** `contentRoots` is for the tests; the build uses this project's own. */
export function rehypeSanitizeMirror({ contentRoots = CONTENT_ROOTS } = {}) {
return (tree, file) => {
const source = String(file?.history?.[0] ?? file?.path ?? '');
if (isFirstParty(source, contentRoots)) return undefined;
return sanitizeTree(tree, file);
};
}