findbrokenlinks 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- findbrokenlinks/__init__.py +1 -0
- findbrokenlinks/__main__.py +4 -0
- findbrokenlinks/checks/__init__.py +27 -0
- findbrokenlinks/checks/antibot.py +157 -0
- findbrokenlinks/checks/base.py +77 -0
- findbrokenlinks/checks/http_status.py +29 -0
- findbrokenlinks/checks/network_error.py +71 -0
- findbrokenlinks/checks/redirect_chain.py +27 -0
- findbrokenlinks/checks/redirect_to_home.py +40 -0
- findbrokenlinks/checks/soft_404_pattern.py +97 -0
- findbrokenlinks/checks/soft_404_probe.py +127 -0
- findbrokenlinks/cli.py +580 -0
- findbrokenlinks/config.py +54 -0
- findbrokenlinks/crawler.py +399 -0
- findbrokenlinks/extractors/__init__.py +0 -0
- findbrokenlinks/extractors/base.py +11 -0
- findbrokenlinks/extractors/html.py +84 -0
- findbrokenlinks/fetcher.py +210 -0
- findbrokenlinks/gha.py +622 -0
- findbrokenlinks/models.py +65 -0
- findbrokenlinks/patterns/builtin.yaml +55 -0
- findbrokenlinks/rate_limiter.py +39 -0
- findbrokenlinks/reporters/__init__.py +22 -0
- findbrokenlinks/reporters/base.py +120 -0
- findbrokenlinks/reporters/csv_reporter.py +33 -0
- findbrokenlinks/reporters/grouped_json_reporter.py +82 -0
- findbrokenlinks/reporters/html_reporter.py +86 -0
- findbrokenlinks/reporters/json_reporter.py +50 -0
- findbrokenlinks/reporters/jsonlines_reporter.py +28 -0
- findbrokenlinks/reporters/junit_reporter.py +59 -0
- findbrokenlinks/reporters/markdown_reporter.py +51 -0
- findbrokenlinks/reporters/sarif_reporter.py +167 -0
- findbrokenlinks/reporters/tsv_reporter.py +41 -0
- findbrokenlinks/robots.py +51 -0
- findbrokenlinks/scope.py +67 -0
- findbrokenlinks/targets.py +138 -0
- findbrokenlinks-1.0.0.dist-info/METADATA +600 -0
- findbrokenlinks-1.0.0.dist-info/RECORD +42 -0
- findbrokenlinks-1.0.0.dist-info/WHEEL +5 -0
- findbrokenlinks-1.0.0.dist-info/entry_points.txt +2 -0
- findbrokenlinks-1.0.0.dist-info/licenses/LICENSE +21 -0
- findbrokenlinks-1.0.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "1.0.0"
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"""Check registry — populated by side-effect when submodules are imported.
|
|
2
|
+
|
|
3
|
+
Auto-discovers every non-private submodule in this package so dropping a new
|
|
4
|
+
file with an ``@register`` decorator is enough — no edits here required.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import importlib
|
|
10
|
+
import pkgutil
|
|
11
|
+
|
|
12
|
+
from findbrokenlinks.checks.base import ( # noqa: F401 — re-export
|
|
13
|
+
REGISTRY,
|
|
14
|
+
Check,
|
|
15
|
+
CheckContext,
|
|
16
|
+
register,
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _discover() -> None:
|
|
21
|
+
for info in pkgutil.iter_modules(__path__):
|
|
22
|
+
if info.name == "base" or info.name.startswith("_"):
|
|
23
|
+
continue
|
|
24
|
+
importlib.import_module(f"{__name__}.{info.name}")
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
_discover()
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
"""Detect anti-bot blocks so they don't masquerade as broken links.
|
|
2
|
+
|
|
3
|
+
Many sites (tass.ru, news portals, anything behind DataDome / PerimeterX /
|
|
4
|
+
Cloudflare interstitial / Imperva) refuse to serve a request from a client
|
|
5
|
+
they classify as a bot. The response is technically a 4xx/5xx, but it's not
|
|
6
|
+
a *broken link* in any user-meaningful sense — a real visitor sees the page
|
|
7
|
+
just fine.
|
|
8
|
+
|
|
9
|
+
This check looks at the response body and headers of any 4xx/5xx response
|
|
10
|
+
and emits ``ANTIBOT_BLOCKED`` (warning, not error) when it matches a known
|
|
11
|
+
anti-bot vendor signature. ``HTTP_ERROR`` continues to fire too — operators
|
|
12
|
+
can suppress one or the other via ``--enable-checks`` / ``--disable-checks``
|
|
13
|
+
depending on whether they want to triage these separately.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import html
|
|
19
|
+
import re
|
|
20
|
+
from dataclasses import dataclass
|
|
21
|
+
|
|
22
|
+
from findbrokenlinks.checks.base import Check, CheckContext, register
|
|
23
|
+
from findbrokenlinks.models import FetchResult, Issue, LinkRef
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@dataclass(frozen=True)
|
|
27
|
+
class _Signature:
|
|
28
|
+
vendor: str
|
|
29
|
+
# Header signature: the named header (case-insensitive) is present.
|
|
30
|
+
# Used either alone (presence is enough — only for headers that are
|
|
31
|
+
# *only* set on blocks, like x-datadome-cid) or in combination with
|
|
32
|
+
# header_value_re for headers whose name is generic but value identifies
|
|
33
|
+
# the vendor (e.g., server: ddos-guard).
|
|
34
|
+
header: str | None = None
|
|
35
|
+
header_value_re: re.Pattern[str] | None = None
|
|
36
|
+
# Body signature: regex search against the response body. Matched against
|
|
37
|
+
# the entity-decoded body so HTML-encoded payloads (Akamai's typical
|
|
38
|
+
# "Reference #..." output) match plain-text patterns.
|
|
39
|
+
body_re: re.Pattern[str] | None = None
|
|
40
|
+
# Status-only signature: matches purely on the response status code.
|
|
41
|
+
# Used for fallback labels like "401 → login_wall" that have no body or
|
|
42
|
+
# header fingerprint to anchor on. Place these at the end of _SIGNATURES
|
|
43
|
+
# so vendor-specific matches (which return earlier) take precedence.
|
|
44
|
+
status_codes: frozenset[int] | None = None
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
_SIGNATURES: tuple[_Signature, ...] = (
|
|
48
|
+
# Vendor-specific blocking headers — these are only set on actual blocks.
|
|
49
|
+
_Signature("datadome", header="x-datadome-cid"),
|
|
50
|
+
_Signature("perimeterx", header="x-sp-crid"), # the tass.ru case
|
|
51
|
+
_Signature("sucuri", header="x-sucuri-block"),
|
|
52
|
+
# Cloudflare sets cf-mitigated specifically on requests it blocked or
|
|
53
|
+
# challenged — distinct from the generic cf-ray that appears everywhere.
|
|
54
|
+
_Signature("cloudflare", header="cf-mitigated"),
|
|
55
|
+
# DDoS-Guard (Russian DDoS protection CDN) — the iz.ru case. The Server
|
|
56
|
+
# header value is the reliable signal; the header name itself is generic
|
|
57
|
+
# but the value isn't.
|
|
58
|
+
_Signature(
|
|
59
|
+
"ddos-guard",
|
|
60
|
+
header="server",
|
|
61
|
+
header_value_re=re.compile(r"(?i)ddos[-_ ]?guard"),
|
|
62
|
+
),
|
|
63
|
+
# Cloudflare interstitial / challenge body (their "Just a moment..." page).
|
|
64
|
+
_Signature(
|
|
65
|
+
"cloudflare",
|
|
66
|
+
body_re=re.compile(r"(?i)just a moment\.\.\.|checking your browser before accessing"),
|
|
67
|
+
),
|
|
68
|
+
_Signature(
|
|
69
|
+
"cloudflare",
|
|
70
|
+
body_re=re.compile(r"(?i)cloudflare[^<]{0,200}(ray id|attention required)"),
|
|
71
|
+
),
|
|
72
|
+
# Akamai bot manager block page. mdpi.com emits HTML-entity-encoded
|
|
73
|
+
# "Reference #..." — handled by entity-decoding the body before
|
|
74
|
+
# regex search (see _detect).
|
|
75
|
+
_Signature(
|
|
76
|
+
"akamai",
|
|
77
|
+
body_re=re.compile(r"(?i)reference\s*#\d+\.[a-f0-9]+|akamaighost|edgesuite\.net"),
|
|
78
|
+
),
|
|
79
|
+
# Imperva / Incapsula.
|
|
80
|
+
_Signature("imperva", body_re=re.compile(r"(?i)incident\s*id:\s*\d+|imperva|incapsula")),
|
|
81
|
+
# PerimeterX / HUMAN block body (in case header missing).
|
|
82
|
+
_Signature("perimeterx", body_re=re.compile(r"(?i)px-captcha|perimeterx")),
|
|
83
|
+
# DDoS-Guard sometimes serves a JS challenge body.
|
|
84
|
+
_Signature("ddos-guard", body_re=re.compile(r"(?i)ddos-guard\.net")),
|
|
85
|
+
# Generic anti-bot text — short bodies typical of WAF block pages.
|
|
86
|
+
_Signature("generic", body_re=re.compile(r"(?i)\bif you are not a bot\b")),
|
|
87
|
+
_Signature("generic", body_re=re.compile(r"(?i)\bbot detected\b|\bare you a bot\b")),
|
|
88
|
+
_Signature(
|
|
89
|
+
"generic",
|
|
90
|
+
body_re=re.compile(r"(?i)please (complete the captcha|verify you'?re human)"),
|
|
91
|
+
),
|
|
92
|
+
_Signature("generic", body_re=re.compile(r"(?i)ddos protection by")),
|
|
93
|
+
_Signature("generic", body_re=re.compile(r"(?i)pardon our interruption")),
|
|
94
|
+
_Signature("generic", body_re=re.compile(r"(?i)access denied[^<]{0,80}bot")),
|
|
95
|
+
# Login wall — bare 401 means the URL needs authentication. From a crawl
|
|
96
|
+
# perspective it's not a broken link; a real user with cookies would get
|
|
97
|
+
# past it. Kept last in the list so any vendor-specific match for the
|
|
98
|
+
# same 401 (e.g., DataDome returning 401 with x-datadome-cid) wins first.
|
|
99
|
+
_Signature("login_wall", status_codes=frozenset({401})),
|
|
100
|
+
)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _detect(fetch: FetchResult) -> str | None:
|
|
104
|
+
"""Return vendor name if any signature matches the response, else None."""
|
|
105
|
+
headers_lower = {k.lower(): v for k, v in fetch.headers.items()}
|
|
106
|
+
raw_body = fetch.body or ""
|
|
107
|
+
# Entity-decode once: catches Akamai's classic "Reference #..."
|
|
108
|
+
# output, where the literal HTML has . in place of `.` and # in
|
|
109
|
+
# place of `#`.
|
|
110
|
+
decoded_body = html.unescape(raw_body) if raw_body else ""
|
|
111
|
+
for sig in _SIGNATURES:
|
|
112
|
+
if sig.header is not None:
|
|
113
|
+
value = headers_lower.get(sig.header.lower())
|
|
114
|
+
if value is None:
|
|
115
|
+
continue
|
|
116
|
+
if sig.header_value_re is None or sig.header_value_re.search(value):
|
|
117
|
+
return sig.vendor
|
|
118
|
+
# Header present but value didn't match — try other signatures.
|
|
119
|
+
continue
|
|
120
|
+
if sig.body_re is not None and decoded_body and sig.body_re.search(decoded_body):
|
|
121
|
+
return sig.vendor
|
|
122
|
+
if sig.status_codes is not None and fetch.status in sig.status_codes:
|
|
123
|
+
return sig.vendor
|
|
124
|
+
return None
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
@register
|
|
128
|
+
class AntibotBlockedCheck(Check):
|
|
129
|
+
code = "ANTIBOT_BLOCKED"
|
|
130
|
+
severity = "warning"
|
|
131
|
+
title = "Blocked by anti-bot protection"
|
|
132
|
+
description = (
|
|
133
|
+
"The target answered 4xx or 5xx with the signature of a web application firewall or "
|
|
134
|
+
"anti-bot service (DataDome, PerimeterX, Cloudflare, Akamai, Imperva, DDoS-Guard) or a "
|
|
135
|
+
"login wall. The link may work in a browser."
|
|
136
|
+
)
|
|
137
|
+
help = (
|
|
138
|
+
"Open the link in a browser. If it works, ignore this alert or disable the check; "
|
|
139
|
+
"HTTP_ERROR reports the same response."
|
|
140
|
+
)
|
|
141
|
+
|
|
142
|
+
def evaluate(
|
|
143
|
+
self, link: LinkRef, fetch: FetchResult, ctx: CheckContext
|
|
144
|
+
) -> Issue | None:
|
|
145
|
+
# Only suspect anti-bot when the server actually returned an error.
|
|
146
|
+
# A 200 page that happens to contain the word "bot" is not a block.
|
|
147
|
+
if fetch.status is None or not (400 <= fetch.status < 600):
|
|
148
|
+
return None
|
|
149
|
+
vendor = _detect(fetch)
|
|
150
|
+
if vendor is None:
|
|
151
|
+
return None
|
|
152
|
+
return Issue(
|
|
153
|
+
code=self.code,
|
|
154
|
+
severity=self.severity,
|
|
155
|
+
message=f"Likely anti-bot block ({vendor}); may not be a real broken link",
|
|
156
|
+
details={"vendor": vendor, "status": fetch.status},
|
|
157
|
+
)
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from abc import ABC, abstractmethod
|
|
4
|
+
from dataclasses import dataclass, field
|
|
5
|
+
from typing import TYPE_CHECKING, Any, ClassVar
|
|
6
|
+
|
|
7
|
+
from findbrokenlinks.models import FetchResult, Issue, LinkRef, Severity
|
|
8
|
+
|
|
9
|
+
if TYPE_CHECKING:
|
|
10
|
+
from findbrokenlinks.config import Config # noqa: F401 — used in annotations
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@dataclass
|
|
14
|
+
class Baseline404:
|
|
15
|
+
status: int | None
|
|
16
|
+
final_url: str
|
|
17
|
+
text_len: int
|
|
18
|
+
text_hash: str
|
|
19
|
+
# False when the host's home page has this same body: then the body tells a
|
|
20
|
+
# missing page from a real one in nothing, and only the redirect comparison
|
|
21
|
+
# is left (the crawler decides, see _ensure_probe).
|
|
22
|
+
compare_body: bool = True
|
|
23
|
+
# Where the host's home page ended up when the probe requested it; None when
|
|
24
|
+
# it was not requested or did not answer. A link to another host's "/" that
|
|
25
|
+
# lands there is an alias of the home page (www., http://), not a soft 404.
|
|
26
|
+
home_final_url: str | None = None
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass
|
|
30
|
+
class CheckContext:
|
|
31
|
+
config: Config
|
|
32
|
+
base_host: str
|
|
33
|
+
baselines: dict[str, Baseline404] = field(default_factory=dict) # host -> baseline
|
|
34
|
+
soft404_patterns: list[Any] = field(default_factory=list) # compiled patterns
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class Check(ABC):
|
|
38
|
+
code: ClassVar[str]
|
|
39
|
+
severity: ClassVar[Severity] = "error"
|
|
40
|
+
# Human-readable rule text, used by the sarif report (Code Scanning shows
|
|
41
|
+
# it next to each alert). Optional: empty falls back to the code.
|
|
42
|
+
title: ClassVar[str] = "" # a short phrase: "Link returns an HTTP error"
|
|
43
|
+
description: ClassVar[str] = "" # when the check fires
|
|
44
|
+
help: ClassVar[str] = "" # what to do about it
|
|
45
|
+
|
|
46
|
+
@abstractmethod
|
|
47
|
+
def evaluate(
|
|
48
|
+
self, link: LinkRef, fetch: FetchResult, ctx: CheckContext
|
|
49
|
+
) -> Issue | None: ...
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
REGISTRY: dict[str, type[Check]] = {}
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def register(cls: type[Check]) -> type[Check]:
|
|
56
|
+
if not getattr(cls, "code", None):
|
|
57
|
+
raise TypeError(f"{cls.__name__} must define a non-empty `code`")
|
|
58
|
+
if cls.code in REGISTRY:
|
|
59
|
+
raise ValueError(f"Check code {cls.code!r} already registered")
|
|
60
|
+
REGISTRY[cls.code] = cls
|
|
61
|
+
return cls
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def active_checks(ctx: CheckContext) -> list[Check]:
|
|
65
|
+
"""Instantiate checks honoring enable/disable config."""
|
|
66
|
+
enabled = ctx.config.enabled_checks
|
|
67
|
+
disabled = ctx.config.disabled_checks
|
|
68
|
+
result: list[Check] = []
|
|
69
|
+
for code, cls in REGISTRY.items():
|
|
70
|
+
if enabled is not None and code not in enabled:
|
|
71
|
+
continue
|
|
72
|
+
if code in disabled:
|
|
73
|
+
continue
|
|
74
|
+
if code == "SOFT_404_PROBE" and not ctx.config.soft404_probe_enabled:
|
|
75
|
+
continue
|
|
76
|
+
result.append(cls())
|
|
77
|
+
return result
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from findbrokenlinks.checks.base import Check, CheckContext, register
|
|
4
|
+
from findbrokenlinks.models import FetchResult, Issue, LinkRef
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
@register
|
|
8
|
+
class HttpStatusCheck(Check):
|
|
9
|
+
code = "HTTP_ERROR"
|
|
10
|
+
severity = "error"
|
|
11
|
+
title = "Link returns an HTTP error"
|
|
12
|
+
description = "The link's target answered with a 4xx or 5xx status."
|
|
13
|
+
help = (
|
|
14
|
+
"Fix the link or remove it, or restore the page it points to. A 404 usually means the "
|
|
15
|
+
"page moved: link to its new address. A 5xx is a server failure: check whether it "
|
|
16
|
+
"persists."
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
def evaluate(self, link: LinkRef, fetch: FetchResult, ctx: CheckContext) -> Issue | None:
|
|
20
|
+
if fetch.status is None:
|
|
21
|
+
return None
|
|
22
|
+
if fetch.status >= 400:
|
|
23
|
+
return Issue(
|
|
24
|
+
code=self.code,
|
|
25
|
+
severity=self.severity,
|
|
26
|
+
message=f"HTTP {fetch.status}",
|
|
27
|
+
details={"status": fetch.status, "final_url": fetch.final_url},
|
|
28
|
+
)
|
|
29
|
+
return None
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from findbrokenlinks.checks.base import Check, CheckContext, register
|
|
4
|
+
from findbrokenlinks.models import FetchResult, Issue, LinkRef
|
|
5
|
+
|
|
6
|
+
# Friendlier messages keyed by Fetcher's short error codes. The "ssl_chain"
|
|
7
|
+
# entry is the most operationally useful — it directs the operator at a server
|
|
8
|
+
# misconfiguration (server isn't sending its intermediate CA) instead of
|
|
9
|
+
# generic "SSL failed".
|
|
10
|
+
_ERROR_MESSAGES: dict[str, str] = {
|
|
11
|
+
"timeout": "Request timed out",
|
|
12
|
+
"dns": "DNS resolution failed",
|
|
13
|
+
"ssl": "SSL/TLS verification failed",
|
|
14
|
+
"ssl_chain": (
|
|
15
|
+
"Incomplete certificate chain — server didn't send the intermediate CA. "
|
|
16
|
+
"Browsers paper over this via AIA fetching; many SDKs/CLI tools won't. "
|
|
17
|
+
"Fix: serve fullchain.pem from the server."
|
|
18
|
+
),
|
|
19
|
+
"connect": "Connection refused or host unreachable",
|
|
20
|
+
"too_many_redirects": "Too many redirects",
|
|
21
|
+
"network": "Network error",
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
# Warnings keyed by FetchResult.tls_warning — the request *succeeded* (status,
|
|
25
|
+
# body present) but only because verification was relaxed for a recoverable
|
|
26
|
+
# reason. We still crawl the page; the operator just needs to know the chain
|
|
27
|
+
# is broken so they can fix the server.
|
|
28
|
+
_WARNING_MESSAGES: dict[str, str] = {
|
|
29
|
+
"ssl_chain": (
|
|
30
|
+
"Incomplete certificate chain — server didn't send the intermediate CA. "
|
|
31
|
+
"Crawled anyway with TLS verification relaxed (browsers tolerate this via "
|
|
32
|
+
"AIA fetching). Fix: serve fullchain.pem from the server."
|
|
33
|
+
),
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
@register
|
|
38
|
+
class NetworkErrorCheck(Check):
|
|
39
|
+
code = "NETWORK_ERROR"
|
|
40
|
+
severity = "error"
|
|
41
|
+
title = "Link target unreachable"
|
|
42
|
+
description = (
|
|
43
|
+
"The request failed before any HTTP response: DNS lookup, connection, TLS or timeout "
|
|
44
|
+
"(error). As a warning: the server sends an incomplete TLS certificate chain, without "
|
|
45
|
+
"the intermediate CA, and the page was crawled with verification relaxed."
|
|
46
|
+
)
|
|
47
|
+
help = (
|
|
48
|
+
"Check that the host exists and answers. For an incomplete chain, configure the server "
|
|
49
|
+
"to send the full chain (fullchain.pem)."
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
def evaluate(self, link: LinkRef, fetch: FetchResult, ctx: CheckContext) -> Issue | None:
|
|
53
|
+
if fetch.error is not None:
|
|
54
|
+
message = _ERROR_MESSAGES.get(fetch.error, f"Network error: {fetch.error}")
|
|
55
|
+
return Issue(
|
|
56
|
+
code=self.code,
|
|
57
|
+
severity="error",
|
|
58
|
+
message=message,
|
|
59
|
+
details={"error": fetch.error},
|
|
60
|
+
)
|
|
61
|
+
if fetch.tls_warning is not None:
|
|
62
|
+
message = _WARNING_MESSAGES.get(
|
|
63
|
+
fetch.tls_warning, f"TLS warning: {fetch.tls_warning}"
|
|
64
|
+
)
|
|
65
|
+
return Issue(
|
|
66
|
+
code=self.code,
|
|
67
|
+
severity="warning",
|
|
68
|
+
message=message,
|
|
69
|
+
details={"tls_warning": fetch.tls_warning},
|
|
70
|
+
)
|
|
71
|
+
return None
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from findbrokenlinks.checks.base import Check, CheckContext, register
|
|
4
|
+
from findbrokenlinks.models import FetchResult, Issue, LinkRef
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
@register
|
|
8
|
+
class RedirectChainCheck(Check):
|
|
9
|
+
code = "REDIRECT_CHAIN"
|
|
10
|
+
severity = "warning"
|
|
11
|
+
title = "Long redirect chain"
|
|
12
|
+
description = (
|
|
13
|
+
"Reaching the target takes at least --redirect-chain-threshold redirects (default 3)."
|
|
14
|
+
)
|
|
15
|
+
help = "Link to the final address directly."
|
|
16
|
+
|
|
17
|
+
def evaluate(self, link: LinkRef, fetch: FetchResult, ctx: CheckContext) -> Issue | None:
|
|
18
|
+
hops = len(fetch.redirect_chain) - 1 # chain includes final URL
|
|
19
|
+
threshold = ctx.config.redirect_chain_threshold
|
|
20
|
+
if hops < threshold:
|
|
21
|
+
return None
|
|
22
|
+
return Issue(
|
|
23
|
+
code=self.code,
|
|
24
|
+
severity=self.severity,
|
|
25
|
+
message=f"Long redirect chain: {hops} hops (threshold {threshold})",
|
|
26
|
+
details={"hops": hops, "chain": fetch.redirect_chain},
|
|
27
|
+
)
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from urllib.parse import urlsplit
|
|
4
|
+
|
|
5
|
+
from findbrokenlinks.checks.base import Check, CheckContext, register
|
|
6
|
+
from findbrokenlinks.models import FetchResult, Issue, LinkRef
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def _is_home_path(path: str) -> bool:
|
|
10
|
+
return path in ("", "/")
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@register
|
|
14
|
+
class RedirectToHomeCheck(Check):
|
|
15
|
+
"""Flag links that redirect to the site's root — a common soft-404 pattern."""
|
|
16
|
+
|
|
17
|
+
code = "REDIRECT_TO_HOME"
|
|
18
|
+
severity = "warning"
|
|
19
|
+
title = "Link redirects to the home page"
|
|
20
|
+
description = (
|
|
21
|
+
"The link redirects to the site's root page: a common way for a removed page to pretend "
|
|
22
|
+
"it still exists (a soft 404)."
|
|
23
|
+
)
|
|
24
|
+
help = "Link to the page that replaced it, or remove the link."
|
|
25
|
+
|
|
26
|
+
def evaluate(self, link: LinkRef, fetch: FetchResult, ctx: CheckContext) -> Issue | None:
|
|
27
|
+
if len(fetch.redirect_chain) < 2:
|
|
28
|
+
return None
|
|
29
|
+
original = urlsplit(fetch.url)
|
|
30
|
+
final = urlsplit(fetch.final_url)
|
|
31
|
+
if not _is_home_path(final.path):
|
|
32
|
+
return None
|
|
33
|
+
if _is_home_path(original.path):
|
|
34
|
+
return None # the link itself pointed to home
|
|
35
|
+
return Issue(
|
|
36
|
+
code=self.code,
|
|
37
|
+
severity=self.severity,
|
|
38
|
+
message=f"Link redirected to home page ({fetch.final_url})",
|
|
39
|
+
details={"final_url": fetch.final_url, "chain": fetch.redirect_chain},
|
|
40
|
+
)
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
import yaml
|
|
8
|
+
from bs4 import BeautifulSoup
|
|
9
|
+
|
|
10
|
+
from findbrokenlinks.checks.base import Check, CheckContext, register
|
|
11
|
+
from findbrokenlinks.models import FetchResult, Issue, LinkRef
|
|
12
|
+
|
|
13
|
+
VALID_TARGETS = {"title", "h1", "body", "raw"}
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass
|
|
17
|
+
class CompiledPattern:
|
|
18
|
+
name: str
|
|
19
|
+
target: str # 'title' | 'h1' | 'body' (BeautifulSoup-extracted text) | 'raw' (HTML as-is)
|
|
20
|
+
regex: re.Pattern[str]
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def load_patterns(extra: Path | None = None) -> list[CompiledPattern]:
|
|
24
|
+
"""Load built-in patterns and optionally user patterns. Composite."""
|
|
25
|
+
paths = [Path(__file__).resolve().parent.parent / "patterns" / "builtin.yaml"]
|
|
26
|
+
if extra is not None:
|
|
27
|
+
paths.append(extra)
|
|
28
|
+
compiled: list[CompiledPattern] = []
|
|
29
|
+
for p in paths:
|
|
30
|
+
if not p.exists():
|
|
31
|
+
continue
|
|
32
|
+
with p.open("r", encoding="utf-8") as f:
|
|
33
|
+
raw = yaml.safe_load(f) or []
|
|
34
|
+
for item in raw:
|
|
35
|
+
target = item.get("target", "body")
|
|
36
|
+
if target not in VALID_TARGETS:
|
|
37
|
+
raise ValueError(
|
|
38
|
+
f"soft-404 pattern {item.get('name', '?')!r}: unknown target "
|
|
39
|
+
f"{target!r} (allowed: {sorted(VALID_TARGETS)})"
|
|
40
|
+
)
|
|
41
|
+
compiled.append(
|
|
42
|
+
CompiledPattern(
|
|
43
|
+
name=item["name"],
|
|
44
|
+
target=target,
|
|
45
|
+
regex=re.compile(item["regex"]),
|
|
46
|
+
)
|
|
47
|
+
)
|
|
48
|
+
return compiled
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _extract_targets(body: str) -> dict[str, str]:
|
|
52
|
+
"""Return the four search surfaces.
|
|
53
|
+
|
|
54
|
+
title/h1/body are BeautifulSoup-extracted text — convenient for human-readable
|
|
55
|
+
error messages but stripped of all markup. `raw` is the unaltered HTML body —
|
|
56
|
+
use it for patterns that need to look at tags, classes, or server signatures
|
|
57
|
+
that don't survive text extraction.
|
|
58
|
+
"""
|
|
59
|
+
soup = BeautifulSoup(body, "lxml")
|
|
60
|
+
title = (soup.title.string if soup.title and soup.title.string else "") or ""
|
|
61
|
+
h1_el = soup.find("h1")
|
|
62
|
+
h1 = h1_el.get_text(" ", strip=True) if h1_el else ""
|
|
63
|
+
text = soup.get_text(" ", strip=True)
|
|
64
|
+
return {"title": title.strip(), "h1": h1, "body": text, "raw": body}
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
@register
|
|
68
|
+
class Soft404PatternCheck(Check):
|
|
69
|
+
code = "SOFT_404_PATTERN"
|
|
70
|
+
severity = "warning"
|
|
71
|
+
title = "Soft 404: the page says it was not found"
|
|
72
|
+
description = (
|
|
73
|
+
'The target answers 200 OK, but its title, heading, text or HTML matches a known "page '
|
|
74
|
+
'not found" pattern.'
|
|
75
|
+
)
|
|
76
|
+
help = "Fix the link or remove it. The server should answer 404 for a missing page."
|
|
77
|
+
|
|
78
|
+
def evaluate(self, link: LinkRef, fetch: FetchResult, ctx: CheckContext) -> Issue | None:
|
|
79
|
+
if fetch.status is None or fetch.status >= 400:
|
|
80
|
+
return None
|
|
81
|
+
if not fetch.body:
|
|
82
|
+
return None
|
|
83
|
+
if not ctx.soft404_patterns:
|
|
84
|
+
return None
|
|
85
|
+
targets = _extract_targets(fetch.body)
|
|
86
|
+
for pat in ctx.soft404_patterns:
|
|
87
|
+
haystack = targets.get(pat.target, "")
|
|
88
|
+
if not haystack:
|
|
89
|
+
continue
|
|
90
|
+
if pat.regex.search(haystack):
|
|
91
|
+
return Issue(
|
|
92
|
+
code=self.code,
|
|
93
|
+
severity=self.severity,
|
|
94
|
+
message=f"Page matched soft-404 pattern {pat.name!r} in {pat.target}",
|
|
95
|
+
details={"pattern": pat.name, "target": pat.target},
|
|
96
|
+
)
|
|
97
|
+
return None
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import hashlib
|
|
4
|
+
import re
|
|
5
|
+
from urllib.parse import urlsplit
|
|
6
|
+
|
|
7
|
+
from bs4 import BeautifulSoup
|
|
8
|
+
|
|
9
|
+
from findbrokenlinks.checks.base import Baseline404, Check, CheckContext, register
|
|
10
|
+
from findbrokenlinks.models import FetchResult, Issue, LinkRef
|
|
11
|
+
from findbrokenlinks.scope import host_of
|
|
12
|
+
|
|
13
|
+
_WS_RE = re.compile(r"\s+")
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def normalize_html_text(body: str) -> str:
|
|
17
|
+
soup = BeautifulSoup(body, "lxml")
|
|
18
|
+
for tag in soup(["script", "style", "noscript"]):
|
|
19
|
+
tag.decompose()
|
|
20
|
+
text = soup.get_text(" ", strip=True)
|
|
21
|
+
return _WS_RE.sub(" ", text)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def baseline_from_fetch(fetch: FetchResult) -> Baseline404:
|
|
25
|
+
text = normalize_html_text(fetch.body or "")
|
|
26
|
+
return Baseline404(
|
|
27
|
+
status=fetch.status,
|
|
28
|
+
final_url=fetch.final_url,
|
|
29
|
+
text_len=len(text),
|
|
30
|
+
text_hash=hashlib.sha1(text.encode("utf-8")).hexdigest(),
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def body_matches(fetch: FetchResult, baseline: Baseline404) -> bool:
|
|
35
|
+
"""Does a 2xx response have the same body as the host's not-found page?"""
|
|
36
|
+
if fetch.status is None or not 200 <= fetch.status < 300 or not fetch.body:
|
|
37
|
+
return False
|
|
38
|
+
if baseline.text_len == 0:
|
|
39
|
+
return False
|
|
40
|
+
text = normalize_html_text(fetch.body)
|
|
41
|
+
if not text:
|
|
42
|
+
return False
|
|
43
|
+
# Compare length within ±10% and hash equality.
|
|
44
|
+
diff = abs(len(text) - baseline.text_len)
|
|
45
|
+
rel = diff / max(baseline.text_len, 1)
|
|
46
|
+
cur_hash = hashlib.sha1(text.encode("utf-8")).hexdigest()
|
|
47
|
+
return rel <= 0.1 and cur_hash == baseline.text_hash
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def is_home(url: str) -> bool:
|
|
51
|
+
parts = urlsplit(url)
|
|
52
|
+
return parts.path in ("", "/") and not parts.query
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def content_comparison_off(host: str, baseline: Baseline404) -> Issue:
|
|
56
|
+
"""The one info finding for a host whose home page is its not-found page."""
|
|
57
|
+
status = "no status" if baseline.status is None else f"HTTP {baseline.status}"
|
|
58
|
+
return Issue(
|
|
59
|
+
code=Soft404ProbeCheck.code,
|
|
60
|
+
severity="info",
|
|
61
|
+
message=(
|
|
62
|
+
f"The home page is the same as the not-found page ({status}), so pages on "
|
|
63
|
+
f"{host} are not compared with it by content"
|
|
64
|
+
),
|
|
65
|
+
details={
|
|
66
|
+
"reason": "home_matches_baseline",
|
|
67
|
+
"baseline_url": baseline.final_url,
|
|
68
|
+
"baseline_status": baseline.status,
|
|
69
|
+
},
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
@register
|
|
74
|
+
class Soft404ProbeCheck(Check):
|
|
75
|
+
"""Compare a 2xx response to a known-404 baseline for the same host."""
|
|
76
|
+
|
|
77
|
+
code = "SOFT_404_PROBE"
|
|
78
|
+
severity = "warning"
|
|
79
|
+
title = "Soft 404: same as the site's not-found page"
|
|
80
|
+
description = (
|
|
81
|
+
"The target answers 2xx with the same body as an address that cannot exist on that "
|
|
82
|
+
"host."
|
|
83
|
+
)
|
|
84
|
+
help = (
|
|
85
|
+
"Fix the link or remove it. When a host's home page is the same as its not-found "
|
|
86
|
+
"page, as on a single-page application, the check does not compare content there "
|
|
87
|
+
"and says so once, as info. Turn the check off with --no-soft404-probe."
|
|
88
|
+
)
|
|
89
|
+
|
|
90
|
+
def evaluate(self, link: LinkRef, fetch: FetchResult, ctx: CheckContext) -> Issue | None:
|
|
91
|
+
if fetch.status is None or fetch.status >= 300 or fetch.status < 200:
|
|
92
|
+
return None
|
|
93
|
+
if not fetch.body:
|
|
94
|
+
return None
|
|
95
|
+
host = host_of(fetch.final_url)
|
|
96
|
+
baseline = ctx.baselines.get(host)
|
|
97
|
+
if baseline is None or baseline.text_len == 0:
|
|
98
|
+
return None
|
|
99
|
+
# The home page is what the baseline is checked against, never a soft 404
|
|
100
|
+
# itself: on a site that sends both "/" and unknown addresses to /en/, the
|
|
101
|
+
# final_url rule below would flag every link to the home page. A home page
|
|
102
|
+
# of the same host, or of another one that lands where this host's home
|
|
103
|
+
# page does (https://www.example.org/ on a site that sends unknown
|
|
104
|
+
# addresses to "/"). Not https://old.example.org/ that lands on
|
|
105
|
+
# example.org's not-found page: a dead link.
|
|
106
|
+
if is_home(fetch.url) and (
|
|
107
|
+
host_of(fetch.url) == host
|
|
108
|
+
or (baseline.home_final_url is not None and fetch.final_url == baseline.home_final_url)
|
|
109
|
+
):
|
|
110
|
+
return None
|
|
111
|
+
# Final URL exactly matching baseline final_url is a strong signal (server redirects
|
|
112
|
+
# unknown URLs to a generic page).
|
|
113
|
+
if fetch.final_url == baseline.final_url and fetch.url != baseline.final_url:
|
|
114
|
+
return Issue(
|
|
115
|
+
code=self.code,
|
|
116
|
+
severity=self.severity,
|
|
117
|
+
message=f"Response identical to baseline 404 endpoint ({baseline.final_url})",
|
|
118
|
+
details={"reason": "final_url_match", "baseline_url": baseline.final_url},
|
|
119
|
+
)
|
|
120
|
+
if baseline.compare_body and body_matches(fetch, baseline):
|
|
121
|
+
return Issue(
|
|
122
|
+
code=self.code,
|
|
123
|
+
severity=self.severity,
|
|
124
|
+
message="Response body matches known 404 baseline",
|
|
125
|
+
details={"reason": "body_match", "baseline_len": baseline.text_len},
|
|
126
|
+
)
|
|
127
|
+
return None
|