test: harden CHRNX visual evidence

This commit is contained in:
chrnx committed 2026-08-13 10:38:29 -05:00
1 parent 4e496b241a
commit 16b6a75b35
3 files changed
+386 -62

No files matched your search

+198 -34
View File
@@ -1,10 +1,20 @@
import { mkdir } from 'node:fs/promises';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
import {
lstat,
mkdir,
mkdtemp,
readFile,
readdir,
rename,
rm,
} from 'node:fs/promises';
import { basename, dirname, join, resolve } from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
import { chromium } from '@playwright/test';
const LOCAL_HOSTS = new Set( [ 'localhost', '127.0.0.1' ] );
const OUTPUT_DIRECTORY = fileURLToPath( new URL( '../tmp/imagegen/', import.meta.url ) );
const REVIEW_PARENT_DIRECTORY = fileURLToPath( new URL( '../tmp/imagegen/', import.meta.url ) );
const OUTPUT_DIRECTORY = join( REVIEW_PARENT_DIRECTORY, 'grunge-stage-review.png' );
const OUTPUT_DIRECTORY_NAME = 'grunge-stage-review.png';
const STORAGE_KEY = 'chrnx-theme';
const THEMES = [ 'light', 'dark' ];
const VIEWPORTS = [
@@ -30,10 +40,26 @@ const TARGETS = [
},
];
function getBaseURL() {
export const CAPTURE_PLAN = TARGETS.flatMap( ( target ) =>
VIEWPORTS.flatMap( ( viewport ) =>
THEMES.map( ( theme ) => ( {
target,
viewport,
theme,
filename: `grunge-stage-${ target.name }-${ viewport.width }-${ theme }.png`,
} ) ),
),
);
function normalizeReviewPath( pathname ) {
const withLeadingSlash = pathname.startsWith( '/' ) ? pathname : `/${ pathname }`;
return withLeadingSlash.endsWith( '/' ) ? withLeadingSlash : `${ withLeadingSlash }/`;
}
export function getBaseURL( value = process.env.CHRNX_REVIEW_URL || 'http://localhost:8888' ) {
let url;
try {
url = new URL( process.env.CHRNX_REVIEW_URL || 'http://localhost:8888' );
url = new URL( value );
} catch {
throw new Error( 'Capture URL must be a valid local HTTP URL.' );
}
@@ -42,7 +68,10 @@ function getBaseURL() {
url.protocol !== 'http:' ||
! LOCAL_HOSTS.has( url.hostname ) ||
url.username ||
url.password
url.password ||
( url.pathname !== '/' && url.pathname !== '' ) ||
url.search ||
url.hash
) {
throw new Error( 'Capture URL must be credential-free HTTP on localhost or 127.0.0.1.' );
}
@@ -50,12 +79,23 @@ function getBaseURL() {
return url;
}
export function assertFinalNavigation( baseURL, expectedPath, finalURL ) {
const final = new URL( finalURL );
if ( final.origin !== baseURL.origin ) {
throw new Error( `Capture redirected to unexpected origin ${ final.origin }.` );
}
if ( normalizeReviewPath( final.pathname ) !== normalizeReviewPath( expectedPath ) ) {
throw new Error( `Capture redirected to unexpected path ${ final.pathname }.` );
}
}
function getPngDimensions( buffer ) {
if (
buffer.length < 24 ||
buffer.subarray( 0, 8 ).toString( 'hex' ) !== '89504e470d0a1a0a'
buffer.length < 33 ||
buffer.subarray( 0, 8 ).toString( 'hex' ) !== '89504e470d0a1a0a' ||
buffer.subarray( 12, 16 ).toString( 'ascii' ) !== 'IHDR'
) {
throw new Error( 'Screenshot did not produce a valid PNG.' );
throw new Error( 'Screenshot did not produce a valid nonempty PNG.' );
}
return {
@@ -64,6 +104,132 @@ function getPngDimensions( buffer ) {
};
}
async function optionalLstat( path ) {
try {
return await lstat( path );
} catch ( error ) {
if ( error.code === 'ENOENT' ) {
return null;
}
throw error;
}
}
async function assertSafeOutput( outputDirectory, allowedParentDirectory, capturePlan ) {
const parentPath = resolve( allowedParentDirectory );
const outputPath = resolve( outputDirectory );
if ( dirname( outputPath ) !== parentPath || basename( outputPath ) !== OUTPUT_DIRECTORY_NAME ) {
throw new Error( 'Review output must be the dedicated direct child of its approved parent.' );
}
const parentStats = await lstat( parentPath );
if ( parentStats.isSymbolicLink() || ! parentStats.isDirectory() ) {
throw new Error( 'Review output parent cannot be a symbolic link.' );
}
const outputStats = await optionalLstat( outputPath );
if ( outputStats?.isSymbolicLink() ) {
throw new Error( 'Review output cannot be a symbolic link.' );
}
if ( outputStats && ! outputStats.isDirectory() ) {
throw new Error( 'Review output must be a directory.' );
}
if ( outputStats ) {
for ( const capture of capturePlan ) {
const fileStats = await optionalLstat( join( outputPath, capture.filename ) );
if ( fileStats?.isSymbolicLink() || ( fileStats && ! fileStats.isFile() ) ) {
throw new Error( `Review output file cannot be a symbolic link: ${ capture.filename }.` );
}
}
}
return { outputPath, parentPath, outputExists: Boolean( outputStats ) };
}
async function removeLegacyEvidence( parentPath, capturePlan ) {
for ( const capture of capturePlan ) {
const legacyPath = join( parentPath, capture.filename );
const stats = await optionalLstat( legacyPath );
if ( stats?.isSymbolicLink() || ( stats && ! stats.isFile() ) ) {
throw new Error( `Legacy review evidence cannot be a symbolic link: ${ capture.filename }.` );
}
if ( stats ) {
await rm( legacyPath );
}
}
}
async function validateEvidence( directory, capturePlan ) {
const expectedNames = capturePlan.map( ( capture ) => capture.filename ).sort();
const actualNames = ( await readdir( directory ) ).sort();
if ( new Set( expectedNames ).size !== 24 || actualNames.length !== 24 ) {
throw new Error( 'Review evidence must contain exactly 24 fresh PNG files.' );
}
if ( expectedNames.some( ( name, index ) => name !== actualNames[ index ] ) ) {
throw new Error( 'Review evidence filenames do not match the approved set.' );
}
for ( const capture of capturePlan ) {
const path = join( directory, capture.filename );
const stats = await lstat( path );
if ( stats.isSymbolicLink() || ! stats.isFile() || stats.size === 0 ) {
throw new Error( `Invalid review evidence file ${ capture.filename }.` );
}
const dimensions = getPngDimensions( await readFile( path ) );
if ( dimensions.width !== capture.viewport.width || dimensions.height < 1 ) {
throw new Error( `Invalid dimensions for ${ capture.filename }.` );
}
}
}
export async function publishReviewEvidence( {
outputDirectory,
allowedParentDirectory,
capturePlan,
captureImage,
} ) {
const { outputPath, parentPath, outputExists } = await assertSafeOutput(
outputDirectory,
allowedParentDirectory,
capturePlan,
);
await removeLegacyEvidence( parentPath, capturePlan );
const stagingPath = await mkdtemp( join( parentPath, '.grunge-stage-staging-' ) );
const backupPath = join( parentPath, '.grunge-stage-backup' );
let backupCreated = false;
let published = false;
try {
for ( const capture of capturePlan ) {
await captureImage( capture, join( stagingPath, capture.filename ) );
}
await validateEvidence( stagingPath, capturePlan );
if ( outputExists ) {
if ( await optionalLstat( backupPath ) ) {
throw new Error( 'A previous review backup must be resolved before publication.' );
}
await rename( outputPath, backupPath );
backupCreated = true;
}
try {
await rename( stagingPath, outputPath );
published = true;
} catch ( error ) {
if ( backupCreated ) {
await rename( backupPath, outputPath );
backupCreated = false;
}
throw error;
}
if ( backupCreated ) {
await rm( backupPath, { recursive: true } );
backupCreated = false;
}
} finally {
if ( ! published ) {
await rm( stagingPath, { recursive: true, force: true } );
}
if ( backupCreated && ! await optionalLstat( outputPath ) ) {
await rename( backupPath, outputPath );
}
}
}
async function waitForStablePage( page ) {
await page.addStyleTag( {
content: '*,*::before,*::after{animation:none!important;transition:none!important}',
@@ -90,7 +256,6 @@ async function waitForStablePage( page ) {
);
window.scrollTo( 0, 0 );
} )();
await Promise.race( [ ready, timeout ] );
} );
}
@@ -99,7 +264,6 @@ async function replaceLongCopy( page, target ) {
if ( ! target.longCopy ) {
return;
}
const title = page.locator( target.longCopy.titleSelector );
const excerpt = page.locator( target.longCopy.excerptSelector );
await title.waitFor( { state: 'visible', timeout: 5_000 } );
@@ -112,7 +276,8 @@ async function replaceLongCopy( page, target ) {
}, target.longCopy.excerpt );
}
async function capture( baseURL, target, viewport, theme ) {
async function captureImage( baseURL, capture, outputPath ) {
const { target, viewport, theme } = capture;
const browser = await chromium.launch();
let context;
try {
@@ -133,13 +298,12 @@ async function capture( baseURL, target, viewport, theme ) {
page.setDefaultNavigationTimeout( 15_000 );
await page.route( '**/*', async ( route ) => {
const requestURL = new URL( route.request().url() );
if ( requestURL.protocol === 'http:' && LOCAL_HOSTS.has( requestURL.hostname ) ) {
if ( requestURL.origin === baseURL.origin ) {
await route.continue();
} else {
await route.abort( 'blockedbyclient' );
}
} );
const response = await page.goto( new URL( target.path, baseURL ).href, {
waitUntil: 'domcontentloaded',
timeout: 15_000,
@@ -149,6 +313,7 @@ async function capture( baseURL, target, viewport, theme ) {
`Capture target ${ target.path } returned HTTP ${ response?.status() ?? 'unknown' }.`,
);
}
assertFinalNavigation( baseURL, target.path, page.url() );
await page.waitForFunction(
( expectedTheme ) => document.documentElement.dataset.theme === expectedTheme,
theme,
@@ -157,22 +322,12 @@ async function capture( baseURL, target, viewport, theme ) {
await page.locator( 'main' ).waitFor( { state: 'visible', timeout: 5_000 } );
await replaceLongCopy( page, target );
await waitForStablePage( page );
const outputName = `grunge-stage-${ target.name }-${ viewport.width }-${ theme }.png`;
const outputPath = join( OUTPUT_DIRECTORY, outputName );
const buffer = await page.screenshot( {
await page.screenshot( {
path: outputPath,
fullPage: true,
animations: 'disabled',
caret: 'hide',
} );
const dimensions = getPngDimensions( buffer );
if ( dimensions.width !== viewport.width ) {
throw new Error(
`${ outputName } width ${ dimensions.width } did not match ${ viewport.width }.`,
);
}
console.log( `${ outputName } ${ dimensions.width }x${ dimensions.height }` );
} finally {
try {
await context?.close();
@@ -182,13 +337,22 @@ async function capture( baseURL, target, viewport, theme ) {
}
}
const baseURL = getBaseURL();
await mkdir( OUTPUT_DIRECTORY, { recursive: true } );
for ( const target of TARGETS ) {
for ( const viewport of VIEWPORTS ) {
for ( const theme of THEMES ) {
await capture( baseURL, target, viewport, theme );
}
async function main() {
const baseURL = getBaseURL();
await mkdir( REVIEW_PARENT_DIRECTORY, { recursive: true } );
await publishReviewEvidence( {
outputDirectory: OUTPUT_DIRECTORY,
allowedParentDirectory: REVIEW_PARENT_DIRECTORY,
capturePlan: CAPTURE_PLAN,
captureImage: ( capture, outputPath ) => captureImage( baseURL, capture, outputPath ),
} );
for ( const capture of CAPTURE_PLAN ) {
const buffer = await readFile( join( OUTPUT_DIRECTORY, capture.filename ) );
const dimensions = getPngDimensions( buffer );
process.stdout.write( `${ capture.filename } ${ dimensions.width }x${ dimensions.height }\n` );
}
}
if ( import.meta.url === pathToFileURL( process.argv[ 1 ] ?? '' ).href ) {
await main();
}