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.

feat(sitemap): --expand follows indexes and reports counts, lastmod and limits; gzip in every mode

Agrici Daniel7569398fcc82
diff --git a/agents/seo-sitemap.md b/agents/seo-sitemap.md
index b609554..4646ba4 100644
--- a/agents/seo-sitemap.md
+++ b/agents/seo-sitemap.md
@@ -10,14 +10,28 @@ You are a Sitemap Architecture specialist.
When working with sitemaps:
-1. Discover candidates with `"${CLAUDE_PLUGIN_ROOT}/scripts/claude-seo" run sitemap_discovery.py <url> --json`.
+1. Discover and read sitemaps with `"${CLAUDE_PLUGIN_ROOT}/scripts/claude-seo" run sitemap_discovery.py <url> --expand --json`.
Use only validated `found` entries and retain declared failures as findings.
-2. Validate XML format and URL status codes
-3. Check for deprecated tags (priority, changefreq: both ignored by Google)
-4. Verify lastmod accuracy (valid W3C Datetime; reflects last *significant* change, not boilerplate)
-5. Compare crawled pages vs sitemap coverage
-6. Enforce the per-file limit: ≤50,000 URLs AND ≤50MB uncompressed (whichever first); for `news:` sitemaps the cap is 1,000 URLs
-7. Apply location page quality gates
+2. Take file facts from `expanded.files` and `expanded.totals` (table below); do not count or parse sitemap files by hand
+3. Check URL status codes on each file's `sample_urls`
+4. Check for deprecated tags (priority, changefreq: both ignored by Google)
+5. Verify lastmod accuracy (reflects last *significant* change, not boilerplate)
+6. Compare crawled pages vs sitemap coverage
+7. For `news:` sitemaps also count `<news:news>` tags: at most 1,000 per file, on top of the general limits
+8. Apply location page quality gates
+
+## Expand Output
+
+| Check | Fields in `expanded` |
+|-------|----------------------|
+| Valid XML, file reachable | `files[].valid`, `error`, `status_code`, `kind` |
+| ≤50,000 URLs AND ≤50MB uncompressed per file | `url_count`, `bytes`, `decompressed_bytes`; `findings`: `over_50000_urls`, `over_50000_sitemaps`, `over_50mib_uncompressed` |
+| Index structure | `child_count`, `parent`; `findings`: `nested_sitemap_index` (index lists an index, not followed) |
+| lastmod present, valid W3C Datetime | `lastmod_count` against `url_count`, `lastmod_invalid_count` |
+| lastmod identical across a file | `lastmod_identical_share` near 1.0, `lastmod_most_common`, `lastmod_oldest`, `lastmod_newest` |
+| URLs on another host than their sitemap | `cross_host_url_count`, `cross_host_url_examples`, `cross_host` on a child file |
+| Duplicate or malformed URLs | `duplicate_count`, `invalid_loc_count`, `totals.unique_urls`, `totals.duplicates_across_files` |
+| Run cut short | `truncated`, `children.skipped`; rerun with a higher `--max-children` (default 50) |
## Quality Gates
diff --git a/scripts/sitemap_discovery.py b/scripts/sitemap_discovery.py
index bae915e..2c2b5ca 100644
--- a/scripts/sitemap_discovery.py
+++ b/scripts/sitemap_discovery.py
@@ -4,16 +4,37 @@
Every network request uses the repository's DNS-pinned URL safety layer. The
helper accepts cross-host Sitemap directives because the sitemap protocol
allows them, but validates each target independently before connecting.
+A gzip sitemap (.xml.gz, detected by its magic bytes) is inflated under the
+50 MiB uncompressed cap and classified by its content; its entry carries
+"gzip": true.
+
+Usage:
+ sitemap_discovery.py <url> --json
+ sitemap_discovery.py <url> --expand --json
+ sitemap_discovery.py <url> --expand --max-children 200 --sample 5 --json
+
+--expand also reads every sitemap that was found: it follows a sitemap index
+one level down to its child sitemaps and adds an "expanded" object with
+per-file statistics
+(URL count, lastmod quality, off-host entries, protocol limit findings) and
+totals across files. Every URL is counted; only a bounded sample is printed.
"""
from __future__ import annotations
import argparse
+import gzip
+import hashlib
+import io
import json
import os
import re
import sys
-from urllib.parse import urlparse, urlunparse
+import zlib
+from collections import Counter
+from collections.abc import Iterable, Iterator
+from datetime import datetime, timedelta, timezone
+from urllib.parse import unquote, urlparse, urlunparse
import requests
from lxml import etree
@@ -33,8 +54,28 @@ COMMON_PATHS = (
MAX_DECLARED = 16
MAX_ROBOTS_BYTES = 1024 * 1024
MAX_SITEMAP_BYTES = 50 * 1024 * 1024
+MAX_SITEMAP_URLS = 50000
+# Protocol limit: a <loc> value must be shorter than 2,048 characters.
+MAX_LOC_CHARS = 2048
+DEFAULT_MAX_CHILDREN = 50
+DEFAULT_SAMPLE = 20
+MAX_EXAMPLES = 5
+# Distinct URLs remembered for duplicate detection (about 100 bytes each).
+MAX_TRACKED_URLS = 2_000_000
USER_AGENT = "ClaudeSEO/2.2 SitemapDiscovery"
_SITEMAP_LINE = re.compile(r"^\s*sitemap\s*:\s*(\S+)\s*$", re.IGNORECASE)
+_TOO_LARGE = "Sitemap exceeds the 50 MiB uncompressed protocol limit"
+_GZIP_MAGIC = b"\x1f\x8b"
+_INFLATE_CHUNK = 1024 * 1024
+_TRACKING_KEYS = frozenset({"fbclid", "gclid", "mc_cid", "mc_eid", "_ga", "ref"})
+# W3C Datetime: YYYY, YYYY-MM, YYYY-MM-DD, or a date with a time and a zone.
+_W3C_DATETIME = re.compile(
+ r"(\d{4})(?:-(\d{2})(?:-(\d{2})"
+ r"(?:T(\d{2}):(\d{2})(?::(\d{2})(?:\.\d{1,9})?)?(Z|[+-]\d{2}:\d{2}))?)?)?",
+ re.ASCII,
+)
+# Element that holds one entry, per sitemap kind.
+_ENTRY_TAG = {"urlset": "url", "sitemapindex": "sitemap", "rss": "item", "feed": "entry"}
def _display_url(url: str) -> tuple[str, bool]:
@@ -140,11 +181,17 @@ def _valid_sitemap_url_syntax(value: str) -> bool:
)
-def _sitemap_kind(content: bytes, content_type: str, url: str) -> tuple[str | None, str | None]:
+def _classify(content: bytes, content_type: str, url: str) -> tuple[str | None, str | None, object, list[str] | None]:
+ """Classify a sitemap body. Returns (kind, error, XML root, text lines).
+
+ The root is set for an accepted XML sitemap and the lines for a text
+ sitemap, including one refused for passing the 50,000 URL limit, so
+ --expand can count entries without parsing the body a second time.
+ """
if not content.strip():
- return None, "empty response"
+ return None, "empty response", None, None
if b"<!DOCTYPE" in content.upper():
- return None, "DOCTYPE is not allowed in sitemap XML"
+ return None, "DOCTYPE is not allowed in sitemap XML", None, None
stripped = content.removeprefix(b"\xef\xbb\xbf").lstrip()
if stripped.startswith(b"<"):
@@ -158,30 +205,445 @@ def _sitemap_kind(content: bytes, content_type: str, url: str) -> tuple[str | No
)
root = etree.fromstring(content, parser=parser)
except (etree.XMLSyntaxError, ValueError):
- return None, "invalid XML"
+ return None, "invalid XML", None, None
local = etree.QName(root).localname.lower()
if local in {"urlset", "sitemapindex"}:
- return local, None
+ return local, None, root, None
if local in {"rss", "feed"}:
- return local, None
- return None, "unsupported XML root"
+ return local, None, root, None
+ return None, "unsupported XML root", None, None
if "text/plain" in content_type.lower() or urlparse(url).path.lower().endswith(".txt"):
# Decode the BOM-free bytes: a leading UTF-8 BOM is an encoding
# signature, not part of the first URL.
lines = [line.strip() for line in stripped.decode("utf-8", errors="replace").splitlines() if line.strip()]
- if len(lines) > 50000:
- return None, "text sitemap exceeds the 50,000 URL protocol limit"
+ if len(lines) > MAX_SITEMAP_URLS:
+ return None, "text sitemap exceeds the 50,000 URL protocol limit", None, lines
# Entries are reported only as a sitemap classification, not fetched.
# Avoid up to 50,000 DNS lookups here; connection-time validation still
# applies to every sitemap candidate that discovery fetches.
if lines and all(_valid_sitemap_url_syntax(line) for line in lines):
- return "text", None
- return None, "invalid text sitemap"
- return None, "response is not a supported sitemap format"
+ return "text", None, None, lines
+ return None, "invalid text sitemap", None, None
+ return None, "response is not a supported sitemap format", None, None
+
+def _sitemap_kind(content: bytes, content_type: str, url: str) -> tuple[str | None, str | None]:
+ kind, error, _root, _lines = _classify(content, content_type, url)
+ return kind, error
+
+
+def _gunzip_bounded(raw: bytes, max_bytes: int) -> tuple[bytes, bool]:
+ """Inflate gzip data in chunks, stopping once the output passes max_bytes.
-def discover_sitemaps(target_url: str) -> dict:
+ Returns (data, too_large). The output is never held past max_bytes plus
+ one chunk, so a gzip bomb cannot exhaust memory. Raises ValueError when
+ the data is not a complete gzip stream.
+ """
+ chunks = []
+ total = 0
+ try:
+ with gzip.GzipFile(fileobj=io.BytesIO(raw)) as stream:
+ while True:
+ chunk = stream.read(_INFLATE_CHUNK)
+ if not chunk:
+ break
+ total += len(chunk)
+ if total > max_bytes:
+ return b"", True
+ chunks.append(chunk)
+ except (OSError, EOFError, zlib.error) as exc:
+ raise ValueError("invalid gzip data") from exc
+ return b"".join(chunks), False
+
+
+def _read_body(fetched: dict) -> dict:
+ """Classify a fetched body. A gzip file is inflated first, under the size cap."""
+ body = {
+ "kind": None,
+ "error": None,
+ "root": None,
+ "lines": None,
+ "gzip": False,
+ "decompressed_bytes": None,
+ "too_large": False,
+ }
+ content = fetched["content"]
+ url = fetched["final_url"]
+ if content[:2] == _GZIP_MAGIC:
+ body["gzip"] = True
+ try:
+ content, body["too_large"] = _gunzip_bounded(content, MAX_SITEMAP_BYTES)
+ except ValueError:
+ body["error"] = "invalid gzip data"
+ return body
+ if body["too_large"]:
+ body["error"] = _TOO_LARGE
+ return body
+ body["decompressed_bytes"] = len(content)
+ parsed = urlparse(url)
+ if parsed.path.lower().endswith(".gz"):
+ # sitemap.txt.gz is a text sitemap: classify it by the inner name.
+ url = urlunparse(parsed._replace(path=parsed.path[:-3]))
+ body["kind"], body["error"], body["root"], body["lines"] = _classify(content, fetched["content_type"], url)
+ return body
+
+
+def _fetch_sitemap(url: str) -> tuple[dict, dict | None, str | None]:
+ """Fetch one sitemap candidate through the bounded, validated fetch.
+
+ Returns (fetched, body, error). The body is None when nothing usable came
+ back: a refused or failed request, an oversized body, or a non-2xx status.
+ """
+ fetched = _bounded_fetch(url, MAX_SITEMAP_BYTES)
+ if fetched["error"]:
+ return fetched, None, fetched["error"]
+ if fetched["too_large"]:
+ return fetched, None, _TOO_LARGE
+ status = fetched["status_code"]
+ if status is None or not 200 <= status < 300:
+ return fetched, None, f"HTTP {status}" if status is not None else "No response"
+ body = _read_body(fetched)
+ return fetched, body, body["error"]
+
+
+def _host(url: str) -> str:
+ return (urlparse(url).hostname or "").lower().rstrip(".")
+
+
+def _local(element) -> str:
+ """Lower-case tag name without its namespace; empty for comments and PIs."""
+ tag = element.tag
+ if not isinstance(tag, str):
+ return ""
+ return tag.rsplit("}", 1)[-1].lower()
+
+
+def _xml_entries(kind: str, root) -> Iterator[tuple[str | None, str | None]]:
+ """Yield (loc, lastmod) for each entry of a parsed sitemap, index, or feed."""
+ feed = kind in {"rss", "feed"}
+ for node in root.iter() if feed else root:
+ if _local(node) != _ENTRY_TAG[kind]:
+ continue
+ loc = lastmod = None
+ for child in node:
+ tag = _local(child)
+ text = (child.text or "").strip()
+ if kind == "feed":
+ if tag == "link" and loc is None and child.get("rel", "alternate") == "alternate":
+ loc = (child.get("href") or "").strip()
+ elif tag == "updated" and lastmod is None:
+ lastmod = text
+ elif kind == "rss":
+ if tag == "link" and loc is None:
+ loc = text
+ elif tag == "loc" and loc is None:
+ loc = text
+ elif tag == "lastmod" and lastmod is None:
+ lastmod = text
+ yield loc or None, lastmod or None
+
+
+def _parse_w3c_datetime(value: str) -> datetime | None:
+ """Return a comparable UTC time for a W3C Datetime value, or None."""
+ match = _W3C_DATETIME.fullmatch(value)
+ if not match:
+ return None
+ year, month, day, hour, minute, second, zone = match.groups()
+ try:
+ moment = datetime(
+ int(year), int(month or 1), int(day or 1),
+ int(hour or 0), int(minute or 0), int(second or 0),
+ tzinfo=timezone.utc,
+ )
+ if zone and zone != "Z":
+ hours, minutes = int(zone[1:3]), int(zone[4:6])
+ if hours > 23 or minutes > 59:
+ return None
+ offset = timedelta(hours=hours, minutes=minutes)
+ moment = moment - offset if zone[0] == "+" else moment + offset
+ except (ValueError, OverflowError):
+ return None
+ return moment
+
+
+def _normalize_url(url: str) -> str | None:
+ """Normalise a URL for duplicate detection only; never fetch or print it.
+
+ Lower-cases scheme and host, drops a default port, the fragment, and
+ tracking parameters, and collapses repeated slashes. The trailing slash is
+ kept: /about and /about/ are different addresses.
+ """
+ try:
+ parsed = urlparse(url)
+ port = parsed.port
+ except ValueError:
+ return None
+ scheme = parsed.scheme.lower()
+ if scheme not in {"http", "https"} or not parsed.hostname:
+ return None
+ host = parsed.hostname.lower().rstrip(".")
+ if ":" in host:
+ host = f"[{host}]"
+ netloc = f"{host}:{port}" if port and port != (443 if scheme == "https" else 80) else host
+ path = re.sub(r"/{2,}", "/", parsed.path or "/")
+ kept = []
+ for pair in parsed.query.split("&"):
+ key = unquote(pair.split("=", 1)[0]).lower()
+ if pair and not key.startswith("utm_") and key not in _TRACKING_KEYS:
+ kept.append(pair)
+ return urlunparse((scheme, netloc, path, parsed.params, "&".join(kept), ""))
+
+
+class _Expansion:
+ """Per-file statistics and cross-file totals for --expand."""
+
+ def __init__(self, sample_size: int) -> None:
+ self.sample_size = sample_size
+ self.files: list[dict] = []
+ # Fetched and final URL of every sitemap request so far, with its kind.
+ self.kinds: dict[str, str | None] = {}
+ # Final URLs of the valid files already reported.
+ self.analysed: set[str] = set()
+ # Top-level indexes waiting for their children: (report, final URL, child URLs).
+ self.pending: list[tuple[dict, str, list[str]]] = []
+ # Digest of a normalised URL -> number of the first file that listed it.
+ self.seen: dict[bytes, int] = {}
+ self.tracking_complete = True
+ self.unique = 0
+
+ def add_top_level(self, candidate: str, entry: dict, fetched: dict, body: dict | None) -> None:
+ """Record a candidate from robots.txt or a common path."""
+ final_url = fetched["final_url"]
+ self.kinds[candidate] = entry["kind"]
+ if entry["valid"] and final_url in self.analysed:
+ return
+ self.kinds[final_url] = entry["kind"]
+ report, children = self._report(entry, fetched, body)
+ if entry["valid"]:
+ self.analysed.add(final_url)
+ if entry["kind"] == "sitemapindex":
+ self.pending.append((report, final_url, children))
+ if entry["valid"] or report["findings"]:
+ self.files.append(report)
+
+ def follow_children(self, max_children: int, warnings: list[str]) -> dict:
+ """Fetch the child sitemaps of every top-level index, one level deep.
+
+ Child URLs come from fetched content, so each one takes the same
+ validated fetch path as any other candidate. A child that is itself an
+ index is reported, never followed.
+ """
+ listed = fetched_count = skipped = 0
+ scheduled: set[str] = set()
+ for parent, parent_url, children in self.pending:
+ for loc in children:
+ if loc in self.kinds:
+ if self.kinds[loc] == "sitemapindex":
+ self._nested(parent, _display_url(loc)[0], warnings)
+ continue
+ if loc in scheduled:
+ continue
+ scheduled.add(loc)
+ listed += 1
+ if fetched_count >= max_children:
+ skipped += 1
+ continue
+ fetched_count += 1
+ fetched, body, error = _fetch_sitemap(loc)
+ kind = body["kind"] if body else None
+ final_url = fetched["final_url"]
+ self.kinds[loc] = kind
+ if kind is not None and final_url in self.analysed:
+ # Redirects to a file that is already reported: count it once.
+ if self.kinds.get(final_url) == "sitemapindex":
+ self._nested(parent, _display_url(final_url)[0], warnings)
+ continue
+ self.kinds[final_url] = kind
+ display, redacted = _display_url(final_url if kind is not None else loc)
+ entry = {
+ "url": display,
+ "query_redacted": redacted or _display_url(loc)[1],
+ "source": "sitemapindex",
+ "parent": parent["url"],
+ "status_code": fetched["status_code"],
+ "kind": kind,
+ "valid": kind is not None,
+ "error": error,
+ }
+ if _host(loc) != _host(parent_url):
+ entry["cross_host"] = True
+ report, _grandchildren = self._report(entry, fetched, body)
+ if kind is not None:
+ self.analysed.add(final_url)
+ self.files.append(report)
+ if kind == "sitemapindex":
+ self._nested(parent, display, warnings)
+ if skipped:
+ warnings.append(
+ f"Child sitemap limit reached ({max_children}); {skipped} child sitemaps were not fetched"
+ )
+ return {"limit": max_children, "listed": listed, "fetched": fetched_count, "skipped": skipped}
+
+ def totals(self, warnings: list[str]) -> dict:
+ valid = [item for item in self.files if item["valid"]]
+ totals = {
+ "sitemap_files": len(valid),
+ "total_urls": sum(item["url_count"] for item in valid),
+ "unique_urls": self.unique,
+ "duplicates_within_files": sum(
+ item["duplicate_count"] or 0 for item in valid if item["kind"] != "sitemapindex"
+ ),
+ "duplicates_across_files": sum(item["_cross_file_duplicates"] for item in valid),
+ "invalid_locs": sum(item["invalid_loc_count"] for item in valid),
+ }
+ if not self.tracking_complete:
+ totals["unique_urls"] = None
+ totals["duplicates_within_files"] = None
+ totals["duplicates_across_files"] = None
+ warnings.append(
+ f"More than {MAX_TRACKED_URLS} distinct URLs; unique and duplicate totals are not reported"
+ )
+ for item in self.files:
+ item.pop("_cross_file_duplicates", None)
+ return totals
+
+ @staticmethod
+ def _nested(parent: dict, display: str, warnings: list[str]) -> None:
+ if "nested_sitemap_index" not in parent["findings"]:
+ parent["findings"].append("nested_sitemap_index")
+ warnings.append(f"Nested sitemap index was not followed: {display} (listed in {parent['url']})")
+
+ def _report(self, entry: dict, fetched: dict, body: dict | None) -> tuple[dict, list[str]]:
+ """Build the report for one file. Returns it with the child URLs of an index."""
+ report = dict(entry)
+ report.update({
+ "gzip": bool(body and body["gzip"]),
+ "bytes": None if fetched["too_large"] else len(fetched["content"]),
+ "decompressed_bytes": body["decompressed_bytes"] if body else None,
+ "url_count": None,
+ "child_count": None,
+ "invalid_loc_count": None,
+ "duplicate_count": None,
+ "lastmod_count": None,
+ "lastmod_invalid_count": None,
+ "lastmod_oldest": None,
+ "lastmod_newest": None,
+ "lastmod_most_common": None,
+ "lastmod_identical_share": None,
+ "cross_host_url_count": None,
+ "cross_host_url_examples": [],
+ "findings": [],
+ "sample_urls": [],
+ "_cross_file_duplicates": 0,
+ })
+ if fetched["too_large"] or (body and body["too_large"]):
+ report["findings"].append("over_50mib_uncompressed")
+ if body is None:
+ return report, []
+ if body["kind"] is None:
+ if body["lines"] is not None:
+ # A text sitemap refused for its size: the count is still known.
+ report["url_count"] = len(body["lines"])
+ report["findings"].append("over_50000_urls")
+ return report, []
+ if body["root"] is not None:
+ entries: Iterable[tuple[str | None, str | None]] = _xml_entries(body["kind"], body["root"])
+ else:
+ entries = ((line, None) for line in body["lines"])
+ return report, self._summarise(report, body["kind"], entries, fetched["final_url"])
+
+ def _summarise(self, report: dict, kind: str, entries: Iterable, final_url: str) -> list[str]:
+ """Count every entry of one file into its report. Returns an index's child URLs."""
+ index = kind == "sitemapindex"
+ file_number = len(self.files)
+ host = _host(final_url)
+ count = invalid = with_lastmod = bad_lastmod = cross_host = repeats = cross_file = 0
+ oldest: tuple[datetime, str] | None = None
+ newest: tuple[datetime, str] | None = None
+ lastmods: Counter[str] = Counter()
+ examples: list[str] = report["cross_host_url_examples"]
+ children: list[str] = []
+ child_set: set[str] = set()
+ for loc, lastmod in entries:
+ count += 1
+ if lastmod:
+ with_lastmod += 1
+ moment = _parse_w3c_datetime(lastmod)
+ if moment is None:
+ bad_lastmod += 1
+ else:
+ lastmods[lastmod] += 1
+ if oldest is None or moment < oldest[0]:
+ oldest = (moment, lastmod)
+ if newest is None or moment > newest[0]:
+ newest = (moment, lastmod)
+ if not loc or len(loc) >= MAX_LOC_CHARS or not _valid_sitemap_url_syntax(loc):
+ invalid += 1
+ continue
+ if _host(loc) != host:
+ cross_host += 1
+ shown = _display_url(loc)[0]
+ if len(examples) < MAX_EXAMPLES and shown not in examples:
+ examples.append(shown)
+ if index:
+ if loc in child_set:
+ repeats += 1
+ else:
+ child_set.add(loc)
+ children.append(loc)
+ continue
+ if len(report["sample_urls"]) < self.sample_size:
+ report["sample_urls"].append(_display_url(loc)[0])
+ first_file = self._track(loc, file_number)
+ if first_file == file_number:
+ repeats += 1
+ elif first_file is not None:
+ cross_file += 1
+
+ report.update({
+ "url_count": 0 if index else count,
+ "child_count": count if index else 0,
+ "invalid_loc_count": invalid,
+ "duplicate_count": repeats if index or self.tracking_complete else None,
+ "lastmod_count": with_lastmod,
+ "lastmod_invalid_count": bad_lastmod,
+ "lastmod_oldest": oldest[1] if oldest else None,
+ "lastmod_newest": newest[1] if newest else None,
+ "cross_host_url_count": cross_host,
+ "_cross_file_duplicates": cross_file,
+ })
+ if lastmods:
+ value, uses = lastmods.most_common(1)[0]
+ report["lastmod_most_common"] = value
+ report["lastmod_identical_share"] = round(uses / with_lastmod, 4)
+ if count > MAX_SITEMAP_URLS:
+ report["findings"].append("over_50000_sitemaps" if index else "over_50000_urls")
+ return children
+
+ def _track(self, loc: str, file_number: int) -> int | None:
+ """Remember a URL. Returns the file that listed it before, or None if new."""
+ key = _normalize_url(loc)
+ if key is None:
+ return None
+ digest = hashlib.blake2b(key.encode("utf-8", "replace"), digest_size=8).digest()
+ first_file = self.seen.get(digest)
+ if first_file is not None:
+ return first_file
+ if len(self.seen) < MAX_TRACKED_URLS:
+ self.seen[digest] = file_number
+ self.unique += 1
+ else:
+ self.tracking_complete = False
+ return None
+
+
+def discover_sitemaps(
+ target_url: str,
+ expand: bool = False,
+ max_children: int = DEFAULT_MAX_CHILDREN,
+ sample_size: int = DEFAULT_SAMPLE,
+) -> dict:
result = {
"target": None,
"robots_url": None,
@@ -230,7 +692,11 @@ def discover_sitemaps(target_url: str) -> dict:
seen.add(candidate)
deduped.append(candidate)
+ expansion = _Expansion(sample_size) if expand else None
target_host = urlparse(origin).hostname
+ # Several paths can redirect to one sitemap (/sitemap.xml to
+ # /sitemap_index.xml): list each file once, by its final URL.
+ listed = set()
for candidate in deduped:
display, query_redacted = _display_url(candidate)
entry = {
@@ -245,41 +711,90 @@ def discover_sitemaps(target_url: str) -> dict:
if urlparse(candidate).hostname != target_host and candidate in declared_raw:
entry["cross_host"] = True
- fetched = _bounded_fetch(candidate, MAX_SITEMAP_BYTES)
+ fetched, body, entry["error"] = _fetch_sitemap(candidate)
entry["status_code"] = fetched["status_code"]
- if fetched["error"]:
- entry["error"] = fetched["error"]
- elif fetched["too_large"]:
- entry["error"] = "Sitemap exceeds the 50 MiB uncompressed protocol limit"
- elif fetched["status_code"] is None or not 200 <= fetched["status_code"] < 300:
- entry["error"] = f"HTTP {fetched['status_code']}" if fetched["status_code"] is not None else "No response"
- else:
- kind, error = _sitemap_kind(
- fetched["content"], fetched["content_type"], fetched["final_url"]
- )
- entry["kind"] = kind
- entry["error"] = error
- entry["valid"] = kind is not None
+ if body is not None:
+ if body["gzip"]:
+ entry["gzip"] = True
+ entry["kind"] = body["kind"]
+ entry["valid"] = body["kind"] is not None
if entry["valid"]:
final_display, final_redacted = _display_url(fetched["final_url"])
entry["url"] = final_display
entry["query_redacted"] = query_redacted or final_redacted
- result["found"].append(dict(entry))
+ if fetched["final_url"] not in listed:
+ listed.add(fetched["final_url"])
+ result["found"].append(dict(entry))
result["checked"].append(entry)
-
+ if expansion is not None:
+ expansion.add_top_level(candidate, entry, fetched, body)
+
+ if expansion is not None:
+ # Release the last parsed tree before the child sitemaps are read.
+ fetched = body = None
+ children = expansion.follow_children(max_children, result["warnings"])
+ result["expanded"] = {
+ "files": expansion.files,
+ "totals": expansion.totals(result["warnings"]),
+ "children": children,
+ "truncated": children["skipped"] > 0,
+ "sample_size": sample_size,
+ }
return result
+def _bounded_int(low: int, high: int):
+ def parse(value: str) -> int:
+ number = int(value)
+ if not low <= number <= high:
+ raise argparse.ArgumentTypeError(f"must be between {low} and {high}")
+ return number
+ return parse
+
+
def main() -> int:
parser = argparse.ArgumentParser(description="Discover sitemaps safely")
parser.add_argument("url", help="Public site URL")
parser.add_argument("--json", action="store_true", help="Output structured JSON")
+ parser.add_argument(
+ "--expand",
+ action="store_true",
+ help="Read each sitemap found, follow a sitemap index to its children, and report per-file statistics",
+ )
+ parser.add_argument(
+ "--max-children",
+ type=_bounded_int(0, MAX_SITEMAP_URLS),
+ default=DEFAULT_MAX_CHILDREN,
+ metavar="N",
+ help=f"With --expand: most child sitemaps to fetch across all indexes (default {DEFAULT_MAX_CHILDREN})",
+ )
+ parser.add_argument(
+ "--sample",
+ type=_bounded_int(0, 1000),
+ default=DEFAULT_SAMPLE,
+ metavar="N",
+ help=f"With --expand: URLs kept per file in sample_urls; all are counted (default {DEFAULT_SAMPLE})",
+ )
args = parser.parse_args()
- result = discover_sitemaps(args.url)
+ result = discover_sitemaps(args.url, expand=args.expand, max_children=args.max_children, sample_size=args.sample)
if args.json:
print(json.dumps(result, indent=2))
elif result["error"]:
print(f"Error: {result['error']}", file=sys.stderr)
+ elif args.expand and result["expanded"]["files"]:
+ for item in result["expanded"]["files"]:
+ if not item["valid"]:
+ detail = item["error"]
+ elif item["kind"] == "sitemapindex":
+ detail = f"{item['child_count']} child sitemaps"
+ else:
+ detail = f"{item['url_count']} URLs"
+ flags = f" [{', '.join(item['findings'])}]" if item["findings"] else ""
+ print(f"{item['url']} ({item['kind'] or 'invalid'}, {detail}){flags}")
+ totals = result["expanded"]["totals"]
+ print(f"Total: {totals['total_urls']} URLs in {totals['sitemap_files']} files, {totals['unique_urls']} unique")
+ for warning in result["warnings"]:
+ print(f"Warning: {warning}", file=sys.stderr)
elif result["found"]:
for item in result["found"]:
print(f"{item['url']} ({item['kind']})")
diff --git a/skills/seo-sitemap/SKILL.md b/skills/seo-sitemap/SKILL.md
index e0b143c..a56cecc 100644
--- a/skills/seo-sitemap/SKILL.md
+++ b/skills/seo-sitemap/SKILL.md
@@ -17,33 +17,53 @@ metadata:
## Mode 1: Analyze Existing Sitemap
-Discover candidates before reporting a sitemap missing:
+Discover candidates before reporting a sitemap missing, and read every sitemap
+found in the same run:
```bash
-"${CLAUDE_PLUGIN_ROOT}/scripts/claude-seo" run sitemap_discovery.py <url> --json
+"${CLAUDE_PLUGIN_ROOT}/scripts/claude-seo" run sitemap_discovery.py <url> --expand --json
```
The helper reads every bounded `Sitemap:` declaration in robots.txt, validates
cross-host targets through the shared SSRF-safe fetch layer, and still probes
common paths when a declared sitemap is stale or invalid. Use only entries in
`found`; preserve declared failures as findings instead of treating a robots.txt
-line alone as proof that a sitemap works.
+line alone as proof that a sitemap works. Gzip sitemaps (`.xml.gz`) are inflated
+and classified by their content; such an entry carries `gzip: true`.
+
+With `--expand` it also follows a sitemap index one level down to its child
+sitemaps and counts every entry. `expanded.files` has one
+object per sitemap file and `expanded.totals` sums them. Read these checks from
+the output; do not count or parse sitemap files by hand:
+
+| Check | Fields in `expanded` |
+|-------|----------------------|
+| Valid XML, file reachable | `files[].valid`, `error`, `status_code`, `kind` |
+| Per-file limit: **≤50,000 URLs AND ≤50MB uncompressed** | `url_count`, `bytes`, `decompressed_bytes`; `findings` holds `over_50000_urls`, `over_50000_sitemaps` or `over_50mib_uncompressed` |
+| Index structure | `child_count`, child files carry `parent`; `nested_sitemap_index` in `findings` means an index lists another index (not allowed, not followed) |
+| `<lastmod>` present and valid **W3C Datetime** | `lastmod_count` against `url_count`, `lastmod_invalid_count` |
+| `<lastmod>` suspiciously uniform | `lastmod_identical_share` near 1.0 on a file with many URLs, with `lastmod_most_common`, `lastmod_oldest`, `lastmod_newest` |
+| URLs on another host than their sitemap | `cross_host_url_count`, `cross_host_url_examples`; a child file on another host has `cross_host` |
+| Duplicate or malformed URLs | `duplicate_count`, `invalid_loc_count`; `totals.unique_urls` against `totals.total_urls`, `totals.duplicates_across_files` |
+| Sitemap referenced in robots.txt | `source` is `robots.txt` (top-level `declared` lists every directive) |
+| Run cut short | `truncated`, `children.skipped`; rerun with a higher `--max-children` (default 50) |
+
+URLs in the output have query strings removed (`query_redacted`). Every URL is
+counted, but only `--sample` URLs per file (default 20) are printed in
+`sample_urls`.
### Validation Checks
-- Valid XML format
-- Per-file limit: **≤50,000 URLs AND ≤50MB uncompressed** (whichever is hit first)
-- All URLs return HTTP 200
-- `<lastmod>` accurate: must be a valid **W3C Datetime** and reflect the **last
- significant content change** (main content, structured data, links, not
- copyright/boilerplate edits). Google only honours `<lastmod>` when consistently
- and verifiably accurate, so warn when values are suspiciously uniform or newer
- than the page's real content.
+The script cannot judge these; check them yourself:
+- URLs return HTTP 200: spot-check `sample_urls` from each file
+- `<lastmod>` accuracy: it must reflect the **last significant content change**
+ (main content, structured data, links, not copyright/boilerplate edits).
+ Google only honours `<lastmod>` when consistently and verifiably accurate, so
+ warn when values are newer than the page's real content.
- No deprecated tags: `<priority>` and `<changefreq>` are ignored by Google
-- Sitemap referenced in robots.txt
- Compare crawled pages vs sitemap; flag missing pages
### Quality Signals
-- Sitemap index file if >50k URLs
+- Sitemap index file if >50k URLs (`totals.total_urls`, `kind`)
- Split by content type (pages, posts, images, videos)
- No non-canonical URLs in sitemap
- No noindexed URLs in sitemap
diff --git a/tests/test_sitemap_discovery.py b/tests/test_sitemap_discovery.py
index bafeec8..73d80f6 100644
--- a/tests/test_sitemap_discovery.py
+++ b/tests/test_sitemap_discovery.py
@@ -2,7 +2,10 @@
from __future__ import annotations
+import gzip
import sys
+import tracemalloc
+import zlib
from pathlib import Path
from unittest.mock import patch
@@ -195,3 +198,99 @@ def test_commented_sitemap_directive_is_the_url_that_gets_fetched():
result = discovery.discover_sitemaps("https://example.com")
assert declared in fetched
assert [item["url"] for item in result["found"] if item["url"] == declared] == [declared]
+
+
+def test_paths_that_redirect_to_one_sitemap_are_listed_once():
+ """Rank Math sends /sitemap.xml to /sitemap_index.xml: one file, one listing."""
+ final = "https://example.com/sitemap_index.xml"
+
+ def fake_fetch(url, _limit):
+ if url.endswith("robots.txt"):
+ return response(content=b"User-agent: *\n")
+ if url.endswith(("/sitemap.xml", "/sitemap_index.xml")):
+ return response(content=INDEX, url=final)
+ return response(status=404, url=url)
+
+ with patch.object(discovery, "_bounded_fetch", side_effect=fake_fetch):
+ result = discovery.discover_sitemaps("https://example.com")
+ assert [item["url"] for item in result["found"]] == [final]
+ # Both paths were checked and both answered with a valid sitemap.
+ assert [item["valid"] for item in result["checked"]] == [True, True, False, False]
+ assert "expanded" not in result
+
+
+def discover_one(body, url="https://example.com/sitemap.xml.gz", content_type="application/gzip"):
+ """Plain discovery of a site whose robots.txt declares one sitemap."""
+
+ def fake_fetch(fetch_url, _limit):
+ if fetch_url.endswith("robots.txt"):
+ return response(content=f"Sitemap: {url}\n".encode())
+ if fetch_url == url:
+ return response(content=body, url=url, content_type=content_type)
+ return response(status=404, url=fetch_url)
+
+ with patch.object(discovery, "_bounded_fetch", side_effect=fake_fetch):
+ result = discovery.discover_sitemaps("https://example.com")
+ return result, result["checked"][0]
+
+
+ ("plain", "kind"),
+ [(URLSET, "urlset"), (INDEX, "sitemapindex"), (b"https://example.com/one\nhttps://example.com/two\n", None)],
+)
+def test_gzip_sitemap_is_classified_by_its_decompressed_content(plain, kind):
+ result, entry = discover_one(gzip.compress(plain))
+ assert entry["gzip"] is True
+ assert (entry["kind"], entry["valid"]) == (kind, kind is not None)
+ assert [item["url"] for item in result["found"]] == (["https://example.com/sitemap.xml.gz"] if kind else [])
+ assert set(result) == {"target", "robots_url", "declared", "found", "checked", "warnings", "error"}
+
+
+def test_gzip_is_detected_by_content_and_plain_entries_carry_no_marker():
+ # No .gz in the name and a generic content type: the magic bytes decide.
+ result, entry = discover_one(gzip.compress(URLSET), "https://example.com/map", "application/octet-stream")
+ assert (entry["kind"], entry["gzip"]) == ("urlset", True)
+ # A .gz name whose transfer encoding was already undone is plain XML.
+ result, entry = discover_one(URLSET)
+ assert entry["kind"] == "urlset"
+ assert "gzip" not in entry and "gzip" not in result["found"][0]
+
+
+def test_gzip_text_sitemap_is_classified_by_its_inner_name():
+ body = gzip.compress(b"https://example.com/one\nhttps://example.com/two\n")
+ _, entry = discover_one(body, "https://example.com/urls.txt.gz")
+ assert (entry["kind"], entry["valid"], entry["gzip"]) == ("text", True, True)
+
+
+def test_gzip_bomb_in_plain_discovery_is_cut_off_at_the_cap():
+ packer = zlib.compressobj(9, zlib.DEFLATED, 16 + zlib.MAX_WBITS)
+ piece = b" " * (1024 * 1024)
+ bomb = b"".join(packer.compress(piece) for _ in range(64)) + packer.flush()
+ assert len(bomb) < 200 * 1024
+ tracemalloc.start()
+ try:
+ with patch.object(discovery, "MAX_SITEMAP_BYTES", 1024 * 1024):
+ result, entry = discover_one(bomb)
+ _current, peak = tracemalloc.get_traced_memory()
+ finally:
+ tracemalloc.stop()
+ assert (entry["valid"], entry["kind"], entry["gzip"]) == (False, None, True)
+ assert "50 MiB" in entry["error"]
+ assert result["found"] == []
+ # Inflating all of it would take 64 MiB; the capped read stays near 2 MiB.
+ assert peak < 8 * 1024 * 1024
+
+
+def test_corrupt_or_truncated_gzip_is_reported_not_found():
+ packed = gzip.compress(URLSET * 50, mtime=0)
+ for damaged in (packed[:-12], packed[:20] + b"\xff" * 20 + packed[40:], b"\x1f\x8b not gzip at all"):
+ result, entry = discover_one(damaged)
+ assert (entry["valid"], entry["error"], entry["gzip"]) == (False, "invalid gzip data", True)
+ assert result["found"] == []
+
+
+def test_doctype_inside_gzip_is_refused():
+ hostile = b'<!DOCTYPE urlset [<!ENTITY x SYSTEM "file:///etc/passwd">]><urlset><url><loc>&x;</loc></url></urlset>'
+ result, entry = discover_one(gzip.compress(hostile))
+ assert (entry["valid"], entry["error"]) == (False, "DOCTYPE is not allowed in sitemap XML")
+ assert result["found"] == []
diff --git a/tests/test_sitemap_expand.py b/tests/test_sitemap_expand.py
new file mode 100644
index 0000000..db0d38f
--- /dev/null
+++ b/tests/test_sitemap_expand.py
@@ -0,0 +1,529 @@
+"""Sitemap expansion: sitemap_discovery.py --expand reads what discovery found.
+
+All fetches are mocked at ``_bounded_fetch``, the single request path of the
+script, so the tests also prove that no child sitemap is fetched another way.
+"""
+
+from __future__ import annotations
+
+import gzip
+import json
+import sys
+import tracemalloc
+import zlib
+from pathlib import Path
+from unittest.mock import patch
+
+import pytest
+
+ROOT = Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(ROOT / "scripts"))
+
+pytest.importorskip("lxml")
+
+import sitemap_discovery as discovery # noqa: E402
+
+SITE = "https://example.com"
+NS = 'xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"'
+BASE_KEYS = {"target", "robots_url", "declared", "found", "checked", "warnings", "error"}
+
+
+def urlset(*entries) -> bytes:
+ """Entries are a loc, or a (loc, lastmod) pair."""
+ rows = []
+ for entry in entries:
+ loc, lastmod = entry if isinstance(entry, tuple) else (entry, None)
+ stamp = f"<lastmod>{lastmod}</lastmod>" if lastmod else ""
+ rows.append(f"<url><loc>{loc}</loc>{stamp}</url>")
+ return f'<?xml version="1.0"?><urlset {NS}>{"".join(rows)}</urlset>'.encode()
+
+
+def index(*locs) -> bytes:
+ rows = "".join(f"<sitemap><loc>{loc}</loc></sitemap>" for loc in locs)
+ return f'<?xml version="1.0"?><sitemapindex {NS}>{rows}</sitemapindex>'.encode()
+
+
+def response(content=b"", url=SITE + "/", status=200, content_type="application/xml", too_large=False):
+ return {
+ "status_code": status,
+ "content": content,
+ "content_type": content_type,
+ "final_url": url,
+ "too_large": too_large,
+ "error": None,
+ }
+
+
+def run(routes, robots=b"", **options):
+ """Run discovery against a route table. Returns (result, fetched URLs).
+
+ A route value is a body (served at its own URL), a full response dict, or
+ a callable taking the URL. Unlisted URLs answer 404.
+ """
+ fetched = []
+
+ def fake_fetch(url, _limit):
+ fetched.append(url)
+ if url == SITE + "/robots.txt":
+ return response(robots, url, content_type="text/plain")
+ route = routes.get(url)
+ if route is None:
+ return response(url=url, status=404)
+ if callable(route):
+ return route(url)
+ return route if isinstance(route, dict) else response(route, url)
+
+ options.setdefault("expand", True)
+ with patch.object(discovery, "_bounded_fetch", side_effect=fake_fetch):
+ result = discovery.discover_sitemaps(SITE, **options)
+ json.dumps(result) # The whole result must stay JSON serialisable.
+ return result, fetched
+
+
+def file_for(result, suffix):
+ return next(item for item in result["expanded"]["files"] if item["url"].endswith(suffix))
+
+
+def test_output_without_expand_keeps_its_keys():
+ result, _ = run({SITE + "/sitemap.xml": urlset(SITE + "/a")}, expand=False)
+ assert set(result) == BASE_KEYS
+ assert set(result["found"][0]) == {
+ "url", "query_redacted", "source", "status_code", "kind", "valid", "error",
+ }
+
+
+def test_expand_adds_one_key_and_leaves_discovery_keys_alone():
+ routes = {SITE + "/sitemap.xml": urlset(SITE + "/a")}
+ plain, _ = run(routes, expand=False)
+ expanded, _ = run(routes)
+ assert set(expanded) == BASE_KEYS | {"expanded"}
+ assert {key: expanded[key] for key in BASE_KEYS} == plain
+
+
+def test_index_children_are_fetched_once_and_totalled():
+ routes = {
+ SITE + "/sitemap_index.xml": index(SITE + "/posts.xml", SITE + "/pages.xml", SITE + "/posts.xml"),
+ SITE + "/posts.xml": urlset(SITE + "/p1", SITE + "/p2"),
+ SITE + "/pages.xml": urlset(SITE + "/about"),
+ }
+ result, fetched = run(routes)
+ top = file_for(result, "/sitemap_index.xml")
+ assert (top["kind"], top["child_count"], top["url_count"], top["duplicate_count"]) == ("sitemapindex", 3, 0, 1)
+ posts = file_for(result, "/posts.xml")
+ assert (posts["source"], posts["parent"], posts["url_count"]) == ("sitemapindex", top["url"], 2)
+ assert fetched.count(SITE + "/posts.xml") == 1
+ assert result["expanded"]["totals"] == {
+ "sitemap_files": 3,
+ "total_urls": 3,
+ "unique_urls": 3,
+ "duplicates_within_files": 0,
+ "duplicates_across_files": 0,
+ "invalid_locs": 0,
+ }
+ assert result["expanded"]["children"] == {"limit": 50, "listed": 2, "fetched": 2, "skipped": 0}
+ assert result["expanded"]["truncated"] is False
+ # Children are reported under "expanded" only; "found" still means discovery.
+ assert [item["url"] for item in result["found"]] == [SITE + "/sitemap_index.xml"]
+
+
+def test_child_limit_stops_fetching_and_says_so():
+ children = [f"{SITE}/c{number}.xml" for number in range(4)]
+ routes = {SITE + "/sitemap.xml": index(*children)}
+ routes.update({child: urlset(child + "/page") for child in children})
+ result, fetched = run(routes, max_children=1)
+ assert [url for url in fetched if url in children] == [children[0]]
+ assert result["expanded"]["children"] == {"limit": 1, "listed": 4, "fetched": 1, "skipped": 3}
+ assert result["expanded"]["truncated"] is True
+ assert sum("Child sitemap limit reached (1)" in warning for warning in result["warnings"]) == 1
+ assert result["expanded"]["totals"]["total_urls"] == 1
+
+
+def test_nested_index_is_a_finding_and_is_not_followed():
+ routes = {
+ SITE + "/sitemap.xml": index(SITE + "/nested.xml"),
+ SITE + "/nested.xml": index(SITE + "/grandchild.xml"),
+ SITE + "/grandchild.xml": urlset(SITE + "/deep"),
+ }
+ result, fetched = run(routes)
+ assert SITE + "/grandchild.xml" not in fetched
+ assert file_for(result, "/sitemap.xml")["findings"] == ["nested_sitemap_index"]
+ nested = file_for(result, "/nested.xml")
+ assert (nested["kind"], nested["child_count"]) == ("sitemapindex", 1)
+ assert any("Nested sitemap index was not followed" in warning for warning in result["warnings"])
+ assert result["expanded"]["totals"]["total_urls"] == 0
+
+
+def test_index_that_lists_itself_is_not_refetched():
+ routes = {SITE + "/sitemap.xml": index(SITE + "/sitemap.xml")}
+ result, fetched = run(routes)
+ assert fetched.count(SITE + "/sitemap.xml") == 1
+ assert file_for(result, "/sitemap.xml")["findings"] == ["nested_sitemap_index"]
+
+
+def test_paths_redirecting_to_one_file_are_reported_and_counted_once():
+ final = SITE + "/sitemap_index.xml"
+ body = index(SITE + "/posts.xml")
+ routes = {
+ SITE + "/sitemap.xml": response(body, final),
+ final: body,
+ SITE + "/posts.xml": urlset(SITE + "/p1"),
+ }
+ result, fetched = run(routes, robots=f"Sitemap: {SITE}/posts.xml\n".encode())
+ assert [item["url"] for item in result["found"]] == [SITE + "/posts.xml", final]
+ assert [item["url"] for item in result["expanded"]["files"]] == [SITE + "/posts.xml", final]
+ # posts.xml was declared in robots.txt and listed in the index: read once.
+ assert fetched.count(SITE + "/posts.xml") == 1
+ assert result["expanded"]["totals"]["total_urls"] == 1
+
+
+def test_child_redirecting_to_a_known_file_is_counted_once():
+ routes = {
+ SITE + "/sitemap.xml": index(SITE + "/posts.xml", SITE + "/old-posts.xml"),
+ SITE + "/posts.xml": urlset(SITE + "/p1"),
+ SITE + "/old-posts.xml": response(urlset(SITE + "/p1"), SITE + "/posts.xml"),
+ }
+ result, _ = run(routes)
+ assert [item["url"] for item in result["expanded"]["files"]].count(SITE + "/posts.xml") == 1
+ assert result["expanded"]["totals"]["total_urls"] == 1
+
+
+def test_gzip_sitemap_is_inflated_by_magic_bytes():
+ plain = urlset(SITE + "/a", SITE + "/b")
+ packed = gzip.compress(plain)
+ # The second URL has no .gz suffix: detection is by content, not by name.
+ routes = {SITE + "/sitemap.xml": index(SITE + "/posts.xml.gz", SITE + "/pages"),
+ SITE + "/posts.xml.gz": response(packed, SITE + "/posts.xml.gz", content_type="application/gzip"),
+ SITE + "/pages": response(packed, SITE + "/pages", content_type="application/octet-stream")}
+ result, _ = run(routes)
+ for suffix in ("/posts.xml.gz", "/pages"):
+ item = file_for(result, suffix)
+ assert (item["kind"], item["valid"], item["gzip"], item["url_count"]) == ("urlset", True, True, 2)
+ assert (item["bytes"], item["decompressed_bytes"]) == (len(packed), len(plain))
+ assert file_for(result, "/sitemap.xml")["gzip"] is False
+ assert file_for(result, "/sitemap.xml")["decompressed_bytes"] is None
+
+
+def test_gzip_is_classified_the_same_with_and_without_expand():
+ packed = gzip.compress(urlset(SITE + "/a"))
+ routes = {SITE + "/sitemap.xml": response(packed, SITE + "/sitemap.xml", content_type="application/gzip")}
+ plain, _ = run(routes, expand=False)
+ expanded, _ = run(routes)
+ assert [(item["kind"], item["gzip"]) for item in plain["found"]] == [("urlset", True)]
+ assert {key: expanded[key] for key in BASE_KEYS} == plain
+
+
+def test_gzip_text_sitemap_is_classified_by_its_inner_name():
+ packed = gzip.compress(f"{SITE}/one\n{SITE}/two\n".encode())
+ routes = {SITE + "/sitemap.xml": index(SITE + "/urls.txt.gz"),
+ SITE + "/urls.txt.gz": response(packed, SITE + "/urls.txt.gz", content_type="application/gzip")}
+ result, _ = run(routes)
+ item = file_for(result, "/urls.txt.gz")
+ assert (item["kind"], item["url_count"], item["lastmod_count"]) == ("text", 2, 0)
+
+
+def bomb(megabytes: int) -> bytes:
+ """A small gzip stream that inflates to the given size, built in pieces."""
+ packer = zlib.compressobj(9, zlib.DEFLATED, 16 + zlib.MAX_WBITS)
+ piece = b" " * (1024 * 1024)
+ return b"".join(packer.compress(piece) for _ in range(megabytes)) + packer.flush()
+
+
+def test_gunzip_stops_at_the_cap_without_inflating_the_rest():
+ data = bomb(64)
+ assert len(data) < 200 * 1024
+ tracemalloc.start()
+ try:
+ assert discovery._gunzip_bounded(data, 1024 * 1024) == (b"", True)
+ _current, peak = tracemalloc.get_traced_memory()
+ finally:
+ tracemalloc.stop()
+ # 64 MiB would be needed to inflate it all; the capped read stays near 2 MiB.
+ assert peak < 8 * 1024 * 1024
+
+
+def test_gunzip_reads_exactly_up_to_the_cap():
+ body = b"x" * 5000
+ assert discovery._gunzip_bounded(gzip.compress(body), 5000) == (body, False)
+ assert discovery._gunzip_bounded(gzip.compress(body), 4999) == (b"", True)
+ # Concatenated gzip members are one file.
+ assert discovery._gunzip_bounded(gzip.compress(b"ab") + gzip.compress(b"cd"), 10) == (b"abcd", False)
+
+
+def test_gzip_over_the_uncompressed_limit_is_a_finding_not_a_parse():
+ packed = gzip.compress(urlset(*[f"{SITE}/{'x' * 200}{number}" for number in range(50)]))
+ routes = {SITE + "/sitemap.xml": index(SITE + "/big.xml.gz"),
+ SITE + "/big.xml.gz": response(packed, SITE + "/big.xml.gz")}
+ with patch.object(discovery, "MAX_SITEMAP_BYTES", 1024):
+ result, _ = run(routes)
+ item = file_for(result, "/big.xml.gz")
+ assert (item["valid"], item["kind"], item["url_count"]) == (False, None, None)
+ assert item["findings"] == ["over_50mib_uncompressed"]
+ assert "50 MiB" in item["error"]
+
+
[email protected]("damage", [lambda data: data[:-12], lambda data: data[:20] + b"\xff" * 20 + data[40:]])
+def test_truncated_or_corrupt_gzip_is_an_error(damage):
+ packed = damage(gzip.compress(urlset(*[f"{SITE}/page-{number}" for number in range(200)]), mtime=0))
+ routes = {SITE + "/sitemap.xml": index(SITE + "/broken.xml.gz"),
+ SITE + "/broken.xml.gz": response(packed, SITE + "/broken.xml.gz")}
+ result, _ = run(routes)
+ item = file_for(result, "/broken.xml.gz")
+ assert (item["valid"], item["error"]) == (False, "invalid gzip data")
+
+
+def test_oversized_body_is_reported_as_a_limit_finding():
+ routes = {SITE + "/sitemap.xml": response(b"<urlset>", SITE + "/sitemap.xml", too_large=True)}
+ result, _ = run(routes)
+ item = file_for(result, "/sitemap.xml")
+ assert (item["valid"], item["bytes"], item["findings"]) == (False, None, ["over_50mib_uncompressed"])
+ assert result["found"] == []
+
+
+def test_more_than_50000_urls_is_a_finding_and_the_sample_stays_bounded():
+ locs = [f"{SITE}/p{number}" for number in range(50001)]
+ result, _ = run({SITE + "/sitemap.xml": urlset(*locs)}, sample_size=3)
+ item = file_for(result, "/sitemap.xml")
+ assert item["url_count"] == 50001
+ assert item["findings"] == ["over_50000_urls"]
+ assert item["sample_urls"] == locs[:3]
+ assert result["expanded"]["sample_size"] == 3
+ assert result["expanded"]["totals"]["unique_urls"] == 50001
+ assert len(json.dumps(result)) < 5000
+
+
+def test_exactly_50000_urls_is_within_the_limit():
+ result, _ = run({SITE + "/sitemap.xml": urlset(*[f"{SITE}/p{number}" for number in range(50000)])}, sample_size=0)
+ item = file_for(result, "/sitemap.xml")
+ assert (item["url_count"], item["findings"], item["sample_urls"]) == (50000, [], [])
+
+
+def test_oversized_text_sitemap_keeps_its_count():
+ body = "\n".join(f"{SITE}/p{number}" for number in range(50001)).encode()
+ routes = {SITE + "/sitemap.xml": index(SITE + "/urls.txt"),
+ SITE + "/urls.txt": response(body, SITE + "/urls.txt", content_type="text/plain")}
+ result, _ = run(routes)
+ item = file_for(result, "/urls.txt")
+ assert (item["valid"], item["url_count"], item["findings"]) == (False, 50001, ["over_50000_urls"])
+
+
+def test_lastmod_statistics():
+ result, _ = run({SITE + "/sitemap.xml": urlset(
+ (SITE + "/a", "2026-03-01T00:30:00+02:00"), # 2026-02-28 22:30 UTC: the oldest
+ (SITE + "/b", "2026-03-01"),
+ (SITE + "/c", "2026-03-01"),
+ (SITE + "/d", "2026-03-01"),
+ (SITE + "/e", "2026-03-01T01:00:00Z"), # the newest
+ (SITE + "/f", "yesterday"),
+ (SITE + "/g", "2026-13-01"),
+ SITE + "/h",
+ )})
+ item = file_for(result, "/sitemap.xml")
+ assert (item["url_count"], item["lastmod_count"], item["lastmod_invalid_count"]) == (8, 7, 2)
+ assert item["lastmod_oldest"] == "2026-03-01T00:30:00+02:00"
+ assert item["lastmod_newest"] == "2026-03-01T01:00:00Z"
+ assert item["lastmod_most_common"] == "2026-03-01"
+ assert item["lastmod_identical_share"] == round(3 / 7, 4)
+
+
+def test_auto_stamped_lastmod_shows_as_a_full_share():
+ stamp = "2026-11-10T03:00:00+00:00"
+ result, _ = run({SITE + "/sitemap.xml": urlset(*[(f"{SITE}/p{number}", stamp) for number in range(40)])})
+ item = file_for(result, "/sitemap.xml")
+ assert (item["lastmod_identical_share"], item["lastmod_oldest"], item["lastmod_newest"]) == (1.0, stamp, stamp)
+
+
+def test_file_without_lastmod_reports_no_share():
+ result, _ = run({SITE + "/sitemap.xml": urlset(SITE + "/a")})
+ item = file_for(result, "/sitemap.xml")
+ assert (item["lastmod_count"], item["lastmod_oldest"], item["lastmod_identical_share"]) == (0, None, None)
+
+
+ ("value", "valid"),
+ [
+ ("2026", True),
+ ("2026-02", True),
+ ("2026-02-07", True),
+ ("2026-02-07T10:15Z", True),
+ ("2026-02-07T10:15:30+01:00", True),
+ ("2026-02-07T10:15:30.25-08:00", True),
+ ("2026-02-07T10:15:30", False), # A time needs a zone.
+ ("2026-02-30", False),
+ ("2026-02-07 10:15:30Z", False),
+ ("07/02/2026", False),
+ ("2026-02-07T10:15:30+25:00", False),
+ ("", False),
+ ],
+)
+def test_w3c_datetime_validation(value, valid):
+ assert (discovery._parse_w3c_datetime(value) is not None) is valid
+
+
+def test_entries_on_another_host_are_counted_with_redacted_examples():
+ locs = [SITE + "/home", "https://www.example.com/a?token=keep-out"]
+ locs += [f"https://other.example.net/p{number}" for number in range(8)]
+ result, _ = run({SITE + "/sitemap.xml": urlset(*locs)})
+ item = file_for(result, "/sitemap.xml")
+ assert item["cross_host_url_count"] == 9
+ assert len(item["cross_host_url_examples"]) == discovery.MAX_EXAMPLES
+ assert item["cross_host_url_examples"][0] == "https://www.example.com/a"
+ assert "keep-out" not in json.dumps(result)
+
+
+def test_duplicates_within_and_across_files_after_normalisation():
+ routes = {
+ SITE + "/sitemap.xml": index(SITE + "/one.xml", SITE + "/two.xml"),
+ SITE + "/one.xml": urlset(
+ SITE + "/a",
+ "HTTPS://EXAMPLE.com:443/a?utm_source=news#top", # same as /a
+ SITE + "/a/", # the trailing slash is a different address
+ SITE + "/b?id=1",
+ ),
+ SITE + "/two.xml": urlset(SITE + "/a", SITE + "/b?id=2", SITE + "/c"),
+ }
+ result, _ = run(routes)
+ assert file_for(result, "/one.xml")["duplicate_count"] == 1
+ assert file_for(result, "/two.xml")["duplicate_count"] == 0
+ assert result["expanded"]["totals"] == {
+ "sitemap_files": 3,
+ "total_urls": 7,
+ "unique_urls": 5,
+ "duplicates_within_files": 1,
+ "duplicates_across_files": 1,
+ "invalid_locs": 0,
+ }
+
+
+def test_duplicate_totals_are_withheld_when_tracking_is_full():
+ locs = [f"{SITE}/p{number}" for number in range(5)]
+ with patch.object(discovery, "MAX_TRACKED_URLS", 2):
+ result, _ = run({SITE + "/sitemap.xml": urlset(*locs)})
+ totals = result["expanded"]["totals"]
+ assert (totals["total_urls"], totals["unique_urls"], totals["duplicates_across_files"]) == (5, None, None)
+ assert file_for(result, "/sitemap.xml")["duplicate_count"] is None
+ assert any("unique and duplicate totals are not reported" in warning for warning in result["warnings"])
+
+
+def test_invalid_locs_are_counted_and_never_printed():
+ body = urlset("/relative", "javascript:alert(1)", "https://user:[email protected]/x", SITE + "/" + "a" * 2048, SITE + "/ok")
+ body = body.replace(b"</urlset>", b"<url></url></urlset>")
+ result, _ = run({SITE + "/sitemap.xml": body})
+ item = file_for(result, "/sitemap.xml")
+ assert (item["url_count"], item["invalid_loc_count"], item["sample_urls"]) == (6, 5, [SITE + "/ok"])
+ assert "secret" not in json.dumps(result)
+
+
+def test_child_urls_are_validated_like_any_other_url():
+ """A child loc is untrusted: bad syntax is never fetched, a private target is refused."""
+ private = "http://127.0.0.1/internal.xml"
+ real_fetch = discovery._bounded_fetch
+ routes = {
+ SITE + "/sitemap.xml": index(
+ private,
+ "file:///etc/passwd",
+ "https://user:[email protected]/a.xml",
+ "//example.com/b.xml",
+ "https://exa mple.com/c.xml",
+ ),
+ # The real fetch path: url_safety refuses the literal before any request.
+ private: lambda url: real_fetch(url, 100),
+ }
+ result, fetched = run(routes)
+ assert [url for url in fetched if "sitemap" not in url and "robots" not in url] == [private]
+ top = file_for(result, "/sitemap.xml")
+ assert (top["child_count"], top["invalid_loc_count"]) == (5, 4)
+ refused = file_for(result, "/internal.xml")
+ assert (refused["valid"], refused["error"], refused["status_code"]) == (False, "URL safety validation failed", None)
+ assert refused["cross_host"] is True
+
+
+def test_cross_host_child_is_flagged_and_uses_the_same_fetch():
+ child = "https://cdn.example.net/posts.xml?sig=private-value"
+ routes = {SITE + "/sitemap.xml": index(child.replace("&", "&amp;")), child: urlset("https://cdn.example.net/p1")}
+ result, fetched = run(routes)
+ assert child in fetched
+ item = file_for(result, "/posts.xml")
+ assert (item["cross_host"], item["valid"], item["query_redacted"]) == (True, True, True)
+ assert item["cross_host_url_count"] == 0 # Entries match the host of their own file.
+ top = file_for(result, "/sitemap.xml")
+ assert (top["cross_host_url_count"], top["cross_host_url_examples"]) == (1, ["https://cdn.example.net/posts.xml"])
+ assert "private-value" not in json.dumps(result)
+
+
+def test_same_host_child_has_no_cross_host_flag():
+ routes = {SITE + "/sitemap.xml": index(SITE + "/posts.xml"), SITE + "/posts.xml": urlset(SITE + "/p1")}
+ result, _ = run(routes)
+ assert "cross_host" not in file_for(result, "/posts.xml")
+
+
+def test_xml_hardening_applies_to_children_and_inside_gzip():
+ hostile = b'<!DOCTYPE urlset [<!ENTITY x SYSTEM "file:///etc/passwd">]><urlset><url><loc>&x;</loc></url></urlset>'
+ routes = {
+ SITE + "/sitemap.xml": index(SITE + "/plain.xml", SITE + "/packed.xml.gz", SITE + "/broken.xml", SITE + "/gone.xml"),
+ SITE + "/plain.xml": hostile,
+ SITE + "/packed.xml.gz": gzip.compress(hostile),
+ SITE + "/broken.xml": b"<urlset><url>",
+ }
+ result, _ = run(routes)
+ for suffix in ("/plain.xml", "/packed.xml.gz"):
+ item = file_for(result, suffix)
+ assert (item["valid"], item["error"], item["url_count"]) == (False, "DOCTYPE is not allowed in sitemap XML", None)
+ assert file_for(result, "/broken.xml")["error"] == "invalid XML"
+ assert (file_for(result, "/gone.xml")["error"], file_for(result, "/gone.xml")["status_code"]) == ("HTTP 404", 404)
+ assert result["expanded"]["totals"]["sitemap_files"] == 1
+
+
+def test_extension_tags_are_not_mistaken_for_entries():
+ body = (
+ f'<urlset {NS} xmlns:image="http://www.google.com/schemas/sitemap-image/1.1" '
+ 'xmlns:xhtml="http://www.w3.org/1999/xhtml"><!-- note -->'
+ f"<url><loc>{SITE}/a</loc>"
+ '<xhtml:link rel="alternate" hreflang="de" href="https://example.de/a"/>'
+ "<image:image><image:loc>https://cdn.example.net/a.png</image:loc></image:image></url></urlset>"
+ ).encode()
+ result, _ = run({SITE + "/sitemap.xml": body})
+ item = file_for(result, "/sitemap.xml")
+ assert (item["url_count"], item["cross_host_url_count"], item["sample_urls"]) == (1, 0, [SITE + "/a"])
+
+
+def test_feeds_count_their_item_links():
+ rss = f"<rss><channel><link>{SITE}/</link><item><link>{SITE}/one</link></item><item><link>{SITE}/two</link></item></channel></rss>"
+ atom = (
+ '<feed xmlns="http://www.w3.org/2005/Atom">'
+ f'<link href="{SITE}/"/><entry><link rel="self" href="{SITE}/feed/1"/>'
+ f'<link href="{SITE}/one"/><updated>2026-02-07T10:00:00Z</updated></entry></feed>'
+ )
+ routes = {SITE + "/sitemap.xml": rss.encode(), SITE + "/wp-sitemap.xml": atom.encode()}
+ result, _ = run(routes)
+ assert (file_for(result, "/sitemap.xml")["kind"], file_for(result, "/sitemap.xml")["url_count"]) == ("rss", 2)
+ feed = file_for(result, "/wp-sitemap.xml")
+ assert (feed["kind"], feed["url_count"], feed["sample_urls"], feed["lastmod_count"]) == ("feed", 1, [SITE + "/one"], 1)
+
+
+def test_cli_prints_expanded_json_and_validates_flags(capsys):
+ routes = {SITE + "/sitemap.xml": urlset(SITE + "/a", SITE + "/b")}
+
+ def fake_fetch(url, _limit):
+ return response(routes[url], url) if url in routes else response(url=url, status=404)
+
+ with patch.object(discovery, "_bounded_fetch", side_effect=fake_fetch):
+ with patch.object(sys, "argv", ["sitemap_discovery.py", SITE, "--expand", "--sample", "1", "--json"]):
+ assert discovery.main() == 0
+ printed = json.loads(capsys.readouterr().out)
+ assert printed["expanded"]["files"][0]["sample_urls"] == [SITE + "/a"]
+ assert printed["expanded"]["totals"]["total_urls"] == 2
+
+ with patch.object(sys, "argv", ["sitemap_discovery.py", SITE, "--expand"]):
+ assert discovery.main() == 0
+ text = capsys.readouterr().out
+ assert f"{SITE}/sitemap.xml (urlset, 2 URLs)" in text
+ assert "Total: 2 URLs in 1 files, 2 unique" in text
+
+ with patch.object(sys, "argv", ["sitemap_discovery.py", SITE, "--json"]):
+ assert discovery.main() == 0
+ assert "expanded" not in json.loads(capsys.readouterr().out)
+
+ with patch.object(sys, "argv", ["sitemap_discovery.py", SITE, "--expand", "--max-children", "-1"]):
+ with pytest.raises(SystemExit) as stop:
+ discovery.main()
+ assert stop.value.code == 2