Files
AndreaSlopFotografie/web/config/inlineScripts.ts
T
SluijsensandClaude Opus 5.5 1574726c1d Adds the step that moves inline scripts to files
TanStack Start writes inline scripts into each page, which the strict CSP
blocks. This step moves them to hashed files and checks the output: every page
is present, no executable inline script remains and the e-mail address appears
nowhere. It is not part of the build yet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 18:12:42 +01:00

371 lines
12 KiB
TypeScript

// 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>
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<string, string>;
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<string, string>();
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<string, RegExp>();
// 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(`</${name}(?=[\\s/>]|$)`, 'gi');
endTagPatterns.set(name, pattern);
}
return pattern;
}
function classify(
attributes: Map<string, string>,
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('<!--', lt)) {
// Vanaf lt + 2, zodat <!--> 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('<!--')) {
return 'commentaaropener in de scriptinhoud';
}
if (script.module && RELATIVE_IMPORT.test(script.body)) {
return 'relatieve import in een module-script';
}
return null;
}
function fileNameOf(body: string): string {
const hash = createHash('sha256')
.update(body, 'utf8')
.digest('hex')
.slice(0, HASH_LENGTH);
return `inline-${hash}.js`;
}
// Vervangt elk uitvoerbaar inline script door een verwijzing naar een bestand
// met de hash van de inhoud als naam. Volgorde, attributen en al het andere
// blijven zoals ze waren; alleen src komt erbij (BR-SCR-06, 09).
export function externalizeInlineScripts(html: string): ExternalizeResult {
const scripts = scanScripts(html);
for (const script of scripts) {
if (!script.terminated) {
throw new ScriptError(
'UNTERMINATED_SCRIPT',
`script zonder eindtag op regel ${lineOf(html, script.start)}`,
);
}
}
const moved: MovedScript[] = [];
const seen = new Set<string>();
let output = '';
let copiedUntil = 0;
for (const script of scripts) {
if (script.kind !== 'executable') continue;
const reason = unsupportedReason(script);
if (reason) {
throw new ScriptError(
'UNSUPPORTED_SCRIPT',
`${reason} op regel ${lineOf(html, script.start)}`,
);
}
const fileName = fileNameOf(script.body);
if (!seen.has(fileName)) {
seen.add(fileName);
moved.push({ fileName, body: script.body });
}
output +=
html.slice(copiedUntil, script.start) +
`<script${script.attributeText} src="/${ASSETS_DIR}/${fileName}"></script>`;
copiedUntil = script.end;
}
return { html: output + html.slice(copiedUntil), moved };
}
// De inhoud van de uitvoerbare inline scripts die er nog staan, in
// documentvolgorde. Datablokken zoals JSON-LD tellen niet mee.
export function findExecutableInlineScripts(html: string): string[] {
return scanScripts(html)
.filter((script) => script.kind === 'executable')
.map((script) => script.body);
}