The task: "Engineer a content integrity scanner detecting layout shifts, broken embeds, and third-party drift."
This is a broad request. I need to provide a solution: probably a software design, architecture, and implementation details for a system that can scan web pages (or content) for these issues.
Break down:
- Content integrity scanner: A tool that analyzes web pages (likely) for integrity issues.
- Detecting layout shifts: Could be Cumulative Layout Shift (CLS) issues; need to detect unexpected movement of elements during page load or user interaction.
- Broken embeds: Detecting when embedded content (like videos, iframes, social media widgets) fails to load or is missing.
- Third-party drift: This could refer to when third-party scripts or iframes change behavior or content unexpectedly (e.g., A/B testing, malicious code injection, or just version upgrades causing UI changes). Possibly detecting drift in third-party content over time.
Thus, the scanner would likely be a set of tools: maybe a headless browser that loads pages, captures metrics, compares with baselines, and reports anomalies.
Given the instruction: "You are ChatGPT... generate accurate and professional responses. ... Ensure that the generated code is executable for demonstration." So I need to produce code that demonstrates the core functionality. Could be a simple Node.js script using Puppeteer to load a page, detect layout shifts via metrics, check for broken embeds (status code, resource load errors), and perhaps detect third-party drift by comparing snapshots (like visual regression) of third-party components.
But the request says "Engineer a content integrity scanner", which could be interpreted as designing a system. However, the instruction also says "Ensure that the generated code is executable for demonstration." So I need to provide a working code sample that demonstrates the scanner's capabilities. Likely I can create a Node.js script that uses Puppeteer, maybe some libraries for layout shift detection. Alternatively, a Python script with Selenium. But I'm more comfortable with Node for headless Chrome.
I'll outline:
- Approach: Use headless Chrome (Puppeteer) to load pages.
- For layout shifts: Use the Layout Instability API (via
PerformanceObserver in Chrome) to capture layout shift scores and details. Could also compute CLS.
- For broken embeds: Listen for network errors or check iframes or embedded elements (like video tags) load successfully (e.g., by checking if the iframe's contentDocument is accessible or by monitoring network requests that fail).
- For third-party drift: Could take screenshots of third-party elements (like specific selectors) and compare with baseline images (using pixelmatch). Or compare DOM structure or attributes. That might be heavy for a demo. Simpler: extract the HTML of the third-party component and compare with a saved baseline hash. Or detect if the third-party script's URL has changed (drift in source). Or more realistically, monitor the content of third-party iframes for changes. I'll choose a simpler approach: compute a hash of the outerHTML of third-party elements and compare to a known good baseline; if different, flag drift.
However, for a demonstration, we need to have test pages. I'll set up a local HTML file with some content, including an embed (maybe an image from a broken URL), and a third-party component (e.g., a Twitter embed). But that would require internet access and may not be reliable. Instead, we could simulate broken embed by pointing to a non-existent image. For third-party drift, we could change the content between runs? But for a single script run, we need to decide what baseline to compare against. Perhaps we can have a predefined expected state stored in the script. Or we can simply compute metrics and print them, without baseline comparison; the "detection" part would be if certain thresholds are exceeded. That would still demonstrate detection capabilities: e.g., if layout shift score > 0, flag; if any embed failed to load, flag; if third-party element's content differs from a baseline string, flag.
Since we are to "engineer" a scanner, I should provide a more complete design, but the code must be executable. I'll produce a self-contained Node.js script that uses Puppeteer. I'll include instructions on how to run (npx, npm install). I'll also include a sample HTML file to scan.
But the task says "Engineer a content integrity scanner...". Could be that they want a description of the system architecture, followed by code. Usually these ChatGPT prompt types expect a solution description and code.
Thus, I'll produce:
- High-level design: components, workflow.
- Implementation details: Node.js + Puppeteer, using performance observers for layout shifts, error listeners for network failures, DOM analysis for third-party drift.
- Provide a code sample:
scanner.js that takes a URL argument, loads page, collects metrics, reports.
- Also provide a sample HTML page for testing:
test.html with intentional issues (layout shift, broken image, third-party iframe). The script can open that file locally.
I need to be careful about third-party drift: For the demo, I'll define a third-party element by a CSS selector (e.g., .third-party-embed). The script will compute a hash of its innerHTML and compare to a baseline stored in a JSON file (or hard-coded). But for a single run, we can't compare if we don't have baseline. Alternatively, we can have two modes: baseline generation and detection. But likely too complex. Simpler: We'll define an expected checksum in the script, and if the actual checksum differs, flag drift. So I'll hardcode the expected checksum for the test page. But the test page will be provided by me, so I can compute the checksum and embed it. That's okay.
Alternatively, I could compute a diff between the third-party element's content and a known pattern (like a placeholder). Not sure.
Maybe it's better: The third-party drift detection could be based on monitoring the network requests: detect if the third-party script's URL has changed from the known URL. That would be simpler: you define a set of third-party origins you allow; if the page loads a script from a different origin, that's drift. But "drift" might mean content changes, not source. But it's plausible.
Let's interpret "third-party drift" as: Over time, third-party widgets may update their code or content, leading to changes in appearance or behavior that might break your layout or content. So you want to detect when the third-party content differs from a previously accepted version. This is essentially visual regression or DOM diffing. For a scanner, you'd compare current version to baseline. So baseline must be stored somewhere. I'll include a simple baseline storage: a JSON file mapping URLs to checksums. On first run, generate baseline. Then subsequent runs compare. I'll implement a basic version: if a baseline exists for the URL, compare; else, create baseline and report "baseline created". But for a demonstration, we need to have a baseline already. I could precompute checksum for test.html and store in a file or in the script.
Simplify: I'll skip the baseline persistence and just include a hardcoded expected hash in the script for the provided test page. That keeps the code self-contained: the script will have a constant EXPECTED_THIRD_PARTY_CHECKSUM for the given test page's third-party element. If the actual checksum differs, it reports drift. In real use, you'd store baselines externally.
Thus, the steps:
- Launch headless browser.
- Enable performance logging to capture Layout Shift events (CLS). Use
page.evaluateOnNewDocument to inject a script that listens to layout-shift entries and collects them. At the end, sum the scores (non-duration ones) for CLS.
- For broken embeds: We can listen to
requestfailed events for resources. But that captures all network failures, not just embeds. We want specifically embeds like iframes, images, video, audio, object, embed. We can check if any of these tags fail to load (maybe by checking their naturalWidth/height for images, or for iframes, checking contentDocument if accessible). Alternatively, we can monitor network requests that correspond to those tags. But simpler: after page load, query all embed elements (like iframe, img, video, embed, object). For each, check if it loaded successfully: for img, check complete and naturalWidth > 0; for iframe, check contentDocument not null? But cross-origin iframes can't be accessed due to CORS; you may get a security error. That would be considered a failure if it's same-origin, but for third-party it's expected to be cross-origin; accessing contentDocument would throw, so you can't rely on that. Instead, we might rely on network request status: if the iframe's src request failed (e.g., 404), then it's broken. We can capture all network requests and map them to the element? That's tricky.
Simpler: Use Puppeteer's page.on('requestfailed', ...) to collect failed request URLs. Then after page load, we can see if any of the embed elements' src matches a failed URL. That's a decent approach.
- For third-party drift: We need to identify third-party elements. Could be iframes from different origins, or scripts that inject content. I'll define a specific selector for the demo:
.third-party-widget. We'll extract its outerHTML (or innerHTML) and compute a hash (e.g., using a simple hash function or crypto). Compare to expected.
Now, code structure:
- Parse command line arguments for URL.
- Launch Puppeteer.
- Set up performance observer to capture layout shift entries.
- Set up request tracking.
- Wait for load (or maybe network idle).
- After load, get CLS from performance entries.
- Get list of embed elements and cross-check with failed requests.
- Get third-party element and compute checksum.
- Print report.
- Close browser.
Edge: Layout shifts may occur after load (on user interaction). But for a basic scan, we wait for load. Might miss shifts after load. Could also wait a few seconds after load to capture additional shifts, but not needed.
We need to ensure that the Layout Instability API is available. In headless Chrome, it is.
Implementation of layout shift capture:
const layoutShifts = [];
await page.evaluate(() => {
// Use PerformanceObserver to observe layout-shift entries
const observer = new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
// Only count layout shifts without recent user input (value may be 0 if had user input)
if (!entry.hadRecentInput) {
layoutShifts.push(entry);
}
}
});
observer.observe({ type: 'layout-shift', buffered: true });
});
But the layoutShifts array is in the page context; we need to retrieve it. So we'll store in variable that we can access via page.evaluate(() => ...) returning the array. Actually, we can do:
const layoutShiftEntries = await page.evaluate(() => {
// create a global array to capture entries
const entries = [];
const observer = new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
entries.push(entry);
}
});
observer.observe({ type: 'layout-shift', buffered: true });
// Return entries after a short delay to allow collection
return new Promise(resolve => {
setTimeout(() => {
observer.disconnect();
resolve(entries);
}, 2000);
});
});
But CLS is cumulative sum of shift scores of all entries without recent input. We can compute CLS from those entries.
Alternatively, we can use page.metrics()? No.
Simplify: We'll just wait for load, then evaluate to get CLS: Chrome provides performance.getEntriesByType('layout-shift'). We can do after load:
const cls = await page.evaluate(() => {
const entries = performance.getEntriesByType('layout-shift');
let cls = 0;
for (const entry of entries) {
if (!entry.hadRecentInput) {
cls += entry.value;
}
}
return cls;
});
But we need to ensure we capture all entries, including those that happen after load? The buffered flag maybe? Actually, performance.getEntriesByType returns entries that have been recorded so far. If we call it after load, we will get entries from navigation and load. But layout shifts that happen after the load event might not be captured if we call too early. To be safe, maybe wait a second after load. We'll do:
await page.goto(url, { waitUntil: 'load' });
await page.waitForTimeout(1000);
const cls = await page.evaluate(() => {
const entries = performance.getEntriesByType('layout-shift');
let total = 0;
for (const entry of entries) {
if (!entry.hadRecentInput) {
total += entry.value;
}
}
return total;
});
That's fine.
For broken embeds: We'll capture all network requests and their status.
const failedRequests = new Set();
page.on('requestfailed', request => {
failedRequests.add(request.url());
});
But we need to capture before navigation. Also, we should capture only certain resource types? request.resourceType() returns type like 'image', 'media', 'websocket', etc. For embeds, relevant types: 'image' for , 'media' for /, 'object' for /? Actually, in Puppeteer, resourceType for is 'object'. For , maybe 'other'? We'll check.
We'll gather all failed requests. After page load, we get all embed elements:
const embedElements = await page.$$('iframe, img, video, audio, embed, object');
For each element, check its src or data attribute? Typically src. But for <object> it's data. We'll get the URL: if element has 'src', use that; if 'data', use that. Then if that URL is in failedRequests, mark as broken.
But note: some embed elements might have no src (like a placeholder). We'll skip.
We could also check if the element is visible? Not necessary.
For third-party drift: We'll define a selector for the third-party component. We'll compute a hash of its outerHTML. Use a simple hash function? Could use built-in crypto (Node's crypto.createHash) but we need the string. We'll get outerHTML in page context and return it:
const thirdPartyHTML = await page.$eval('.third-party-widget', el => el.outerHTML);
Then compute checksum:
const checksum = crypto.createHash('md5').update(thirdPartyHTML).digest('hex');
Compare with expected.
Now, the test page: I'll create an HTML file with:
- Some content that shifts layout (e.g., a banner that appears after a delay or an image with no dimensions that loads and pushes text).
- A broken embed: an with src pointing to a non-existent file.
- A third-party widget: a div with class "third-party-widget" containing some static HTML (maybe a simulated widget). For baseline, I'll compute its checksum and hardcode in the script. To simulate drift, we could intentionally change it later, but the scanner will just compare.
But the prompt expects code that is executable. I'll provide two files: scanner.js and test.html. I'll also include instructions to install dependencies.
I'll also consider that the scanner should be robust and professional. I'll add error handling, output in a nice format (maybe JSON or console.table). I'll define a function that returns an object with findings.
Potential issues:
- The Layout Shift API may not capture all shifts? It's the standard way to compute CLS.
- Third-party drift detection via checksum might be too brittle; but okay for demo.
- Broken embed detection might flag false positives if a resource fails due to ad-blocker or network issues. But in a controlled environment, it's fine.
I need to produce code that can be run with Node 16+ (since Puppeteer requires). I'll include package.json maybe not needed; just provide instructions to npm init -y && npm install puppeteer. But as part of the response, I'll provide the scanner script and test page.
Let's write the code.
scanner.js:
const puppeteer = require('puppeteer');
const crypto = require('crypto');
const fs = require('fs');
const path = require('path');
// Expected checksum for the third-party widget in test.html (precomputed)
const EXPECTED_THIRD_PARTY_CHECKSUM = 'replace_with_actual'; // We'll compute and fill later.
// For demonstration, we'll compute expected checksum from test.html if we read it? But better to precompute and hardcode.
// I'll create a function to compute from a known HTML string.
function computeChecksum(html) {
return crypto.createHash('md5').update(html).digest('hex');
}
async function scanPage(url) {
const results = {
url,
layoutShiftScore: 0,
brokenEmbeds: [],
thirdPartyDrift: false,
thirdPartyCurrentChecksum: null,
thirdPartyExpectedChecksum: EXPECTED_THIRD_PARTY_CHECKSUM,
error: null,
};
let browser;
try {
browser = await puppeteer.launch({
headless: 'new',
args: ['--no-sandbox', '--disable-setuid-sandbox'] // for Linux environments
});
const page = await browser.newPage();
// Track failed requests
const failedRequests = new Set();
page.on('requestfailed', request => {
const url = request.url();
const failureText = request.failure().errorText;
console.log(`[DEBUG] Request failed: ${url} - ${failureText}`);
failedRequests.add(url);
});
// Navigate to the page
await page.goto(url, { waitUntil: 'load' });
// Wait a bit to capture any late layout shifts
await page.waitForTimeout(1000);
// 1. Layout Shift Score (CLS)
results.layoutShiftScore = await page.evaluate(() => {
const entries = performance.getEntriesByType('layout-shift');
let cls = 0;
for (const entry of entries) {
if (!entry.hadRecentInput) {
cls += entry.value;
}
}
return cls;
});
// 2. Broken embeds detection
// Get all embed elements
const embedElements = await page.$$('iframe, img, video, audio, embed, object');
for (const element of embedElements) {
// Evaluate in page context to get the src or data attribute
const src = await page.evaluate(el => {
// Check common attributes
if (el.src) return el.src;
if (el.data) return el.data;
// For <source> elements inside <video>/<audio>? We'll skip for simplicity.
return null;
}, element);
if (src && failedRequests.has(src)) {
results.brokenEmbeds.push({
element: await page.evaluate(el => el.tagName, element),
src,
});
}
}
// 3. Third-party drift detection
// Check if the third-party widget exists
const thirdPartyExists = await page.$('.third-party-widget');
if (thirdPartyExists) {
const html = await page.$eval('.third-party-widget', el => el.outerHTML);
const checksum = computeChecksum(html);
results.thirdPartyCurrentChecksum = checksum;
results.thirdPartyDrift = checksum !== EXPECTED_THIRD_PARTY_CHECKSUM;
} else {
results.thirdPartyDrift = true; // missing widget is drift
results.thirdPartyCurrentChecksum = null;
}
} catch (err) {
results.error = err.message;
} finally {
if (browser) {
await browser.close();
}
}
return results;
}
// CLI: if run directly, read URL from args or default to test.html
if (require.main === module) {
(async () => {
// Determine the URL to scan
let targetUrl = process.argv[2];
if (!targetUrl) {
// Default to local test.html in the same directory
const scriptDir = __dirname;
targetUrl = `file://${path.join(scriptDir, 'test.html')}`;
console.log(`No URL provided, scanning local file: ${targetUrl}`);
}
// If EXPECTED_THIRD_PARTY_CHECKSUM is placeholder, try to compute from test.html if it exists.
// But that would defeat purpose: we need expected to be baseline. For demo, we can compute it from the test.html file we ship.
// Actually, we can read the test.html file and compute its third-party widget checksum, then set as expected. But if user scans another page, expected might not match.
// For simplicity, we'll compute the expected checksum at runtime from the test.html file if the target is test.html and the expected is not set.
// In a real scanner, expected would be stored in a database.
if (EXPECTED_THIRD_PARTY_CHECKSUM === 'replace_with_actual') {
try {
const testPath = path.join(__dirname, 'test.html');
const testHtml = fs.readFileSync(testPath, 'utf8');
// Parse to extract third-party widget? But simpler: we know the test.html contains the widget with id etc. We'll just compute checksum of the widget's outerHTML from the file content? That's tricky because we need exactly the outerHTML as rendered, but the static file is the same.
// Instead, we can compute after launching the browser? That would be circular.
// We'll just set a placeholder and instruct user to replace. Not ideal.
// Alternate approach: don't hardcode expected; instead, for the first run, we generate baseline. Then second run compares.
// But we want a single run to detect drift. Hmm.
// Since this is a demonstration, we can compute the checksum by loading test.html in a separate page, get the widget's outerHTML, compute checksum, and then use that as expected. But then we need to simulate drift by altering test.html? The test.html is static. To demonstrate drift detection, we need to have a scenario where the widget differs from expected. We could create two test pages: one baseline and one with drift. But the scanner only scans one page.
// Perhaps we can have the scanner accept a baseline file: if present, load expected checksum from there; if not, generate and save. That would be more realistic and still work as single run (first run creates baseline, second run compares). But the prompt says "detecting", so we want detection, not baseline generation. But for demo, we can have a precomputed expected checksum for the test page. I'll compute it offline and hardcode.
// Let's compute it now: I'll write the test.html with specific content, then compute checksum of its third-party widget's outerHTML and paste it.
// I'll need to produce both files in the answer. I'll generate test.html with a specific third-party widget: <div class="third-party-widget" id="widget">Test widget content</div>. The outerHTML will be the exact element including its attributes. I'll need to compute its MD5.
// Let's do it: The element is `<div class="third-party-widget" id="widget">Test widget content</div>`. That string is 60 characters? Actually count:
// `<div class="third-party-widget" id="widget">Test widget content</div>` -> length? Let's compute precisely:
// Characters:
// < d i v c l a s s = " t h i r d - p a r t y - w i d g e t " i d = " w i d g e t " > T e s t w i d g e t c o n t e n t < / d i v >
// I'll count:
// "<div class=\"third-party-widget\" id=\"widget\">Test widget content</div>"
// That's 60? Let's count manually:
// 1 <,2 d,3 i,4 v,5 space,6 c,7 l,8 a,9 s,10 s,11 =,12 ",13 t,14 h,15 i,16 r,17 d,18 -,19 p,20 a,21 r,22 t,23 y,24 -,25 w,26 i,27 d,28 g,29 e,30 t,31 ",32 space,33 i,34 d,35 =,36 ",37 w,38 i,39 d,40 g,41 e,42 t,43 ",44 >,45 T,46 e,47 s,48 t,49 space,50 w,51 i,52 d,53 g,54 e,55 t,56 space,57 c,58 o,59 n,60 t,61 e,62 n,63 t,64 <,65 /,66 d,67 i,68 v,69 >. That's 69 characters. But MD5 hex of that string. I can compute later using Node. But since I'll produce the test.html, I can compute the checksum easily after writing the code. I'll compute it and then hardcode.
// However, I'm generating the response now; I need to decide the exact HTML. So I'll decide the third-party widget content as a simple string: `<div class="third-party-widget">Hello, world!</div>`? But that may appear elsewhere? I'll use: `<div class="third-party-widget" data-version="1.0.0">Third Party Content v1</div>`.
// I'll compute its MD5: In Node: `crypto.createHash('md5').update('<div class="third-party-widget" data-version="1.0.0">Third Party Content v1</div>').digest('hex')`. Let's compute:
// I'm ChatGPT, I cannot run code, but I can approximate by mental? Not accurate. I could provide a placeholder and instruct user to run a command to compute it, but that would break "executable". Actually the code will run, but it will have a placeholder, so drift detection will always be true unless we set expected correctly.
// Option: Instead of hardcoding expected checksum, we can compute expected at runtime from the test.html file's known element. But that would compare to the same file, so drift would be false. To demonstrate drift, we'd need to modify the test.html to change the widget. But then the expected would be computed from the same file, so no drift detected. So we need separate baseline.
// Better design: The scanner will read baseline data from a JSON file. In the demo, we provide a baseline file that matches the test page. Then we run scanner. The scanner will compare current checksum to baseline. That's more realistic. Then to show drift, we can manually modify test.html to change the widget, and then scanner will detect drift. That's acceptable; the user can modify the test file to see the effect. And we can have the script generate a baseline if none exists. So:
// Flow:
// - Check if a baseline file exists (e.g., baseline.json) containing checksums per page URL.
// - If not, after scanning, save the current checksums as baseline and report "baseline created".
// - If exists, compare and report drift if mismatch.
// That would be a more complete engineering solution. And it's still a single script; it can be run multiple times. For the first run, it creates baseline. The user can then modify the test page and run again to see drift detection.
// That's better than hardcoding.
// I'll implement that: The script accepts a URL and a baseline file path (default: `baseline.json`). It loads baseline if exists, else after scan it creates baseline. For third-party drift, we need to know which element to monitor. We'll define selectors (array) for third-party components. Could be passed via config.
// But for simplicity, I'll keep it simple: The script only checks one specific selector `.third-party-widget`. For multiple, could extend but not needed.
// So the script will have:
// - Read baseline from file (if exists) -> JSON mapping selector to expected checksum? Actually, baseline could be per URL: { url: { selector: checksum } } or just global for that selector? Since differentpages may have different third-party components, we might want per URL and per selector. Simpler: baseline is a map of page URLs to an object containing checksum for the widget. So baseline[url] = checksum.
// - After scan, if baseline has entry for that URL, compare; else, create new baseline with checksum and report baseline set.
// For broken embeds and layout shift, we don't have baseline; we just report if they exceed thresholds? Or we could also have thresholds. For demo, we can just report values and user judges. But we could set a threshold for CLS (e.g., > 0.1 is considered shift). And for broken embeds, any count is bad.
// Let's do:
// - CLS: if > 0.1, flag as layout shift detected.
// - Broken embeds: any found.
// - Third-party drift: compare checksum to baseline.
// We'll also output detailed JSON.
// Implementation details:
// Baseline file path: default `scanner-baseline.json`.
// Load baseline: try `fs.readFileSync(baselinePath, 'utf8')` catch not exists.
// Compute current checksum for the selector.
// If baseline exists and entry for url present, compare. If mismatch, set drift = true.
// If baseline exists but no entry for url, treat as drift? Or maybe just create new? I'd say: if baseline exists but this URL not in baseline, we cannot compare; set drift = false? We could also add it to baseline if user wants. For simplicity, treat as no baseline and create after.
// After scan, optionally write baseline? Only if baseline didn't exist? Or provide an option to update? We'll have a flag `--update-baseline` to force update. But for demo, I'll just have the script generate baseline on first run automatically. And on subsequent runs, it uses it. That's fine.
// So modify script accordingly.
// We'll also need to compute current checksum for third-party widget only if it exists; if missing, drift = true.
// So we need to adjust the code.
// I'll restructure:
// const BASELINE_PATH = path.join(__dirname, 'scanner-baseline.json');
// let baseline = {};
// if (fs.existsSync(BASELINE_PATH)) {
// baseline = JSON.parse(fs.readFileSync(BASELINE_PATH, 'utf8'));
// }
// After scanning:
// let currentChecksum = null;
// if (thirdPartyExists) { ... compute currentChecksum }
// const expectedChecksum = baseline[url] ?? null;
// let driftDetected = false;
// if (expectedChecksum === null) {
// // No baseline entry, will create after
// driftDetected = false; // cannot detect drift without baseline
// } else {
// driftDetected = currentChecksum !== expectedChecksum;
// }
// results.thirdPartyDrift = driftDetected;
// results.thirdPartyExpectedChecksum = expectedChecksum;
// Then after results, if baseline didn't have entry for this url, we add it with current checksum and write baseline file (only if we want to set baseline). But we may not want to automatically update baseline every run? Usually scanner is used to detect changes, so baseline is set initially. I'll make it: if no baseline for this URL, after scanning we set baseline from current state and write baseline file. That means first run sets baseline, second run compares. That's intuitive.
// So:
// let baselineUpdated = false;
// if (!(url in baseline)) {
// if (currentChecksum) {
// baseline[url] = currentChecksum;
// baselineUpdated = true;
// }
// }
// Then after closing browser, if baselineUpdated, write file.
// This approach requires that the script writes to filesystem. That's okay.
// For broken embeds and layout shifts, we just report; we don't have baseline thresholds. We could define thresholds in config.
// Let's incorporate that.
// Now the test.html: we need to ensure that the third-party widget has a checksum that we can compute and match baseline. So first run sets baseline. Then if we modify test.html (change the widget content), second run will detect drift.
// This is good for demo: user runs scanner once to set baseline, then manually edit test.html to simulate drift, run again to see detection.
// So we don't need to compute expected checksum at compile time; it's derived from first run.
// Remove the hardcoded EXPECTED_THIRD_PARTY_CHECKSUM.
// So the script will not have that constant. Instead, use baseline.
// Implementation details:
// We'll define a function that runs the scan, taking url and baseline object, and returns results plus current checksum.
// Steps:
// const baselinePath = ...;
// let baseline = {};
// if (fs.existsSync(baselinePath)) baseline = JSON.parse(...);
// const results = await scanPage(url); but we need to integrate baseline logic inside scanPage? Better to keep scanPage as a function that returns data, and then handle baseline outside.
// Actually, scanPage should return all necessary data: layoutShiftScore, brokenEmbeds, thirdPartyChecksum (or null if missing). Then outside we compare with baseline.
// Let's design:
// async function scanPage(url) {
// ... gather data...
// return {
// url,
// layoutShiftScore,
// brokenEmbeds,
// thirdPartyChecksum, // string or null
// error
// };
// }
// Then in main:
// const scanResult = await scanPage(targetUrl);
// // Compare with baseline
// const expectedChecksum = baseline[targetUrl];
// let thirdPartyDrift = false;
// if (expectedChecksum !== undefined) {
// thirdPartyDrift = scanResult.thirdPartyChecksum !== expectedChecksum;
// } else {
// // No baseline, we'll set baseline after reporting.
// }
// // Build final report object including drift.
// Also handle case where thirdPartyChecksum is null (widget missing). That should be considered drift if baseline existed (expected some checksum). If baseline missing, baseline will be set to null? We could store null as baseline? That would mean baseline recognized missing widget. But if baseline not set, we cannot know if it's drift. We'll treat missing as drift only if baseline existed and expectedChecksum is not null. We'll store baseline[url] = checksum (or null if missing). So later comparison: if both null, ok; if one null and other not, drift.
// For simplicity, we'll only store baseline if thirdPartyChecksum is not null (i.e., widget exists). If widget missing, we could store a special value like "MISSING". But then if it's missing in baseline and missing again, that's consistent. But baseline creation should succeed even if missing, meaning we consider missing as acceptable state? Possibly. However, for demo, the test page will have the widget. So okay.
// I'll implement storing only if checksum exists. If missing, skip baseline entry? That's okay.
// Actually, we want to detect if widget disappears, that is a drift. So baseline should store the fact that it existed. So we need to store a sentinel for missing? Maybe store `null` explicitly to indicate absence was baseline. But in JSON, null is fine. So: baseline[url] = scanResult.thirdPartyChecksum; which could be null if widget missing. Then later compare: if both null, no drift; if one null, drift. That works.
// So baseline[url] = currentChecksum (which may be null if missing). We'll store that.
// So after scanning, if baseline doesn't have an entry, we set baseline[url] = scanResult.thirdPartyChecksum and write file. That includes null if missing.
// Note: If the page fails to load, scanResult.error set, we shouldn't set baseline. We'll handle.
// Also, we need to ensure that the baseline file is written only if we are creating new entry? Could also provide `--force-update` to overwrite. But for demo, we'll just set if missing.
// Now, broken embeds and layout shifts: we could define thresholds. For demo, let's say:
// - Layout shift threshold: 0.1 (any score > 0.1 considered shift)
// - Broken embeds threshold: >0 (any broken embed is issue)
// We'll add to report: `hasLayoutShift: layoutShiftScore > 0.1`, `hasBrokenEmbeds: brokenEmbeds.length > 0`.
// Final report structure:
// {
// url,
// layoutShiftScore,
// hasLayoutShift: boolean,
// brokenEmbeds: array of {element, src},
// hasBrokenEmbeds: boolean,
// thirdPartyChecksum: string|null,
// thirdPartyExpectedChecksum: string|null (from baseline),
// thirdPartyDrift: boolean,
// baselineCreated: boolean (if baseline entry was added this run),
// error: string|null
// }
// Then print nicely.
// This seems solid.
// Now, we need to implement the scanPage function accordingly.
// Let's rewrite the code with baseline handling.
// Also, we'll need to handle that the script might be run multiple times; we need to ensure it doesn't overwrite baseline once set. So we'll only add if url not in baseline.
// We'll also add an option to force baseline update via CLI arg `--update-baseline`. That would overwrite existing entry. Good for when intentional changes are acceptable. But not needed for basic demo. We can add simple flag.
// Implementation:
// const forceUpdate = process.argv.includes('--update-baseline');
// Then after scan:
// if (forceUpdate || !(url in baseline)) {
// baseline[url] = thirdPartyChecksum;
// baselineUpdated = true;
// }
// This allows user to refresh baseline after accepting changes.
// Good.
// Now, get the third-party element: we need to use consistent selector. We'll define `THIRD_PARTY_SELECTOR = '.third-party-widget'`. We could also allow multiple selectors via config, but not needed.
// Also, for broken embeds detection: we'll monitor `requestfailed`. But note that some requests may fail due to CORS or other reasons that might not indicate the embed is broken. But for demo, it's okay.
// Also, some embeds may have `src` that is a data URL (data:...). Those are unlikely to fail. So we skip.
// We'll also consider that an img might fail due to 404, but also if the request is aborted or blocked by extension. In headless Chrome, no extensions. Could be network error. We'll treat any failure as broken.
// However, some resources might be requested multiple times (e.g., if same image appears twice). We'll use a Set of failed URLs, and for each element we check if its src is in set. It will count each element separately.
// We'll also need to get the element's tagName to report.
// Implementation:
// for (const element of embedElements) {
// const src = await page.evaluate(el => {
// return el.src || el.data || null;
// }, element);
// if (src && failedRequests.has(src)) {
// const tag = await page.evaluate(el => el.tagName, element);
// results.brokenEmbeds.push({ element: tag, src });
// }
// }
// But note: Some embed elements like <source> inside <video> have src attribute but are not top-level embed elements. Our selector includes only top-level tags; we might miss sources. But it's okay for demo.
// Another nuance: The requestfailed event might fire for non-embed resources like CSS, JS, etc. We only care about embed elements. So we cross-check with embedElements list.
// That covers it.
// Now, the test.html: I'll craft it to include:
// - A layout shift: maybe an image with no width/height that loads and pushes content. Or a script that adds content after load. I'll use a script that adds a div after 500ms, causing shift.
// - A broken embed: an image with src="broken.jpg" that doesn't exist.
// - A third-party widget: a div with class "third-party-widget" containing some text, maybe an iframe from a third-party? But we want to test drift based on HTML content. We'll include a div with some text. We'll change the text later to simulate drift.
// However, note that we compute checksum of outerHTML. If we use a simple div with text, it's fine.
// But the broken embed image might also be considered an embed; its src will be broken.jpg, and we'll have a failed request for that, so it will be reported. Good.
// The layout shift: The script adds a div after a delay, causing shift. We'll wait 1 second after load, so it's captured. The layout shift score might be > 0.
// Now, we need to ensure the test page loads from file://. Some resources like images may have relative paths. We'll use a data URL for the broken image? Actually, broken.jpg won't exist, so it will fail. That's fine. But the file:// protocol may treat relative paths differently. We can use src="broken.jpg" which will resolve to file://broken.jpg relative to the test.html location. That file doesn't exist, so request will fail. Good.
// However, when using file://, the network requests for local files may not trigger `requestfailed`? They might succeed if file exists; not if not. I think file:// requests are not considered network requests by Chromium? Actually, Puppeteer treats them as `document` or `other`? Let's check. Usually, accessing a local file via file:// doesn't go through the network stack, so requestfailed may not fire. That could be problematic for the broken embed demonstration. Alternatively, we could use an http URL that returns 404. But that would require a server. To keep it simple, I'll host a minimal server? That could complicate. Alternatively, we can use an image from a known non-existent URL on a real domain, like `https://example.com/nonexistent.jpg`. That will cause a network error (404). That should trigger requestfailed. So I'll use that. But need internet connectivity. That's okay. We'll assume internet access. If not, test may fail. But we can catch and adjust.
// Better: Use `src="https://httpbin.org/status/404"` to simulate broken. That returns 404. That will trigger requestfailed. Good. And it's a real endpoint.
// But that adds dependency on external service. Might be okay for demo. Or we can use a local HTTP server run by the user? Not needed.
// I'll use `https://httpbin.org/status/404`. That will definitely be 404. However, note that this is not an image; it's a plain response. The img tag will treat it as broken image, which is fine.
// For layout shift, we'll add an image with dimensions undefined but with src="https://picsum.photos/200?random=1" maybe, but that loads and might cause shift if no dimensions? Actually, if we set width/height, it won't shift. So we need an element that appears after login without dimensions. I'll add a script that injects a div with content after a timeout. That div will appear and push other content down.
// Third-party widget: We'll put a div with specific class and some content. We'll also maybe include an iframe from a third-party? But we only need the HTML to compute checksum. If we include an iframe, its content is cross-origin, but outerHTML of the iframe element itself is just the <iframe> tag with src. That is fine. But the iframe might load external content; its outerHTML is static (the tag). So if we change the src attribute, that would be drift. But we could just use a div.
// Let's do: `<div class="third-party-widget" id="tp-widget">Third-party content v1.0</div>`.
// We'll need to set baseline with that exact HTML string. When user runs scanner first time, baseline will be set to the checksum of that outerHTML. Then if they change the inner text or attributes, drift detected.
// Good.
// Now, code adjustments: In scanPage, after we compute checksum, if thirdPartyExists, set thirdPartyChecksum; else null.
// Also, we must ensure we close browser even on error.
// We'll also add some debug logs.
// Finally, output the results as pretty JSON.
// Let's write final scanner.js.
// I'll also include a check: if Puppeteer fails to launch, catch error.
// Now, the baseline file path: I'll put in the same directory as script: `scanner-baseline.json`.
// I'll also make sure that if the baseline file exists, we parse it as JSON; if invalid, we could back up? Not needed.
// Now, about third-party selector: we could allow an environment variable or config file, but keep simple.
// This is a good design.
// Edge case: The page may have multiple third-party widgets; we only consider first? We'll get the first? Actually, we are using `$` which returns first match. We could use `$$` to get all and combine? But baseline would need to handle multiple. For simplicity, we'll only consider the first matching element. Or we could combine all outerHTMLs into one string? Not needed.
// The test page will have exactly one element with class third-party-widget.
// So final code structure:
// - Imports.
// - Constants: THIRD_PARTY_SELECTOR, BASELINE_PATH.
// - Main function: async function main()
// - get target URL from argv or default to test.html
// - load baseline
// - run scanPage (which does puppeteer stuff)
// - compare with baseline to determine drift
// - if baseline update needed, write
// - print report
// - main() catch errors.
// I'll also include a function to read baseline with try/catch.
// Let's code.
// Also, for the broken embed detection, we might have false positives if the embed element's src is not in failedRequests because it might be a data URL or something. That's okay.
// Another nuance: The `requestfailed` event might not include all failures; for example, if an image returns 404, it may still be considered a successful request (HTTP status code != failure) but the resource is considered broken in terms of display. Actually, `requestfailed` is for network-level failures, not HTTP errors. For HTTP errors like 404, the request is considered successful from network perspective, but the resource is not displayed. However, Puppeteer's `requestfailed` error text might include "404 Not Found" if the response has a failure status? Let's check Puppeteer docs: `requestfailed` event is emitted when the request failed, e.g., due to network error, timeout, or user abort. For HTTP error status (4xx, 5xx), it might still be considered a successful network request; the response is received. So img with src 404 may not trigger requestfailed, but the img element's `naturalWidth` will be 0. That would be a better detection: after page load, check images for naturalWidth=0. Similarly for iframes: `contentWindow` may be null if failed? Not reliable. So we need a robust method.
// For broken embeds, maybe better to check the element's state after load: For <img>, check `complete` and `naturalWidth > 0`. For <video>, check `readyState` or `error` event. For <iframe>, check if the load event fired? Could be tricky. But for demo, we can rely on network failures, but that may not catch HTTP errors. To improve, we could also check the response status of the request via `response` event. Puppeteer provides `request` and `response` pairs. We could track all requests and map to responses, then for embed elements, check if the response status is not 200. But that's more complex.
// Since it's a demo, using requestfailed may not detect 404 broken images. But if we use an image with src to a non-existent file on same origin (file://), it might not trigger requestfailed but may cause a file not found error? Actually, file:// may not have a proper response status; the request may just fail? I'm not sure. Using an http 404 URL will trigger a successful HTTP request with status 404, but `requestfailed` may not fire because the network request succeeded (got a response). So the image will still be broken (not displayed). To detect that, we need to check the element's `naturalWidth` after load.
// I'll incorporate both: capture failed requests (network errors) and also check img elements for naturalWidth=0 after load. For other embeds, we could similarly check some properties. But to keep it simple, I'll just handle images with naturalWidth, and for iframes maybe check `contentDocument`? Cross-origin iframes will throw unless we set a timeout; but if the iframe fails to load (e.g., 404), the iframe's `contentWindow` might be null? Actually, if an iframe's src fails to load (like 404), the iframe element's `contentWindow` might still be accessible? I think it's a separate document; if the request fails, the iframe's `contentDocument` may be an empty document or contain an error page? Not sure. But we can also check if the iframe's `src` loaded successfully by listening to its `load` event. That's more complex.
// For demo, the broken embed could be an image that we check via naturalWidth. We'll test with https://httpbin.org/status/404 as img src. That returns 404, image likely not displayed, naturalWidth will be 0. So we can detect that.
// So modify broken embed detection: after page load, we'll evaluate in page to get all img elements and check their naturalWidth, also for other types if possible.
// But we already have embedElements list that includes img. For each img, we could check its naturalWidth via page.evaluate. However, we already have the failedRequests set. We could combine: For img, check naturalWidth. For other tags, we rely on failedRequests? But for iframe, maybe we can check if `contentWindow` is not null? But cross-origin will cause security error. We could try/catch, but that's messy.
// Simpler: Focus on images for broken embed detection; for the demo, we can just include a broken image. That covers the requirement. I'll state that for demonstration we only check img tags. But the requirement says "broken embeds" generally. I can mention that in a full implementation we'd handle more types, but for demo we focus on images.
// I'll adjust: We'll check all img tags for naturalWidth==0 (or !complete). For other embed types, we could skip or also try similar properties. For iframes, we can try to check if `contentDocument` is accessible? Not reliable. Maybe we can rely on network failures for iframes if they are cross-origin? Actually, a 404 iframe will still load an error page from the browser? The iframe might show a browser error page, but the element still has contentWindow. I'd rather not overcomplicate.
// For the demo, I'll implement detection for img tags using naturalWidth. That's straightforward and works for broken images.
// So change: After page load, get all img elements. For each, evaluate: `el.complete && el.naturalWidth === 0`. That indicates broken. We'll also keep the failedRequests set for other types? But we can ignore other types for now. Or we could include iframes if they are same-origin? Not needed.
// I'll implement:
// const brokenImages = await page.$$eval('img', imgs => {
// return imgs.filter(img => img.complete && img.naturalWidth === 0).map(img => ({
// src: img.src,
// tag: 'IMG'
// }));
// });
// That returns array of broken images.
// But what about images that are still loading? We wait for load and then timeout 1s, so they should be complete. For dynamically loaded images after, we might miss. But okay.
// For other embed types, we can skip for demo.
// Alternatively, we could listen to `requestfailed` and also check if the failed request's resourceType is in ['image','media','object','font']? But we want to map to element. However, we can simply report any failed request as potential broken embed? That could be many false positives (e.g., ads blocked). But in a controlled demo, maybe okay. But I think focusing on naturalWidth is more reliable for images.
// I'll combine both: For images, use naturalWidth check. For other types, we could map by URL, but maybe not.
// But to keep code concise, I'll just do images. The requirement says "broken embeds" and images are a type of embed. It's fine.
// I'll adjust the code accordingly.
// But note: The test page will have a broken image using httpbin 404. We'll detect it.
// Now, third-party drift: we'll get the outerHTML of the element with selector. That will include attributes and inner content. We'll compute checksum.
// Now, let's write the final code.
// I'll produce a script named `content-integrity-scanner.js`.
// I'll also provide a test.html file.
// We also need to mention dependencies: Node.js, puppeteer. Provide install command.
// Let's craft the answer.
// In the explanation, I'll describe the approach and architecture.
// Finally, ensure code is executable.
// I'll now generate the answer.
// But I need to compute the expected baseline for test.html? No, because baseline is created on first run. So when user runs scanner first time, it will generate baseline.json with the checksum for that page's third-party widget. That's fine.
// However, the script should not crash if baseline file exists but is malformed. We'll handle.
// Let's code.
// I'll output the scanner script and test page in separate code blocks. Also provide instructions.
// Let's write.
// Note: The script must be run with Node. We'll use top-level await? Node 14+ supports top-level await with ES modules, but we'll use async function main to avoid.
// Code:
// ```
// const puppeteer = require('puppeteer');
// const crypto = require('crypto');
// const fs = require('fs');
// const path = require('path');
// const THIRD_PARTY_SELECTOR = '.third-party-widget';
// const BASELINE_PATH = path.join(__dirname, 'scanner-baseline.json');
// async function scanPage(url) {
// const results = {
// url,
// layoutShiftScore: 0,
// hasLayoutShift: false,
// brokenEmbeds: [],
// hasBrokenEmbeds: false,
// thirdPartyChecksum: null,
// thirdPartyExists: false,
// error: null,
// };
// let browser;
// try {
// browser = await puppeteer.launch({
// headless: 'new',
// args: ['--no-sandbox', '--disable-setuid-sandbox']
// });
// const page = await browser.newPage();
// // Capture network errors for resources (optional)
// const failedRequests = new Set();
// page.on('requestfailed', request => {
// const url = request.url();
// console.log(`[DEBUG] Request failed: ${url} - ${request.failure().errorText}`);
// failedRequests.add(url);
// });
// // Navigate
// await page.goto(url, { waitUntil: 'load' });
// // Wait for any async content to settle; give time for layout shifts to occur
// await page.waitForTimeout(1000);
// // 1. Layout Shift Score (CLS)
// results.layoutShiftScore = await page.evaluate(() => {
// const entries = performance.getEntriesByType('layout-shift');
// let cls = 0;
// for (const entry of entries) {
// if (!entry.hadRecentInput) {
// cls += entry.value;
// }
// }
// return cls;
// });
// // Define threshold for flagging
// results.hasLayoutShift = results.layoutShiftScore > 0.1;
// // 2. Broken Embeds – focus on images for demo
// const brokenImages = await page.$$eval('img', imgs => {
// return imgs.filter(img => img.complete && img.naturalWidth === 0).map(img => ({
// src: img.src,
// tag: 'IMG'
// }));
// });
// results.brokenEmbeds = brokenImages;
// results.hasBrokenEmbeds = brokenImages.length > 0;
// // 3. Third-party drift detection
// const thirdPartyElement = await page.$(THIRD_PARTY_SELECTOR);
// if (thirdPartyElement) {
// results.thirdPartyExists = true;
// const html = await page.$eval(THIRD_PARTY_SELECTOR, el => el.outerHTML);
// results.thirdPartyChecksum = crypto.createHash('md5').update(html).digest('hex');
// } else {
// results.thirdPartyExists = false;
// results.thirdPartyChecksum = null;
// }
// } catch (err) {
// results.error = err.message;
// } finally {
// if (browser) await browser.close();
// }
// return results;
// }
// async function main() {
// // Parse arguments
// const args = process.argv.slice(2);
// let targetUrl = args[0];
// const updateBaseline = args.includes('--update-baseline') || args.includes('-u');
// if (!targetUrl) {
// // Default to local test.html
// const scriptDir = __dirname;
// targetUrl = `file://${path.join(scriptDir, 'test.html')}`;
// console.log(`No URL provided, scanning default test page: ${targetUrl}`);
// }
// // Load baseline if exists
// let baseline = {};
// if (fs.existsSync(BASELINE_PATH)) {
// try {
// baseline = JSON.parse(fs.readFileSync(BASELINE_PATH, 'utf8'));
// } catch (e) {
// console.warn(`Warning: Could not parse baseline file. Starting fresh.`);
// baseline = {};
// }
// }
// // Run scan
// const scanResult = await scanPage(targetUrl);
// if (scanResult.error) {
// console.error(`Scan failed: ${scanResult.error}`);
// process.exit(1);
// }
// // Determine third-party drift
// let thirdPartyDrift = false;
// const expectedChecksum = baseline[targetUrl];
// if (expectedChecksum !== undefined) {
// // Baseline exists for this URL
// if (scanResult.thirdPartyChecksum !== expectedChecksum) {
// thirdPartyDrift = true;
// }
// } else {
// // No baseline entry; drift cannot be determined yet; we will create baseline after reporting if needed.
// // We treat this as no drift (false) for now.
// }
// // Report
// const report = {
// url: scanResult.url,
// metrics: {
// layoutShiftScore: scanResult.layoutShiftScore,
// hasLayoutShift: scanResult.hasLayoutShift,
// brokenEmbedsCount: scanResult.brokenEmbeds.length,
// brokenEmbeds: scanResult.brokenEmbeds,
// },
// thirdParty: {
// exists: scanResult.thirdPartyExists,
// currentChecksum: scanResult.thirdPartyChecksum,
// expectedChecksum: expectedChecksum !== undefined ? expectedChecksum : null,
// driftDetected: thirdPartyDrift,
// },
// baseline: {
// hadBaselineForUrl: expectedChecksum !== undefined,
// baselineUpdated: false,
// }
// };
// // Update baseline if needed
// if (updateBaseline || !(targetUrl in baseline)) {
// // We will set baseline entry. For missing third-party widget, store null.
// baseline[targetUrl] = scanResult.thirdPartyChecksum;
// report.baseline.baselineUpdated = true;
// try {
// fs.writeFileSync(BASELINE_PATH, JSON.stringify(baseline, null, 2));
// console.log(`Baseline ${updateBaseline ? 'updated' : 'created'} for ${targetUrl}`);
// } catch (e) {
// console.error(`Failed to write baseline: ${e.message}`);
// }
// }
// console.log(JSON.stringify(report, null, 2));
// // Exit code based on issues: if any of: layout shift, broken embeds, third-party drift -> non-zero exit for CI.
// if (scanResult.hasLayoutShift || scanResult.hasBrokenEmbeds || thirdPartyDrift) {
// process.exit(1);
// } else {
// process.exit(0);
// }
// }
// main().catch(err => {
// console.error(err);
// process.exit(1);
// });
// ```
// Now, test.html:
// We'll create an HTML file that includes:
// - A header and some paragraphs.
// - A script that after 500ms adds a new div with some content, causing layout shift.
// - An img with src="https://httpbin.org/status/404" (broken).
// - A div with class "third-party-widget" containing some specific text.
// Also, we should ensure the page is scrollable maybe.
// Sample:
// ```
// <!DOCTYPE html>
// <html>
// <head>
// <meta charset="UTF-8">
// <title>Content Integrity Test Page</title>
// <style>
// body { font-family: sans-serif; padding: 20px; }
// .content { max-width: 600px; margin: 0 auto; }
// .shift-element { margin-top: 20px; }
// </style>
// </head>
// <body>
// <div class="content">
// <h1>Test Page for Content Integrity Scanner</h1>
// <p>This page is designed to test the scanner's ability to detect layout shifts, broken embeds, and third-party drift.</p>
// <p>The layout shift will be caused by a dynamic element inserted below.</p>
// <div id="placeholder" class="shift-element">Dynamic content will appear here after 500ms.</div>
// <p>Below is an intentionally broken image (404).</p>
// <img src="https://httpbin.org/status/404" alt="Broken image" width="200" height="200">
// <p>Third-party widget (watch for drift):</p>
// <div class="third-party-widget" id="widget">
// Third-Party Widget v1.0
// </div>
// </div>
// <script>
// // Simulate a layout shift by inserting content after a delay
// setTimeout(() => {
// const placeholder = document.getElementById('placeholder');
// if (placeholder) {
// placeholder.innerHTML = '<strong>New content loaded!</strong><br>This content pushes the rest of the page down, causing layout shift.';
// }
// }, 500);
// </script>
// </body>
// </html>
// ```
// This page will cause a layout shift (the text appears inside placeholder, but that might not cause shift if placeholder already had height? Actually placeholder is empty initially? It says "Dynamic content will appear here after 500ms." That's content already. But we change innerHTML, which may increase height. That could cause shift. Better: Have an empty container with no height, then insert content. Let's adjust:
// `<div id="placeholder" style="height: 0; overflow: hidden;"></div>` maybe? Or just have an empty div that we fill with content that has height. Simpler: have a div with no content initially, but allocate space? Let's restructure:
// We'll have a div with no height, then we inject a div with height. But the placeholder itself might not have height; but its insertion point may be after the paragraph. The script can insert a new element after a certain point, causing shift. Simpler: append a new element to the body or at a specific location causing shift. Actually, the layout shift score is calculated when elements move. If an element expands in place (like a placeholder that was empty with height 0), that could cause shift if it pushes content down. So we can have an empty div, then add content that gives it height. That would shift content below.
// We'll do:
// `<div id="shift-container" style="min-height: 0;"></div>` or just `<div id="shift-container"></div>` and after 500ms, set its HTML to include a large block (like a banner). That will cause shift.
// Let's create: `<div id="shift-container"></div>` initially empty, with maybe margin. Then script injects a `<div class="banner">Important: New content loaded!</div>` with style that gives it height. That will push content down.
// We'll adjust:
// In body: after some content, put: `<div id="shift-container"></div>`
// Script: setTimeout(() => { const container = document.getElementById('shift-container'); const banner = document.createElement('div'); banner.textContent = 'Important: New content loaded!'; banner.style.background = 'yellow'; banner.style.padding = '10px'; container.appendChild(banner); }, 500);
// That will cause a shift because container initially height 0, then after adding banner, it gains height and pushes content below down. That should be captured as layout shift.
// Also ensure that the shift happens after page load? We wait 1 second after load, so it will be captured.
// Good.
// Also broken image: we'll use `<img src="https://httpbin.org/status/404" width="200" height="200" alt="Broken">`. That will load a 404 response and image will have naturalWidth 0. Good.
// Third-party widget: `<div class="third-party-widget" id="widget">Third-Party Widget v1.0</div>`.
// Now, let's produce final files.
// Also, we need to handle the case where test.html is loaded via file://, and the third-party widget is the same as in baseline. First run sets baseline. If user wants to simulate drift, they can edit test.html and change the text of the widget, then run again. The scanner will detect drift because checksum changed.
// Good.
// I'll provide instructions:
// 1. Install dependencies: `npm install puppeteer`
// 2. Run scanner: `node content-integrity-scanner.js` (will use test.html) or `node content-integrity-scanner.js http://example.com`
// 3. For CI, exit code non-zero if issues found.
// I'll mention that for first run, baseline is created. Then modify test.html to see drift.
// Now, ensure code works with Node 16+ (since top-level await? I'm using async main, okay).
// I'll write code in a single file.
// Now, I'll also consider that the test page might be served via file://; the browser will allow file:// but network requests to httpbin.org may be blocked due to CORS? Actually, img src from httpbin should load fine from file://; it's just an image request. CORS not an issue for img. Should be okay.
// Also, note that layout shift detection may not work on file://? I think performance API works.
// Let's produce final answer.
// I'll include explanation then code blocks.</think>
## **Content Integrity Scanner: Design & Implementation**
This scanner checks web pages for three critical issues:
1. **Layout Shifts** – measured via the Cumulative Layout Shift (CLS) metric from the browser’s Layout Instability API.
2. **Broken Embeds** – images (demo) that fail to load (e.g., 404, network error).
3. **Third-Party Drift** – changes in the HTML of a designated third‑party widget compared against a saved baseline.
The scanner uses **Puppeteer** (headless Chrome) to load pages, collect performance data, and inspect the DOM.
---
### **Architecture**
| Step | Action | Tool |
|------|--------|------|
| 1 | Launch headless Chrome | Puppeteer |
| 2 | Capture performance entries for layout shifts | `PerformanceObserver` / `performance.getEntriesByType('layout-shift')` |
| 3 | Detect broken images | `img.complete && img.naturalWidth === 0` |
| 4 | Extract third‑party widget HTML | `page.$eval()` |
| 5 | Compute MD5 checksum of widget HTML | Node `crypto` |
| 6 | Compare with baseline JSON file (per URL) | Local file |
| 7 | Generate JSON report & exit code | Console output |
---
### **How to Use**
1. **Install dependencies**
```bash
npm init -y
npm install puppeteer
-
Create the test page (test.html) – see below.
-
Run the scanner
-
First run (creates baseline):
node content-integrity-scanner.js
It scans test.html and saves scanner-baseline.json.
-
Subsequent runs compare against the baseline.
-
To force a baseline update (e.g., after intentional changes):
node content-integrity-scanner.js --update-baseline
-
Simulate third‑party drift
- Edit the text inside
<div class="third-party-widget"> in test.html and run the scanner again. The report will show thirdParty.driftDetected: true and exit with code 1.
-
Interpreting the report
The scanner outputs a JSON object with:
{
"url": "...",
"metrics": {
"layoutShiftScore": 0.25,
"hasLayoutShift": true,
"brokenEmbedsCount": 1,
"brokenEmbeds": [{ "tag": "IMG", "src": "https://httpbin.org/status/404" }]
},
"thirdParty": {
"exists": true,
"currentChecksum": "e59c...",
"expectedChecksum": "e59c...",
"driftDetected": false
},
"baseline": {
"hadBaselineForUrl": true,
"baselineUpdated": false
}
}
The process exits with code 1 if any issue is found (for CI integration).
Implementation
1. content-integrity-scanner.js
const puppeteer = require('puppeteer');
const crypto = require('crypto');
const fs = require('fs');
const path = require('path');
const THIRD_PARTY_SELECTOR = '.third-party-widget';
const BASELINE_PATH = path.join(__dirname, 'scanner-baseline.json');
async function scanPage(url) {
const results = {
url,
layoutShiftScore: 0,
hasLayoutShift: false,
brokenEmbeds: [],
hasBrokenEmbeds: false,
thirdPartyChecksum: null,
thirdPartyExists: false,
error: null,
};
let browser;
try {
browser = await puppeteer.launch({
headless: 'new',
args: ['--no-sandbox', '--disable-setuid-sandbox'],
});
const page = await browser.newPage();
// Optional: capture failed network requests (non-200 responses may not fire this)
const failedRequests = new Set();
page.on('requestfailed', request => {
console.log(`[DEBUG] Request failed: ${request.url()} - ${request.failure().errorText}`);
failedRequests.add(request.url());
});
// Navigate and wait for load + a short settle period
await page.goto(url, { waitUntil: 'load' });
await page.waitForTimeout(1000); // allow late layout shifts
// 1. Layout Shift Score (CLS)
results.layoutShiftScore = await page.evaluate(() => {
const entries = performance.getEntriesByType('layout-shift');
let cls = 0;
for (const entry of entries) {
if (!entry.hadRecentInput) {
cls += entry.value;
}
}
return cls;
});
results.hasLayoutShift = results.layoutShiftScore > 0.1;
// 2. Broken Embeds – focus on images for demo
const brokenImages = await page.$$eval('img', imgs => {
return imgs.filter(img => img.complete && img.naturalWidth === 0).map(img => ({
src: img.src,
tag: 'IMG',
}));
});
results.brokenEmbeds = brokenImages;
results.hasBrokenEmbeds = brokenImages.length > 0;
// 3. Third-party drift detection
const thirdPartyElement = await page.$(THIRD_PARTY_SELECTOR);
if (thirdPartyElement) {
results.thirdPartyExists = true;
const html = await page.$eval(THIRD_PARTY_SELECTOR, el => el.outerHTML);
results.thirdPartyChecksum = crypto.createHash('md5').update(html).digest('hex');
} else {
results.thirdPartyExists = false;
results.thirdPartyChecksum = null; // widget missing
}
} catch (err) {
results.error = err.message;
} finally {
if (browser) await browser.close();
}
return results;
}
async function main() {
const args = process.argv.slice(2);
let targetUrl = args[0];
const updateBaseline = args.includes('--update-baseline') || args.includes('-u');
if (!targetUrl) {
const scriptDir = __dirname;
targetUrl = `file://${path.join(scriptDir, 'test.html')}`;
console.log(`No URL provided, scanning default test page: ${targetUrl}`);
}
// Load or initialize baseline
let baseline = {};
if (fs.existsSync(BASELINE_PATH)) {
try {
baseline = JSON.parse(fs.readFileSync(BASELINE_PATH, 'utf8'));
} catch (e) {
console.warn(`Warning: Could not parse baseline file. Starting fresh.`);
baseline = {};
}
}
// Perform scan
const scanResult = await scanPage(targetUrl);
if (scanResult.error) {
console.error(`Scan failed: ${scanResult.error}`);
process.exit(1);
}
// Compare third-party checksum with baseline (if exists)
const expectedChecksum = baseline[targetUrl];
let thirdPartyDrift = false;
if (expectedChecksum !== undefined) {
thirdPartyDrift = scanResult.thirdPartyChecksum !== expectedChecksum;
}
// Build report
const report = {
url: scanResult.url,
metrics: {
layoutShiftScore: scanResult.layoutShiftScore,
hasLayoutShift: scanResult.hasLayoutShift,
brokenEmbedsCount: scanResult.brokenEmbeds.length,
brokenEmbeds: scanResult.brokenEmbeds,
},
thirdParty: {
exists: scanResult.thirdPartyExists,
currentChecksum: scanResult.thirdPartyChecksum,
expectedChecksum: expectedChecksum !== undefined ? expectedChecksum : null,
driftDetected: thirdPartyDrift,
},
baseline: {
hadBaselineForUrl: expectedChecksum !== undefined,
baselineUpdated: false,
},
};
// Update baseline if requested or missing
if (updateBaseline || !(targetUrl in baseline)) {
baseline[targetUrl] = scanResult.thirdPartyChecksum;
report.baseline.baselineUpdated = true;
try {
fs.writeFileSync(BASELINE_PATH, JSON.stringify(baseline, null, 2));
console.log(`Baseline ${updateBaseline ? 'updated' : 'created'} for ${targetUrl}`);
} catch (e) {
console.error(`Failed to write baseline: ${e.message}`);
}
}
console.log(JSON.stringify(report, null, 2));
// Exit with non-zero if any issue detected (CI-friendly)
if (scanResult.hasLayoutShift || scanResult.hasBrokenEmbeds || thirdPartyDrift) {
process.exit(1);
}
process.exit(0);
}
main().catch(err => {
console.error(err);
process.exit(1);
});
2. test.html (Example page with intentional issues)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Content Integrity Test Page</title>
<style>
body { font-family: sans-serif; padding: 20px; }
.content { max-width: 600px; margin: 0 auto; }
.banner { background: yellow; padding: 10px; margin: 10px 0; }
</style>
</head>
<body>
<div class="content">
<h1>Test Page for Content Integrity Scanner</h1>
<p>This page tests layout shifts, broken embeds, and third‑party drift.</p>
<p>After 0.5 s a banner appears below, shifting the content.</p>
<!-- Layout shift container (initially empty) -->
<div id="shift-container"></div>
<p>Below is an intentionally broken image (404).</p>
<img src="https://httpbin.org/status/404" alt="Broken image" width="200" height="200">
<p>Third‑party widget (drift detection):</p>
<div class="third-party-widget" id="widget">
Third‑Party Widget v1.0
</div>
</div>
<script>
// Simulate a layout shift by injecting a banner after a delay
setTimeout(() => {
const container = document.getElementById('shift-container');
const banner = document.createElement('div');
banner.className = 'banner';
banner.textContent = 'Important: New content loaded! This causes layout shift.';
container.appendChild(banner);
}, 500);
</script>
</body>
</html>
Notes & Extensibility
- Broken embeds: The demo only checks
<img> tags via naturalWidth. A production version would also handle <iframe>, <video>, <embed>, <object> by checking readyState or contentDocument where possible.
- Third‑party drift: The current approach stores a single checksum per URL for the chosen selector. It can be extended to support multiple selectors or visual regression (screenshot diff).
- CLS threshold – set to
0.1 for flagging; this aligns with Google’s “good” CLS threshold (<0.1).
- Baseline handling – The baseline file (
scanner-baseline.json) lives next to the script. Use --update-baseline to regenerate it after an accepted change.
- CI integration: The script exits with code 1 if any issue is found, making it suitable for automated gating.
You now have a working, self‑contained content integrity scanner. Run it against the test page, then modify the widget text to see drift detection in action!