mirror of
https://github.com/rcourtman/Pulse.git
synced 2026-11-28 16:58:31 +01:00
Check browser integrity before promoting frontend output (#4110)
**Check browser integrity before promoting frontend output** Reuse the existing byte-bound preload and integrity validator for both compiler output and copied embeds. Refuse stale entry, vendor and lazy-chunk hashes before replacing usable output; preserve byte-exact valid builds and nested asset support. Contract-Neutral: Enforces existing complete-output and preload/SRI requirements before frontend promotion; rendered source, valid generated bytes, budgets, dependencies and subsystem contracts are unchanged. **Target the shared parser in its tokenization regression** Keep the existing scripting-disabled negative control executable after extracting the unchanged parser into build-integrity. The initial exact-source run passed 176 script cases but caught this old fixture target. Contract-Neutral: Corrects a regression fixture target only; build runtime, generated assets and subsystem contracts are unchanged. **Keep the extracted integrity helper whitespace-clean** Remove only the surplus trailing blank line caught by the complete candidate diff check; the parser, hashing and admission logic are byte-identical before EOF. Contract-Neutral: Removes one surplus EOF newline only; runtime behavior, generated output and subsystem contracts are unchanged. --- Fleet candidate `20261108T020428Z-web-product` from the `web-product` lane. Reviewed tip `6fce72790440486c4347047f5bf675470e89e30f` on `main`. [How Pulse handles triage](https://github.com/rcourtman/Pulse/blob/main/docs/AI_TRANSPARENCY.md)
This commit is contained in:
@@ -9,25 +9,27 @@ import {
|
||||
readdirSync,
|
||||
readFileSync,
|
||||
rmSync,
|
||||
symlinkSync,
|
||||
writeFileSync,
|
||||
} from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath, pathToFileURL } from 'node:url';
|
||||
import { afterEach, describe, expect, it } from 'vitest';
|
||||
import { completeBuild } from './build-output-fixture.mjs';
|
||||
|
||||
const repository = fileURLToPath(new URL('../../../', import.meta.url));
|
||||
const roots = [];
|
||||
const previousFiles = {
|
||||
'index.html': '<script type="module" src="/assets/previous.js"></script>\n',
|
||||
const previousFiles = completeBuild({
|
||||
'assets/previous.js': 'console.log("previous successful frontend");\n',
|
||||
'docs/previous.md': 'Previously usable help.\n',
|
||||
};
|
||||
const completedFiles = {
|
||||
'index.html': '<script type="module" src="/assets/current.js"></script>\n',
|
||||
'assets/current.js': 'console.log("new frontend from this compiler");\n',
|
||||
}, { entry: 'previous.js' });
|
||||
const completedFiles = completeBuild({
|
||||
'assets/current.js': 'import "./vendor.js"; import("./lazy.js"); console.log("new frontend from this compiler");\n',
|
||||
'assets/vendor.js': 'export const vendor = true;\n',
|
||||
'assets/lazy.js': 'export const lazy = true;\n',
|
||||
'docs/current.md': 'New local help.\n',
|
||||
};
|
||||
}, { entry: 'current.js', preloads: ['vendor.js'] });
|
||||
|
||||
function writeFiles(root, files) {
|
||||
for (const [name, bytes] of Object.entries(files)) {
|
||||
@@ -55,6 +57,7 @@ function fixture({ previous = true, files = completedFiles, code = 0, signal, fa
|
||||
for (const name of [
|
||||
'frontend-modern/scripts/build-embed-assets.mjs',
|
||||
'frontend-modern/scripts/sync-embed-dist.mjs',
|
||||
'frontend-modern/scripts/build-integrity.mjs',
|
||||
'frontend-modern/scripts/sync-public-docs.mjs',
|
||||
'scripts/exclusive-lock.mjs',
|
||||
]) {
|
||||
@@ -62,6 +65,9 @@ function fixture({ previous = true, files = completedFiles, code = 0, signal, fa
|
||||
mkdirSync(path.dirname(destination), { recursive: true });
|
||||
cpSync(path.join(repository, name), destination);
|
||||
}
|
||||
const modules = path.join(root, 'frontend-modern', 'node_modules');
|
||||
mkdirSync(modules, { recursive: true });
|
||||
symlinkSync(path.join(repository, 'frontend-modern', 'node_modules', 'jsdom'), path.join(modules, 'jsdom'), 'junction');
|
||||
writeFiles(
|
||||
root,
|
||||
Object.fromEntries(
|
||||
@@ -167,6 +173,16 @@ describe.each([true, false])('frontend producer with previous output: %s', (prev
|
||||
{ name: 'empty nonzero output', files: {}, code: 17, reason: /exited with code 17/ },
|
||||
{ name: 'signalled complete-looking output', signal: 'SIGTERM', reason: /terminated by signal SIGTERM/ },
|
||||
{ name: 'incomplete zero-exit output', files: { 'index.html': completedFiles['index.html'] }, reason: /frontend build output incomplete/ },
|
||||
...['current.js', 'vendor.js', 'lazy.js'].map((asset) => ({
|
||||
name: `zero-exit output with stale ${asset} integrity`,
|
||||
files: { ...completedFiles, [`assets/${asset}`]: 'export const changedBytes = true;\n' },
|
||||
reason: /integrity mismatch against built asset bytes/,
|
||||
})),
|
||||
{
|
||||
name: 'zero-exit output without an import map',
|
||||
files: { ...completedFiles, 'index.html': completedFiles['index.html'].replace(/<script type="importmap">.*?<\/script>/, '') },
|
||||
reason: /importmap script block missing/,
|
||||
},
|
||||
])('does not admit $name to canonical dist or the embed', (compiler) => {
|
||||
const f = fixture({ previous, ...compiler });
|
||||
const sourceBefore = tree(f.source);
|
||||
|
||||
26
frontend-modern/scripts/__tests__/build-output-fixture.mjs
Normal file
26
frontend-modern/scripts/__tests__/build-output-fixture.mjs
Normal file
@@ -0,0 +1,26 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
|
||||
// Model a completed compiler output, not the validator: expectations still
|
||||
// compare every published byte and exercise the real scripts in child processes.
|
||||
export function completeBuild(files, { entry, preloads = [], styles = [] }) {
|
||||
const integrity = Object.fromEntries(
|
||||
Object.entries(files)
|
||||
.filter(([name]) => name.startsWith('assets/') && name.endsWith('.js'))
|
||||
.map(([name, bytes]) => [
|
||||
`/${name}`,
|
||||
`sha384-${createHash('sha384').update(bytes).digest('base64')}`,
|
||||
]),
|
||||
);
|
||||
return {
|
||||
...files,
|
||||
'index.html': [
|
||||
'<!doctype html>',
|
||||
`<script type="importmap">${JSON.stringify({ integrity })}</script>`,
|
||||
`<script type="module" src="/assets/${entry}" integrity="${integrity[`/assets/${entry}`]}"></script>`,
|
||||
...preloads.map((name) =>
|
||||
`<link rel="modulepreload" href="/assets/${name}" integrity="${integrity[`/assets/${name}`]}">`),
|
||||
...styles.map((name) => `<link rel="stylesheet" href="/assets/${name}">`),
|
||||
'',
|
||||
].join('\n'),
|
||||
};
|
||||
}
|
||||
@@ -20,6 +20,7 @@ function fixture(algorithm = 'sha384') {
|
||||
mkdirSync(path.join(root, 'dist/assets'), { recursive: true });
|
||||
const script = path.join(root, 'scripts/check-bundle-size.mjs');
|
||||
cpSync(checker, script);
|
||||
cpSync(path.join(path.dirname(checker), 'build-integrity.mjs'), path.join(root, 'scripts/build-integrity.mjs'));
|
||||
// The copied CLI uses the same already-declared, locked parser as the real
|
||||
// build check. No dependency install or resource loading occurs in fixtures.
|
||||
symlinkSync(
|
||||
@@ -338,7 +339,7 @@ describe('built JavaScript integrity checks', () => {
|
||||
|
||||
it('fails closed if the parser changes to scripting-disabled tokenization', () => {
|
||||
const f = fixture();
|
||||
const script = path.join(f.root, 'scripts/check-bundle-size.mjs');
|
||||
const script = path.join(f.root, 'scripts/build-integrity.mjs');
|
||||
const source = readFileSync(script, 'utf8');
|
||||
const changed = source.replace('includeNodeLocations: true', 'includeNodeLocations: false');
|
||||
expect(changed).not.toBe(source);
|
||||
|
||||
@@ -18,23 +18,21 @@ import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath, pathToFileURL } from 'node:url';
|
||||
import { afterEach, describe, expect, it } from 'vitest';
|
||||
import { completeBuild } from './build-output-fixture.mjs';
|
||||
|
||||
const repository = fileURLToPath(new URL('../../../', import.meta.url));
|
||||
const roots = [];
|
||||
const oldFiles = {
|
||||
'index.html': '<!doctype html><script src="/assets/previous.js"></script>\n',
|
||||
const oldFiles = completeBuild({
|
||||
'assets/previous.js': 'console.log("previous frontend");\n',
|
||||
'docs/retained.md': 'Previously usable help.\n',
|
||||
};
|
||||
const validFiles = {
|
||||
'index.html':
|
||||
'<!doctype html><script type="module" src="/assets/app.js"></script>\n<link rel="stylesheet" href="/assets/app.css">\n<link rel="modulepreload" href="/assets/vendor.js">\n<script type="importmap">{"integrity":{"/assets/lazy.js":"synthetic-integrity"}}</script>\n',
|
||||
'assets/app.js': 'console.log("current frontend");\n',
|
||||
}, { entry: 'previous.js' });
|
||||
const validFiles = completeBuild({
|
||||
'assets/app.js': 'import "./vendor.js"; import("./lazy.js"); console.log("current frontend");\n',
|
||||
'assets/vendor.js': 'export const vendor = true;\n',
|
||||
'assets/lazy.js': 'export const lazy = true;\n',
|
||||
'assets/app.css': 'body { color: black; }\n',
|
||||
'docs/current.md': 'Current help.\n',
|
||||
};
|
||||
}, { entry: 'app.js', preloads: ['vendor.js'], styles: ['app.css'] });
|
||||
|
||||
function writeFiles(directory, files) {
|
||||
for (const [name, content] of Object.entries(files)) {
|
||||
@@ -64,12 +62,18 @@ function fixture(files, { previous = true, failure } = {}) {
|
||||
// but own every file it can replace inside this disposable fixture repository.
|
||||
for (const name of [
|
||||
'frontend-modern/scripts/sync-embed-dist.mjs',
|
||||
'frontend-modern/scripts/build-integrity.mjs',
|
||||
'scripts/exclusive-lock.mjs',
|
||||
]) {
|
||||
const destination = path.join(root, name);
|
||||
mkdirSync(path.dirname(destination), { recursive: true });
|
||||
cpSync(path.join(repository, name), destination);
|
||||
}
|
||||
// The production validator uses the already-locked inert HTML parser.
|
||||
// Keep Vite's fixture path writable while resolving jsdom's real dependency graph.
|
||||
const modules = path.join(root, 'frontend-modern', 'node_modules');
|
||||
mkdirSync(modules, { recursive: true });
|
||||
symlinkSync(path.join(repository, 'frontend-modern', 'node_modules', 'jsdom'), path.join(modules, 'jsdom'), 'junction');
|
||||
const source = path.join(root, 'frontend-modern', 'dist');
|
||||
const target = path.join(root, 'internal', 'api', 'frontend-modern', 'dist');
|
||||
mkdirSync(source, { recursive: true });
|
||||
@@ -331,6 +335,26 @@ const invalidBuilds = [
|
||||
),
|
||||
reason: new RegExp(asset.replace('.', '\\.')),
|
||||
})),
|
||||
...['app.js', 'vendor.js', 'lazy.js'].map((asset) => ({
|
||||
name: `stale integrity for ${asset}`,
|
||||
files: { ...validFiles, [`assets/${asset}`]: 'export const changedBytes = true;\n' },
|
||||
reason: /integrity mismatch against built asset bytes/,
|
||||
})),
|
||||
{
|
||||
name: 'missing import map',
|
||||
files: { ...validFiles, 'index.html': validFiles['index.html'].replace(/<script type="importmap">.*?<\/script>/, '') },
|
||||
reason: /importmap script block missing/,
|
||||
},
|
||||
{
|
||||
name: 'empty entry integrity',
|
||||
files: { ...validFiles, 'index.html': validFiles['index.html'].replace(/(src="\/assets\/app.js" integrity=")[^"]+/, '$1') },
|
||||
reason: /entry script.*invalid or unsupported integrity/,
|
||||
},
|
||||
{
|
||||
name: 'duplicate import map',
|
||||
files: { ...validFiles, 'index.html': validFiles['index.html'] + '<script type="importmap">{}</script>' },
|
||||
reason: /exactly one importmap/,
|
||||
},
|
||||
...['../outside.js', 'nested/../../outside.js', 'nested\\outside.js'].map((asset) => ({
|
||||
name: `invalid asset path ${asset}`,
|
||||
files: { ...validFiles, 'index.html': `<script src="/assets/${asset}"></script>` },
|
||||
@@ -370,10 +394,12 @@ describe.each(['CLI', 'builder'])('%s embed publication preserves usable output'
|
||||
});
|
||||
|
||||
it('accepts single-quoted and nested generated asset references', () => {
|
||||
const f = fixture({
|
||||
'index.html': "<script src='/assets/nested/entry.js'></script>",
|
||||
'assets/nested/entry.js': validFiles['assets/app.js'],
|
||||
});
|
||||
const files = completeBuild({
|
||||
'assets/nested/entry.js': 'import "./vendor.js"; export const nested = true;\n',
|
||||
'assets/nested/vendor.js': 'export const nestedVendor = true;\n',
|
||||
}, { entry: 'nested/entry.js', preloads: ['nested/vendor.js'] });
|
||||
files['index.html'] = files['index.html'].replace('src="/assets/nested/entry.js"', "src='/assets/nested/entry.js'");
|
||||
const f = fixture(files);
|
||||
const result = f.run(mode);
|
||||
expect(result.status, result.stderr).toBe(0);
|
||||
expect(tree(f.target)).toEqual(tree(f.source));
|
||||
|
||||
263
frontend-modern/scripts/build-integrity.mjs
Normal file
263
frontend-modern/scripts/build-integrity.mjs
Normal file
@@ -0,0 +1,263 @@
|
||||
// Read-only admission for the built JavaScript bytes and their browser controls.
|
||||
// Shared by the bundle checker and BOTH pre-promotion build/embed boundaries.
|
||||
// Parsing never executes scripts or loads resources; only owned inventory files
|
||||
// are hashed. Valid output is read, not rewritten.
|
||||
import { lstatSync, readdirSync, readFileSync } from 'node:fs';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { join, posix } from 'node:path';
|
||||
import { JSDOM, VirtualConsole } from 'jsdom';
|
||||
|
||||
/**
|
||||
* Verify the deployment-installability preload invariant against the built
|
||||
* index.html (see the subsystem contract clause on modulepreload posture):
|
||||
* - the import map integrity block covers every JS asset in dist/assets,
|
||||
* and its values and entry/preload attributes match the actual bytes;
|
||||
* - modulepreload links reference only the entry chunk's static imports —
|
||||
* preloading lazy route chunks (preloadDynamicChunks: true) would fetch
|
||||
* the whole app at cold start and defeat route-level code splitting.
|
||||
* Returns a list of violation messages (empty on pass).
|
||||
*/
|
||||
export function checkPreloadPosture(distDir) {
|
||||
const distAssets = join(distDir, 'assets');
|
||||
const errors = [];
|
||||
let html;
|
||||
try {
|
||||
html = readFileSync(join(distDir, 'index.html'));
|
||||
} catch {
|
||||
errors.push('dist/index.html not found. Run "npx vite build" first.');
|
||||
return errors;
|
||||
}
|
||||
|
||||
// Only inventory filenames may be read, never a path supplied by HTML.
|
||||
// Hash raw bytes: decoding a chunk as UTF-8 can replace invalid sequences.
|
||||
const assets = new Map();
|
||||
function readAssets(directory, prefix = '') {
|
||||
if (!lstatSync(directory).isDirectory()) throw new Error('irregular asset directory');
|
||||
for (const entry of readdirSync(directory, { withFileTypes: true })) {
|
||||
const relative = `${prefix}${entry.name}`;
|
||||
const file = join(directory, entry.name);
|
||||
if (entry.isDirectory()) readAssets(file, `${relative}/`);
|
||||
else if (entry.name.endsWith('.js')) {
|
||||
if (!entry.isFile()) throw new Error('irregular JavaScript asset');
|
||||
assets.set(relative, readFileSync(file));
|
||||
}
|
||||
}
|
||||
}
|
||||
try {
|
||||
readAssets(distAssets);
|
||||
} catch {
|
||||
errors.push('dist/assets/ JavaScript inventory is missing, unreadable or irregular');
|
||||
return errors;
|
||||
}
|
||||
const hashes = new Map();
|
||||
function checkIntegrity(file, value, context) {
|
||||
if (!assets.has(file)) {
|
||||
errors.push(`${context} references a missing or invalid JS asset`);
|
||||
return;
|
||||
}
|
||||
const tokens = typeof value === 'string' && value.trim() ? value.trim().split(/\s+/) : [];
|
||||
if (
|
||||
tokens.length === 0 ||
|
||||
tokens.some((token) => !/^(sha256|sha384|sha512)-[A-Za-z0-9+/]+={0,2}$/.test(token))
|
||||
) {
|
||||
errors.push(`${context} has invalid or unsupported integrity metadata`);
|
||||
return;
|
||||
}
|
||||
// Generated output uses one digest. If it ever supplies alternatives,
|
||||
// require all of them to match, not just a weaker matching algorithm.
|
||||
// This deliberately validates a strict subset of browser SRI metadata.
|
||||
for (const token of tokens) {
|
||||
const algorithm = token.slice(0, token.indexOf('-'));
|
||||
const key = `${file}:${algorithm}`;
|
||||
if (!hashes.has(key)) {
|
||||
hashes.set(
|
||||
key,
|
||||
`${algorithm}-${createHash(algorithm).update(assets.get(file)).digest('base64')}`,
|
||||
);
|
||||
}
|
||||
if (token !== hashes.get(key)) {
|
||||
errors.push(`${context} integrity mismatch against built asset bytes`);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Parse elements, never rewritten HTML. Deleting or masking comments can
|
||||
// invent tags/attributes, and regexes can mistake inert text for controls.
|
||||
// No runScripts/resources options: this is an inert, offline document, not
|
||||
// a preview. Do not emit parser diagnostics containing build-source text.
|
||||
// The locked jsdom/parse5 pair uses scripting-enabled tokenization with
|
||||
// node locations, independently of execution. Verify that behavior instead
|
||||
// of silently counting controls hidden inside noscript after a parser update.
|
||||
const parserOptions = {
|
||||
includeNodeLocations: true,
|
||||
virtualConsole: new VirtualConsole(),
|
||||
};
|
||||
const probe = new JSDOM('<noscript><p></p></noscript>', parserOptions);
|
||||
try {
|
||||
if (probe.window.document.querySelector('p')) {
|
||||
errors.push('HTML parser scripting mode is unsupported; build controls are unverified');
|
||||
return errors;
|
||||
}
|
||||
} finally {
|
||||
probe.window.close();
|
||||
}
|
||||
const dom = new JSDOM(html, parserOptions);
|
||||
let importmaps;
|
||||
let entries;
|
||||
let preloads;
|
||||
try {
|
||||
const document = dom.window.document;
|
||||
const htmlElements = (tag) =>
|
||||
[...document.querySelectorAll(tag)].filter(
|
||||
(element) => element.namespaceURI === 'http://www.w3.org/1999/xhtml',
|
||||
);
|
||||
// Declarative shadow DOM is unsupported by this parser. It is absent
|
||||
// from Vite output: do not silently ignore potentially active controls.
|
||||
if (document.querySelector('template[shadowrootmode]')) {
|
||||
errors.push('index.html declarative shadow DOM controls are unverified');
|
||||
return errors;
|
||||
}
|
||||
const scripts = htmlElements('script');
|
||||
const asciiLower = (value) =>
|
||||
(value ?? '').replace(/[A-Z]/g, (character) => character.toLowerCase());
|
||||
importmaps = scripts
|
||||
.filter((element) => asciiLower(element.getAttribute('type')) === 'importmap')
|
||||
.map((element) => ({ text: element.textContent, external: element.hasAttribute('src') }));
|
||||
entries = scripts
|
||||
.filter(
|
||||
(element) =>
|
||||
asciiLower(element.getAttribute('type')) === 'module' && element.hasAttribute('src'),
|
||||
)
|
||||
.map((element) => ({
|
||||
src: element.getAttribute('src'),
|
||||
integrity: element.getAttribute('integrity'),
|
||||
}));
|
||||
preloads = htmlElements('link')
|
||||
.filter((element) =>
|
||||
asciiLower(element.getAttribute('rel'))
|
||||
.split(/[\t\n\f\r ]+/)
|
||||
.includes('modulepreload'),
|
||||
)
|
||||
.map((element) => ({
|
||||
href: element.getAttribute('href'),
|
||||
integrity: element.getAttribute('integrity'),
|
||||
}));
|
||||
} finally {
|
||||
dom.window.close();
|
||||
}
|
||||
let integrity = null;
|
||||
if (importmaps.length === 0) {
|
||||
errors.push('importmap script block missing from index.html (dynamic-import SRI unenforced)');
|
||||
} else if (importmaps.length !== 1) {
|
||||
errors.push('index.html must contain exactly one importmap script block');
|
||||
} else if (importmaps[0].external) {
|
||||
errors.push('index.html importmap must be inline, not an external script');
|
||||
} else {
|
||||
let parsed;
|
||||
try {
|
||||
parsed = JSON.parse(importmaps[0].text);
|
||||
} catch {
|
||||
errors.push('importmap block in index.html is not valid JSON');
|
||||
}
|
||||
if (parsed !== undefined) {
|
||||
if (
|
||||
!parsed ||
|
||||
typeof parsed !== 'object' ||
|
||||
Array.isArray(parsed) ||
|
||||
!parsed.integrity ||
|
||||
typeof parsed.integrity !== 'object' ||
|
||||
Array.isArray(parsed.integrity) ||
|
||||
Object.keys(parsed.integrity).length === 0
|
||||
) {
|
||||
errors.push(
|
||||
'importmap in index.html has no integrity block (dynamic-import SRI unenforced)',
|
||||
);
|
||||
} else {
|
||||
integrity = parsed.integrity;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (integrity) {
|
||||
for (const file of assets.keys()) {
|
||||
if (!Object.hasOwn(integrity, `/assets/${file}`)) {
|
||||
errors.push(`importmap integrity missing entry for /assets/${file}`);
|
||||
} else {
|
||||
checkIntegrity(file, integrity[`/assets/${file}`], `importmap /assets/${file}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (entries.length !== 1) {
|
||||
errors.push('index.html must contain exactly one external module entry script');
|
||||
return errors;
|
||||
}
|
||||
const entryMatch = entries[0].src.match(/^\/assets\/(.+\.js)$/);
|
||||
if (!entryMatch) {
|
||||
errors.push('module entry script not found in index.html');
|
||||
return errors;
|
||||
}
|
||||
const entryFile = entryMatch[1];
|
||||
checkIntegrity(
|
||||
entryFile,
|
||||
entries[0].integrity,
|
||||
`entry script /assets/${entryFile}`,
|
||||
);
|
||||
|
||||
if (!assets.has(entryFile)) {
|
||||
errors.push(`entry chunk ${entryFile} not found in dist/assets/`);
|
||||
return errors;
|
||||
}
|
||||
const entrySource = assets.get(entryFile).toString('utf8');
|
||||
|
||||
// Static imports/re-exports in Rollup output: import ... from"./x.js",
|
||||
// import"./x.js", export ... from"./x.js". Dynamic imports never match:
|
||||
// their specifier follows an opening parenthesis, not the keyword.
|
||||
const staticImportRe =
|
||||
/\b(?:import|export)\s*(?:[\w$*{},\s]+?\s*from\s*)?["']\.\/([^"']+\.js)["']/g;
|
||||
function staticImportsOf(source, importer) {
|
||||
const specifiers = [];
|
||||
let m;
|
||||
while ((m = staticImportRe.exec(source))) {
|
||||
specifiers.push(posix.join(posix.dirname(importer), m[1]));
|
||||
}
|
||||
return specifiers;
|
||||
}
|
||||
|
||||
// Vite preloads the entry's TRANSITIVE static import graph, so walk it:
|
||||
// a chunk is preloadable iff it is reachable from the entry through static
|
||||
// imports alone. Lazy route chunks are only reachable dynamically and stay
|
||||
// excluded, as do their own static-only dependencies.
|
||||
const allowedPreloads = new Set([entryFile]);
|
||||
const queue = staticImportsOf(entrySource, entryFile);
|
||||
while (queue.length > 0) {
|
||||
const file = queue.pop();
|
||||
if (allowedPreloads.has(file)) continue;
|
||||
allowedPreloads.add(file);
|
||||
if (!assets.has(file)) {
|
||||
errors.push(`statically imported chunk ${file} not found in dist/assets/`);
|
||||
continue;
|
||||
}
|
||||
queue.push(...staticImportsOf(assets.get(file).toString('utf8'), file));
|
||||
}
|
||||
|
||||
for (const preload of preloads) {
|
||||
const href = preload.href?.match(/^\/assets\/(.+)$/);
|
||||
if (!href) {
|
||||
errors.push('modulepreload link with unrecognized href in index.html');
|
||||
continue;
|
||||
}
|
||||
if (!allowedPreloads.has(href[1])) {
|
||||
errors.push(
|
||||
`modulepreload of lazy chunk /assets/${href[1]} — only the entry's static imports may be preloaded (keep preloadDynamicChunks: false in vite.config.ts)`,
|
||||
);
|
||||
}
|
||||
checkIntegrity(
|
||||
href[1],
|
||||
preload.integrity,
|
||||
`modulepreload of /assets/${href[1]}`,
|
||||
);
|
||||
}
|
||||
|
||||
return errors;
|
||||
}
|
||||
@@ -19,11 +19,10 @@
|
||||
*/
|
||||
|
||||
import { readdirSync, readFileSync, writeFileSync } from 'node:fs';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { join, resolve } from 'node:path';
|
||||
import { gzipSync } from 'node:zlib';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { JSDOM, VirtualConsole } from 'jsdom';
|
||||
import { checkPreloadPosture } from './build-integrity.mjs';
|
||||
|
||||
const __dirname = fileURLToPath(new URL('.', import.meta.url));
|
||||
const ROOT = resolve(__dirname, '..');
|
||||
@@ -99,244 +98,6 @@ function measureBuild() {
|
||||
// Built index.html preload posture
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Verify the deployment-installability preload invariant against the built
|
||||
* index.html (see the subsystem contract clause on modulepreload posture):
|
||||
* - the import map integrity block covers every JS asset in dist/assets,
|
||||
* and its values and entry/preload attributes match the actual bytes;
|
||||
* - modulepreload links reference only the entry chunk's static imports —
|
||||
* preloading lazy route chunks (preloadDynamicChunks: true) would fetch
|
||||
* the whole app at cold start and defeat route-level code splitting.
|
||||
* Returns a list of violation messages (empty on pass).
|
||||
*/
|
||||
function checkPreloadPosture() {
|
||||
const errors = [];
|
||||
let html;
|
||||
try {
|
||||
html = readFileSync(join(ROOT, 'dist', 'index.html'));
|
||||
} catch {
|
||||
errors.push('dist/index.html not found. Run "npx vite build" first.');
|
||||
return errors;
|
||||
}
|
||||
|
||||
// Only inventory filenames may be read, never a path supplied by HTML.
|
||||
// Hash raw bytes: decoding a chunk as UTF-8 can replace invalid sequences.
|
||||
const assets = new Map(
|
||||
readdirSync(DIST_ASSETS)
|
||||
.filter((file) => file.endsWith('.js'))
|
||||
.map((file) => [file, readFileSync(join(DIST_ASSETS, file))]),
|
||||
);
|
||||
const hashes = new Map();
|
||||
function checkIntegrity(file, value, context) {
|
||||
if (!assets.has(file)) {
|
||||
errors.push(`${context} references a missing or invalid JS asset`);
|
||||
return;
|
||||
}
|
||||
const tokens = typeof value === 'string' && value.trim() ? value.trim().split(/\s+/) : [];
|
||||
if (
|
||||
tokens.length === 0 ||
|
||||
tokens.some((token) => !/^(sha256|sha384|sha512)-[A-Za-z0-9+/]+={0,2}$/.test(token))
|
||||
) {
|
||||
errors.push(`${context} has invalid or unsupported integrity metadata`);
|
||||
return;
|
||||
}
|
||||
// Generated output uses one digest. If it ever supplies alternatives,
|
||||
// require all of them to match, not just a weaker matching algorithm.
|
||||
// This deliberately validates a strict subset of browser SRI metadata.
|
||||
for (const token of tokens) {
|
||||
const algorithm = token.slice(0, token.indexOf('-'));
|
||||
const key = `${file}:${algorithm}`;
|
||||
if (!hashes.has(key)) {
|
||||
hashes.set(
|
||||
key,
|
||||
`${algorithm}-${createHash(algorithm).update(assets.get(file)).digest('base64')}`,
|
||||
);
|
||||
}
|
||||
if (token !== hashes.get(key)) {
|
||||
errors.push(`${context} integrity mismatch against built asset bytes`);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Parse elements, never rewritten HTML. Deleting or masking comments can
|
||||
// invent tags/attributes, and regexes can mistake inert text for controls.
|
||||
// No runScripts/resources options: this is an inert, offline document, not
|
||||
// a preview. Do not emit parser diagnostics containing build-source text.
|
||||
// The locked jsdom/parse5 pair uses scripting-enabled tokenization with
|
||||
// node locations, independently of execution. Verify that behavior instead
|
||||
// of silently counting controls hidden inside noscript after a parser update.
|
||||
const parserOptions = {
|
||||
includeNodeLocations: true,
|
||||
virtualConsole: new VirtualConsole(),
|
||||
};
|
||||
const probe = new JSDOM('<noscript><p></p></noscript>', parserOptions);
|
||||
try {
|
||||
if (probe.window.document.querySelector('p')) {
|
||||
errors.push('HTML parser scripting mode is unsupported; build controls are unverified');
|
||||
return errors;
|
||||
}
|
||||
} finally {
|
||||
probe.window.close();
|
||||
}
|
||||
const dom = new JSDOM(html, parserOptions);
|
||||
let importmaps;
|
||||
let entries;
|
||||
let preloads;
|
||||
try {
|
||||
const document = dom.window.document;
|
||||
const htmlElements = (tag) =>
|
||||
[...document.querySelectorAll(tag)].filter(
|
||||
(element) => element.namespaceURI === 'http://www.w3.org/1999/xhtml',
|
||||
);
|
||||
// Declarative shadow DOM is unsupported by this parser. It is absent
|
||||
// from Vite output: do not silently ignore potentially active controls.
|
||||
if (document.querySelector('template[shadowrootmode]')) {
|
||||
errors.push('index.html declarative shadow DOM controls are unverified');
|
||||
return errors;
|
||||
}
|
||||
const scripts = htmlElements('script');
|
||||
const asciiLower = (value) =>
|
||||
(value ?? '').replace(/[A-Z]/g, (character) => character.toLowerCase());
|
||||
importmaps = scripts
|
||||
.filter((element) => asciiLower(element.getAttribute('type')) === 'importmap')
|
||||
.map((element) => ({ text: element.textContent, external: element.hasAttribute('src') }));
|
||||
entries = scripts
|
||||
.filter(
|
||||
(element) =>
|
||||
asciiLower(element.getAttribute('type')) === 'module' && element.hasAttribute('src'),
|
||||
)
|
||||
.map((element) => ({
|
||||
src: element.getAttribute('src'),
|
||||
integrity: element.getAttribute('integrity'),
|
||||
}));
|
||||
preloads = htmlElements('link')
|
||||
.filter((element) =>
|
||||
asciiLower(element.getAttribute('rel'))
|
||||
.split(/[\t\n\f\r ]+/)
|
||||
.includes('modulepreload'),
|
||||
)
|
||||
.map((element) => ({
|
||||
href: element.getAttribute('href'),
|
||||
integrity: element.getAttribute('integrity'),
|
||||
}));
|
||||
} finally {
|
||||
dom.window.close();
|
||||
}
|
||||
let integrity = null;
|
||||
if (importmaps.length === 0) {
|
||||
errors.push('importmap script block missing from index.html (dynamic-import SRI unenforced)');
|
||||
} else if (importmaps.length !== 1) {
|
||||
errors.push('index.html must contain exactly one importmap script block');
|
||||
} else if (importmaps[0].external) {
|
||||
errors.push('index.html importmap must be inline, not an external script');
|
||||
} else {
|
||||
let parsed;
|
||||
try {
|
||||
parsed = JSON.parse(importmaps[0].text);
|
||||
} catch {
|
||||
errors.push('importmap block in index.html is not valid JSON');
|
||||
}
|
||||
if (parsed !== undefined) {
|
||||
if (
|
||||
!parsed ||
|
||||
typeof parsed !== 'object' ||
|
||||
Array.isArray(parsed) ||
|
||||
!parsed.integrity ||
|
||||
typeof parsed.integrity !== 'object' ||
|
||||
Array.isArray(parsed.integrity) ||
|
||||
Object.keys(parsed.integrity).length === 0
|
||||
) {
|
||||
errors.push(
|
||||
'importmap in index.html has no integrity block (dynamic-import SRI unenforced)',
|
||||
);
|
||||
} else {
|
||||
integrity = parsed.integrity;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (integrity) {
|
||||
for (const file of assets.keys()) {
|
||||
if (!Object.hasOwn(integrity, `/assets/${file}`)) {
|
||||
errors.push(`importmap integrity missing entry for /assets/${file}`);
|
||||
} else {
|
||||
checkIntegrity(file, integrity[`/assets/${file}`], `importmap /assets/${file}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (entries.length !== 1) {
|
||||
errors.push('index.html must contain exactly one external module entry script');
|
||||
return errors;
|
||||
}
|
||||
const entryMatch = entries[0].src.match(/^\/assets\/(.+\.js)$/);
|
||||
if (!entryMatch) {
|
||||
errors.push('module entry script not found in index.html');
|
||||
return errors;
|
||||
}
|
||||
const entryFile = entryMatch[1];
|
||||
checkIntegrity(
|
||||
entryFile,
|
||||
entries[0].integrity,
|
||||
`entry script /assets/${entryFile}`,
|
||||
);
|
||||
|
||||
if (!assets.has(entryFile)) {
|
||||
errors.push(`entry chunk ${entryFile} not found in dist/assets/`);
|
||||
return errors;
|
||||
}
|
||||
const entrySource = assets.get(entryFile).toString('utf8');
|
||||
|
||||
// Static imports/re-exports in Rollup output: import ... from"./x.js",
|
||||
// import"./x.js", export ... from"./x.js". Dynamic imports never match:
|
||||
// their specifier follows an opening parenthesis, not the keyword.
|
||||
const staticImportRe =
|
||||
/\b(?:import|export)\s*(?:[\w$*{},\s]+?\s*from\s*)?["']\.\/([^"']+\.js)["']/g;
|
||||
function staticImportsOf(source) {
|
||||
const specifiers = [];
|
||||
let m;
|
||||
while ((m = staticImportRe.exec(source))) specifiers.push(m[1]);
|
||||
return specifiers;
|
||||
}
|
||||
|
||||
// Vite preloads the entry's TRANSITIVE static import graph, so walk it:
|
||||
// a chunk is preloadable iff it is reachable from the entry through static
|
||||
// imports alone. Lazy route chunks are only reachable dynamically and stay
|
||||
// excluded, as do their own static-only dependencies.
|
||||
const allowedPreloads = new Set([entryFile]);
|
||||
const queue = staticImportsOf(entrySource);
|
||||
while (queue.length > 0) {
|
||||
const file = queue.pop();
|
||||
if (allowedPreloads.has(file)) continue;
|
||||
allowedPreloads.add(file);
|
||||
if (!assets.has(file)) {
|
||||
errors.push(`statically imported chunk ${file} not found in dist/assets/`);
|
||||
continue;
|
||||
}
|
||||
queue.push(...staticImportsOf(assets.get(file).toString('utf8')));
|
||||
}
|
||||
|
||||
for (const preload of preloads) {
|
||||
const href = preload.href?.match(/^\/assets\/(.+)$/);
|
||||
if (!href) {
|
||||
errors.push('modulepreload link with unrecognized href in index.html');
|
||||
continue;
|
||||
}
|
||||
if (!allowedPreloads.has(href[1])) {
|
||||
errors.push(
|
||||
`modulepreload of lazy chunk /assets/${href[1]} — only the entry's static imports may be preloaded (keep preloadDynamicChunks: false in vite.config.ts)`,
|
||||
);
|
||||
}
|
||||
checkIntegrity(
|
||||
href[1],
|
||||
preload.integrity,
|
||||
`modulepreload of /assets/${href[1]}`,
|
||||
);
|
||||
}
|
||||
|
||||
return errors;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Update baseline mode
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -513,7 +274,7 @@ function check() {
|
||||
|
||||
console.log();
|
||||
|
||||
const postureErrors = checkPreloadPosture();
|
||||
const postureErrors = checkPreloadPosture(join(ROOT, 'dist'));
|
||||
console.log('index.html preload posture');
|
||||
console.log('==========================');
|
||||
if (postureErrors.length === 0) {
|
||||
|
||||
@@ -3,6 +3,7 @@ import path from 'node:path';
|
||||
import { fileURLToPath, pathToFileURL } from 'node:url';
|
||||
|
||||
import { withExclusiveLock } from '../../scripts/exclusive-lock.mjs';
|
||||
import { checkPreloadPosture } from './build-integrity.mjs';
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = path.dirname(__filename);
|
||||
@@ -76,6 +77,11 @@ export async function validateBuildOutput(stagingDir) {
|
||||
throw incomplete(`referenced asset ${asset} must be a nonempty regular file`, error);
|
||||
}
|
||||
}
|
||||
// Nonempty files can still be unusable when index.html advertises stale
|
||||
// integrity hashes. Check the same byte-bound controls as the bundle check
|
||||
// before either the producer or copied embed can replace usable output.
|
||||
const integrityErrors = checkPreloadPosture(stagingDir);
|
||||
if (integrityErrors.length) throw incomplete(integrityErrors.join('; '));
|
||||
}
|
||||
|
||||
async function publishDirAtomically() {
|
||||
|
||||
Reference in New Issue
Block a user