1. Understand the Goal: The user wants an "Engineer a content integrity scanner detecting layout shifts, broken embeds, and third-party drift." This is a request for software design or code to build a specific tool.
-
Analyze the Intent: The intent is technical implementation of a monitoring tool.
-
Determine the Output Strategy: I should design the architecture and provide a functional prototype (likely Python-based using Selenium or Playwright) that addresses the three specific problems:
- Layout Shifts (CLS).
- Broken Embeds (IFrame/Image checking).
- Third-party Drift (Tracking changes in external resources).
-
Drafting the Solution (Mental Sandbox):
- Tooling: Python + Playwright is good for modern web testing and metrics.
- CLS: Playwright has access to web metrics, or I can use standard
PerformanceObserver JS injection.
- Broken Embeds: Check
response status for iframes/images. Check iframes actually load content.
- Third-party Drift: This requires a baseline. Hashing external scripts/content and comparing against a previous run is the standard approach.
-
Refining the Output Structure:
- Architecture Overview: Explain how the scanner works.
- Python Implementation: A class-based structure is best.
- Key Components:
LayoutShiftMonitor: Uses JS execution to get cumulativeLayoutShift.
EmbedValidator: Checks tags and network requests.
DriftDetector: Hashes 3rd party resources (JS/CSS) to detect changes.
- Usage Example: How to run it.
-
Writing the Code (Mental Draft):
- Imports:
asyncio, playwright.async_api.
- Class
ContentIntegrityScanner:
- Method
scan(url):
- Launch browser.
- Enable network interception (to log 3rd party requests).
- Navigate.
- Inject script to measure CLS.
- Wait for stability.
- Extract results.
- Drift Logic: Maintain a
baseline.json. Compare current hashes of external scripts to baseline.
-
Final Polish: Ensure the code is commented and explains the logic clearly. The "Drift" part is complex, so a simplified explanation of hashing external resources is necessary.
-
Constructing the Response: (Self-correction: Make sure to mention that real-world CLS requires interaction sometimes, but we will simulate idle time).
- Introduction: Scope of the scanner.
- Code: Python + Playwright.
- Explanation: Breakdown of the three detection methods.
- Drift Implementation: specific detail on hashing.
(Self-Correction during drafting): I should provide a complete, runnable script concept, not just snippets. I will use Playwright as it's the modern standard for this type of browser automation.
(Plan):
- Define the Architecture.
- Provide the Python Code (using Playwright).
- Explain the detection logic for each component (CLS, Embeds, Drift).
- Suggest enhancements.
This is a sophisticated quality assurance tool. To build a robust Content Integrity Scanner, we need a headless browser environment that can emulate user behavior, capture rendering metrics, and analyze network activity.
We will use Python with Playwright. Playwright is ideal here because it provides low-level control over the browser's performance metrics (for Layout Shifts) and network interception (for Drift and Broken Embeds).
Architecture Overview
- Layout Shift Detection: We will inject a script to observe the browser's
PerformanceObserver API, specifically listening for layout-shift entries that do not occur during user input (indicating unexpected shifts).
- Broken Embed Detection: We will scan the DOM for
iframe, video, and object tags, then validate their src or data attributes by checking HTTP status codes.
- Third-Party Drift: We will capture all network requests initiated by the page. By comparing the SHA-256 hash of the response body against a "golden master" (baseline) or simply flagging unexpected third-party domains, we detect code drift.
Prerequisites
You will need to install Playwright and the browser binaries:
pip install playwright
playwright install chromium
The Python Implementation
Here is the complete ContentIntegrityScanner class.
import asyncio
import hashlib
import json
from playwright.async_api import async_playwright, Page, Response
from typing import Dict, List, Set, Optional
from dataclasses import dataclass, field
# --- Data Structures ---
@dataclass
class IntegrityReport:
url: str
layout_shift_score: float = 0.0
broken_embeds: List[Dict] = field(default_factory=list)
third_party_requests: List[Dict] = field(default_factory=list)
resource_hashes: Dict[str, str] = field(default_factory=dict) # URL -> Hash
drift_detected: List[str] = field(default_factory=list)
# --- The Scanner ---
class ContentIntegrityScanner:
def __init__(self, baseline_hashes: Dict[str, str] = None, allowed_domains: List[str] = None):
self.baseline_hashes = baseline_hashes or {}
self.allowed_domains = allowed_domains or []
async def scan(self, url: str) -> IntegrityReport:
report = IntegrityReport(url=url)
async with async_playwright() as p:
# Launch browser with logging enabled
browser = await p.chromium.launch()
context = await browser.new_context()
page = await context.new_page()
# 1. Setup Listeners
await self._setup_layout_listener(page, report)
await self._setup_network_listener(page, report)
# 2. Navigate and wait for network to settle
try:
await page.goto(url, wait_until="networkidle", timeout=60000)
except Exception as e:
print(f"Navigation failed: {e}")
return report
# 3. Post-Load Analysis
await self._check_embeds(page, report)
await self._detect_drift(report)
await browser.close()
return report
async def _setup_layout_listener(self, page: Page, report: IntegrityReport):
"""
Injects a script to capture Cumulative Layout Shift (CLS)
via the PerformanceObserver API.
"""
# We capture the shift value inside the browser and expose it to Python
await page.expose_function('reportLayoutShift', lambda v: setattr(report, 'layout_shift_score', report.layout_shift_score + v))
await page.add_init_script("""
let clsScore = 0;
const observer = new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
// Only count unexpected shifts (no user input)
if (!entry.hadRecentInput) {
clsScore += entry.value;
window.reportLayoutShift(entry.value);
}
}
});
observer.observe({ type: 'layout-shift', buffered: true });
""")
async def _setup_network_listener(self, page: Page, report: IntegrityReport):
"""
Intercepts network requests to log 3rd parties and hash content.
"""
async def on_response(response: Response):
request = response.request
url = request.url
# Filter out data URIs and browser internals
if not url.startswith('http'):
return
try:
# Determine if 3rd party (simplified domain check)
req_domain = urlparse(url).netloc
base_domain = urlparse(page.url).netloc
is_third_party = req_domain != base_domain
if is_third_party:
body = await response.body()
content_hash = hashlib.sha256(body).hexdigest()
report.third_party_requests.append({
"url": url,
"type": request.resource_type,
"status": response.status,
"hash": content_hash
})
# Store hash for drift comparison
report.resource_hashes[url] = content_hash
except Exception:
pass # Ignore resources that fail to decode (e.g., binaries, streams)
page.on("response", lambda r: asyncio.create_task(on_response(r)))
async def _check_embeds(self, page: Page, report: IntegrityReport):
"""
Validates iframes and embeds by checking HTTP status.
"""
# Find all iframes
frames = await page.locator('iframe, embed, object').all()
for frame_locator in frames:
src = await frame_locator.get_attribute('src')
if not src:
src = await frame_locator.get_attribute('data')
if src and src.startswith('http'):
try:
# Use the page's context to request just the headers to avoid downloading heavy content twice
status = (await page.request.head(src, timeout=5000)).status
if status >= 400:
report.broken_embeds.append({"url": src, "status": status, "reason": "HTTP Error"})
except Exception as e:
report.broken_embeds.append({"url": src, "status": 0, "reason": str(e)})
def _detect_drift(self, report: IntegrityReport):
"""
Compares current resource hashes against the baseline.
"""
if not self.baseline_hashes:
return
for url, current_hash in report.resource_hashes.items():
known_hash = self.baseline_hashes.get(url)
if known_hash and known_hash != current_hash:
report.drift_detected.append(url)
# --- Utility for URL parsing (simplified) ---
from urllib.parse import urlparse
# --- Execution Example ---
async def main():
# Example Baseline (In prod, load this from a JSON file from a previous 'good' run)
# If you run this once without a baseline, you can save the output as the new baseline.
known_good_hashes = {
"https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js": "fake_known_hash_123"
}
scanner = ContentIntegrityScanner(baseline_hashes=known_good_hashes)
print("Scanning target site...")
report = await scanner.scan("https://example.com") # Replace with target URL
print(f"\n--- Report for {report.url} ---")
print(f"Layout Shift Score (CLS): {report.layout_shift_score:.4f} (Goal: < 0.1)")
print(f"Broken Embeds Found: {len(report.broken_embeds)}")
for item in report.broken_embeds:
print(f" - [X] {item['url']} ({item['reason']})")
print(f"Third-Party Resources: {len(report.third_party_requests)}")
if report.drift_detected:
print(f"!!! DRIFT DETECTED in {len(report.drift_detected)} resources !!!")
for url in report.drift_detected:
print(f" - CHANGED: {url}")
if __name__ == "__main__":
asyncio.run(main())
How It Works
1. Layout Shift Detection (CLS)
The scanner injects a PerformanceObserver into the page context. Unlike simple screenshot comparisons, this captures specific rendering metrics defined by the Core Web Vitals. It sums up entry.value only when !entry.hadRecentInput (shifts caused by clicks are usually valid). A score above 0.1 is generally considered poor.
2. Broken Embed Validation
The scanner locates iframe and embed nodes. Instead of just checking if the attribute exists, it issues a lightweight HEAD request to the URL. This verifies that the server responds with a 200 OK without downloading the entire video or heavy script payload.
3. Third-Party Drift
This is the most complex feature.
- Capture: It intercepts all HTTP responses. If the domain differs from the main page, it classifies it as third-party.
- Hashing: It computes a SHA-256 hash of the response body (the JS/CSS/JSON payload).
- Comparison: It compares this hash against a
baseline_hashes dictionary. If analytics-v1.js (hash abc) suddenly becomes analytics-v1.js (hash xyz), the scanner flags Drift.
Usage Workflow
- Golden Master Run: Run the scanner on a known-good version of your site. Save the
report.resource_hashes to a file (baseline.json).
- CI/CD Integration: In your pipeline, run the scanner. Load
baseline.json into the ContentIntegrityScanner.
- Alerting: If
drift_detected is populated or broken_embeds exists, fail the build or alert the team.