← Files ProdVerityARCHIVED FILE

source/scripts/prodverity-vision-audit.mjs

19.7 KB · Nov 29, 2026 · 00:48 UTC

↓ Download file

See the change to this file →

/**
 * ProdVerity Vision: independent, read-only browser rendering evidence.
 *
 * This audit does not click controls, submit forms, use credentials or mutate the
 * audited site. It records what a real Chromium renderer receives at three fixed
 * viewport widths and compares screenshots with an immutable reference when one
 * is supplied by CI.
 */
import fs from 'node:fs'
import path from 'node:path'
import { pathToFileURL } from 'node:url'
import { chromium } from 'playwright'
import { normalizePublicBaseUrl } from './prodverity-public-edge-audit-lib.mjs'
import {
  VIEWPORTS,
  boundedRatio,
  comparePngBuffers,
  makeReferenceManifest,
  parseVisionRoutes,
  sha256,
} from './prodverity-vision-audit-lib.mjs'

const SOURCE = 'BROWSER_RENDERED_PLAYWRIGHT'
const OUTPUT_DIR = 'audit-artifacts/prodverity-vision'
const USER_AGENT = 'ProdVerity-Vision/1.0 (read-only public render audit)'
const IMPORTANT_RESOURCE_TYPES = new Set(['document', 'script', 'stylesheet', 'image', 'font'])

function cleanMessage(value, maximum = 800) {
  return String(value ?? '').replace(/\s+/g, ' ').trim().slice(0, maximum)
}

function relativeArtifactPath(...parts) {
  return path.join(...parts).replaceAll('\\', '/')
}

function sameOrigin(rawUrl, base) {
  try { return new URL(rawUrl).origin === new URL(base).origin } catch { return false }
}

async function fetchRevision(base, expectedRevision, issues) {
  try {
    const response = await fetch(`${base}/build-version.json`, {
      headers: { Accept: 'application/json', 'User-Agent': USER_AGENT },
      signal: AbortSignal.timeout(15000),
    })
    if (!response.ok) throw new Error(`HTTP ${response.status}`)
    const body = await response.json()
    const revision = typeof body?.commit === 'string' ? body.commit : null
    if (!revision || !/^[0-9a-f]{40}$/i.test(revision)) {
      issues.push('build-marker: no valid 40-character production commit')
      return revision
    }
    if (expectedRevision && revision !== expectedRevision) {
      issues.push(`build-marker: expected revision ${expectedRevision}, received ${revision}`)
    }
    return revision
  } catch (error) {
    issues.push(`build-marker: ${cleanMessage(error instanceof Error ? error.message : error)}`)
    return null
  }
}

async function settlePublicPage(page) {
  await page.waitForLoadState('networkidle', { timeout: 8000 }).catch(() => {})
  await page.evaluate(async () => {
    if (document.fonts?.ready) await document.fonts.ready.catch(() => {})
    const maximum = Math.min(document.documentElement.scrollHeight, 30000)
    for (let y = 0; y < maximum; y += Math.max(320, Math.floor(window.innerHeight * 0.75))) {
      window.scrollTo(0, y)
      await new Promise(resolve => setTimeout(resolve, 35))
    }
    window.scrollTo(0, 0)
  })
  await page.waitForLoadState('networkidle', { timeout: 5000 }).catch(() => {})
  await page.waitForTimeout(150)
  await page.addStyleTag({ content: `
    *, *::before, *::after {
      animation-duration: 0s !important;
      animation-delay: 0s !important;
      transition-duration: 0s !important;
      transition-delay: 0s !important;
      caret-color: transparent !important;
    }
  ` })
}

async function inspectDom(page) {
  return page.evaluate(() => {
    const visible = element => {
      const style = getComputedStyle(element)
      const rect = element.getBoundingClientRect()
      return style.visibility !== 'hidden' && style.display !== 'none' && Number(style.opacity) > 0 && rect.width > 1 && rect.height > 1
    }
    const selector = element => {
      const id = element.id ? `#${CSS.escape(element.id)}` : ''
      const classes = [...element.classList].slice(0, 2).map(name => `.${CSS.escape(name)}`).join('')
      return `${element.tagName.toLowerCase()}${id}${classes}`.slice(0, 180)
    }
    const label = element => (
      element.getAttribute('aria-label') ||
      element.getAttribute('title') ||
      element.innerText ||
      element.querySelector('img')?.getAttribute('alt') ||
      ''
    ).replace(/\s+/g, ' ').trim()

    const images = [...document.images].filter(visible)
    const brokenImages = images.filter(image => image.complete && image.naturalWidth === 0).slice(0, 20).map(image => ({
      selector: selector(image),
      src: image.currentSrc || image.src,
      alt: image.alt || null,
    }))
    const sourceCounts = new Map()
    for (const image of images) {
      const src = image.currentSrc || image.src
      if (src) sourceCounts.set(src, (sourceCounts.get(src) || 0) + 1)
    }
    const duplicateImages = [...sourceCounts.entries()]
      .filter(([, count]) => count > 1)
      .sort((a, b) => b[1] - a[1])
      .slice(0, 20)
      .map(([src, count]) => ({ src, count }))
    const coverCrops = images.flatMap(image => {
      const style = getComputedStyle(image)
      if (style.objectFit !== 'cover' || !image.naturalWidth || !image.naturalHeight) return []
      const boxRatio = image.clientWidth / Math.max(1, image.clientHeight)
      const sourceRatio = image.naturalWidth / image.naturalHeight
      const visibleFraction = Math.min(boxRatio / sourceRatio, sourceRatio / boxRatio)
      if (visibleFraction >= 0.5) return []
      return [{ selector: selector(image), src: image.currentSrc || image.src, visible_fraction_estimate: Number(visibleFraction.toFixed(3)) }]
    }).slice(0, 20)

    const interactive = [...document.querySelectorAll('button, a[href], input[type="button"], input[type="submit"], [role="button"]')]
      .filter(visible)
    const unnamedControls = interactive.filter(element => !label(element)).slice(0, 20).map(element => ({ selector: selector(element) }))
    const rects = interactive.slice(0, 250).map(element => {
      const rect = element.getBoundingClientRect()
      return { element, selector: selector(element), label: label(element).slice(0, 100), left: rect.left, top: rect.top, right: rect.right, bottom: rect.bottom, area: rect.width * rect.height }
    })
    const overlaps = []
    for (let leftIndex = 0; leftIndex < rects.length && overlaps.length < 20; leftIndex += 1) {
      for (let rightIndex = leftIndex + 1; rightIndex < rects.length && overlaps.length < 20; rightIndex += 1) {
        const first = rects[leftIndex]
        const second = rects[rightIndex]
        if (first.element.contains(second.element) || second.element.contains(first.element)) continue
        const width = Math.max(0, Math.min(first.right, second.right) - Math.max(first.left, second.left))
        const height = Math.max(0, Math.min(first.bottom, second.bottom) - Math.max(first.top, second.top))
        const ratio = width * height / Math.max(1, Math.min(first.area, second.area))
        if (ratio > 0.2) overlaps.push({
          first: { selector: first.selector, label: first.label },
          second: { selector: second.selector, label: second.label },
          overlap_ratio: Number(ratio.toFixed(3)),
        })
      }
    }

    const clippedText = [...document.querySelectorAll('body *')].filter(element => {
      if (!visible(element) || !element.textContent?.trim()) return false
      const style = getComputedStyle(element)
      const clipsX = ['hidden', 'clip'].includes(style.overflowX) && element.scrollWidth > element.clientWidth + 2
      const clipsY = ['hidden', 'clip'].includes(style.overflowY) && element.scrollHeight > element.clientHeight + 2
      return clipsX || clipsY
    }).slice(0, 20).map(element => ({
      selector: selector(element),
      text: element.textContent.replace(/\s+/g, ' ').trim().slice(0, 160),
      client: { width: element.clientWidth, height: element.clientHeight },
      scroll: { width: element.scrollWidth, height: element.scrollHeight },
    }))

    return {
      document: {
        title: document.title,
        lang: document.documentElement.lang || null,
        scroll_width: document.documentElement.scrollWidth,
        client_width: document.documentElement.clientWidth,
        scroll_height: document.documentElement.scrollHeight,
      },
      horizontal_overflow_px: Math.max(0, document.documentElement.scrollWidth - document.documentElement.clientWidth),
      image_count: images.length,
      interactive_control_count: interactive.length,
      broken_images: brokenImages,
      duplicate_images: duplicateImages,
      severe_cover_crops: coverCrops,
      unnamed_controls: unnamedControls,
      possible_interactive_overlaps: overlaps,
      possible_clipped_text: clippedText,
    }
  })
}

async function auditRender({ browser, base, route, viewport, baselineDir, maximumDifferenceRatio, outputDir, issues, warnings }) {
  const context = await browser.newContext({
    viewport: { width: viewport.width, height: viewport.height },
    deviceScaleFactor: 1,
    colorScheme: 'light',
    locale: 'en-CA',
    timezoneId: 'America/Toronto',
    reducedMotion: 'reduce',
    userAgent: USER_AGENT,
  })
  const page = await context.newPage()
  const targetUrl = new URL(route.path, `${base}/`).href
  const prefix = `${route.id}/${viewport.id}`
  const consoleErrors = []
  const pageErrors = []
  const failedRequests = []
  const badResponses = []
  page.on('console', message => {
    if (message.type() === 'error' && consoleErrors.length < 30) consoleErrors.push(cleanMessage(message.text()))
  })
  page.on('pageerror', error => {
    if (pageErrors.length < 30) pageErrors.push(cleanMessage(error.message))
  })
  page.on('requestfailed', request => {
    if (failedRequests.length < 40) failedRequests.push({
      url: request.url(),
      resource_type: request.resourceType(),
      failure: cleanMessage(request.failure()?.errorText),
    })
  })
  page.on('response', response => {
    if (response.status() >= 400 && badResponses.length < 40) badResponses.push({
      url: response.url(),
      status: response.status(),
      resource_type: response.request().resourceType(),
    })
  })

  const started = performance.now()
  let navigationStatus = null
  let dom = null
  let screenshotBuffer = null
  let screenshotPath = null
  let comparison = { status: 'NOT_AVAILABLE_FIRST_RUN', difference_ratio: null }
  try {
    const response = await page.goto(targetUrl, { waitUntil: 'domcontentloaded', timeout: 30000 })
    navigationStatus = response?.status() ?? null
    if (!response || navigationStatus >= 400) issues.push(`${prefix}: navigation returned HTTP ${navigationStatus ?? 'none'}`)
    await settlePublicPage(page)
    if (!sameOrigin(page.url(), base)) issues.push(`${prefix}: browser left the audited origin and reached ${page.url()}`)
    dom = await inspectDom(page)

    if (dom.horizontal_overflow_px > 2) issues.push(`${prefix}: horizontal overflow is ${dom.horizontal_overflow_px}px`)
    if (dom.broken_images.length) issues.push(`${prefix}: ${dom.broken_images.length} visible image(s) failed to render`)
    if (dom.unnamed_controls.length) issues.push(`${prefix}: ${dom.unnamed_controls.length} visible interactive control(s) have no accessible name`)
    if (dom.possible_interactive_overlaps.length) warnings.push(`${prefix}: ${dom.possible_interactive_overlaps.length} possible interactive overlap(s) require screenshot review`)
    if (dom.possible_clipped_text.length) warnings.push(`${prefix}: ${dom.possible_clipped_text.length} possible clipped-text element(s) require screenshot review`)
    if (dom.severe_cover_crops.length) warnings.push(`${prefix}: ${dom.severe_cover_crops.length} severe object-fit crop(s) detected; artistic intent is not inferred`)

    for (const error of pageErrors) issues.push(`${prefix}: uncaught JavaScript error: ${error}`)
    for (const failure of failedRequests) {
      const message = `${prefix}: request failed (${failure.resource_type}) ${failure.url}: ${failure.failure}`
      if (sameOrigin(failure.url, base) && IMPORTANT_RESOURCE_TYPES.has(failure.resource_type)) issues.push(message)
      else warnings.push(message)
    }
    for (const bad of badResponses) {
      const message = `${prefix}: HTTP ${bad.status} (${bad.resource_type}) ${bad.url}`
      if (sameOrigin(bad.url, base) && IMPORTANT_RESOURCE_TYPES.has(bad.resource_type)) issues.push(message)
      else warnings.push(message)
    }
    for (const error of consoleErrors) {
      if (!error.startsWith('Failed to load resource:')) issues.push(`${prefix}: browser console error: ${error}`)
    }

    const filename = `${route.id}-${viewport.id}.png`
    screenshotPath = path.join(outputDir, 'screenshots', filename)
    fs.mkdirSync(path.dirname(screenshotPath), { recursive: true })
    screenshotBuffer = await page.screenshot({ fullPage: true, animations: 'disabled', type: 'png' })
    fs.writeFileSync(screenshotPath, screenshotBuffer)
    const baselinePath = baselineDir ? path.join(baselineDir, 'screenshots', filename) : null
    if (baselinePath && fs.existsSync(baselinePath)) {
      const baselineBuffer = fs.readFileSync(baselinePath)
      const result = comparePngBuffers(screenshotBuffer, baselineBuffer)
      comparison = {
        status: result.comparable ? (result.changed_pixels ? 'CHANGED' : 'UNCHANGED') : 'DIMENSION_MISMATCH',
        baseline_path: relativeArtifactPath(baselinePath),
        changed_pixels: result.changed_pixels,
        difference_ratio: result.difference_ratio,
        baseline_dimensions: result.baseline_dimensions,
      }
      if (result.diff_png && result.changed_pixels) {
        const diffPath = path.join(outputDir, 'diffs', filename)
        fs.mkdirSync(path.dirname(diffPath), { recursive: true })
        fs.writeFileSync(diffPath, result.diff_png)
        comparison.diff_path = relativeArtifactPath(diffPath)
      }
      if (!result.comparable || result.difference_ratio > maximumDifferenceRatio) {
        issues.push(`${prefix}: visual regression ratio ${result.difference_ratio.toFixed(4)} exceeds ${maximumDifferenceRatio.toFixed(4)}`)
      } else if (result.difference_ratio > 0.005) {
        warnings.push(`${prefix}: visual difference ratio is ${result.difference_ratio.toFixed(4)}`)
      }
    }

    return {
      route_id: route.id,
      route_path: route.path,
      target_url: targetUrl,
      final_url: page.url(),
      viewport_id: viewport.id,
      viewport: { width: viewport.width, height: viewport.height },
      navigation_status: navigationStatus,
      duration_ms: Math.round(performance.now() - started),
      source: SOURCE,
      public_http_observed: true,
      browser_rendered: true,
      visual_render_verified: Boolean(dom && screenshotBuffer),
      screenshot: {
        filename,
        artifact_path: relativeArtifactPath(screenshotPath),
        sha256: sha256(screenshotBuffer),
        width: viewport.width,
        height: dom.document.scroll_height,
      },
      comparison,
      dom,
      diagnostics: { console_errors: consoleErrors, page_errors: pageErrors, failed_requests: failedRequests, bad_responses: badResponses },
    }
  } catch (error) {
    const message = cleanMessage(error instanceof Error ? error.message : error)
    issues.push(`${prefix}: browser audit failed: ${message}`)
    return {
      route_id: route.id,
      route_path: route.path,
      target_url: targetUrl,
      final_url: page.url(),
      viewport_id: viewport.id,
      viewport: { width: viewport.width, height: viewport.height },
      navigation_status: navigationStatus,
      duration_ms: Math.round(performance.now() - started),
      source: SOURCE,
      public_http_observed: navigationStatus !== null,
      browser_rendered: false,
      visual_render_verified: false,
      error: message,
      diagnostics: { console_errors: consoleErrors, page_errors: pageErrors, failed_requests: failedRequests, bad_responses: badResponses },
    }
  } finally {
    await context.close()
  }
}

export async function runVisionAudit(env = process.env) {
  const base = normalizePublicBaseUrl(env.PRODVERITY_AUDIT_BASE_URL || 'https://greatskillsacademy.com')
  const routes = parseVisionRoutes(env.PRODVERITY_VISION_ROUTES)
  const expectedRevision = String(env.EXPECTED_REVISION || '').trim()
  const baselineDir = String(env.PRODVERITY_VISION_BASELINE_DIR || '').trim()
  const outputDir = String(env.PRODVERITY_VISION_OUTPUT_DIR || OUTPUT_DIR).trim()
  const maximumDifferenceRatio = boundedRatio(env.PRODVERITY_VISION_MAX_DIFF_RATIO, 0.03, 0, 0.5)
  const observedAt = new Date().toISOString()
  const issues = []
  const warnings = []
  const observedRevision = await fetchRevision(base, expectedRevision, issues)
  const browser = await chromium.launch({ headless: true })
  const browserVersion = browser.version()
  const results = []
  try {
    for (const route of routes) {
      for (const viewport of VIEWPORTS) {
        results.push(await auditRender({ browser, base, route, viewport, baselineDir, maximumDifferenceRatio, outputDir, issues, warnings }))
      }
    }
  } finally {
    await browser.close()
  }

  const screenshotEvidence = results.filter(result => result.screenshot).map(result => ({
    route_id: result.route_id,
    viewport_id: result.viewport_id,
    filename: result.screenshot.filename,
    sha256: result.screenshot.sha256,
    width: result.screenshot.width,
    height: result.screenshot.height,
  }))
  const report = {
    schema_version: '1',
    audit_id: env.GITHUB_RUN_ID || 'manual',
    observed_at: observedAt,
    source: SOURCE,
    scope: 'Read-only Chromium rendering of bounded public routes at fixed viewport widths. No clicks, form submissions, credentials, authenticated pages, writes or inferred artistic judgments.',
    base_url: base,
    expected_revision: expectedRevision || null,
    observed_revision: observedRevision,
    browser: { engine: 'chromium', version: browserVersion, headless: true },
    policy: {
      viewport_widths: VIEWPORTS.map(viewport => viewport.width),
      routes,
      maximum_visual_difference_ratio: maximumDifferenceRatio,
      immutable_reference_key: 'prodverity-vision-reference-v1',
      artifact_retention_days: 30,
      authenticated_routes_allowed: false,
      interactive_actions_allowed: false,
    },
    baseline: {
      directory: baselineDir || null,
      available_screenshot_count: results.filter(result => !['NOT_AVAILABLE_FIRST_RUN', undefined].includes(result.comparison?.status)).length,
      status: baselineDir && results.some(result => result.comparison?.status !== 'NOT_AVAILABLE_FIRST_RUN') ? 'COMPARED' : 'NOT_AVAILABLE_FIRST_RUN',
    },
    verdict: issues.length ? 'FAIL' : 'PASS',
    issues,
    warnings,
    results,
    limitations: [
      'Only configured public routes and one Chromium version are sampled.',
      'Possible overlaps, clipping, duplicate imagery and object-fit cropping are evidence for review, not automatic proof of a defect.',
      'A first run without an immutable reference cannot prove absence of visual regression.',
      'No authenticated or transactional workflow is exercised.',
      'Browser results are runner-, time- and network-specific.',
    ],
  }
  fs.mkdirSync(outputDir, { recursive: true })
  fs.writeFileSync(path.join(outputDir, 'report.json'), JSON.stringify(report, null, 2) + '\n')
  fs.writeFileSync(path.join(outputDir, 'reference-manifest.json'), JSON.stringify(makeReferenceManifest({
    revision: observedRevision,
    screenshots: screenshotEvidence,
    observedAt,
  }), null, 2) + '\n')
  return report
}

async function main() {
  const report = await runVisionAudit()
  console.log(`ProdVerity Vision audit: ${report.verdict} (renders=${report.results.length}; verified=${report.results.filter(result => result.visual_render_verified).length}; issues=${report.issues.length}; warnings=${report.warnings.length}; baseline=${report.baseline.status}; revision=${report.observed_revision || 'missing'})`)
  for (const issue of report.issues) console.error(`::error::${issue}`)
  for (const warning of report.warnings) console.warn(`::warning::${warning}`)
  if (report.issues.length) process.exitCode = 1
}

const invokedPath = process.argv[1] ? pathToFileURL(path.resolve(process.argv[1])).href : null
if (invokedPath === import.meta.url) await main()

SHA-256: 3873a8f56b0feadc70b323f72e9d6442161f1e7e0c50802a48fb1a1df3c0fdac