From 16b6a75b358e981b1d0aeecfadd69961fd9cfc03 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Thu, 13 Aug 2026 10:38:29 -0500 Subject: [PATCH] test: harden CHRNX visual evidence --- README.md | 40 +++- scripts/capture-visual-review.mjs | 232 ++++++++++++++++++++---- tests/smoke/visual-integration.test.mjs | 176 ++++++++++++++++-- 3 files changed, 386 insertions(+), 62 deletions(-) diff --git a/README.md b/README.md index f9bc965..a8c1439 100644 --- a/README.md +++ b/README.md @@ -92,19 +92,43 @@ WebP sources, with the original source as a fallback. Capture the approved local review routes with Chromium: +Create the ignored local override `.wp-env.override.json` so this checkout stays +isolated from the root environment: + +```json +{ + "port": 8908, + "testsPort": 8909 +} +``` + +Then start WordPress, activate the theme, and seed the deterministic fixtures: + +```sh +npm run env:start +npm run env:activate +./scripts/seed-test-content.sh +``` + +Capture only after those commands succeed: + ```sh CHRNX_REVIEW_URL=http://localhost:8908 node scripts/capture-visual-review.mjs ``` The capture script rejects public hosts and writes its screenshots to -`tmp/imagegen/`, which Git ignores. It captures the rendered Music and Podcasts -pages at 375, 768, 1440, and 2560 px in light and dark themes. The long-copy -Podcast state changes only the rendered latest-card title and excerpt; it does -not write to the database. Source masters remain authoritative, and responsive -media must be rebuilt with `scripts/build-responsive-images.sh` after any -approved source change. Treat these screenshots as disposable review evidence: -keep them uncommitted, obtain visual approval before committing this stage, and -do not begin the next visual task until that approval is recorded. +`tmp/imagegen/grunge-stage-review.png/`, which Git ignores. The directory's +`.png` suffix intentionally matches the existing review-artifact ignore rule; +the script builds all 24 files in a private staging directory, validates the +complete inventory, and publishes the directory as one fresh set; a failed +capture leaves the prior published set unchanged. It captures the rendered +Music and Podcasts pages at 375, 768, 1440, and 2560 px in light and dark themes. +The long-copy Podcast state changes only the rendered latest-card title and +excerpt; it does not write to the database. Source masters remain authoritative, +and responsive media must be rebuilt with `scripts/build-responsive-images.sh` +after any approved source change. Treat these screenshots as disposable review +evidence: keep them uncommitted, obtain visual approval before committing this +stage, and do not begin the next visual task until that approval is recorded. PHPUnit always runs through wp-env's isolated `tests-cli` database. The browser suite uses the separate development `cli` database; its serial scenario project diff --git a/scripts/capture-visual-review.mjs b/scripts/capture-visual-review.mjs index 57939ed..e7f681d 100644 --- a/scripts/capture-visual-review.mjs +++ b/scripts/capture-visual-review.mjs @@ -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(); +} diff --git a/tests/smoke/visual-integration.test.mjs b/tests/smoke/visual-integration.test.mjs index 405e73e..7d91ed5 100644 --- a/tests/smoke/visual-integration.test.mjs +++ b/tests/smoke/visual-integration.test.mjs @@ -1,11 +1,13 @@ import assert from 'node:assert/strict'; import { createHash } from 'node:crypto'; +import { createServer } from 'node:http'; import { chmodSync, existsSync, linkSync, lstatSync, mkdtempSync, + mkdirSync, readFileSync, readdirSync, rmSync, @@ -17,7 +19,13 @@ import { import { execFileSync } from 'node:child_process'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; +import { once } from 'node:events'; import { test } from 'node:test'; +import { + CAPTURE_PLAN, + assertFinalNavigation, + publishReviewEvidence, +} from '../../scripts/capture-visual-review.mjs'; const read = ( path ) => readFileSync( new URL( `../../${ path }`, import.meta.url ), 'utf8' ); const PODCAST_BACKGROUND_SOURCE = 'assets/images/podcast-frequency-grunge.png'; @@ -92,23 +100,18 @@ test( 'the visual layer is separately enqueued and covers responsive accessible assert.match( components, /html\[data-theme="light"\]/ ); } ); -test( 'grunge stage capture stays bounded to approved routes, widths, themes, and filenames', () => { - const capture = read( 'scripts/capture-visual-review.mjs' ); - - for ( const target of [ 'music', 'podcasts', 'podcasts-long-copy' ] ) { - assert.match( capture, new RegExp( `name: '${ target }'` ) ); +test( 'grunge stage capture exposes exactly 24 approved routes, widths, themes, and filenames', () => { + assert.equal( CAPTURE_PLAN.length, 24 ); + assert.equal( new Set( CAPTURE_PLAN.map( ( capture ) => capture.filename ) ).size, 24 ); + assert.deepEqual( [ ...new Set( CAPTURE_PLAN.map( ( capture ) => capture.target.path ) ) ].sort(), [ '/music/', '/podcasts/' ] ); + assert.deepEqual( [ ...new Set( CAPTURE_PLAN.map( ( capture ) => capture.viewport.width ) ) ], [ 375, 768, 1440, 2560 ] ); + assert.deepEqual( [ ...new Set( CAPTURE_PLAN.map( ( capture ) => capture.theme ) ) ], [ 'light', 'dark' ] ); + for ( const capture of CAPTURE_PLAN ) { + assert.equal( + capture.filename, + `grunge-stage-${ capture.target.name }-${ capture.viewport.width }-${ capture.theme }.png`, + ); } - assert.match( capture, /path: '\/music\/'/ ); - assert.equal( capture.match( /path: '\/podcasts\/'/g )?.length, 2 ); - for ( const width of [ 375, 768, 1440, 2560 ] ) { - assert.match( capture, new RegExp( `width: ${ width }` ) ); - } - assert.match( capture, /const THEMES = \[ 'light', 'dark' \]/ ); - assert.match( - capture, - /`grunge-stage-\$\{\s*target\.name\s*\}-\$\{\s*viewport\.width\s*\}-\$\{\s*theme\s*\}\.png`/, - ); - assert.doesNotMatch( capture, /name: 'home'|name: 'post'|name: 'footer'|editorial-polish/ ); } ); test( 'grunge stage capture isolates every image and waits for stable rendered assets', () => { @@ -134,10 +137,143 @@ test( 'grunge stage capture isolates every image and waits for stable rendered a assert.match( capture, /LOCAL_HOSTS/ ); assert.match( capture, /route\.abort\( 'blockedbyclient' \)/ ); assert.equal( capture.match( /const browser = await chromium\.launch\(\)/g )?.length, 1 ); - assert.match( - capture, - /for \( const target[\s\S]*for \( const viewport[\s\S]*for \( const theme[\s\S]*await capture\( baseURL, target, viewport, theme \)/, - ); + assert.match( capture, /for \( const capture of capturePlan \)[\s\S]*await captureImage/ ); +} ); + +test( 'grunge stage publication is atomic across a failure and removes private staging', async () => { + const parent = mkdtempSync( join( tmpdir(), 'chrnx-review-parent-' ) ); + const output = join( parent, 'grunge-stage-review.png' ); + const png = ( width, height, marker ) => { + const buffer = Buffer.alloc( 33, marker ); + Buffer.from( '89504e470d0a1a0a', 'hex' ).copy( buffer, 0 ); + buffer.writeUInt32BE( 13, 8 ); + buffer.write( 'IHDR', 12, 'ascii' ); + buffer.writeUInt32BE( width, 16 ); + buffer.writeUInt32BE( height, 20 ); + buffer[ 24 ] = 8; + buffer[ 25 ] = 2; + return buffer; + }; + try { + await publishReviewEvidence( { + outputDirectory: output, + allowedParentDirectory: parent, + capturePlan: CAPTURE_PLAN, + captureImage: async ( capture, path ) => writeFileSync( path, png( capture.viewport.width, 10, 1 ) ), + } ); + const before = new Map( readdirSync( output ).map( ( name ) => [ name, sha256( join( output, name ) ) ] ) ); + let count = 0; + await assert.rejects( + publishReviewEvidence( { + outputDirectory: output, + allowedParentDirectory: parent, + capturePlan: CAPTURE_PLAN, + captureImage: async ( capture, path ) => { + count++; + if ( count === 9 ) { + throw new Error( 'injected capture failure' ); + } + writeFileSync( path, png( capture.viewport.width, 11, 2 ) ); + }, + } ), + /injected capture failure/, + ); + assert.deepEqual( readdirSync( output ).sort(), CAPTURE_PLAN.map( ( capture ) => capture.filename ).sort() ); + for ( const [ name, hash ] of before ) { + assert.equal( sha256( join( output, name ) ), hash, `${ name } changed after failed capture` ); + } + assert.deepEqual( readdirSync( parent ).sort(), [ 'grunge-stage-review.png' ] ); + } finally { + rmSync( parent, { recursive: true, force: true } ); + } +} ); + +test( 'grunge stage publication rejects output and file aliases without touching sentinels', async () => { + const parent = mkdtempSync( join( tmpdir(), 'chrnx-review-alias-parent-' ) ); + const external = mkdtempSync( join( tmpdir(), 'chrnx-review-alias-external-' ) ); + const parentAlias = `${ parent }-alias`; + const output = join( parent, 'grunge-stage-review.png' ); + const sentinel = join( external, 'sentinel' ); + writeFileSync( sentinel, 'unchanged' ); + try { + symlinkSync( parent, parentAlias ); + await assert.rejects( + publishReviewEvidence( { + outputDirectory: join( parentAlias, 'grunge-stage-review.png' ), + allowedParentDirectory: parentAlias, + capturePlan: CAPTURE_PLAN, + captureImage: async () => {}, + } ), + /symbolic link/, + ); + symlinkSync( external, output ); + await assert.rejects( + publishReviewEvidence( { + outputDirectory: output, + allowedParentDirectory: parent, + capturePlan: CAPTURE_PLAN, + captureImage: async () => {}, + } ), + /symbolic link/, + ); + assert.equal( readFileSync( sentinel, 'utf8' ), 'unchanged' ); + rmSync( output ); + mkdirSync( output ); + symlinkSync( sentinel, join( output, CAPTURE_PLAN[ 0 ].filename ) ); + await assert.rejects( + publishReviewEvidence( { + outputDirectory: output, + allowedParentDirectory: parent, + capturePlan: CAPTURE_PLAN, + captureImage: async () => {}, + } ), + /symbolic link/, + ); + assert.equal( readFileSync( sentinel, 'utf8' ), 'unchanged' ); + } finally { + rmSync( parentAlias, { force: true } ); + rmSync( parent, { recursive: true, force: true } ); + rmSync( external, { recursive: true, force: true } ); + } +} ); + +test( 'final navigation rejects local redirects to a wrong review path or origin before capture', async () => { + const otherServer = createServer( ( request, response ) => { + response.writeHead( 200, { 'Content-Type': 'text/plain' } ); + response.end( request.url ); + } ); + otherServer.listen( 0, '127.0.0.1' ); + await once( otherServer, 'listening' ); + const server = createServer( ( request, response ) => { + if ( request.url === '/music/' ) { + response.writeHead( 302, { Location: '/wrong/' } ); + response.end(); + return; + } + if ( request.url === '/podcasts/' ) { + response.writeHead( 302, { Location: `http://127.0.0.1:${ otherServer.address().port }/podcasts/` } ); + response.end(); + return; + } + response.writeHead( 200, { 'Content-Type': 'text/plain' } ); + response.end( 'wrong path' ); + } ); + server.listen( 0, '127.0.0.1' ); + await once( server, 'listening' ); + try { + const { port } = server.address(); + const baseURL = new URL( `http://127.0.0.1:${ port }` ); + const response = await fetch( new URL( '/music/', baseURL ), { redirect: 'follow' } ); + assert.throws( () => assertFinalNavigation( baseURL, '/music/', response.url ), /unexpected path/ ); + const crossOrigin = await fetch( new URL( '/podcasts/', baseURL ), { redirect: 'follow' } ); + assert.throws( () => assertFinalNavigation( baseURL, '/podcasts/', crossOrigin.url ), /unexpected origin/ ); + } finally { + await Promise.all( [ server.closeAllConnections(), otherServer.closeAllConnections() ] ); + await Promise.all( [ + new Promise( ( resolve ) => server.close( resolve ) ), + new Promise( ( resolve ) => otherServer.close( resolve ) ), + ] ); + } } ); test( 'long-copy review mutates only the rendered latest podcast title and excerpt', () => {