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(parse): survive malformed URLs, tighten the image probe, base and BOM handling
Agrici Daniel339213868ab5
diff --git a/scripts/drift_compare.py b/scripts/drift_compare.pyindex b2a8a87..c9b7dee 100644--- a/scripts/drift_compare.py+++ b/scripts/drift_compare.py@@ -187,8 +187,9 @@ def rule_04_noindex_added(baseline: dict, current: dict) -> dict:"""CRITICAL: Noindex directive added."""def directives(value: str) -> set[str]:# A parameter value such as max-image-preview: none is not a directive.- standalone = re.sub(r"\b[\w-]+\s*:\s*[^,\s]+", "", value.lower())- return set(re.split(r"[,\s]+", standalone))+ # Directives are separated by commas, semicolons or whitespace.+ standalone = re.sub(r"\b[\w-]+\s*:\s*[^,;\s]+", "", value.lower())+ return set(re.split(r"[,;\s]+", standalone))old_robots = directives(baseline.get("robots") or "")new_robots = directives(current.get("meta_robots") or "")diff --git a/scripts/parse_html.py b/scripts/parse_html.pyindex a124f99..42ae2ce 100755--- a/scripts/parse_html.py+++ b/scripts/parse_html.py@@ -9,12 +9,13 @@ Usage:"""import argparse+import copyimport jsonimport osimport reimport sysfrom typing import Any, Optional-from urllib.parse import urljoin, urlparse+from urllib.parse import urldefrag, urljoin, urlparsetry:from bs4 import BeautifulSoup@@ -52,7 +53,7 @@ _GENERIC_LAZY_CLASSES = {"lazyload", "lazyloaded", "lazy", "lazy-loaded"}# URL extension is not the format visitors receive. The probe asks the way a# browser does and reads the format from Content-Type, then the magic bytes.IMAGE_ACCEPT = "image/avif,image/webp,image/apng,image/*,*/*;q=0.8"-_SNIFF_BYTES = 32+_SNIFF_BYTES = 512 # room for an XML prolog and comment ahead of an <svg> root_CONTENT_TYPE_FORMATS = {"image/avif": "avif","image/webp": "webp",@@ -67,6 +68,28 @@ _CONTENT_TYPE_FORMATS = {}+def _has_svg_root(head: bytes) -> bool:+ """Return True when the first element in ``head`` is ``<svg``.++ An XML declaration alone proves nothing: sitemaps, feeds and XHTML error+ pages start with ``<?xml`` too. Skip the prolog (declaration, processing+ instructions, comments, DOCTYPE) and look at the root element itself.+ """+ rest = head.removeprefix(b"\xef\xbb\xbf").lstrip()+ while True:+ if rest.startswith(b"<?"):+ end, skip = rest.find(b"?>"), 2+ elif rest.startswith(b"<!--"):+ end, skip = rest.find(b"-->"), 3+ elif rest[:9].upper() == b"<!DOCTYPE":+ end, skip = rest.find(b">"), 1+ else:+ return rest[:4].lower() == b"<svg"+ if end < 0:+ return False+ rest = rest[end + skip:].lstrip()++def _sniff_image_format(head: bytes) -> Optional[str]:"""Return the image format named by the file's magic bytes, or None."""if head.startswith(b"\xff\xd8\xff"):@@ -81,7 +104,7 @@ def _sniff_image_format(head: bytes) -> Optional[str]:return "avif"if head.startswith((b"\xff\x0a", b"\x00\x00\x00\x0cJXL ")):return "jxl"- if head.lstrip().startswith((b"<svg", b"<?xml")):+ if _has_svg_root(head):return "svg"return None@@ -92,7 +115,9 @@ def probe_image_format(src: str, timeout: int = 15) -> dict:Returns ``served_format`` (from the magic bytes, else Content-Type),``served_bytes`` (Content-Length, or None when the server omits it),``negotiated`` (True when the response varies on Accept, so the format- depends on the client) and ``probe_error`` (None on success).+ depends on the client) and ``probe_error`` (None on success). A response+ that is not a recognized image, such as an HTML soft 404 or a hotlink+ protection page, sets ``probe_error`` so the format is never read as known."""result = {"served_format": None,@@ -100,7 +125,12 @@ def probe_image_format(src: str, timeout: int = 15) -> dict:"negotiated": False,"probe_error": None,}- if not src or urlparse(src).scheme not in ("http", "https"):+ try:+ scheme = urlparse(src).scheme if src else ""+ except ValueError as exc:+ result["probe_error"] = f"malformed URL: {exc}"+ return result+ if scheme not in ("http", "https"):result["probe_error"] = "not an http(s) URL"return result@@ -121,6 +151,10 @@ def probe_image_format(src: str, timeout: int = 15) -> dict:result["served_format"] = (_sniff_image_format(head) or _CONTENT_TYPE_FORMATS.get(content_type))+ if result["served_format"] is None:+ result["probe_error"] = (+ f"not a recognized image (Content-Type: {content_type or 'none'})"+ )length = resp.headers.get("Content-Length")result["served_bytes"] = int(length) if length and length.isdigit() else Nonevary = resp.headers.get("Vary", "").lower()@@ -180,7 +214,16 @@ def _element_text(tag) -> str:spaces next to inline tags are lost (``for <em>every</em> dollar`` becomes``foreverydollar``). Joining the unstripped text and collapsing whitespacekeeps those spaces and also folds newlines in multi-line headings.++ A ``<br>`` is a line break, so it separates words (``Foo<br>Bar`` reads+ ``Foo Bar``). Other inline tags add nothing: ``Web<span>Obs</span>`` stays+ ``WebObs``. The break is swapped for a space on a copy, so the parsed+ document is left as it was."""+ if tag.find("br") is not None:+ tag = copy.copy(tag)+ for br in tag.find_all("br"):+ br.replace_with(" ")return " ".join(tag.get_text().split())@@ -243,7 +286,10 @@ def parse_html(html: str, base_url: Optional[str] = None) -> dict:if base:try:candidate = urljoin(base_url or "", base["href"])- if urlparse(candidate).scheme.lower() not in {"data", "javascript"}:+ # Only a web base is honoured, so file:, mailto:, data: and+ # javascript: never reach the output. An empty scheme is a relative+ # base read without a page URL, and it stays relative.+ if urlparse(candidate).scheme.lower() in {"http", "https", ""}:resource_base_url = candidateexcept ValueError:pass # An invalid base falls back to the document URL.@@ -332,7 +378,12 @@ def parse_html(html: str, base_url: Optional[str] = None) -> dict:for img in soup.find_all("img"):src = img.get("src", "")if resource_base_url and src:- src = urljoin(resource_base_url, src)+ try:+ src = urljoin(resource_base_url, src)+ except ValueError:+ # Such as http://[bad/a.jpg. Keep the raw value so the image+ # is still counted, and carry on with the rest of the page.+ result.setdefault("malformed_urls", []).append({"tag": "img", "value": src})result["images"].append({"src": src,@@ -346,14 +397,25 @@ def parse_html(html: str, base_url: Optional[str] = None) -> dict:# Linksif base_url:base_domain = urlparse(base_url).netloc+ # A fragment-only href resolves against the document base URL (HTML+ # spec), so it stays on this page only while the base is this page.+ # With <base> pointing elsewhere, #frag is a link to that other URL.+ base_is_page = urldefrag(resource_base_url)[0] == urldefrag(base_url)[0]for a in soup.find_all("a", href=True):href = a.get("href", "")- if not href or href.startswith("#") or href.startswith("javascript:"):+ if not href or href.startswith("javascript:"):+ continue+ if href.startswith("#") and base_is_page:continue- full_url = urljoin(resource_base_url, href)- parsed = urlparse(full_url)+ try:+ full_url = urljoin(resource_base_url, href)+ parsed = urlparse(full_url)+ except ValueError:+ # Such as http://[bad/x. Record it and carry on.+ result.setdefault("malformed_urls", []).append({"tag": "a", "value": href})+ continuelink_data = {"href": full_url,diff --git a/scripts/sitemap_discovery.py b/scripts/sitemap_discovery.pyindex 6e09f6c..bae915e 100644--- a/scripts/sitemap_discovery.py+++ b/scripts/sitemap_discovery.py@@ -167,7 +167,9 @@ def _sitemap_kind(content: bytes, content_type: str, url: str) -> tuple[str | Noreturn None, "unsupported XML root"if "text/plain" in content_type.lower() or urlparse(url).path.lower().endswith(".txt"):- lines = [line.strip() for line in content.decode("utf-8", errors="replace").splitlines() if line.strip()]+ # 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"# Entries are reported only as a sitemap classification, not fetched.diff --git a/skills/seo-images/SKILL.md b/skills/seo-images/SKILL.mdindex 3eed958..4cdc8f3 100644--- a/skills/seo-images/SKILL.md+++ b/skills/seo-images/SKILL.md@@ -69,10 +69,10 @@ which fetches each image with a browser `Accept` header and adds to every image| Field | Meaning ||---|---|-| `served_format` | Format actually served (`webp`, `avif`, `jpeg`, `png`, `gif`, `svg`, `jxl`), from the magic bytes |+| `served_format` | Format actually served (`webp`, `avif`, `jpeg`, `png`, `gif`, `svg`, `jxl`), from the magic bytes, else `null` || `served_bytes` | Size actually served (Content-Length), or `null` when the server omits it || `negotiated` | `true` when the response has `Vary: Accept`, so the format depends on the browser |-| `probe_error` | Why the image could not be checked, else `null` |+| `probe_error` | Why the image could not be checked (fetch failed, malformed URL, or the response is not a recognized image, such as an HTML error or hotlink-protection page), else `null` |- Flag "Wrong Format" and size savings only from `served_format` / `served_bytes`. A `.jpg` URL with`served_format: webp` is already optimized: do not recommend converting it.diff --git a/tests/test_document_base_url.py b/tests/test_document_base_url.pyindex dac1fd7..235f5ad 100644--- a/tests/test_document_base_url.py+++ b/tests/test_document_base_url.py@@ -19,6 +19,10 @@ from parse_html import parse_html # noqa: E402('<base href="">', "https://example.com/blog/", "internal"),('<base href="javascript:alert(1)"><base href="/ignored/">', "https://example.com/blog/", "internal"),('<base href="http://[invalid">', "https://example.com/blog/", "internal"),+ ('<base href="file:///etc/">', "https://example.com/blog/", "internal"),+ ('<base href="mailto:x">', "https://example.com/blog/", "internal"),+ ('<base href="ftp://files.example.net/pub/">', "https://example.com/blog/", "internal"),+ ('<base href="HTTPS://cdn.example.net/docs/">', "https://cdn.example.net/docs/", "external"),("", "https://example.com/blog/", "internal"),],)@@ -28,3 +32,41 @@ def test_resource_urls_follow_document_base(head, prefix, kind):assert result["links"][kind][0]["href"] == prefix + "guide"assert result["links"]["internal" if kind == "external" else "external"] == []assert result["images"][0]["src"] == prefix + "cover.png"+++def _hrefs(result, kind):+ return [link["href"] for link in result["links"][kind]]++[email protected]("head", ["", '<base href="">', '<base href="/blog/post">', '<base href="file:///etc/">'])+def test_fragment_only_link_is_skipped_while_the_base_is_the_page(head):+ html = f'<html><head>{head}</head><body><a href="#top">Top</a></body></html>'+ result = parse_html(html, "https://example.com/blog/post")+ assert result["links"] == {"internal": [], "external": []}+++def test_fragment_only_link_follows_a_base_that_points_elsewhere():+ """HTML resolves #frag against the document base URL, so it leaves the page."""+ html = (+ '<html><head><base href="https://other.example/page"></head>'+ '<body><a href="#frag">Jump</a></body></html>'+ )+ result = parse_html(html, "https://example.com/blog/post")+ assert _hrefs(result, "external") == ["https://other.example/page#frag"]+ assert _hrefs(result, "internal") == []+++def test_fragment_only_link_follows_a_same_site_base():+ html = '<html><head><base href="/"></head><body><a href="#pricing">Pricing</a></body></html>'+ result = parse_html(html, "https://example.com/blog/post")+ assert _hrefs(result, "internal") == ["https://example.com/#pricing"]+++def test_relative_base_without_a_page_url_still_prefixes_images():+ result = parse_html('<base href="/docs/"><img src="cover.png">')+ assert result["images"][0]["src"] == "/docs/cover.png"+++def test_non_web_base_without_a_page_url_is_ignored():+ result = parse_html('<base href="file:///etc/"><img src="cover.png">')+ assert result["images"][0]["src"] == "cover.png"diff --git a/tests/test_drift_robots_directives.py b/tests/test_drift_robots_directives.pyindex c16987b..cc8f779 100644--- a/tests/test_drift_robots_directives.py+++ b/tests/test_drift_robots_directives.py@@ -47,3 +47,21 @@ def test_previous_parameter_value_does_not_hide_a_new_restriction():assert rule_04_noindex_added({"robots": "max-image-preview: none"}, {"meta_robots": "none"},)["triggered"] is True++[email protected]("current", [+ "noindex;nofollow", "index; NOINDEX", "follow;none",+ "max-image-preview:none;noindex", "max-snippet:0; noindex",+])+def test_semicolon_separated_noindex_triggers(current):+ assert rule_04_noindex_added({"robots": "index, follow"}, {"meta_robots": current})["triggered"] is True+++def test_semicolon_separated_existing_restriction_is_not_new():+ result = rule_04_noindex_added({"robots": "noindex;nofollow"}, {"meta_robots": "noindex, nofollow"})+ assert result["triggered"] is False++[email protected]("current", ["max-image-preview:none;follow", "index;follow", "max-snippet:0;max-image-preview: none"])+def test_semicolons_do_not_turn_parameter_values_into_directives(current):+ assert rule_04_noindex_added({}, {"meta_robots": current})["triggered"] is Falsediff --git a/tests/test_image_format_probe.py b/tests/test_image_format_probe.pyindex 592442c..7a8b740 100644--- a/tests/test_image_format_probe.py+++ b/tests/test_image_format_probe.py@@ -66,6 +66,16 @@ def fake_get(monkeypatch):(b"\x89PNG\r\n\x1a\n" + b"\x00" * 8, "png"),(b"GIF89a" + b"\x00" * 8, "gif"),(b"<svg xmlns='http://www.w3.org/2000/svg'>", "svg"),+ (b'<?xml version="1.0" encoding="UTF-8"?>\n<svg xmlns="http://www.w3.org/2000/svg">', "svg"),+ (+ b'\xef\xbb\xbf<?xml version="1.0"?><!-- Generator: Illustrator -->'+ b'<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "svg11.dtd"><svg>',+ "svg",+ ),+ (b'<?xml version="1.0" encoding="UTF-8"?><urlset><url></url></urlset>', None),+ (b'<?xml version="1.0"?><!DOCTYPE html><html><body><svg>', None),+ (b'<?xml version="1.0" encoding="UTF-8"', None),+ (b"<!DOCTYPE html><html><body><svg>", None),(b"not an image", None),],)@@ -165,3 +175,73 @@ def test_parse_html_alone_makes_no_requests(fake_get):assert calls == []assert "served_format" not in result["images"][0]+++def test_malformed_src_is_reported_not_raised(fake_get):+ calls, _ = fake_get++ result = probe_image_format("http://[bad/a.jpg")++ assert result["served_format"] is None+ assert result["probe_error"].startswith("malformed URL")+ assert calls == []+++def test_probe_images_survives_a_malformed_src(fake_get):+ calls, responses = fake_get+ good = "https://example.com/a.jpg"+ responses[good] = _FakeResponse(WEBP, {"Content-Type": "image/webp"})+ images = [{"src": "http://[bad/a.jpg"}, {"src": good}]++ probe_images(images)++ assert images[0]["probe_error"].startswith("malformed URL")+ assert images[1]["served_format"] == "webp"+ assert [url for url, _ in calls] == [good]+++ "body, content_type",+ [+ (b"<!DOCTYPE html><html><head><title>Not found</title>", "text/html; charset=utf-8"),+ (b"Hotlinking is not allowed", "text/plain"),+ (b"\x00" * 32, ""),+ ],+)+def test_non_image_200_sets_probe_error(fake_get, body, content_type):+ _, responses = fake_get+ url = "https://example.com/photo.jpg"+ headers = {"Content-Type": content_type} if content_type else {}+ responses[url] = _FakeResponse(body, headers)++ result = probe_image_format(url)++ assert result["served_format"] is None+ assert result["probe_error"].startswith("not a recognized image")+ assert responses[url].closed+++def test_xml_that_is_not_svg_is_not_labelled_svg(fake_get):+ _, responses = fake_get+ url = "https://example.com/logo.svg"+ responses[url] = _FakeResponse(+ b'<?xml version="1.0" encoding="UTF-8"?><urlset><url></url></urlset>',+ {"Content-Type": "application/xml"},+ )++ result = probe_image_format(url)++ assert result["served_format"] is None+ assert "application/xml" in result["probe_error"]+++def test_svg_content_type_is_trusted_when_the_root_is_past_the_sniffed_bytes(fake_get):+ _, responses = fake_get+ url = "https://example.com/logo.svg"+ body = b'<?xml version="1.0"?><!-- ' + b"x" * 2000 + b" --><svg></svg>"+ responses[url] = _FakeResponse(body, {"Content-Type": "image/svg+xml"})++ result = probe_image_format(url)++ assert result["served_format"] == "svg"+ assert result["probe_error"] is Nonediff --git a/tests/test_parse_html_inline_spacing.py b/tests/test_parse_html_inline_spacing.pyindex 4b92a57..0cc7b47 100644--- a/tests/test_parse_html_inline_spacing.py+++ b/tests/test_parse_html_inline_spacing.py@@ -57,3 +57,41 @@ def test_link_text_is_still_capped_at_100_characters():text = result["links"]["internal"][0]["text"]assert len(text) == 100assert text == ("word " * 20)[:100]+++def test_br_separates_words_in_headings():+ html = "<h1>Foo<br>Bar</h1><h2>Fast<br/>Cheap<br />Good</h2><h3>One <br> Two</h3>"+ result = parse_html(html)+ assert result["h1"] == ["Foo Bar"]+ assert result["h2"] == ["Fast Cheap Good"]+ assert result["h3"] == ["One Two"]+++def test_br_separates_words_in_link_text():+ html = '<a href="/x">Read<br>more</a>'+ result = parse_html(html, base_url="https://example.com/")+ assert result["links"]["internal"][0]["text"] == "Read more"+++def test_br_inside_a_nested_inline_tag_still_separates_words():+ html = "<h2><span>Plans<br>and</span> pricing</h2>"+ assert parse_html(html)["h2"] == ["Plans and pricing"]+++def test_br_never_shows_as_glued_words_in_the_title():+ # Parsers differ on <title>: some read the <br> as a tag, some as literal+ # text (which is what a browser shows). Neither may glue the two words.+ html = "<html><head><title>Foo<br>Bar</title></head></html>"+ assert parse_html(html)["title"] in ("Foo Bar", "Foo<br>Bar")+++def test_inline_tags_without_spaces_still_add_none():+ html = "<h1>Web<span>Obs</span></h1><h2>$<b>99</b> a month</h2>"+ result = parse_html(html)+ assert result["h1"] == ["WebObs"]+ assert result["h2"] == ["$99 a month"]+++def test_br_handling_leaves_the_word_count_alone():+ html = "<body><h1>Foo<br>Bar</h1><p>three more words</p></body>"+ assert parse_html(html)["word_count"] == 5diff --git a/tests/test_parse_html_malformed_urls.py b/tests/test_parse_html_malformed_urls.pynew file mode 100644index 0000000..0842d94--- /dev/null+++ b/tests/test_parse_html_malformed_urls.py@@ -0,0 +1,38 @@+"""A malformed URL in one attribute must not abort the whole parse.++Background: `urljoin` and `urlparse` raise ValueError on an unbalanced IPv6+bracket such as `http://[bad/x`. One such value in any `<img src>` or+`<a href>` used to end the run with a traceback, so the page got no report.+"""+import sys+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "scripts"))+from parse_html import parse_html # noqa: E402++PAGE = "https://example.com/blog/post"+++def test_malformed_img_src_is_kept_raw_and_the_parse_continues():+ html = '<h1>Title</h1><img src="http://[bad/a.jpg" alt="broken"><img src="ok.png" alt="fine">'+ result = parse_html(html, PAGE)+ assert [img["src"] for img in result["images"]] == [+ "http://[bad/a.jpg",+ "https://example.com/blog/ok.png",+ ]+ assert result["images"][0]["alt"] == "broken"+ assert result["h1"] == ["Title"]+ assert result["malformed_urls"] == [{"tag": "img", "value": "http://[bad/a.jpg"}]+++def test_malformed_a_href_is_recorded_and_the_parse_continues():+ html = '<a href="http://[bad/x">Bad</a><a href="/ok">Ok</a><a href="https://other.example/">Out</a>'+ result = parse_html(html, PAGE)+ assert [link["href"] for link in result["links"]["internal"]] == ["https://example.com/ok"]+ assert [link["href"] for link in result["links"]["external"]] == ["https://other.example/"]+ assert result["malformed_urls"] == [{"tag": "a", "value": "http://[bad/x"}]+++def test_clean_page_has_no_malformed_urls_key():+ result = parse_html('<img src="ok.png"><a href="/ok">Ok</a>', PAGE)+ assert "malformed_urls" not in resultdiff --git a/tests/test_sitemap_bom.py b/tests/test_sitemap_bom.pyindex 5eff7aa..6e740f5 100644--- a/tests/test_sitemap_bom.py+++ b/tests/test_sitemap_bom.py@@ -5,7 +5,7 @@ from pathlib import Pathimport pytestsys.path.insert(0, str(Path(__file__).resolve().parents[1] / "scripts"))-from sitemap_discovery import _sitemap_kind # noqa: E402+from sitemap_discovery import _robots_sitemaps, _sitemap_kind # noqa: E402@pytest.mark.parametrize("root", ["urlset", "sitemapindex", "rss", "feed"])@@ -19,3 +19,31 @@ def test_utf8_bom_xml_has_the_same_kind(root):def test_bom_does_not_bypass_xml_safety_checks():xml = b'\xef\xbb\xbf<!DOCTYPE urlset [<!ENTITY x "unsafe">]><urlset>&x;</urlset>'assert _sitemap_kind(xml, "application/xml", "https://example.com/sitemap.xml")[0] is None+++ ("content_type", "url"),+ [+ ("text/plain; charset=utf-8", "https://example.com/sitemap.txt"),+ ("application/octet-stream", "https://example.com/sitemap.txt"),+ ("text/plain", "https://example.com/sitemap"),+ ],+)+def test_utf8_bom_text_sitemap_is_valid(content_type, url):+ body = b"https://example.com/one\nhttps://example.com/two\n"+ assert _sitemap_kind(body, content_type, url) == ("text", None)+ assert _sitemap_kind(b"\xef\xbb\xbf" + body, content_type, url) == ("text", None)+++def test_bom_does_not_make_an_invalid_text_sitemap_valid():+ body = b"\xef\xbb\xbfhttps://example.com/one\nnot a url\n"+ assert _sitemap_kind(body, "text/plain", "https://example.com/sitemap.txt") == (+ None,+ "invalid text sitemap",+ )+++def test_robots_bom_and_trailing_comment_together():+ declared = "https://example.com/products.xml"+ robots = b"\xef\xbb\xbf" + f"Sitemap: {declared} # catalog\nSitemap: {declared}\n".encode()+ assert _robots_sitemaps(robots) == [declared]