// Verplaatst de inline scripts van Start naar bestanden onder /assets. // // Waarom (NFR-PR-Q-05, BR-BLD-12): de CSP staat alleen script-src 'self' en // het Umami-script toe, zonder 'unsafe-inline'. Start zet in elke // geprerenderde pagina inline scripts (bootstrap, grensmarkering, scroll // herstel), die de browser daardoor zou blokkeren. De CSP blijft daarom // ongewijzigd; de scripts krijgen een eigen bestand, genoemd naar de hash van // hun inhoud. // // Eén scanner en één classificatie voor herschrijven en controleren (BR-SCR-01), // zodat de controle niet kan afwijken van het herschrijven. Geen // HTML-parser als afhankelijkheid: de uitvoer van Start is een bekende, kleine // vorm en alles wat de scanner niet aankan faalt hard in plaats van stil. import { createHash } from 'node:crypto'; export interface MovedScript { // inline-<12 hex>.js; het bestand staat op /assets/ fileName: string; body: string; } export interface ExternalizeResult { html: string; // Elke bestandsnaam één keer, op volgorde van eerste voorkomen moved: MovedScript[]; } export type ScriptErrorCode = 'UNSUPPORTED_SCRIPT' | 'UNTERMINATED_SCRIPT'; // De code laat de runner de fout als overtreding melden. Het bericht noemt een // regelnummer en nooit de inhoud van het script (BR-SCR-21). export class ScriptError extends Error { code: ScriptErrorCode; constructor(code: ScriptErrorCode, detail: string) { super(`${code}: ${detail}`); this.name = 'ScriptError'; this.code = code; } } const ASSETS_DIR = 'assets'; const HASH_LENGTH = 12; // Typen die een browser als JavaScript uitvoert (BR-SCR-04), plus module. // Al het andere (ld+json, importmap, speculationrules) is een datablok. const JAVASCRIPT_TYPES = new Set([ 'application/javascript', 'application/ecmascript', 'application/x-ecmascript', 'application/x-javascript', 'text/javascript', 'text/javascript1.0', 'text/javascript1.1', 'text/javascript1.2', 'text/javascript1.3', 'text/javascript1.4', 'text/javascript1.5', 'text/ecmascript', 'text/jscript', 'text/livescript', 'text/x-ecmascript', 'text/x-javascript', ]); // Elementen waarvan de inhoud tekst is: een script daarin is geen script // (BR-SCR-02) const RAW_TEXT_ELEMENTS = new Set([ 'style', 'textarea', 'title', 'noscript', 'xmp', 'iframe', 'noembed', 'noframes', ]); type ScriptKind = 'external' | 'empty' | 'data' | 'executable'; interface ScriptElement { start: number; end: number; // Alles tussen de tagnaam en de sluitende '>', letterlijk (BR-SCR-06) attributeText: string; body: string; // Heeft het element een eindtag met '>'? terminated: boolean; kind: ScriptKind; module: boolean; asyncOrDefer: boolean; } interface StartTag { name: string; attributes: Map; attributeStart: number; close: number; } const isWhitespace = (char: string | undefined) => char === ' ' || char === '\t' || char === '\n' || char === '\f' || char === '\r'; const isLetter = (char: string | undefined) => char !== undefined && /[A-Za-z]/.test(char); // Leest een starttag vanaf de '<'. De eerste waarde van een attribuut telt, // zoals in een browser. Geeft null als de tag niet eindigt (een aanhalingsteken // of de tag loopt door tot het einde van de tekst): een browser gooit die weg. function readStartTag(html: string, lt: number): StartTag | null { const length = html.length; let pos = lt + 1; while ( pos < length && !isWhitespace(html[pos]) && html[pos] !== '/' && html[pos] !== '>' ) { pos++; } const name = html.slice(lt + 1, pos).toLowerCase(); const attributeStart = pos; const attributes = new Map(); for (;;) { while (pos < length && (isWhitespace(html[pos]) || html[pos] === '/')) { pos++; } if (pos >= length) return null; if (html[pos] === '>') { return { name, attributes, attributeStart, close: pos }; } // Het eerste teken hoort altijd bij de naam, ook als het een '=' is const nameStart = pos; pos++; while ( pos < length && !isWhitespace(html[pos]) && html[pos] !== '/' && html[pos] !== '>' && html[pos] !== '=' ) { pos++; } const attributeName = html.slice(nameStart, pos).toLowerCase(); let probe = pos; while (isWhitespace(html[probe])) probe++; let value = ''; if (html[probe] === '=') { probe++; while (isWhitespace(html[probe])) probe++; const quote = html[probe]; if (quote === '"' || quote === "'") { const closing = html.indexOf(quote, probe + 1); if (closing === -1) return null; value = html.slice(probe + 1, closing); pos = closing + 1; } else { const valueStart = probe; while ( probe < length && !isWhitespace(html[probe]) && html[probe] !== '>' ) { probe++; } value = html.slice(valueStart, probe); pos = probe; } } if (!attributes.has(attributeName)) { attributes.set(attributeName, value); } } } const endTagPatterns = new Map(); // Zoekt de eindtag van een tekstelement: naam, dan witruimte, '/' of '>' (of // het einde van de tekst). Met de g-vlag zodat lastIndex de startplaats is. function endTagPattern(name: string): RegExp { let pattern = endTagPatterns.get(name); if (!pattern) { pattern = new RegExp(`]|$)`, 'gi'); endTagPatterns.set(name, pattern); } return pattern; } function classify( attributes: Map, body: string, ): { kind: ScriptKind; module: boolean } { if (attributes.has('src')) return { kind: 'external', module: false }; if (body.trim() === '') return { kind: 'empty', module: false }; const type = (attributes.get('type') ?? '').trim().toLowerCase(); if (type === 'module') return { kind: 'executable', module: true }; if (type === '' || JAVASCRIPT_TYPES.has(type)) { return { kind: 'executable', module: false }; } return { kind: 'data', module: false }; } // Loopt één keer van links naar rechts door de tekst en levert de // script-elementen (BR-SCR-02, 03). Commentaar, tekstelementen en // attribuutwaarden worden overgeslagen, zodat tekst die op een script lijkt // nooit meetelt. function scanScripts(html: string): ScriptElement[] { const found: ScriptElement[] = []; const length = html.length; const scriptEnd = /<\/script(?=[\s/>])/gi; let pos = 0; while (pos < length) { const lt = html.indexOf('<', pos); if (lt === -1) break; const next = html[lt + 1]; if (html.startsWith(' en zoals in een browser sluiten const closing = html.indexOf('-->', lt + 2); pos = closing === -1 ? length : closing + 3; continue; } if (next === '!' || next === '?' || next === '/') { const closing = html.indexOf('>', lt + 2); pos = closing === -1 ? length : closing + 1; continue; } if (!isLetter(next)) { pos = lt + 1; continue; } const tag = readStartTag(html, lt); if (!tag) break; const bodyStart = tag.close + 1; if (tag.name === 'script') { scriptEnd.lastIndex = bodyStart; const endTag = scriptEnd.exec(html); let body: string; let end: number; let terminated: boolean; if (!endTag) { body = html.slice(bodyStart); end = length; terminated = false; } else { body = html.slice(bodyStart, endTag.index); const closing = html.indexOf('>', endTag.index); terminated = closing !== -1; end = terminated ? closing + 1 : length; } const { kind, module } = classify(tag.attributes, body); found.push({ start: lt, end, attributeText: html.slice(tag.attributeStart, tag.close), body, terminated, kind, module, asyncOrDefer: tag.attributes.has('async') || tag.attributes.has('defer'), }); pos = end; continue; } if (RAW_TEXT_ELEMENTS.has(tag.name)) { const pattern = endTagPattern(tag.name); pattern.lastIndex = bodyStart; const endTag = pattern.exec(html); pos = endTag ? endTag.index : length; continue; } pos = bodyStart; } return found; } // Een relatieve importspecifier ('./x', '../x') zou na het verplaatsen tegen // /assets/ oplossen in plaats van tegen de pagina const RELATIVE_IMPORT = /\bfrom\s*['"`]\.{1,2}(?:\/|(?=['"`]))|\bimport\s*\(?\s*['"`]\.{1,2}(?:\/|(?=['"`]))/; function lineOf(html: string, index: number): number { return html.slice(0, index).split('\n').length; } // Vormen die we niet veilig kunnen verplaatsen (BR-SCR-05): liever een // mislukte build dan stil ander gedrag als Start zijn uitvoer wijzigt. function unsupportedReason(script: ScriptElement): string | null { if (!script.module && script.asyncOrDefer) { return 'async of defer op een klassiek script'; } if (script.body.includes('