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>
508 lines
19 KiB
TypeScript
508 lines
19 KiB
TypeScript
import { createHash } from 'node:crypto';
|
|
import fc from 'fast-check';
|
|
import { describe, expect, it } from 'vitest';
|
|
import {
|
|
canonicalHtmlWithModel,
|
|
htmlFragments,
|
|
htmlWithModel,
|
|
scriptBody,
|
|
} from '../src/test/htmlArbitraries';
|
|
import {
|
|
ScriptError,
|
|
externalizeInlineScripts,
|
|
findExecutableInlineScripts,
|
|
} from './inlineScripts';
|
|
|
|
// Onafhankelijk van de implementatie: de naam volgens BR-SCR-07
|
|
const fileOf = (body: string) =>
|
|
`inline-${createHash('sha256').update(body, 'utf8').digest('hex').slice(0, 12)}.js`;
|
|
|
|
const referenceOf = (attributes: string, body: string) =>
|
|
`<script${attributes} src="/assets/${fileOf(body)}"></script>`;
|
|
|
|
// Een door de stap geplaatste verwijzing: <script ... src="/assets/inline-..">
|
|
const referenceElement =
|
|
/<script(?:[^>"']|"[^"]*"|'[^']*')* src="\/assets\/inline-[0-9a-f]{12}\.js"><\/script>/g;
|
|
|
|
const fails = (html: string, code: string) => {
|
|
try {
|
|
externalizeInlineScripts(html);
|
|
} catch (error) {
|
|
expect(error).toBeInstanceOf(ScriptError);
|
|
expect((error as ScriptError).code).toBe(code);
|
|
return error as ScriptError;
|
|
}
|
|
throw new Error('verwacht een ScriptError');
|
|
};
|
|
|
|
describe('externalizeInlineScripts: voorbeelden', () => {
|
|
it('verplaatst het bootstrapscript en behoudt de attributen', () => {
|
|
const result = externalizeInlineScripts(
|
|
'<script data-tsr-stream-part="">A</script>',
|
|
);
|
|
expect(result.html).toBe(referenceOf(' data-tsr-stream-part=""', 'A'));
|
|
expect(result.moved).toEqual([{ fileName: fileOf('A'), body: 'A' }]);
|
|
});
|
|
|
|
it('laat een extern module-script met async ongemoeid', () => {
|
|
const html = '<script type="module" async src="/assets/x.js"></script>';
|
|
expect(externalizeInlineScripts(html)).toEqual({ html, moved: [] });
|
|
});
|
|
|
|
it('verplaatst een kaal script en kent het bestand de inhoud toe', () => {
|
|
const result = externalizeInlineScripts(
|
|
'<script>document.currentScript.remove()</script>',
|
|
);
|
|
expect(result.html).toBe(
|
|
referenceOf('', 'document.currentScript.remove()'),
|
|
);
|
|
expect(result.moved).toHaveLength(1);
|
|
});
|
|
|
|
it.each([
|
|
[
|
|
'een JSON-LD-blok',
|
|
'<script type="application/ld+json">{"a":1}</script>',
|
|
],
|
|
[
|
|
'een style-body',
|
|
'<style>.a::before{content:"<script>x</script>"}</style>',
|
|
],
|
|
['commentaar', '<!-- <script>x</script> -->'],
|
|
['een attribuutwaarde', '<div title="<script>x</script>"></div>'],
|
|
])('laat %s ongemoeid', (_, html) => {
|
|
expect(externalizeInlineScripts(html)).toEqual({ html, moved: [] });
|
|
});
|
|
|
|
it('laat al het andere byte voor byte staan, ook regeleinden', () => {
|
|
const html =
|
|
'<!doctype html>\r\n<html>\r\n<!-- c -->\r\n<style>a{}</style>' +
|
|
'<script type="application/ld+json">{}</script>' +
|
|
'<script>go()</script>\r\n<script src="/a.js"></script>\r\n</html>';
|
|
expect(externalizeInlineScripts(html).html).toBe(
|
|
html.replace('<script>go()</script>', referenceOf('', 'go()')),
|
|
);
|
|
});
|
|
|
|
it('hasht de inhoud zoals geschreven, zonder trimmen', () => {
|
|
const a = externalizeInlineScripts('<script>x()</script>');
|
|
const b = externalizeInlineScripts('<script> x() </script>');
|
|
expect(a.moved[0].fileName).not.toBe(b.moved[0].fileName);
|
|
expect(b.moved[0].body).toBe(' x() ');
|
|
expect(b.moved[0].fileName).toBe(fileOf(' x() '));
|
|
});
|
|
|
|
it('geeft gelijke inhoud één bestand, op volgorde van eerste voorkomen', () => {
|
|
const result = externalizeInlineScripts(
|
|
'<script>b()</script><script>a()</script><script>b()</script>',
|
|
);
|
|
expect(result.moved.map((m) => m.body)).toEqual(['b()', 'a()']);
|
|
expect(result.html).toBe(
|
|
referenceOf('', 'b()') +
|
|
referenceOf('', 'a()') +
|
|
referenceOf('', 'b()'),
|
|
);
|
|
});
|
|
});
|
|
|
|
describe('classificatie (BR-SCR-04)', () => {
|
|
it.each([
|
|
' type="text/javascript"',
|
|
' type="TEXT/JavaScript"',
|
|
' type=" text/javascript "',
|
|
' type="application/javascript"',
|
|
' type="application/ecmascript"',
|
|
' type="application/x-ecmascript"',
|
|
' type="application/x-javascript"',
|
|
' type="text/javascript1.0"',
|
|
' type="text/javascript1.5"',
|
|
' type="text/ecmascript"',
|
|
' type="text/jscript"',
|
|
' type="text/livescript"',
|
|
' type="text/x-ecmascript"',
|
|
' type="text/x-javascript"',
|
|
' type=""',
|
|
' type',
|
|
' type="module"',
|
|
' type="Module"',
|
|
' language="vbscript"',
|
|
])('verplaatst een script met %s', (attributes) => {
|
|
const html = `<script${attributes}>go()</script>`;
|
|
expect(externalizeInlineScripts(html).html).toBe(
|
|
referenceOf(attributes, 'go()'),
|
|
);
|
|
expect(findExecutableInlineScripts(html)).toEqual(['go()']);
|
|
});
|
|
|
|
it.each([
|
|
' type="application/ld+json"',
|
|
' type="application/json"',
|
|
' type="importmap"',
|
|
' type="speculationrules"',
|
|
' type="text/plain"',
|
|
' type="text/javascript2.0"',
|
|
' type="jscript"',
|
|
])('laat een datablok met %s staan', (attributes) => {
|
|
const html = `<script${attributes}>{"a":1}</script>`;
|
|
expect(externalizeInlineScripts(html)).toEqual({ html, moved: [] });
|
|
expect(findExecutableInlineScripts(html)).toEqual([]);
|
|
});
|
|
|
|
it.each([
|
|
['src met waarde', '<script src="/a.js">go()</script>'],
|
|
['src zonder waarde', '<script src>go()</script>'],
|
|
['lege src', '<script src="">go()</script>'],
|
|
['src in hoofdletters', '<script SRC=/a.js>go()</script>'],
|
|
])('laat een extern script staan: %s', (_, html) => {
|
|
expect(externalizeInlineScripts(html)).toEqual({ html, moved: [] });
|
|
expect(findExecutableInlineScripts(html)).toEqual([]);
|
|
});
|
|
|
|
it('laat een leeg script staan, ook met alleen witruimte', () => {
|
|
const html = '<script></script><script> \n\t</script>';
|
|
expect(externalizeInlineScripts(html)).toEqual({ html, moved: [] });
|
|
expect(findExecutableInlineScripts(html)).toEqual([]);
|
|
});
|
|
|
|
it('leest alleen het eerste type-attribuut, zoals een browser', () => {
|
|
const html = '<script type="importmap" type="module">{}</script>';
|
|
expect(externalizeInlineScripts(html).moved).toEqual([]);
|
|
});
|
|
});
|
|
|
|
describe('niet-ondersteunde vormen (BR-SCR-05)', () => {
|
|
it.each([
|
|
'<script async>go()</script>',
|
|
'<script defer>go()</script>',
|
|
'<script type="text/javascript" ASYNC>go()</script>',
|
|
])('(a) weigert een klassiek script met async of defer: %s', (html) => {
|
|
fails(html, 'UNSUPPORTED_SCRIPT');
|
|
});
|
|
|
|
it('(a) staat async op een module-script wel toe', () => {
|
|
expect(
|
|
externalizeInlineScripts(
|
|
'<script type="module" async>go()</script>',
|
|
).moved,
|
|
).toHaveLength(1);
|
|
});
|
|
|
|
it('(b) weigert een commentaaropener in de body', () => {
|
|
fails('<script>var a = "<!--";</script>', 'UNSUPPORTED_SCRIPT');
|
|
});
|
|
|
|
it('(b) weigert ook in een module-script', () => {
|
|
fails('<script type="module">// <!--\n</script>', 'UNSUPPORTED_SCRIPT');
|
|
});
|
|
|
|
it.each([
|
|
"import a from './x.js';",
|
|
'import a from "../x.js";',
|
|
"import './side.js';",
|
|
"const m = await import('./x.js');",
|
|
'const m = import( "../x.js" );',
|
|
"export * from './x.js';",
|
|
"import a from '.';",
|
|
])('(c) weigert een module met relatieve import: %s', (body) => {
|
|
fails(`<script type="module">${body}</script>`, 'UNSUPPORTED_SCRIPT');
|
|
});
|
|
|
|
it.each([
|
|
"import a from '/assets/x.js';",
|
|
"import a from 'https://cdn.test/x.js';",
|
|
"import a from 'pakket';",
|
|
'const from = 1; const s = "x./y";',
|
|
])('(c) staat een module zonder relatieve import toe: %s', (body) => {
|
|
expect(
|
|
externalizeInlineScripts(`<script type="module">${body}</script>`)
|
|
.moved,
|
|
).toHaveLength(1);
|
|
});
|
|
|
|
it('(c) geldt niet voor een klassiek script', () => {
|
|
expect(
|
|
externalizeInlineScripts("<script>import('./x.js')</script>").moved,
|
|
).toHaveLength(1);
|
|
});
|
|
|
|
it('noemt de regel en de code, nooit de inhoud van het script', () => {
|
|
const error = fails(
|
|
'<p>\n</p>\n<script async>geheim();</script>',
|
|
'UNSUPPORTED_SCRIPT',
|
|
);
|
|
expect(error.message).toContain('regel 3');
|
|
expect(error.message).not.toContain('geheim');
|
|
});
|
|
|
|
it('controleert alleen scripts die verplaatst zouden worden', () => {
|
|
const html =
|
|
'<script async src="/a.js"></script>' +
|
|
'<script type="application/ld+json">"<!--"</script>';
|
|
expect(externalizeInlineScripts(html).moved).toEqual([]);
|
|
});
|
|
});
|
|
|
|
describe('scriptgrenzen en scanner (BR-SCR-02, 03)', () => {
|
|
it('weigert een script zonder eindtag', () => {
|
|
const error = fails('<p></p><script>go()', 'UNTERMINATED_SCRIPT');
|
|
expect(error.message).toContain('regel 1');
|
|
expect(error.message).not.toContain('go()');
|
|
});
|
|
|
|
it('weigert een eindtag zonder sluitende >', () => {
|
|
fails('<script>go()</script', 'UNTERMINATED_SCRIPT');
|
|
fails('<script>go()</script ', 'UNTERMINATED_SCRIPT');
|
|
});
|
|
|
|
it('weigert ook een extern of data-script zonder eindtag', () => {
|
|
fails('<script src="/a.js">', 'UNTERMINATED_SCRIPT');
|
|
fails('<script type="importmap">{}', 'UNTERMINATED_SCRIPT');
|
|
});
|
|
|
|
it('meldt bij het zoeken de rest van de tekst als body', () => {
|
|
expect(findExecutableInlineScripts('<p></p><script>go()')).toEqual([
|
|
'go()',
|
|
]);
|
|
// Zonder teken na </script is het geen eindtag, dus hoort het bij de body
|
|
expect(findExecutableInlineScripts('<script>go()</script')).toEqual([
|
|
'go()</script',
|
|
]);
|
|
expect(findExecutableInlineScripts('<script>go()</script ')).toEqual([
|
|
'go()',
|
|
]);
|
|
});
|
|
|
|
it('sluit een script pas bij </script gevolgd door witruimte, / of >', () => {
|
|
const html = '<script>a = "</scripts>"; b = 1;</script>';
|
|
expect(findExecutableInlineScripts(html)).toEqual([
|
|
'a = "</scripts>"; b = 1;',
|
|
]);
|
|
expect(findExecutableInlineScripts('<script>a</script/>')).toEqual([
|
|
'a',
|
|
]);
|
|
expect(findExecutableInlineScripts('<script>a</SCRIPT\n>')).toEqual([
|
|
'a',
|
|
]);
|
|
});
|
|
|
|
it('neemt een > binnen een aanhalingsteken in een attribuut niet als einde van de tag', () => {
|
|
const attributes = ' data-x="a>b" data-y=\'c > d\'';
|
|
const result = externalizeInlineScripts(
|
|
`<script${attributes}>go()</script>`,
|
|
);
|
|
expect(result.html).toBe(referenceOf(attributes, 'go()'));
|
|
});
|
|
|
|
it('behoudt een afsluitende / in de tag en leest de naam hoofdletterongevoelig', () => {
|
|
expect(externalizeInlineScripts('<script />go()</script>').html).toBe(
|
|
referenceOf(' /', 'go()'),
|
|
);
|
|
expect(
|
|
externalizeInlineScripts('<SCRIPT TYPE="Module">go()</SCRIPT>')
|
|
.html,
|
|
).toBe(referenceOf(' TYPE="Module"', 'go()'));
|
|
});
|
|
|
|
it('een ongeldig <-teken is tekst', () => {
|
|
const html = '<p>1 < 2</p><script>go()</script><3><script>x</script>';
|
|
expect(findExecutableInlineScripts(html)).toEqual(['go()', 'x']);
|
|
});
|
|
|
|
it('slaat tekstelementen over tot hun eindtag, ook zonder eindtag', () => {
|
|
expect(
|
|
findExecutableInlineScripts(
|
|
'<title>a<script>x</script></title><script>y</script>',
|
|
),
|
|
).toEqual(['y']);
|
|
expect(
|
|
findExecutableInlineScripts('<style>a<script>x</script>'),
|
|
).toEqual([]);
|
|
expect(
|
|
findExecutableInlineScripts(
|
|
'<TEXTAREA><script>x</script></TextArea >',
|
|
),
|
|
).toEqual([]);
|
|
// </styled is geen eindtag van style
|
|
expect(
|
|
findExecutableInlineScripts(
|
|
'<style></styled><script>x</script></style><script>y</script>',
|
|
),
|
|
).toEqual(['y']);
|
|
});
|
|
|
|
it('slaat commentaar over, ook <!--> en een niet-afgesloten commentaar', () => {
|
|
expect(findExecutableInlineScripts('<!--><script>x</script>')).toEqual([
|
|
'x',
|
|
]);
|
|
expect(findExecutableInlineScripts('<!---><script>x</script>')).toEqual(
|
|
['x'],
|
|
);
|
|
expect(findExecutableInlineScripts('<!-- <script>x</script>')).toEqual(
|
|
[],
|
|
);
|
|
});
|
|
|
|
it('slaat declaraties, instructies en eindtags over tot de >', () => {
|
|
expect(
|
|
findExecutableInlineScripts(
|
|
'<!doctype html><?php <script>a</script> ?></p <script>b</script>><script>c</script>',
|
|
),
|
|
).toEqual(['c']);
|
|
expect(findExecutableInlineScripts('<!doctype')).toEqual([]);
|
|
expect(findExecutableInlineScripts('</p')).toEqual([]);
|
|
});
|
|
|
|
it('gooit een tag weg die niet eindigt', () => {
|
|
expect(findExecutableInlineScripts('<div class="a')).toEqual([]);
|
|
expect(findExecutableInlineScripts('<div class')).toEqual([]);
|
|
expect(
|
|
findExecutableInlineScripts('<script>a</script><div x="'),
|
|
).toEqual(['a']);
|
|
});
|
|
|
|
it('leest een attribuut dat met = begint en een waarde zonder aanhalingstekens', () => {
|
|
expect(
|
|
externalizeInlineScripts('<script =x data-n=1>go()</script>').html,
|
|
).toBe(referenceOf(' =x data-n=1', 'go()'));
|
|
});
|
|
});
|
|
|
|
describe('externalizeInlineScripts: eigenschappen', () => {
|
|
it('laat alles buiten de vervangen scripts byte voor byte staan (invariant)', () => {
|
|
fc.assert(
|
|
fc.property(htmlWithModel, ({ html, pieces, separator }) => {
|
|
const { html: output } = externalizeInlineScripts(html);
|
|
const inputWithoutScripts = pieces
|
|
.map((piece) =>
|
|
piece.kind === 'executable' ? '' : piece.html,
|
|
)
|
|
.join(separator);
|
|
expect(output.replace(referenceElement, '')).toBe(
|
|
inputWithoutScripts,
|
|
);
|
|
}),
|
|
);
|
|
});
|
|
|
|
it('bewaart de volgorde van de verwijzingen (invariant)', () => {
|
|
fc.assert(
|
|
fc.property(htmlWithModel, ({ html, pieces }) => {
|
|
const { html: output } = externalizeInlineScripts(html);
|
|
const references = [
|
|
...output.matchAll(
|
|
/src="\/assets\/(inline-[0-9a-f]{12}\.js)"/g,
|
|
),
|
|
].map((match) => match[1]);
|
|
const expected = pieces
|
|
.filter((piece) => piece.kind === 'executable')
|
|
.map((piece) => fileOf(piece.body!));
|
|
expect(references).toEqual(expected);
|
|
}),
|
|
);
|
|
});
|
|
|
|
it('herstelt de invoer door elke verwijzing door haar inhoud te vervangen (round-trip)', () => {
|
|
fc.assert(
|
|
fc.property(canonicalHtmlWithModel, ({ html }) => {
|
|
const { html: output, moved } = externalizeInlineScripts(html);
|
|
const bodies = new Map(
|
|
moved.map((m) => [m.fileName, m.body] as const),
|
|
);
|
|
const restored = output.replace(
|
|
/ src="\/assets\/(inline-[0-9a-f]{12}\.js)"><\/script>/g,
|
|
(_, name: string) => `>${bodies.get(name)}</script>`,
|
|
);
|
|
expect(restored).toBe(html);
|
|
}),
|
|
);
|
|
});
|
|
|
|
it('geeft bij een tweede keer dezelfde html en niets te verplaatsen (idempotent)', () => {
|
|
fc.assert(
|
|
fc.property(htmlWithModel, ({ html }) => {
|
|
const first = externalizeInlineScripts(html);
|
|
const second = externalizeInlineScripts(first.html);
|
|
expect(second.html).toBe(first.html);
|
|
expect(second.moved).toEqual([]);
|
|
}),
|
|
);
|
|
});
|
|
|
|
it('laat datablokken, externe en lege scripts, commentaar en style ongewijzigd (invariant)', () => {
|
|
fc.assert(
|
|
fc.property(htmlWithModel, ({ html, pieces }) => {
|
|
const { html: output } = externalizeInlineScripts(html);
|
|
for (const piece of pieces) {
|
|
if (piece.kind !== 'executable') {
|
|
expect(output).toContain(piece.html);
|
|
}
|
|
}
|
|
}),
|
|
);
|
|
});
|
|
|
|
it('laat na het verplaatsen geen uitvoerbaar inline script over (invariant)', () => {
|
|
fc.assert(
|
|
fc.property(htmlWithModel, ({ html }) => {
|
|
const { html: output } = externalizeInlineScripts(html);
|
|
expect(findExecutableInlineScripts(output)).toEqual([]);
|
|
}),
|
|
);
|
|
});
|
|
|
|
it('vindt precies de uitvoerbare scripts van het model, in volgorde (oracle)', () => {
|
|
fc.assert(
|
|
fc.property(htmlWithModel, ({ html, pieces }) => {
|
|
expect(findExecutableInlineScripts(html)).toEqual(
|
|
pieces
|
|
.filter((piece) => piece.kind === 'executable')
|
|
.map((piece) => piece.body),
|
|
);
|
|
}),
|
|
);
|
|
});
|
|
|
|
it('geeft gelijke inhoud één naam en verschillende inhoud verschillende namen (invariant)', () => {
|
|
fc.assert(
|
|
fc.property(
|
|
fc.array(scriptBody, { minLength: 1, maxLength: 8 }),
|
|
(bodies) => {
|
|
const html = bodies
|
|
.map((body) => `<script>${body}</script>`)
|
|
.join('');
|
|
const { moved } = externalizeInlineScripts(html);
|
|
const names = moved.map((m) => m.fileName);
|
|
for (const name of names) {
|
|
expect(name).toMatch(/^inline-[0-9a-f]{12}\.js$/);
|
|
}
|
|
expect(new Set(names).size).toBe(names.length);
|
|
expect(names).toHaveLength(new Set(bodies).size);
|
|
expect(names).toEqual(
|
|
[...new Set(bodies)].map((body) => fileOf(body)),
|
|
);
|
|
},
|
|
),
|
|
);
|
|
});
|
|
|
|
it('geeft hetzelfde bij samenvoegen als bij los verwerken (split en join)', () => {
|
|
fc.assert(
|
|
fc.property(htmlFragments, (fragments) => {
|
|
const joined = externalizeInlineScripts(
|
|
fragments.map((f) => f.html).join(''),
|
|
);
|
|
const separate = fragments.map((f) =>
|
|
externalizeInlineScripts(f.html),
|
|
);
|
|
expect(joined.html).toBe(separate.map((r) => r.html).join(''));
|
|
const names = new Map(
|
|
separate
|
|
.flatMap((r) => r.moved)
|
|
.map((m) => [m.fileName, m]),
|
|
);
|
|
expect(joined.moved).toEqual([...names.values()]);
|
|
}),
|
|
);
|
|
});
|
|
});
|