Skip to content

Universal SEO skill for Claude Code. 26 sub-skills + 19 sub-agents covering technical SEO, E-E-A-T, schema, GEO/AEO, agent readiness (Lighthouse Agentic Browsing, WebMCP, llms.txt), backlinks, local SEO, e-commerce, international SEO, Google APIs, and PDF/Excel reporting. 9 optional extensions for live SEO data.

fix(technical,render): sibling certificate false alarm, bounded js_gap output, timed page-side steps for screenshots

Agrici Danielc8a4ed1b4a6b
diff --git a/scripts/capture_screenshot.py b/scripts/capture_screenshot.py
index ec322ef..37d3075 100755
--- a/scripts/capture_screenshot.py
+++ b/scripts/capture_screenshot.py
@@ -12,10 +12,12 @@ taken, both bounded so a page cannot hang the capture:
- scroll-through: the page is scrolled once from top to bottom so lazy
images load, then returned to the top. At most SCROLL_MAX_STEPS steps
- and SCROLL_MAX_MS of wall-clock time; the page height is read once, so
- an infinite-scroll page cannot extend it. Turn off with --no-scroll.
+ and SCROLL_MAX_MS on the way down, and SCROLL_TOTAL_MS of wall-clock
+ time for the whole phase; the page height is read once, so an
+ infinite-scroll page cannot extend it. Turn off with --no-scroll.
- settle: waits up to SETTLE_MAX_MS for finite animations to finish and,
- after a scroll-through, for the images it triggered.
+ after a scroll-through, for the images it triggered (SETTLE_TOTAL_MS of
+ wall-clock time at most).
--hide-overlays is opt-in and off by default: it hides fixed or stuck
floating elements (cookie banners, chat widgets, bottom bars) before the
@@ -25,6 +27,21 @@ overlays. When it is used the result says so.
Neither step opens a new navigation or request path: they only scroll and
restyle the page already loaded behind the url_safety route guard.
+How the page-side steps are bounded
+===================================
+Each of these steps runs a few lines of JavaScript in the page, and the
+page is hostile input: a scroll handler that loops forever blocks its main
+thread for good. ``page.evaluate`` takes no timeout in Playwright's sync
+API, so a call into such a page would never return. No step uses it. Each
+one goes through ``Locator.wait_for_function`` (and ``get_attribute`` to
+read the result back), which take a timeout that the Playwright driver
+enforces with a timer of its own, outside the page. When a step times out,
+or its phase runs out of wall-clock budget, no further page-side step is
+made and the capture goes straight on to the picture, which has its own
+Playwright timeout. The result then says ``scroll_timed_out`` (or
+``timed_out`` under ``settle``, or ``hide_overlays_error``). A Playwright
+without ``Locator.wait_for_function`` skips these steps and says so.
+
Usage:
python capture_screenshot.py https://example.com
python capture_screenshot.py https://example.com --viewport mobile
@@ -35,16 +52,23 @@ Usage:
Output (--json prints {"captures": [...]}, one entry per viewport):
url, output, viewport, success, error as before
full_page True for a full-page capture
- scroll_through None, or {steps, capped, returned_to_top} (plus error)
- settle None, or {waited_ms, animations_pending, images_pending}
+ scroll_through None, or {steps, capped, returned_to_top} (plus error,
+ and timed_out: true when the page stopped answering)
+ scroll_timed_out True when the scroll-through hit its time bound; the
+ picture was still attempted and may lack lazy content
+ settle None (also when skipped after a timeout), or
+ {waited_ms, animations_pending, images_pending}
+ (plus error, and timed_out: true)
hide_overlays True when --hide-overlays was used
overlays_hidden None, or the number of elements hidden for the capture
- (hide_overlays_error is added when hiding failed)
+ (hide_overlays_error is added when hiding failed, timed
+ out or was skipped)
"""
from __future__ import annotations
import argparse
+import itertools
import json
import os
import sys
@@ -93,9 +117,23 @@ SCROLL_REST_MS = 250 # after the return, so scroll handlers can run
SETTLE_MAX_MS = 1500 # wait for finite animations and triggered images
SETTLE_POLL_MS = 100
+# Wall-clock limits for the JavaScript run in the page. The Playwright driver
+# enforces them, so they hold when the page's main thread is stuck.
+JS_STEP_TIMEOUT_MS = 2000 # one driver call (run a snippet, or read its result)
+SCROLL_TOTAL_MS = 9000 # the whole scroll phase: down, back to the top, rest
+SETTLE_TOTAL_MS = SETTLE_MAX_MS + JS_STEP_TIMEOUT_MS
+HIDE_OVERLAYS_MAX_MS = 5000 # the one pass that hides overlays, on a large DOM
+
+# Where a page-side step runs and where it leaves its result for the read.
+_ROOT = ":root"
+_RESULT_ATTR = "data-claude-seo-result"
+_RESULT_MAX_CHARS = 1000
+_CALL_IDS = itertools.count(1)
+
# The snippets below are adapted from web-obs (engine/page_snapshots.py).
-# Each one is synchronous and returns at once; the waiting happens in
-# Python, where it is counted against the bounds above.
+# Each one is synchronous and is written to return at once; the waiting
+# happens in Python, where it is counted against the bounds above. They are
+# never handed to page.evaluate: see _page_step.
# Smooth scrolling (common) turns every jump into a slow glide, so the
# steps would never reach their positions and the picture would be taken
@@ -191,17 +229,102 @@ def _error_text(exc: Exception) -> str:
return f"{type(exc).__name__}: {lines[0][:200] if lines else 'failed'}"
+class _StepTimeout(Exception):
+ """A page-side step did not finish inside its wall-clock limit."""
+
+
+class _Budget:
+ """Wall-clock allowance for one group of page-side steps."""
+
+ def __init__(self, total_ms: float, clock=time.monotonic, # type: ignore[no-untyped-def]
+ step_ms: float = JS_STEP_TIMEOUT_MS) -> None:
+ self._clock = clock
+ self._end = clock() + total_ms / 1000.0
+ self._step_ms = step_ms
+
+ def step_timeout(self) -> int:
+ """Timeout in ms for the next driver call. Raises once the allowance is spent.
+
+ Never 0: Playwright reads a timeout of 0 as "no timeout".
+ """
+ left = int((self._end - self._clock()) * 1000.0)
+ if left < 1:
+ raise _StepTimeout("TimeoutError: the time budget for this phase is spent")
+ return min(int(self._step_ms), left)
+
+
+def _timed(snippet: str) -> str:
+ """Wrap a snippet as a ``Locator.wait_for_function`` expression.
+
+ The wrapper runs the snippet once, leaves its result as JSON on the root
+ element for a second, equally bounded call to read, and returns true so
+ the driver does not poll.
+ """
+ return (
+ "(root, call) => {\n"
+ f" const value = ({snippet})(call.arg);\n"
+ " const result = { id: call.id, value: value === undefined ? null : value };\n"
+ f" root.setAttribute('{_RESULT_ATTR}', JSON.stringify(result));\n"
+ " return true;\n"
+ "}"
+ )
+
+
+def _page_step(page, snippet: str, arg=None, *, budget: _Budget, # type: ignore[no-untyped-def]
+ want_result: bool = True):
+ """Run one snippet in the page under a timeout the Playwright driver enforces.
+
+ ``page.evaluate`` takes no timeout, so a page whose main thread is stuck
+ would block it for good. ``Locator.wait_for_function`` and
+ ``Locator.get_attribute`` carry one, and the driver races the page
+ against its own timer for the whole call, so they give up on time
+ whatever the page does. Raises _StepTimeout when a limit is hit.
+
+ The result is whatever the page left: treat it as untrusted.
+ """
+ root = page.locator(_ROOT)
+ run = getattr(root, "wait_for_function", None)
+ if run is None:
+ raise RuntimeError(
+ "this Playwright has no Locator.wait_for_function, so page-side steps "
+ "cannot be time-limited and are skipped"
+ )
+ call_id = next(_CALL_IDS)
+ try:
+ run(_timed(snippet), arg={"id": call_id, "arg": arg}, timeout=budget.step_timeout())
+ if not want_result:
+ return None
+ raw = root.get_attribute(_RESULT_ATTR, timeout=budget.step_timeout())
+ except PlaywrightTimeout as exc:
+ raise _StepTimeout(_error_text(exc)) from exc
+ # The id shows the result belongs to this call and not to an earlier one.
+ try:
+ if not isinstance(raw, str) or len(raw) > _RESULT_MAX_CHARS:
+ raise ValueError
+ payload = json.loads(raw)
+ if not isinstance(payload, dict) or payload.get("id") != call_id:
+ raise ValueError
+ except (ValueError, RecursionError):
+ raise ValueError("the page-side step left no usable result") from None
+ return payload.get("value")
+
+
def _scroll_through(page, clock=time.monotonic) -> dict: # type: ignore[no-untyped-def]
"""Scroll once down the page so lazy images load, then back to the top.
- Bounded by SCROLL_MAX_STEPS and SCROLL_MAX_MS, whichever comes first;
- ``capped`` is True when a limit cut the scroll short. Never raises: a
- failure is recorded under ``error`` and the capture goes on.
+ The way down is bounded by SCROLL_MAX_STEPS and SCROLL_MAX_MS, whichever
+ comes first; ``capped`` is True when a limit cut it short. The whole
+ phase is bounded by SCROLL_TOTAL_MS, and every page-side step by a
+ driver timeout: when either is hit, ``timed_out`` is set and nothing
+ more is run in the page. Never raises: a failure is recorded under
+ ``error`` and the capture goes on.
"""
info: dict = {"steps": 0, "capped": False, "returned_to_top": False}
+ budget = _Budget(SCROLL_TOTAL_MS, clock)
deadline = clock() + SCROLL_MAX_MS / 1000.0
try:
- dims = page.evaluate(_JS_SCROLL_PREPARE) or {}
+ dims = _page_step(page, _JS_SCROLL_PREPARE, budget=budget)
+ dims = dims if isinstance(dims, dict) else {}
height = int(dims.get("height") or 0)
step = max(1, int(dims.get("step") or 0))
# The first screen is already on display, so start one step down.
@@ -210,35 +333,46 @@ def _scroll_through(page, clock=time.monotonic) -> dict: # type: ignore[no-unty
if info["steps"] >= SCROLL_MAX_STEPS or clock() >= deadline:
info["capped"] = True
break
- page.evaluate(_JS_SCROLL_TO, y)
+ _page_step(page, _JS_SCROLL_TO, y, budget=budget, want_result=False)
page.wait_for_timeout(SCROLL_PAUSE_MS)
info["steps"] += 1
y += step
+ except _StepTimeout as exc:
+ info["timed_out"] = True
+ info["error"] = str(exc)
+ return info # the page is not answering: do not ask it to scroll back
except Exception as exc:
info["error"] = _error_text(exc)
try:
for _ in range(SCROLL_TOP_RETRIES):
- if not page.evaluate(_JS_SCROLL_TO, 0):
+ if not _page_step(page, _JS_SCROLL_TO, 0, budget=budget):
info["returned_to_top"] = True
break
page.wait_for_timeout(SCROLL_TOP_PAUSE_MS)
if info["steps"]:
page.wait_for_timeout(SCROLL_REST_MS)
+ except _StepTimeout as exc:
+ info["timed_out"] = True
+ info.setdefault("error", str(exc))
except Exception as exc:
info.setdefault("error", _error_text(exc))
return info
-def _settle(page, wait_images: bool) -> dict: # type: ignore[no-untyped-def]
+def _settle(page, wait_images: bool, clock=time.monotonic) -> dict: # type: ignore[no-untyped-def]
"""Wait up to SETTLE_MAX_MS for finite animations (and images) to finish.
The ``*_pending`` counts are what was still unfinished when the wait
- ended. Never raises.
+ ended. Bounded by SETTLE_TOTAL_MS of wall-clock time and a driver
+ timeout per page-side step; ``timed_out`` is set when one is hit.
+ Never raises.
"""
info: dict = {"waited_ms": 0, "animations_pending": 0, "images_pending": 0}
+ budget = _Budget(SETTLE_TOTAL_MS, clock)
try:
while True:
- pending = page.evaluate(_JS_PENDING) or {}
+ pending = _page_step(page, _JS_PENDING, budget=budget)
+ pending = pending if isinstance(pending, dict) else {}
info["animations_pending"] = int(pending.get("animations") or 0)
info["images_pending"] = int(pending.get("images") or 0) if wait_images else 0
busy = info["animations_pending"] or info["images_pending"]
@@ -246,11 +380,25 @@ def _settle(page, wait_images: bool) -> dict: # type: ignore[no-untyped-def]
break
page.wait_for_timeout(SETTLE_POLL_MS)
info["waited_ms"] += SETTLE_POLL_MS
+ except _StepTimeout as exc:
+ info["timed_out"] = True
+ info["error"] = str(exc)
except Exception as exc:
info["error"] = _error_text(exc)
return info
+def _hide_overlays(page, clock=time.monotonic) -> dict: # type: ignore[no-untyped-def]
+ """Hide floating elements; returns the result keys to merge. Never raises."""
+ budget = _Budget(HIDE_OVERLAYS_MAX_MS, clock, step_ms=HIDE_OVERLAYS_MAX_MS)
+ try:
+ return {"overlays_hidden": int(_page_step(page, _JS_HIDE_OVERLAYS, budget=budget) or 0)}
+ except _StepTimeout as exc:
+ return {"overlays_hidden": 0, "hide_overlays_error": str(exc)}
+ except Exception as exc:
+ return {"overlays_hidden": 0, "hide_overlays_error": _error_text(exc)}
+
+
def capture_screenshot(
url: str,
output_path: str,
@@ -285,6 +433,7 @@ def capture_screenshot(
"error": None,
"full_page": full_page,
"scroll_through": None,
+ "scroll_timed_out": False,
"settle": None,
"hide_overlays": hide_overlays,
"overlays_hidden": None,
@@ -312,6 +461,7 @@ def capture_screenshot(
vp = VIEWPORTS[viewport]
route_handler = make_safe_playwright_route_handler()
+ loaded = False
try:
with sync_playwright() as p:
@@ -330,21 +480,28 @@ def capture_screenshot(
# Navigate and wait for network idle
page.goto(url, wait_until="networkidle", timeout=timeout)
+ loaded = True
# Wait a bit more for any lazy-loaded content
page.wait_for_timeout(1000)
+ # Once a page-side step has timed out the page is not answering:
+ # the steps left are skipped and the picture is tried at once.
+ stalled = False
if full_page:
if scroll_through:
result["scroll_through"] = _scroll_through(page)
- result["settle"] = _settle(page, wait_images=scroll_through)
-
- if hide_overlays:
- try:
- result["overlays_hidden"] = int(page.evaluate(_JS_HIDE_OVERLAYS) or 0)
- except Exception as exc:
- result["overlays_hidden"] = 0
- result["hide_overlays_error"] = _error_text(exc)
+ stalled = bool(result["scroll_through"].get("timed_out"))
+ result["scroll_timed_out"] = stalled
+ if not stalled:
+ result["settle"] = _settle(page, wait_images=scroll_through)
+ stalled = bool(result["settle"].get("timed_out"))
+
+ if hide_overlays and stalled:
+ result["overlays_hidden"] = 0
+ result["hide_overlays_error"] = "skipped: an earlier page-side step timed out"
+ elif hide_overlays:
+ result.update(_hide_overlays(page))
# Capture screenshot
page.screenshot(path=output_path, full_page=full_page)
@@ -353,7 +510,12 @@ def capture_screenshot(
browser.close()
except PlaywrightTimeout:
- result["error"] = f"Page load timed out after {timeout}ms"
+ # After the load, only the screenshot can time out here: the page-side
+ # steps record their own timeouts and never raise.
+ if loaded:
+ result["error"] = "Screenshot timed out: the page did not answer in time"
+ else:
+ result["error"] = f"Page load timed out after {timeout}ms"
except Exception as e:
result["error"] = str(e)
@@ -443,6 +605,12 @@ def main():
)
captures.append(result)
+ if result.get("scroll_timed_out"):
+ print(
+ " scroll-through timed out: the page stopped answering, "
+ "lazy content may be missing",
+ file=progress,
+ )
if result["success"]:
print(f" ✓ Saved to {output_path}", file=progress)
if args.hide_overlays:
diff --git a/scripts/render_page.py b/scripts/render_page.py
index 62c7ba2..b2be9a5 100644
--- a/scripts/render_page.py
+++ b/scripts/render_page.py
@@ -73,6 +73,12 @@ Words are every text token outside script, style, noscript, template and
head; hidden elements are not detected. The share limits (``JS_GAP_*``) are
this tool's heuristics, not Google rules.
+Every string in ``js_gap`` that comes from the page (schema type names,
+title, canonical, robots directives, H1 text, and what ``reasons`` quotes)
+has its whitespace collapsed and is cut at a ``JS_GAP_MAX_*`` length, and
+every list has an item limit. ``--max-text`` does not apply to ``js_gap``;
+these limits keep the whole object to about 24,000 characters of JSON.
+
SSRF
====
The URL is validated via :func:`url_safety.validate_url_strict` before
@@ -202,7 +208,9 @@ JS_GAP_LINKS_MIN = 3 # and at least this many such links
JS_GAP_MAX_ITEMS = 12 # schema types, H1 texts, robots directives
JS_GAP_MAX_CANONICALS = 5
JS_GAP_MAX_TEXT = 300 # characters kept per title, H1 or canonical
+JS_GAP_MAX_NAME = 80 # characters kept per schema type name or robots directive
JS_GAP_REASON_TEXT = 80 # characters of page text quoted inside a reason
+JS_GAP_REASON_ITEMS = 5 # schema type names listed inside a reason
# The comparison parses both versions again. Past this size it is skipped
# (js_gap stays None, with a render diagnostic) so a huge DOM cannot stall it.
JS_GAP_MAX_HTML_CHARS = 5_000_000
@@ -345,8 +353,9 @@ def _is_spa(raw_html: Optional[str]) -> bool:
return False
-def _clean_text(value: object) -> str:
- return _WHITESPACE.sub(" ", str(value or "")).strip()[:JS_GAP_MAX_TEXT]
+def _clean_text(value: object, limit: Optional[int] = None) -> str:
+ """Page text for js_gap: whitespace collapsed, cut at ``limit`` characters."""
+ return _WHITESPACE.sub(" ", str(value or "")).strip()[:limit or JS_GAP_MAX_TEXT]
def _gap_signals(html: str) -> tuple[dict, dict]:
@@ -360,9 +369,14 @@ def _gap_signals(html: str) -> tuple[dict, dict]:
# Dicts keep first-seen order and make de-duplication linear, so a page
# with a huge number of distinct values cannot slow the comparison down.
+ # A type name is page text like any other: cleaned and cut before it is
+ # kept, so a huge @type value cannot ride into the output.
schema_types: dict[str, None] = {}
for block in _extract_json_ld(html, soup=soup)["blocks"]:
- schema_types.update(dict.fromkeys(block.get("types") or []))
+ for name in block.get("types") or []:
+ name = _clean_text(name, JS_GAP_MAX_NAME)
+ if name:
+ schema_types[name] = None
# An <svg><title> is an accessible name, not the document title.
title = None
@@ -385,7 +399,7 @@ def _gap_signals(html: str) -> tuple[dict, dict]:
if str(tag.get("name") or "").strip().lower() != "robots":
continue
for directive in str(tag.get("content") or "").lower().split(","):
- directive = _clean_text(directive)
+ directive = _clean_text(directive, JS_GAP_MAX_NAME)
if directive:
robots[directive] = None
@@ -515,7 +529,10 @@ def js_gap_reasons(gap: Optional[dict]) -> list[str]:
if diff["schema_types_only_rendered"]:
reasons.append(
"structured data appears only after JavaScript: "
- + ", ".join(diff["schema_types_only_rendered"][:5])
+ + ", ".join(
+ _quoted(name)
+ for name in diff["schema_types_only_rendered"][:JS_GAP_REASON_ITEMS]
+ )
)
if diff["h1_only_rendered"]:
reasons.append(
diff --git a/scripts/transport_check.py b/scripts/transport_check.py
index 2e54a6a..5727f2f 100644
--- a/scripts/transport_check.py
+++ b/scripts/transport_check.py
@@ -60,8 +60,11 @@ Result JSON::
"first_hop_same_host", "permanent", "hops",
"final_url", "error"},
"www": {"host", "sibling_host", "host_final_url",
- "sibling_final_url", "sibling_resolves", "same_final_url",
- "error"}
+ "sibling_final_url", "sibling_resolves",
+ "sibling_tls_error", # true: the counterpart's own HTTPS
+ # request failed on its certificate
+ # or TLS; null: it was not fetched
+ "same_final_url", "error"}
},
"findings": [{"id", "severity", "message", "evidence"}],
"summary": {"critical", "high", "medium", "low", "info"}
@@ -70,6 +73,13 @@ Result JSON::
A refused or malformed target prints ``{"url": ..., "error": ...}`` instead.
Cookies are reported by NAME only. A cookie value never enters the output.
+``covers_sibling: false`` alone is not a finding: the www and the bare host
+often serve one certificate each. ``tls-sibling-not-covered`` is reported
+only when the counterpart's own HTTPS request also failed with a certificate
+or TLS error (``sibling_tls_error``). A counterpart that does not resolve,
+times out or refuses the connection is ``www-sibling-unreachable`` (Info)
+with the reason, never a certificate finding.
+
Safety
======
The target is validated with ``url_safety.validate_url_strict`` before any
@@ -105,6 +115,8 @@ from datetime import datetime, timezone
from typing import Optional
from urllib.parse import urlparse
+from requests.exceptions import SSLError as RequestsSSLError
+
_SCRIPTS_DIR = os.path.dirname(os.path.abspath(__file__))
if _SCRIPTS_DIR not in sys.path:
sys.path.insert(0, _SCRIPTS_DIR)
@@ -675,7 +687,8 @@ def _fetch(url: str, timeout: float) -> dict:
apart from ``headers`` so a cookie value cannot ride along into output.
"""
record: dict = {"url": url, "final_url": None, "status": None, "hops": [],
- "headers": {}, "set_cookies": [], "error": None}
+ "headers": {}, "set_cookies": [], "error": None,
+ "tls_error_url": None}
response = None
try:
response = safe_requests_get(url, timeout=timeout, allow_redirects=True, stream=True)
@@ -695,6 +708,11 @@ def _fetch(url: str, timeout: float) -> dict:
record["error"] = _clip(f"url_safety: {exc}", 300)
except Exception as exc: # requests / urllib3 errors: report, never raise
record["error"] = _clip(f"{type(exc).__name__}: {exc}", 300)
+ # Judged by exception type, never by the error text. requests names
+ # the hop that failed; without it the failure is on ``url`` itself.
+ if isinstance(exc, (ssl.SSLError, RequestsSSLError)):
+ failed = getattr(getattr(exc, "request", None), "url", None)
+ record["tls_error_url"] = _clip(failed or url, 500)
finally:
if response is not None:
response.close()
@@ -705,6 +723,22 @@ def _url_host(host: str) -> str:
return f"[{host}]" if ":" in host else host
+def _tls_failed_on(record: dict, host: str) -> bool:
+ """True when ``record``'s fetch failed on TLS at an https URL of ``host``.
+
+ A TLS failure on another host later in the redirect chain says nothing
+ about the certificate ``host`` serves, so it does not count.
+ """
+ failed = record.get("tls_error_url")
+ if not failed:
+ return False
+ try:
+ parsed = urlparse(failed)
+ return parsed.scheme == "https" and normalize_hostname(parsed.hostname or "") == host
+ except ValueError: # includes URLSafetyError: an unusable URL is no evidence
+ return False
+
+
def _same_url(left: Optional[str], right: Optional[str]) -> Optional[bool]:
if not left or not right:
return None
@@ -767,6 +801,7 @@ def check_redirects(url: str, timeout: float = 10.0, primary: Optional[dict] = N
www_check = {"host": host, "sibling_host": sibling,
"host_final_url": host_record["final_url"],
"sibling_final_url": None, "sibling_resolves": False,
+ "sibling_tls_error": None,
"same_final_url": None, "error": host_record["error"]}
try:
validate_url_strict(sibling_url)
@@ -776,6 +811,7 @@ def check_redirects(url: str, timeout: float = 10.0, primary: Optional[dict] = N
www_check["sibling_resolves"] = True
sibling_record = _fetch(sibling_url, timeout)
www_check["sibling_final_url"] = sibling_record["final_url"]
+ www_check["sibling_tls_error"] = _tls_failed_on(sibling_record, sibling)
www_check["error"] = www_check["error"] or sibling_record["error"]
www_check["same_final_url"] = _same_url(host_record["final_url"],
sibling_record["final_url"])
@@ -848,11 +884,17 @@ def _tls_findings(tls: dict, redirects: dict) -> list[dict]:
out.append(_finding("tls-old-protocol", "Medium",
"The server negotiated a TLS version older than 1.2.",
{"protocol": tls["protocol"]}))
- if tls.get("covers_sibling") is False and redirects.get("www", {}).get("sibling_resolves"):
+ # A certificate that does not name the counterpart is normal when the
+ # counterpart serves its own. It is a finding only with evidence that the
+ # counterpart is broken over TLS: its own HTTPS request failed that way.
+ www = redirects.get("www", {})
+ if tls.get("covers_sibling") is False and www.get("sibling_tls_error") is True:
out.append(_finding("tls-sibling-not-covered", "Medium",
- "The certificate does not cover the www or non-www counterpart, "
- "which resolves in DNS.",
- {"sibling_host": tls.get("sibling_host")}))
+ "The www or non-www counterpart fails its HTTPS request with a "
+ "certificate or TLS error, and this host's certificate does not "
+ "cover it.",
+ {"sibling_host": tls.get("sibling_host"),
+ "error": www.get("error")}))
return out
diff --git a/tests/test_capture_screenshot_hygiene.py b/tests/test_capture_screenshot_hygiene.py
index 3e3fe2e..8c746b2 100644
--- a/tests/test_capture_screenshot_hygiene.py
+++ b/tests/test_capture_screenshot_hygiene.py
@@ -4,11 +4,17 @@ Playwright is mocked the way tests/test_render_page.py does it: a fake page
records every call in order, and the context is built by the real
url_safety.new_guarded_context, so the tests also prove the guards are still
installed. No browser and no network.
+
+Page-side steps must go through calls that carry a driver-enforced timeout
+(Locator.wait_for_function, Locator.get_attribute). The fake records every
+timeout it is given, and an autouse fixture fails any test in which
+page.evaluate, which takes no timeout, was called.
"""
from __future__ import annotations
import json
+import re
import sys
from pathlib import Path
from types import SimpleNamespace
@@ -23,41 +29,104 @@ import url_safety # noqa: E402
URL = "https://site.example/"
+class FakeRoot:
+ """The locator the page-side steps run through; every call carries a timeout."""
+
+ def __init__(self, page: FakePage) -> None:
+ self._page = page
+
+ def wait_for_function(self, expression, *, arg=None, timeout=None):
+ page = self._page
+ snippet = {cs._timed(known): known for known in SNIPPETS}[expression]
+ name = SNIPPETS[snippet]
+ page.timeouts.append((name, timeout))
+ page.calls.append((name, arg["arg"]))
+ page.spend(name, timeout, "Locator.wait_for_function")
+ if page.fail == name:
+ raise RuntimeError("Execution context was destroyed\nstack line")
+ value = page.run_snippet(snippet, arg["arg"])
+ page.attribute = json.dumps({"id": arg["id"], "value": value})
+
+ def get_attribute(self, name, *, timeout=None):
+ page = self._page
+ assert name == cs._RESULT_ATTR
+ page.timeouts.append(("read", timeout))
+ page.spend("read", timeout, "Locator.get_attribute")
+ return page.attribute
+
+
class FakePage:
- """Records calls in order; answers the hygiene snippets like a page would."""
+ """Records calls in order; answers the hygiene snippets like a page would.
+
+ ``calls`` holds one entry per page-side step, as it did when the steps
+ went through page.evaluate; the read of a step's result is not a step.
+ """
+
+ instances: list[FakePage] = []
- def __init__(self, *, height=5000, step=1000, pending=(), overlays=3, top_lag=(), fail=None):
+ def __init__(self, *, height=5000, step=1000, pending=(), overlays=3, top_lag=(),
+ fail=None, hang=None, cost_ms=None):
self.height = height
self.step = step
self.pending = list(pending) # successive _JS_PENDING answers; last one repeats
self.overlays = overlays
self.top_lag = list(top_lag) # scrollY values reported before the page is at 0
self.fail = fail # snippet whose evaluation raises
+ self.hang = hang # step that never answers: "prepare", ..., or "read"
+ self.hang_everything = False # a stuck main thread also stalls the picture
+ self.cost_ms = dict(cost_ms or {}) # fake time a step takes, by name
+ self.now = 0.0 # fake clock in seconds, moved by spend() and waits
+ self.attribute = None
self.calls: list[tuple] = []
+ self.timeouts: list[tuple] = [] # (step name or "read", timeout in ms)
+ self.untimed: list[tuple] = []
self.routes: list[tuple] = []
+ FakePage.instances.append(self)
+
+ def clock(self) -> float:
+ return self.now
+
+ def spend(self, name, timeout, api) -> None:
+ """Behave like the driver: give up when the step outlasts its timeout."""
+ assert isinstance(timeout, (int, float)) and timeout >= 1, (name, timeout)
+ cost = self.cost_ms.get(name, 0)
+ if self.hang == name or cost > timeout:
+ self.now += timeout / 1000
+ # The wording Playwright 1.65 uses, call log included.
+ raise cs.PlaywrightTimeout(
+ f"{api}: Timeout {timeout}ms exceeded.\nCall log:\n - waiting for locator(':root')"
+ )
+ self.now += cost / 1000
+
+ def locator(self, selector):
+ assert selector == cs._ROOT
+ return FakeRoot(self)
def route(self, pattern, handler):
self.routes.append((pattern, handler))
def goto(self, url, **kwargs):
self.calls.append(("goto", url, kwargs))
+ if self.hang == "goto":
+ raise cs.PlaywrightTimeout("Page.goto: Timeout 30000ms exceeded.")
def wait_for_timeout(self, ms):
self.calls.append(("wait", ms))
+ self.now += ms / 1000
def screenshot(self, **kwargs):
self.calls.append(("screenshot", kwargs))
+ if self.hang == "screenshot" or self.hang_everything:
+ raise cs.PlaywrightTimeout("Page.screenshot: Timeout 30000ms exceeded.")
- def evaluate(self, snippet, arg=None):
- name = {
- cs._JS_SCROLL_PREPARE: "prepare",
- cs._JS_SCROLL_TO: "scroll_to",
- cs._JS_PENDING: "pending",
- cs._JS_HIDE_OVERLAYS: "hide_overlays",
- }[snippet]
- self.calls.append((name, arg))
- if self.fail == name:
- raise RuntimeError("Execution context was destroyed\nstack line")
+ def evaluate(self, *args, **kwargs):
+ # No timeout: a stuck page would block this for good. Recorded, because
+ # the code under test swallows exceptions from page-side steps.
+ self.untimed.append(args)
+ raise AssertionError("page.evaluate takes no timeout and must not be used")
+
+ def run_snippet(self, snippet, arg=None):
+ name = SNIPPETS[snippet]
if name == "prepare":
return {"height": self.height, "step": self.step}
if name == "scroll_to":
@@ -77,6 +146,26 @@ class FakePage:
return sum(call[1] for call in self.calls if call[0] == "wait")
+SNIPPETS = {
+ cs._JS_SCROLL_PREPARE: "prepare",
+ cs._JS_SCROLL_TO: "scroll_to",
+ cs._JS_PENDING: "pending",
+ cs._JS_HIDE_OVERLAYS: "hide_overlays",
+}
+STEP_NAMES = ("prepare", "scroll_to", "pending", "hide_overlays")
+
+
[email protected](autouse=True)
+def no_untimed_page_calls():
+ """No test may end with an untimed call into the page, or a call without a timeout."""
+ FakePage.instances.clear()
+ yield
+ for page in FakePage.instances:
+ assert page.untimed == [], "page.evaluate was called; it has no timeout"
+ for name, timeout in page.timeouts:
+ assert 1 <= timeout <= cs.HIDE_OVERLAYS_MAX_MS, (name, timeout)
+
+
class FakeManager:
def __init__(self, page):
page.context_kwargs = None
@@ -190,25 +279,27 @@ def test_scroll_steps_are_capped_on_an_endless_page(monkeypatch) -> None:
def test_height_is_read_once_so_a_growing_page_cannot_extend_the_scroll() -> None:
page = FakePage(height=3000, step=1000)
- original = page.evaluate
+ original = page.run_snippet
def growing(snippet, arg=None):
answer = original(snippet, arg)
page.height += 5000 # infinite scroll: the page is taller after every call
return answer
- page.evaluate = growing
+ page.run_snippet = growing
info = cs._scroll_through(page)
assert info == {"steps": 2, "capped": False, "returned_to_top": True}
assert page.names().count("prepare") == 1
def test_scroll_stops_at_the_time_budget() -> None:
- page = FakePage(height=10**9, step=1000)
- ticks = iter(range(0, 1000, 2)) # the fake clock advances 2 s per reading
- info = cs._scroll_through(page, clock=lambda: float(next(ticks)))
- # Budget is SCROLL_MAX_MS (6 s): readings at 2 s and 4 s pass, 6 s stops it.
- assert info == {"steps": 2, "capped": True, "returned_to_top": True}
+ # The fake clock moves when the page is used: every scroll step takes 1.5 s
+ # and its pause 0.12 s. Budget is SCROLL_MAX_MS (6 s): steps start at 0 s,
+ # 1.62 s, 3.24 s and 4.86 s, and the check at 6.48 s stops the scroll.
+ page = FakePage(height=10**9, step=1000, cost_ms={"scroll_to": 1500})
+ info = cs._scroll_through(page, clock=page.clock)
+ assert info == {"steps": 4, "capped": True, "returned_to_top": True}
+ assert page.now <= cs.SCROLL_TOTAL_MS / 1000
def test_return_to_top_retries_are_bounded() -> None:
@@ -271,6 +362,247 @@ def test_hygiene_failure_never_fails_the_capture(monkeypatch) -> None:
assert result["scroll_through"]["returned_to_top"] is False
+# ---------------------------------------------------------------------------
+# A page whose main thread is stuck: every page-side step is time-limited
+# ---------------------------------------------------------------------------
+
+
+def test_worst_case_wall_clock_is_the_sum_of_the_phase_budgets() -> None:
+ # The waits counted above are what a healthy page costs. The ceiling with a
+ # slow or stuck page is the budgets, which also cover the page-side steps.
+ healthy_scroll_ms = (
+ cs.SCROLL_MAX_MS + cs.SCROLL_PAUSE_MS
+ + cs.SCROLL_TOP_RETRIES * cs.SCROLL_TOP_PAUSE_MS + cs.SCROLL_REST_MS
+ )
+ assert healthy_scroll_ms + cs.JS_STEP_TIMEOUT_MS <= cs.SCROLL_TOTAL_MS
+ assert cs.SETTLE_TOTAL_MS == cs.SETTLE_MAX_MS + cs.JS_STEP_TIMEOUT_MS
+ assert cs.SCROLL_TOTAL_MS + cs.SETTLE_TOTAL_MS + cs.HIDE_OVERLAYS_MAX_MS == 17500
+
+
[email protected]("stuck", ["prepare", "scroll_to", "read"])
+def test_stuck_scroll_step_times_out_and_the_picture_is_still_tried(monkeypatch, stuck) -> None:
+ page = FakePage(hang=stuck)
+ result = _capture(monkeypatch, page, full_page=True, hide_overlays=True)
+ # The screenshot is still attempted, and the result says what happened.
+ assert page.names()[-1] == "screenshot"
+ assert result["success"] is True and result["error"] is None
+ assert result["scroll_timed_out"] is True
+ info = result["scroll_through"]
+ assert info["timed_out"] is True
+ assert info["returned_to_top"] is False
+ api = "get_attribute" if stuck == "read" else "wait_for_function"
+ assert info["error"] == (
+ f"TimeoutError: Locator.{api}: Timeout {cs.JS_STEP_TIMEOUT_MS}ms exceeded."
+ )
+ # Nothing else is asked of a page that stopped answering.
+ assert page.timeouts[-1][0] == stuck
+ assert "pending" not in page.names() and "hide_overlays" not in page.names()
+ assert result["settle"] is None
+ assert result["overlays_hidden"] == 0
+ assert result["hide_overlays_error"] == "skipped: an earlier page-side step timed out"
+ # One driver timeout, not one per remaining step.
+ assert page.now == 1 + cs.JS_STEP_TIMEOUT_MS / 1000
+
+
+def test_page_that_gets_stuck_part_way_down_stops_the_scroll_at_once(monkeypatch) -> None:
+ page = FakePage(height=10**9, step=1000)
+ answered = []
+ original = page.spend
+
+ def stuck_after_three(name, timeout, api):
+ if name == "scroll_to" and answered.count("scroll_to") >= 3:
+ page.hang = "scroll_to" # the scroll handler now loops forever
+ answered.append(name)
+ return original(name, timeout, api)
+
+ page.spend = stuck_after_three
+ result = _capture(monkeypatch, page, full_page=True)
+ assert result["scroll_through"]["steps"] == 3
+ assert result["scroll_through"]["timed_out"] is True
+ assert result["scroll_timed_out"] is True
+ assert page.names().count("scroll_to") == 4 # three answered, one timed out, no more
+ assert page.names()[-1] == "screenshot"
+
+
+def test_picture_that_also_times_out_is_a_failed_capture_that_says_why(monkeypatch) -> None:
+ # With the main thread stuck for good the screenshot runs into its own
+ # Playwright timeout. The capture ends, and the result names both facts.
+ page = FakePage(hang="scroll_to")
+ page.hang_everything = True
+ result = _capture(monkeypatch, page, full_page=True)
+ assert page.names()[-1] == "screenshot"
+ assert result["success"] is False
+ assert result["error"] == "Screenshot timed out: the page did not answer in time"
+ assert result["scroll_timed_out"] is True
+
+ # A navigation timeout keeps its own message.
+ page = FakePage(hang="goto")
+ result = _capture(monkeypatch, page, full_page=True, timeout=1234)
+ assert result["error"] == "Page load timed out after 1234ms"
+ assert result["scroll_timed_out"] is False
+ assert "screenshot" not in page.names()
+
+
+def test_stuck_settle_step_is_flagged_and_overlays_are_skipped(monkeypatch) -> None:
+ page = FakePage(hang="pending")
+ result = _capture(monkeypatch, page, full_page=True, hide_overlays=True)
+ assert result["scroll_through"] == {"steps": 4, "capped": False, "returned_to_top": True}
+ assert result["scroll_timed_out"] is False
+ assert result["settle"]["timed_out"] is True
+ assert result["settle"]["error"].startswith(
+ "TimeoutError: Locator.wait_for_function: Timeout ")
+ assert page.names().count("pending") == 1
+ assert "hide_overlays" not in page.names()
+ assert result["hide_overlays_error"] == "skipped: an earlier page-side step timed out"
+ assert page.names()[-1] == "screenshot" and result["success"] is True
+
+
+def test_stuck_hide_overlays_is_reported_and_the_picture_is_still_tried(monkeypatch) -> None:
+ page = FakePage(hang="hide_overlays")
+ result = _capture(monkeypatch, page, hide_overlays=True)
+ assert page.names() == ["goto", "wait", "hide_overlays", "screenshot"]
+ assert result["overlays_hidden"] == 0
+ # The whole allowance for this step, less the instant it took to get here.
+ waited = re.fullmatch(r"TimeoutError: Locator\.wait_for_function: Timeout (\d+)ms exceeded\.",
+ result["hide_overlays_error"])
+ assert waited and cs.HIDE_OVERLAYS_MAX_MS - 100 <= int(waited[1]) <= cs.HIDE_OVERLAYS_MAX_MS
+ assert result["scroll_timed_out"] is False and result["success"] is True
+
+
+def test_every_page_side_call_carries_a_driver_timeout(monkeypatch) -> None:
+ page = FakePage(
+ height=10**9, top_lag=[900, 300], overlays=2,
+ pending=[{"animations": 1, "images": 1}, {"animations": 0, "images": 0}],
+ )
+ result = _capture(monkeypatch, page, full_page=True, hide_overlays=True)
+ assert result["success"] is True and result["overlays_hidden"] == 2
+ steps = [name for name in page.names() if name in STEP_NAMES]
+ assert set(steps) == set(STEP_NAMES)
+ # One timeout per step, plus one per result that was read back; the scroll
+ # steps on the way down need no result.
+ assert [name for name, _timeout in page.timeouts if name != "read"] == steps
+ reads = sum(1 for name, _timeout in page.timeouts if name == "read")
+ assert reads == len(steps) - cs.SCROLL_MAX_STEPS
+ scroll_and_settle = [t for name, t in page.timeouts if name != "hide_overlays"][:-1]
+ assert all(1 <= timeout <= cs.JS_STEP_TIMEOUT_MS for timeout in scroll_and_settle)
+ assert page.untimed == []
+
+
+def test_scroll_phase_has_a_total_wall_clock_budget() -> None:
+ # No single step outlasts its own limit, but together they would run for
+ # more than 80 s. The phase stops when SCROLL_TOTAL_MS is spent.
+ slow = cs.JS_STEP_TIMEOUT_MS - 100
+ page = FakePage(height=10**9, cost_ms={"prepare": slow, "read": slow, "scroll_to": slow})
+ info = cs._scroll_through(page, clock=page.clock)
+ assert info["timed_out"] is True
+ assert info["returned_to_top"] is False
+ assert info["steps"] <= 2
+ assert page.now <= cs.SCROLL_TOTAL_MS / 1000
+ # The last call was only given what was left of the budget.
+ assert page.timeouts[-1][1] < cs.JS_STEP_TIMEOUT_MS
+
+
+def test_spent_budget_never_becomes_a_zero_timeout() -> None:
+ # Playwright reads timeout=0 as "wait for ever".
+ page = FakePage()
+ budget = cs._Budget(1000, clock=page.clock)
+ assert budget.step_timeout() == 1000
+ page.now = 0.5004
+ assert budget.step_timeout() == 499 # whole milliseconds, rounded down
+ page.now = 0.9995
+ with pytest.raises(cs._StepTimeout):
+ budget.step_timeout()
+ page.now = 5.0
+ with pytest.raises(cs._StepTimeout):
+ cs._page_step(page, cs._JS_PENDING, budget=budget)
+ assert page.timeouts == [] and page.calls == []
+
+
+def test_settle_has_a_total_wall_clock_budget() -> None:
+ slow = cs.JS_STEP_TIMEOUT_MS - 100
+ page = FakePage(pending=[{"animations": 4, "images": 9}], cost_ms={"pending": slow})
+ info = cs._settle(page, wait_images=True, clock=page.clock)
+ assert info["timed_out"] is True
+ assert page.now <= cs.SETTLE_TOTAL_MS / 1000
+
+
[email protected]("left_by_the_page", [
+ None, # the attribute was never written
+ json.dumps({"id": -1, "value": {"height": 10**9, "step": 1}}), # an earlier call's
+ "not json",
+ "[" * 900,
+ json.dumps({"id": 0, "value": "x" * 5000}), # oversized
+ json.dumps([1, 2, 3]),
+])
+def test_result_the_page_tampered_with_is_an_error_not_a_value(left_by_the_page) -> None:
+ page = FakePage()
+
+ def tamper(_snippet, _arg=None):
+ return None
+
+ page.run_snippet = tamper
+ root = FakeRoot(page)
+ page.locator = lambda _selector: root
+ root.get_attribute = lambda _name, *, timeout=None: left_by_the_page
+ info = cs._scroll_through(page)
+ assert info["steps"] == 0
+ assert info["error"] == "ValueError: the page-side step left no usable result"
+ assert "timed_out" not in info
+
+
+def test_odd_values_from_the_page_do_not_raise() -> None:
+ for dims in ({"height": "tall", "step": []}, {"height": float("inf")}, "x", 7, None):
+ page = FakePage()
+ page.run_snippet = lambda snippet, arg=None, dims=dims: (
+ dims if SNIPPETS[snippet] == "prepare" else 0
+ )
+ info = cs._scroll_through(page)
+ assert info["steps"] == 0, dims
+ assert info["returned_to_top"] is True, dims # the return to the top still ran
+ assert "timed_out" not in info, dims
+ page = FakePage(pending=[{"animations": "many", "images": None}])
+ assert "error" in cs._settle(page, wait_images=True)
+
+
+def test_playwright_without_a_timed_page_call_skips_the_steps(monkeypatch) -> None:
+ # Older Playwright has no Locator.wait_for_function. The steps are skipped
+ # with a clear reason; falling back to page.evaluate would bring the hang back.
+ page = FakePage()
+ page.locator = lambda _selector: SimpleNamespace()
+ result = _capture(monkeypatch, page, full_page=True, hide_overlays=True)
+ assert result["success"] is True and page.names()[-1] == "screenshot"
+ assert not set(page.names()) & set(STEP_NAMES)
+ for error in (result["scroll_through"]["error"], result["settle"]["error"],
+ result["hide_overlays_error"]):
+ assert error.startswith("RuntimeError: this Playwright has no Locator.wait_for_function")
+ assert result["scroll_timed_out"] is False
+
+
+def test_source_makes_no_untimed_call_into_the_page() -> None:
+ source = Path(cs.__file__).read_text(encoding="utf-8")
+ for untimed in ("evaluate", "evaluate_handle", "eval_on_selector", "eval_on_selector_all",
+ "add_script_tag", "add_init_script", "json_value"):
+ assert not re.search(rf"\.{untimed}\(", source), untimed
+ # Each timed call names its timeout.
+ assert len(re.findall(r"timeout=budget\.step_timeout\(\)", source)) == 2
+
+
+def test_wrapper_runs_the_snippet_once_and_never_polls() -> None:
+ wrapped = cs._timed(cs._JS_SCROLL_TO)
+ assert wrapped.startswith("(root, call) => {")
+ assert f"({cs._JS_SCROLL_TO})(call.arg)" in wrapped
+ assert cs._RESULT_ATTR in wrapped and "JSON.stringify" in wrapped
+ # A truthy return ends Locator.wait_for_function at the first run.
+ assert wrapped.rstrip().endswith("return true;\n}")
+ forbidden = (
+ "fetch", "XMLHttpRequest", "sendBeacon", "WebSocket", "EventSource", "import(",
+ "location", "open(", "href", "src", "createElement", "innerHTML", "eval(",
+ "navigator", "postMessage", "submit", "click", "url(", "async", "await",
+ )
+ for token in forbidden:
+ assert token not in cs._timed("() => 1"), token
+
+
# ---------------------------------------------------------------------------
# --hide-overlays: opt-in, and said so in the result
# ---------------------------------------------------------------------------
@@ -409,3 +741,21 @@ def test_cli_json_exits_non_zero_when_a_capture_fails(cli, capsys) -> None:
cli("--json")
assert exc.value.code == 1
assert json.loads(capsys.readouterr().out)["captures"][0]["error"] == "boom"
+
+
+def test_cli_json_says_when_the_scroll_timed_out(tmp_path, monkeypatch, capsys) -> None:
+ monkeypatch.setenv("HOME", str(tmp_path))
+ monkeypatch.setenv("USERPROFILE", str(tmp_path))
+ monkeypatch.chdir(tmp_path)
+ page = FakePage(hang="scroll_to")
+ monkeypatch.setattr(cs, "validate_url_strict", lambda url: (url, "93.184.216.34"))
+ monkeypatch.setattr(cs, "sync_playwright", lambda: FakeManager(page))
+ monkeypatch.setattr(sys, "argv", ["capture_screenshot.py", URL, "--full", "--json"])
+ cs.main()
+ captured = capsys.readouterr()
+ (capture,) = json.loads(captured.out)["captures"]
+ assert capture["scroll_timed_out"] is True
+ assert capture["scroll_through"]["timed_out"] is True
+ assert capture["success"] is True # the picture was still taken
+ assert "scroll-through timed out" in captured.err
+ assert page.names()[-1] == "screenshot"
diff --git a/tests/test_render_js_gap.py b/tests/test_render_js_gap.py
index 1b0ce19..4a664a4 100644
--- a/tests/test_render_js_gap.py
+++ b/tests/test_render_js_gap.py
@@ -22,6 +22,11 @@ pytest.importorskip("requests")
import render_page # noqa: E402
from render_page import js_gap, js_gap_reasons # noqa: E402
+# Ceiling for the whole js_gap object as JSON when a page pushes every field to
+# its limit on both sides. The limits add up to about 22,200 characters, most of
+# it the 12 H1 texts of 300 characters kept for raw, rendered and the diff.
+MAX_GAP_JSON_CHARS = 24_000
+
SHELL = "<html><head><title>App</title></head><body><p>one two</p></body></html>"
HYDRATED = (
"<html><head><title>App</title>"
@@ -262,6 +267,89 @@ def test_output_is_bounded_for_hostile_pages() -> None:
assert all(len(reason) < 400 for reason in gap["reasons"])
+def _hostile(tag: str) -> str:
+ """A page that pushes every js_gap field to its limit; ``tag`` keeps two apart."""
+ big = tag * 2_000
+ return (
+ f"<html><head><title>{big}</title>"
+ + "".join(f'<link rel="canonical" href="https://x.example/{i}/{big}">' for i in range(40))
+ + '<meta name="robots" content="' + ",".join(f"{i}{big}" for i in range(40)) + '">'
+ + '<script type="application/ld+json">['
+ + ",".join('{"@type":"%d%s"}' % (i, big) for i in range(60))
+ + "]</script>"
+ + "".join(
+ f'<script type="application/ld+json">{{"@type": "{i}{tag * 200_000}"}}</script>'
+ for i in range(3)
+ )
+ + "</head><body>"
+ + "".join(f"<h1>{i} {big}</h1>" for i in range(40))
+ + "".join(f'<a href="/{tag}/{i}/{big}">{tag}{i}</a>' for i in range(40))
+ + "</body></html>"
+ )
+
+
+def test_huge_schema_type_names_cannot_inflate_the_output() -> None:
+ # Found in review: five blocks with 200,000-character @type values made
+ # 3 MB of js_gap, and --max-text does not cut js_gap.
+ big = "A" * 200_000
+ blocks = "".join(
+ f'<script type="application/ld+json">{{"@type": "{big}{i}"}}</script>' for i in range(5)
+ )
+ gap = js_gap(
+ "<html><body>x</body></html>", f"<html><head>{blocks}</head><body>x</body></html>"
+ )
+ names = gap["rendered"]["schema_types"]
+ assert names and all(len(name) <= render_page.JS_GAP_MAX_NAME for name in names)
+ assert gap["diff"]["schema_types_only_rendered"] == names
+ assert all(len(reason) < 400 for reason in gap["reasons"])
+ assert len(json.dumps(gap)) < 2_000
+
+
+def test_schema_type_names_are_cleaned_like_the_other_page_text() -> None:
+ block = '<script type="application/ld+json">{"@type": [" Local\\n\\t Business ", " ", ""]}</script>'
+ gap = js_gap(_page(), _page(block))
+ assert gap["rendered"]["schema_types"] == ["Local Business"]
+ assert gap["reasons"] == ["structured data appears only after JavaScript: 'Local Business'"]
+
+
+def test_reason_lists_a_bounded_number_of_quoted_type_names() -> None:
+ types = ",".join(f'"Type{i:02d}"' for i in range(30))
+ block = f'<script type="application/ld+json">{{"@type": [{types}]}}</script>'
+ gap = js_gap(_page(), _page(block))
+ assert len(gap["rendered"]["schema_types"]) == render_page.JS_GAP_MAX_ITEMS
+ assert gap["reasons"] == [
+ "structured data appears only after JavaScript: "
+ "'Type00', 'Type01', 'Type02', 'Type03', 'Type04'"
+ ]
+ # js_gap_reasons is public: it bounds what it quotes even for a gap it did not build.
+ gap["diff"]["schema_types_only_rendered"] = ["Z" * 100_000] * 50
+ (reason,) = js_gap_reasons(gap)
+ assert len(reason) < 600
+
+
+def test_whole_js_gap_json_stays_small_when_every_field_is_pushed_to_its_limit() -> None:
+ gap = js_gap(_hostile("a"), _hostile("b"), raw_truncated=True)
+ # Both versions are at their limits, and they differ everywhere.
+ for side in ("raw", "rendered"):
+ signals = gap[side]
+ assert len(signals["title"]) == render_page.JS_GAP_MAX_TEXT
+ assert len(signals["h1"]) == render_page.JS_GAP_MAX_ITEMS
+ assert len(signals["schema_types"]) == render_page.JS_GAP_MAX_ITEMS
+ assert len(signals["canonical_all"]) == render_page.JS_GAP_MAX_CANONICALS
+ assert len(signals["meta_robots"].split(", ")) == render_page.JS_GAP_MAX_ITEMS
+ assert all(len(name) <= render_page.JS_GAP_MAX_NAME for name in signals["schema_types"])
+ assert all(
+ len(part) <= render_page.JS_GAP_MAX_NAME
+ for part in signals["meta_robots"].split(", ")
+ )
+ assert len(gap["diff"]["schema_types_only_rendered"]) == render_page.JS_GAP_MAX_ITEMS
+ assert len(gap["diff"]["h1_only_rendered"]) == render_page.JS_GAP_MAX_ITEMS
+ assert len(gap["reasons"]) == 7 # every reason js_gap can give
+ assert all(len(reason) < 600 for reason in gap["reasons"])
+ assert len(json.dumps(gap)) < MAX_GAP_JSON_CHARS, len(json.dumps(gap))
+ assert len(json.dumps(gap, indent=2)) < MAX_GAP_JSON_CHARS, len(json.dumps(gap, indent=2))
+
+
def test_malformed_json_ld_and_markup_do_not_raise() -> None:
broken = (
'<html><head><script type="application/ld+json">{"@type": </script>'
diff --git a/tests/test_render_page.py b/tests/test_render_page.py
index 793bd46..8fff042 100644
--- a/tests/test_render_page.py
+++ b/tests/test_render_page.py
@@ -600,6 +600,26 @@ def test_rendered_result_carries_the_js_gap() -> None:
json.dumps(summary)
+def test_js_gap_in_the_cli_json_is_bounded_without_max_text() -> None:
+ """--max-text does not cut js_gap, so js_gap has to be small on its own."""
+ big = "A" * 200_000
+ blocks = "".join(
+ f'<script type="application/ld+json">{{"@type": "{big}{i}"}}</script>' for i in range(5)
+ )
+ page = _FakeBrowserPage([(200, 20), (200, 20), (200, 20)])
+ page.content = lambda: (
+ f"<html><head><title>{big}</title>{blocks}</head>"
+ f"<body><h1>{big}</h1>" + ("hydrated content " * 20) + "</body></html>"
+ )
+ result = _render_with_fake_browser(page)
+ gap = result["js_gap"]
+ assert gap["diff"]["schema_types_only_rendered"]
+ for max_text in (0, 2000):
+ summary = render_page._json_summary(result, max_text=max_text)
+ assert summary["js_gap"] == gap
+ assert len(json.dumps(summary["js_gap"], indent=2)) < 5_000
+
+
def test_js_gap_stays_null_when_the_render_fails() -> None:
spa_html = '<html><body><div id="root"></div></body></html>'
with patch.object(render_page, "validate_url_strict", side_effect=_mock_validate_strict), \
diff --git a/tests/test_transport_check.py b/tests/test_transport_check.py
index 47d1b18..a93c779 100644
--- a/tests/test_transport_check.py
+++ b/tests/test_transport_check.py
@@ -21,6 +21,7 @@ import sys
from datetime import datetime, timezone
import pytest
+import requests
_SCRIPTS = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "scripts")
if _SCRIPTS not in sys.path:
@@ -752,6 +753,113 @@ def test_sibling_that_resolves_but_is_not_on_the_certificate_is_medium(net, publ
assert report["redirects"]["www"]["sibling_resolves"] is True
+def test_sibling_with_its_own_valid_certificate_is_not_a_finding(net, public, web) -> None:
+ # One certificate per host is a normal setup. This certificate does not name
+ # www, but www answered over HTTPS, so the certificate it serves verified.
+ net.verified = FakeTLS(cert=peercert("example.com"))
+ web(site())
+ report = tc.run("https://example.com/", now=NOW)
+ assert report["tls"]["covers_sibling"] is False
+ www = report["redirects"]["www"]
+ assert www["sibling_resolves"] is True
+ assert www["sibling_final_url"] == "https://example.com/"
+ assert www["sibling_tls_error"] is False
+ assert report["findings"] == []
+
+
+def test_sibling_finding_needs_evidence_of_a_tls_failure_not_just_dns() -> None:
+ # The shape the independent review probed: covered host, uncovered sibling
+ # that resolves and whose HTTPS fetch succeeded.
+ tls = {"host": "example.com", "verified": True, "verify_code": None, "verify_error": None,
+ "expired": False, "not_yet_valid": False, "covers_host": True,
+ "sibling_host": "www.example.com", "covers_sibling": False,
+ "days_until_expiry": 60, "protocol": "TLSv1.3", "san": ["example.com"]}
+ www = {"host": "example.com", "sibling_host": "www.example.com",
+ "host_final_url": "https://example.com/",
+ "sibling_final_url": "https://example.com/", "sibling_resolves": True,
+ "same_final_url": True, "error": None}
+ assert tc._tls_findings(tls, {"www": www}) == []
+ # No verdict on the sibling's TLS (not checked) is not evidence either.
+ assert tc._tls_findings(tls, {"www": {**www, "sibling_tls_error": None}}) == []
+ assert tc._tls_findings(tls, {}) == []
+ assert ids(tc._tls_findings(tls, {"www": {**www, "sibling_tls_error": True}})) == [
+ "tls-sibling-not-covered"]
+
+
[email protected]("failure", [
+ ConnectionRefusedError("refused"),
+ TimeoutError("timed out"),
+ requests.exceptions.ConnectTimeout("connect timed out"),
+ requests.exceptions.ConnectionError("Name or service not known"),
+])
+def test_sibling_that_fails_for_a_non_tls_reason_is_info_with_the_reason(
+ failure, net, public, web) -> None:
+ net.verified = FakeTLS(cert=peercert("example.com"))
+ routes = site()
+ routes["https://www.example.com/"] = failure
+ web(routes)
+ report = tc.run("https://example.com/", now=NOW)
+ assert report["tls"]["covers_sibling"] is False
+ assert report["redirects"]["www"]["sibling_tls_error"] is False
+ assert ids(report) == ["www-sibling-unreachable"]
+ finding = report["findings"][0]
+ assert finding["severity"] == "Info"
+ assert finding["evidence"]["error"].startswith(type(failure).__name__)
+ assert "certificate" not in finding["message"].lower()
+
+
+def test_requests_ssl_error_on_the_sibling_is_the_certificate_finding(net, public, web) -> None:
+ net.verified = FakeTLS(cert=peercert("example.com"))
+ routes = site()
+ routes["https://www.example.com/"] = requests.exceptions.SSLError(
+ "[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: Hostname mismatch")
+ web(routes)
+ report = tc.run("https://example.com/", now=NOW)
+ assert report["redirects"]["www"]["sibling_tls_error"] is True
+ finding = by_id(report)["tls-sibling-not-covered"]
+ assert finding["severity"] == "Medium"
+ assert finding["evidence"]["sibling_host"] == "www.example.com"
+ assert finding["evidence"]["error"].startswith("SSLError")
+ assert "resolves in DNS" not in finding["message"]
+ assert finding["message"].endswith(".") and finding["message"].count(". ") == 0
+
+
+def test_tls_failure_on_another_host_in_the_sibling_redirects_is_not_blamed_on_the_sibling(
+ net, public, web) -> None:
+ # www redirects to a third host whose certificate is broken. That says
+ # nothing about the certificate www itself serves.
+ net.verified = FakeTLS(cert=peercert("example.com"))
+ failing_hop = requests.Request("GET", "https://cdn.elsewhere.example/").prepare()
+ routes = site()
+ routes["https://www.example.com/"] = requests.exceptions.SSLError(
+ "certificate verify failed", request=failing_hop)
+ web(routes)
+ report = tc.run("https://example.com/", now=NOW)
+ assert report["redirects"]["www"]["sibling_tls_error"] is False
+ assert ids(report) == ["www-sibling-unreachable"]
+ assert report["findings"][0]["severity"] == "Info"
+
+
+def test_error_text_that_mentions_ssl_is_not_taken_for_a_tls_failure(net, public, web) -> None:
+ # The verdict comes from the exception type. Text is page and network data.
+ net.verified = FakeTLS(cert=peercert("example.com"))
+ routes = site()
+ routes["https://www.example.com/"] = OSError("SSLError: certificate verify failed")
+ web(routes)
+ report = tc.run("https://example.com/", now=NOW)
+ assert report["redirects"]["www"]["sibling_tls_error"] is False
+ assert "tls-sibling-not-covered" not in ids(report)
+
+
+def test_sibling_tls_verdict_is_null_when_the_sibling_was_not_fetched(net, public, web) -> None:
+ public.add("www.blog.example.com")
+ net.verified = FakeTLS(cert=peercert("blog.example.com"))
+ web(site("blog.example.com"))
+ report = tc.run("https://blog.example.com/", now=NOW)
+ assert report["redirects"]["www"]["sibling_tls_error"] is None
+ assert "sibling_tls_error" in tc.__doc__
+
+
def test_www_input_uses_the_bare_domain_as_sibling() -> None:
assert tc.sibling_host("www.example.com") == "example.com"
assert tc.sibling_host("example.com") == "www.example.com"