omnirank 0.5.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.
- omnirank/__init__.py +14 -0
- omnirank/__main__.py +6 -0
- omnirank/adapters/__init__.py +202 -0
- omnirank/adapters/astro.py +338 -0
- omnirank/adapters/base.py +372 -0
- omnirank/adapters/html.py +561 -0
- omnirank/adapters/jsx.py +340 -0
- omnirank/adapters/nextjs.py +692 -0
- omnirank/aeo/__init__.py +9 -0
- omnirank/aeo/extract.py +383 -0
- omnirank/aeo/propose.py +84 -0
- omnirank/aeo/rules.py +964 -0
- omnirank/aeo/runner.py +148 -0
- omnirank/applicability.py +98 -0
- omnirank/apply/__init__.py +23 -0
- omnirank/apply/engine.py +1254 -0
- omnirank/apply/journal.py +139 -0
- omnirank/apply/patch.py +144 -0
- omnirank/audit.py +185 -0
- omnirank/bands.py +106 -0
- omnirank/brief/__init__.py +0 -0
- omnirank/brief/analyze.py +197 -0
- omnirank/brief/constants.py +89 -0
- omnirank/brief/cost.py +62 -0
- omnirank/brief/egress.py +23 -0
- omnirank/brief/fetchpages.py +239 -0
- omnirank/brief/render.py +151 -0
- omnirank/brief/runner.py +369 -0
- omnirank/brief/serp.py +274 -0
- omnirank/brief/text.py +181 -0
- omnirank/cli.py +844 -0
- omnirank/clock.py +22 -0
- omnirank/cms/__init__.py +1 -0
- omnirank/cms/runner.py +170 -0
- omnirank/cms/wordpress.py +495 -0
- omnirank/cms/wordpress_apply.py +508 -0
- omnirank/cms/wordpress_plan.py +280 -0
- omnirank/config.py +81 -0
- omnirank/connect/__init__.py +4 -0
- omnirank/connect/bing.py +284 -0
- omnirank/connect/cloud_setup.py +43 -0
- omnirank/connect/confirm.py +242 -0
- omnirank/connect/constants.py +226 -0
- omnirank/connect/doctor.py +270 -0
- omnirank/connect/ga4.py +749 -0
- omnirank/connect/ga4_ai.py +123 -0
- omnirank/connect/google_auth.py +657 -0
- omnirank/connect/gsc.py +630 -0
- omnirank/connect/gsc_reports.py +169 -0
- omnirank/connect/http.py +310 -0
- omnirank/connect/indexnow.py +373 -0
- omnirank/connect/naver.py +536 -0
- omnirank/connect/runner.py +515 -0
- omnirank/connect/runner_ga4_ai.py +59 -0
- omnirank/connect/runner_more.py +489 -0
- omnirank/connect/runner_regional.py +260 -0
- omnirank/connect/secrets.py +190 -0
- omnirank/connect/urlcheck.py +41 -0
- omnirank/connect/yandex.py +350 -0
- omnirank/crawl/__init__.py +11 -0
- omnirank/crawl/analyze.py +493 -0
- omnirank/crawl/crawler.py +491 -0
- omnirank/crawl/custom.py +175 -0
- omnirank/crawl/export.py +67 -0
- omnirank/crawl/fetcher.py +212 -0
- omnirank/crawl/parse.py +102 -0
- omnirank/crawl/render.py +148 -0
- omnirank/crawl/robotsgate.py +198 -0
- omnirank/crawl/runner.py +295 -0
- omnirank/crawl/sitemap.py +99 -0
- omnirank/crawl/text.py +20 -0
- omnirank/crawl/urls.py +100 -0
- omnirank/crawlers.py +564 -0
- omnirank/data/ai_crawlers.json +269 -0
- omnirank/data/ai_referrers.json +42 -0
- omnirank/fetch.py +107 -0
- omnirank/fixes/__init__.py +92 -0
- omnirank/fixes/base.py +232 -0
- omnirank/fixes/canonical.py +243 -0
- omnirank/fixes/schema.py +126 -0
- omnirank/formats.py +134 -0
- omnirank/framework.py +223 -0
- omnirank/gates/__init__.py +48 -0
- omnirank/gates/aeo.py +114 -0
- omnirank/gates/contradictions.py +280 -0
- omnirank/gates/crawler_policy.py +85 -0
- omnirank/gates/geo.py +152 -0
- omnirank/gates/hygiene.py +81 -0
- omnirank/gates/jsonld.py +282 -0
- omnirank/gates/onpage.py +177 -0
- omnirank/gates/perf.py +115 -0
- omnirank/gates/security.py +264 -0
- omnirank/gates/seo.py +118 -0
- omnirank/gates/site.py +248 -0
- omnirank/geo_artifacts.py +199 -0
- omnirank/html.py +79 -0
- omnirank/keywords/__init__.py +5 -0
- omnirank/keywords/constants.py +69 -0
- omnirank/keywords/engine.py +384 -0
- omnirank/keywords/report.py +143 -0
- omnirank/keywords/runner.py +160 -0
- omnirank/keywords/source.py +60 -0
- omnirank/keywords/text.py +45 -0
- omnirank/locator.py +480 -0
- omnirank/logs/__init__.py +0 -0
- omnirank/logs/analyze.py +127 -0
- omnirank/logs/bots.py +69 -0
- omnirank/logs/ipranges.py +191 -0
- omnirank/logs/parse.py +452 -0
- omnirank/logs/paths.py +22 -0
- omnirank/logs/privacy.py +105 -0
- omnirank/logs/runner.py +179 -0
- omnirank/mcp_server.py +1480 -0
- omnirank/netguard.py +525 -0
- omnirank/packs/__init__.py +6 -0
- omnirank/packs/backlinks.py +535 -0
- omnirank/packs/blog.py +544 -0
- omnirank/packs/blog_cross.py +468 -0
- omnirank/packs/crawlers.py +23 -0
- omnirank/packs/entity.py +492 -0
- omnirank/packs/feeds.py +150 -0
- omnirank/packs/frontmatter.py +59 -0
- omnirank/packs/gsc.py +421 -0
- omnirank/packs/local.py +879 -0
- omnirank/packs/mdscan.py +326 -0
- omnirank/packs/miniyaml.py +378 -0
- omnirank/packs/model.py +46 -0
- omnirank/packs/product.py +979 -0
- omnirank/packs/refresh.py +165 -0
- omnirank/packs/runner.py +277 -0
- omnirank/packs/sitescan.py +294 -0
- omnirank/packs/textsafe.py +79 -0
- omnirank/packs/xmlsafe.py +92 -0
- omnirank/page.py +42 -0
- omnirank/registry.py +302 -0
- omnirank/report.py +251 -0
- omnirank/report_cmd/__init__.py +7 -0
- omnirank/report_cmd/delta.py +58 -0
- omnirank/report_cmd/files.py +64 -0
- omnirank/report_cmd/model.py +208 -0
- omnirank/report_cmd/notify.py +195 -0
- omnirank/report_cmd/pdf.py +83 -0
- omnirank/report_cmd/portfolio.py +342 -0
- omnirank/report_cmd/render.py +379 -0
- omnirank/report_cmd/runner.py +267 -0
- omnirank/robots.py +172 -0
- omnirank/scanner/__init__.py +10 -0
- omnirank/scanner/badge.py +90 -0
- omnirank/scanner/cache.py +69 -0
- omnirank/scanner/cli.py +96 -0
- omnirank/scanner/engine.py +289 -0
- omnirank/scanner/limits.py +98 -0
- omnirank/scanner/server.py +143 -0
- omnirank/scanner/service.py +328 -0
- omnirank/schema/__init__.py +13 -0
- omnirank/schema/catalog.py +679 -0
- omnirank/schema/catalog_specs.py +350 -0
- omnirank/schema/core.py +306 -0
- omnirank/schema/extract.py +396 -0
- omnirank/schema/gate.py +121 -0
- omnirank/schema/runner.py +213 -0
- omnirank/schema/validate.py +504 -0
- omnirank/schema/vocab.py +305 -0
- omnirank/schemas/omnirank.config.schema.json +268 -0
- omnirank/track/__init__.py +0 -0
- omnirank/track/ai_prompts.py +207 -0
- omnirank/track/analysis.py +197 -0
- omnirank/track/constants.py +155 -0
- omnirank/track/cost.py +229 -0
- omnirank/track/discover.py +277 -0
- omnirank/track/discover_cli.py +309 -0
- omnirank/track/discover_constants.py +95 -0
- omnirank/track/engines.py +216 -0
- omnirank/track/estimate_view.py +212 -0
- omnirank/track/history.py +261 -0
- omnirank/track/runner.py +586 -0
- omnirank/track/stats.py +138 -0
- omnirank/track/storage.py +128 -0
- omnirank-0.5.0.dist-info/METADATA +47 -0
- omnirank-0.5.0.dist-info/RECORD +183 -0
- omnirank-0.5.0.dist-info/WHEEL +5 -0
- omnirank-0.5.0.dist-info/entry_points.txt +2 -0
- omnirank-0.5.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
"""robots.txt as a crawl gate for the ``OmniRank`` user-agent (RFC 9309).
|
|
2
|
+
|
|
3
|
+
The file is parsed ONCE into a compiled rule index and verdicts are cached per path.
|
|
4
|
+
Matching is RFC 9309 section 2.2.2: the most specific (longest) matching rule wins, an
|
|
5
|
+
``Allow`` wins a tie, ``*`` matches any run of characters and a trailing ``$`` anchors
|
|
6
|
+
the end. Literal rules (most of any real file) are looked up through the prefixes of the
|
|
7
|
+
path (O(path length) set lookups); wildcard rules are indexed by their literal prefix and
|
|
8
|
+
only the candidates whose prefix matches are run through a linear-time glob matcher (no
|
|
9
|
+
regex, so no backtracking blow-up).
|
|
10
|
+
|
|
11
|
+
Why not ``urllib.robotparser`` (as ``omnirank.robots`` uses for findings)? On Python
|
|
12
|
+
3.11-3.13 it has no wildcards and is first-match, and it re-scans every rule for every
|
|
13
|
+
URL (a 20,000-rule file made a 200-URL check take seconds). This matcher implements the
|
|
14
|
+
RFC directly; tests/test_crawl_fixes.py checks it against the RFC examples.
|
|
15
|
+
|
|
16
|
+
Fetch outcomes, RFC 9309 section 2.3.1: 2xx -> rules; 4xx ("unavailable") -> allow
|
|
17
|
+
everything; 5xx or unreachable -> disallow everything. Redirects are followed by the
|
|
18
|
+
crawler (up to 5 hops, see crawler.py); more than 5, or a loop, counts as unavailable.
|
|
19
|
+
"""
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
from dataclasses import dataclass, field
|
|
23
|
+
from urllib.parse import urlsplit
|
|
24
|
+
|
|
25
|
+
from .urls import _pct
|
|
26
|
+
|
|
27
|
+
AGENT = "OmniRank"
|
|
28
|
+
MAX_ROBOTS_BYTES = 512 * 1024
|
|
29
|
+
MAX_CRAWL_DELAY = 30.0
|
|
30
|
+
MAX_CACHE = 100_000
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _glob_match(pattern: str, text: str) -> bool:
|
|
34
|
+
"""Full match of ``pattern`` (``*`` = any run) against ``text``; O(len(p) * len(t))
|
|
35
|
+
worst case, no regex and no backtracking blow-up."""
|
|
36
|
+
p = t = 0
|
|
37
|
+
star = -1
|
|
38
|
+
mark = 0
|
|
39
|
+
while t < len(text):
|
|
40
|
+
if p < len(pattern) and pattern[p] != "*" and pattern[p] == text[t]:
|
|
41
|
+
p += 1
|
|
42
|
+
t += 1
|
|
43
|
+
elif p < len(pattern) and pattern[p] == "*":
|
|
44
|
+
star, mark = p, t
|
|
45
|
+
p += 1
|
|
46
|
+
elif star != -1:
|
|
47
|
+
p = star + 1
|
|
48
|
+
mark += 1
|
|
49
|
+
t = mark
|
|
50
|
+
else:
|
|
51
|
+
return False
|
|
52
|
+
while p < len(pattern) and pattern[p] == "*":
|
|
53
|
+
p += 1
|
|
54
|
+
return p == len(pattern)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def rule_matches(rule: str, path: str) -> bool:
|
|
58
|
+
"""robots.txt path rule semantics: prefix match, ``*`` wildcard, trailing ``$`` anchor."""
|
|
59
|
+
if rule.endswith("$"):
|
|
60
|
+
return _glob_match(rule[:-1], path)
|
|
61
|
+
return _glob_match(rule + "*", path)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _groups(text: str) -> list[tuple[list[str], list[tuple[str, str]], float | None]]:
|
|
65
|
+
"""(agents, [(field, path)], crawl_delay) per group; consecutive User-agent lines share."""
|
|
66
|
+
groups: list[tuple[list[str], list[tuple[str, str]], float | None]] = []
|
|
67
|
+
agents: list[str] = []
|
|
68
|
+
rules: list[tuple[str, str]] = []
|
|
69
|
+
delay: float | None = None
|
|
70
|
+
in_agents = False
|
|
71
|
+
for raw in text.splitlines():
|
|
72
|
+
line = raw.split("#", 1)[0].strip()
|
|
73
|
+
if ":" not in line:
|
|
74
|
+
continue
|
|
75
|
+
name, _, value = line.partition(":")
|
|
76
|
+
name, value = name.strip().lower(), value.strip()
|
|
77
|
+
if name == "user-agent":
|
|
78
|
+
if not in_agents and agents:
|
|
79
|
+
groups.append((agents, rules, delay))
|
|
80
|
+
agents, rules, delay = [], [], None
|
|
81
|
+
agents.append(value.lower())
|
|
82
|
+
in_agents = True
|
|
83
|
+
continue
|
|
84
|
+
in_agents = False
|
|
85
|
+
if name in ("allow", "disallow"):
|
|
86
|
+
rules.append((name, value))
|
|
87
|
+
elif name == "crawl-delay":
|
|
88
|
+
try:
|
|
89
|
+
delay = float(value)
|
|
90
|
+
except ValueError:
|
|
91
|
+
pass
|
|
92
|
+
if agents:
|
|
93
|
+
groups.append((agents, rules, delay))
|
|
94
|
+
return groups
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
class RuleIndex:
|
|
98
|
+
"""Compiled Allow/Disallow rules of the applicable group(s)."""
|
|
99
|
+
|
|
100
|
+
def __init__(self, rules: list[tuple[str, str]]):
|
|
101
|
+
self.prefix: dict[str, bool] = {} # literal rule -> allow?
|
|
102
|
+
self.exact: dict[str, bool] = {} # literal rule ending in $ -> allow?
|
|
103
|
+
self.wild: dict[str, list[tuple[str, bool]]] = {}
|
|
104
|
+
self.count = 0
|
|
105
|
+
for kind, value in rules:
|
|
106
|
+
if not value:
|
|
107
|
+
continue # "Disallow:" with no path = no rule
|
|
108
|
+
path = _pct(value)
|
|
109
|
+
if not path.startswith(("/", "*")):
|
|
110
|
+
path = "/" + path
|
|
111
|
+
allow = kind == "allow"
|
|
112
|
+
self.count += 1
|
|
113
|
+
body = path.removesuffix("$")
|
|
114
|
+
if "*" not in body:
|
|
115
|
+
table = self.exact if path.endswith("$") else self.prefix
|
|
116
|
+
table[body] = table.get(body, False) or allow
|
|
117
|
+
else:
|
|
118
|
+
lead = body.split("*", 1)[0]
|
|
119
|
+
self.wild.setdefault(lead, []).append((path, allow))
|
|
120
|
+
|
|
121
|
+
def allowed(self, path: str) -> bool:
|
|
122
|
+
best_len, best_allow = -1, True
|
|
123
|
+
for end in range(len(path) + 1):
|
|
124
|
+
stem = path[:end]
|
|
125
|
+
allow = self.prefix.get(stem)
|
|
126
|
+
if allow is not None and (len(stem) > best_len or (len(stem) == best_len
|
|
127
|
+
and allow)):
|
|
128
|
+
best_len, best_allow = len(stem), allow
|
|
129
|
+
for rule, allow in self.wild.get(stem, ()):
|
|
130
|
+
if rule_matches(rule, path):
|
|
131
|
+
n = len(rule)
|
|
132
|
+
if n > best_len or (n == best_len and allow):
|
|
133
|
+
best_len, best_allow = n, allow
|
|
134
|
+
allow = self.exact.get(path)
|
|
135
|
+
if allow is not None and (len(path) + 1 > best_len or
|
|
136
|
+
(len(path) + 1 == best_len and allow)):
|
|
137
|
+
best_len, best_allow = len(path) + 1, allow
|
|
138
|
+
return best_allow
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
@dataclass
|
|
142
|
+
class RobotsGate:
|
|
143
|
+
status: int
|
|
144
|
+
policy: str # "rules" | "allow-all" | "disallow-all"
|
|
145
|
+
text: str = ""
|
|
146
|
+
mode: str | None = None # "rfc9309" for "rules"
|
|
147
|
+
reason: str | None = None
|
|
148
|
+
crawl_delay: float | None = None
|
|
149
|
+
sitemaps: list[str] = field(default_factory=list)
|
|
150
|
+
redirects: list[str] = field(default_factory=list)
|
|
151
|
+
_index: RuleIndex | None = field(default=None, repr=False)
|
|
152
|
+
_cache: dict[str, bool] = field(default_factory=dict, repr=False)
|
|
153
|
+
|
|
154
|
+
@classmethod
|
|
155
|
+
def from_response(cls, status: int, text: str) -> RobotsGate:
|
|
156
|
+
if 200 <= status < 300:
|
|
157
|
+
return cls._from_text(status, text[:MAX_ROBOTS_BYTES])
|
|
158
|
+
if 400 <= status < 500:
|
|
159
|
+
return cls(status=status, policy="allow-all", reason="unavailable")
|
|
160
|
+
return cls(status=status, policy="disallow-all", reason="unreachable")
|
|
161
|
+
|
|
162
|
+
@classmethod
|
|
163
|
+
def _from_text(cls, status: int, text: str) -> RobotsGate:
|
|
164
|
+
gate = cls(status=status, policy="rules", text=text, mode="rfc9309")
|
|
165
|
+
groups = _groups(text)
|
|
166
|
+
mine = [g for g in groups if "omnirank" in g[0]]
|
|
167
|
+
chosen = mine or [g for g in groups if "*" in g[0]]
|
|
168
|
+
gate._index = RuleIndex([r for g in chosen for r in g[1]])
|
|
169
|
+
delays = [g[2] for g in chosen if g[2] is not None]
|
|
170
|
+
if delays:
|
|
171
|
+
gate.crawl_delay = min(max(delays), MAX_CRAWL_DELAY)
|
|
172
|
+
for raw in text.splitlines():
|
|
173
|
+
name, _, value = raw.split("#", 1)[0].partition(":")
|
|
174
|
+
if name.strip().lower() == "sitemap" and value.strip():
|
|
175
|
+
gate.sitemaps.append(value.strip())
|
|
176
|
+
return gate
|
|
177
|
+
|
|
178
|
+
def allowed(self, url: str) -> bool:
|
|
179
|
+
if self.policy == "allow-all":
|
|
180
|
+
return True
|
|
181
|
+
if self.policy == "disallow-all":
|
|
182
|
+
return False
|
|
183
|
+
parts = urlsplit(url)
|
|
184
|
+
path = (parts.path or "/") + (f"?{parts.query}" if parts.query else "")
|
|
185
|
+
if path == "/robots.txt":
|
|
186
|
+
return True
|
|
187
|
+
cached = self._cache.get(path)
|
|
188
|
+
if cached is None:
|
|
189
|
+
cached = self._index.allowed(path)
|
|
190
|
+
if len(self._cache) < MAX_CACHE:
|
|
191
|
+
self._cache[path] = cached
|
|
192
|
+
return cached
|
|
193
|
+
|
|
194
|
+
def to_dict(self) -> dict:
|
|
195
|
+
return {"status": self.status, "policy": self.policy, "mode": self.mode,
|
|
196
|
+
"reason": self.reason, "crawl_delay": self.crawl_delay,
|
|
197
|
+
"sitemaps": list(self.sitemaps), "redirects": list(self.redirects),
|
|
198
|
+
"rules": self._index.count if self._index else 0, "agent": AGENT}
|
omnirank/crawl/runner.py
ADDED
|
@@ -0,0 +1,295 @@
|
|
|
1
|
+
"""`omnirank crawl <url>`: argument parsing, output files and the terminal summary.
|
|
2
|
+
|
|
3
|
+
Exit codes: 0 crawl finished (issues found or not); 1 the start page could not be crawled
|
|
4
|
+
(blocked by robots.txt, no response, or 4xx/5xx); 2 usage, policy or output-path errors
|
|
5
|
+
(nothing is fetched in that case).
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import argparse
|
|
10
|
+
import json
|
|
11
|
+
import os
|
|
12
|
+
import secrets
|
|
13
|
+
import sys
|
|
14
|
+
import time
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
|
|
17
|
+
from ..mcp_server import EgressPolicy, GuardedTransport
|
|
18
|
+
from ..packs.xmlsafe import MAX_XML_BYTES
|
|
19
|
+
from .analyze import build_report
|
|
20
|
+
from .crawler import CrawlAborted, CrawlConfig, CrawlError, crawl
|
|
21
|
+
from .custom import ExtractError, parse_extractor
|
|
22
|
+
from .export import to_csv_issues, to_csv_pages, to_sarif_report
|
|
23
|
+
from .render import TRUSTED_HINT, RenderUnavailable, playwright_renderer
|
|
24
|
+
from .text import clean
|
|
25
|
+
|
|
26
|
+
DEFAULT_OUT = ".omnirank/crawl"
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class OutputError(Exception):
|
|
30
|
+
pass
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _make_policy(allow_private: bool, *, max_bytes: int = 5_000_000,
|
|
34
|
+
timeout: float = 15.0) -> EgressPolicy:
|
|
35
|
+
# The transport's own caps follow the crawl's: raw body bytes = the largest
|
|
36
|
+
# per-request limit (pages, or sitemaps at 5 MB) and the whole-request deadline =
|
|
37
|
+
# --timeout. The crawl's fetcher applies the exact per-request cap on top.
|
|
38
|
+
return EgressPolicy(allow_private=allow_private,
|
|
39
|
+
max_response_bytes=max(max_bytes, MAX_XML_BYTES),
|
|
40
|
+
fetch_deadline=min(float(timeout), 300.0))
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _make_transport(policy: EgressPolicy):
|
|
44
|
+
# The MCP server's transport: request-time URL check, connect-time address check
|
|
45
|
+
# (DNS rebinding), body byte cap and per-request deadline.
|
|
46
|
+
return GuardedTransport(policy)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
_sleep = time.sleep
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _bounded_int(low: int, high: int):
|
|
53
|
+
def parse(text: str) -> int:
|
|
54
|
+
try:
|
|
55
|
+
value = int(text)
|
|
56
|
+
except ValueError:
|
|
57
|
+
raise argparse.ArgumentTypeError(f"{text!r} is not a whole number") from None
|
|
58
|
+
if not low <= value <= high:
|
|
59
|
+
raise argparse.ArgumentTypeError(f"must be between {low} and {high}")
|
|
60
|
+
return value
|
|
61
|
+
return parse
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _bounded_float(low: float, high: float):
|
|
65
|
+
def parse(text: str) -> float:
|
|
66
|
+
try:
|
|
67
|
+
value = float(text)
|
|
68
|
+
except ValueError:
|
|
69
|
+
raise argparse.ArgumentTypeError(f"{text!r} is not a number") from None
|
|
70
|
+
if not low <= value <= high:
|
|
71
|
+
raise argparse.ArgumentTypeError(f"must be between {low:g} and {high:g}")
|
|
72
|
+
return value
|
|
73
|
+
return parse
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def add_parser(sub) -> None:
|
|
77
|
+
p = sub.add_parser(
|
|
78
|
+
"crawl", help="Crawl a site politely (robots.txt, rate limit, same-site) and report "
|
|
79
|
+
"redirects, broken links, orphans, duplicates, hreflang and more")
|
|
80
|
+
p.add_argument("url", help="Start URL, e.g. https://example.com/")
|
|
81
|
+
p.add_argument("--max", type=_bounded_int(1, 100_000), default=500, metavar="N",
|
|
82
|
+
help="Maximum URLs to fetch (default 500)")
|
|
83
|
+
p.add_argument("--depth", type=_bounded_int(0, 100), default=10, metavar="N",
|
|
84
|
+
help="Maximum link depth from the start URL (default 10)")
|
|
85
|
+
p.add_argument("--render", action="store_true",
|
|
86
|
+
help="Render pages with JavaScript (needs the optional Playwright package "
|
|
87
|
+
"and --render-trusted-site)")
|
|
88
|
+
p.add_argument("--render-trusted-site", action="store_true",
|
|
89
|
+
help="Confirm you trust the site enough to run its JavaScript in a "
|
|
90
|
+
"headless browser (required with --render; see docs/crawl.md)")
|
|
91
|
+
p.add_argument("--extract", action="append", default=[], metavar="NAME=KIND:EXPR",
|
|
92
|
+
help="Custom extraction: name=css:SELECTOR, name=xpath:EXPR or "
|
|
93
|
+
"name=regex:PATTERN (repeatable)")
|
|
94
|
+
p.add_argument("--out", default=DEFAULT_OUT, metavar="DIR",
|
|
95
|
+
help=f"Output directory inside the current directory (default {DEFAULT_OUT})")
|
|
96
|
+
p.add_argument("--format", choices=("json", "csv", "sarif"), default="json",
|
|
97
|
+
help="json: crawl.json; csv: pages.csv + issues.csv; sarif: crawl.sarif")
|
|
98
|
+
p.add_argument("--delay", type=_bounded_float(0, 60), default=1.0, metavar="SECONDS",
|
|
99
|
+
help="Minimum seconds between requests (default 1.0; a larger robots.txt "
|
|
100
|
+
"Crawl-delay wins, up to 30)")
|
|
101
|
+
p.add_argument("--concurrency", type=_bounded_int(1, 8), default=2, metavar="N",
|
|
102
|
+
help="Parallel requests (default 2, max 8)")
|
|
103
|
+
p.add_argument("--max-redirects", type=_bounded_int(0, 20), default=5, metavar="N",
|
|
104
|
+
help="Redirect hops followed per URL (default 5)")
|
|
105
|
+
p.add_argument("--max-page-bytes", type=_bounded_int(100, 50_000_000), default=5_000_000,
|
|
106
|
+
metavar="BYTES", help="Per-response byte cap (default 5,000,000)")
|
|
107
|
+
p.add_argument("--max-total-bytes", type=_bounded_int(100, 10_000_000_000),
|
|
108
|
+
default=500_000_000, metavar="BYTES",
|
|
109
|
+
help="Total download budget (default 500,000,000)")
|
|
110
|
+
p.add_argument("--max-seconds", type=_bounded_float(1, 86_400), default=1800,
|
|
111
|
+
metavar="SECONDS", help="Total time budget (default 1800)")
|
|
112
|
+
p.add_argument("--timeout", type=_bounded_float(1, 300), default=15, metavar="SECONDS",
|
|
113
|
+
help="Per-request timeout (default 15)")
|
|
114
|
+
p.add_argument("--check-external", action="store_true",
|
|
115
|
+
help="Also request linked external URLs (robots.txt obeyed, at most "
|
|
116
|
+
"--external-per-host per host, 200 in total)")
|
|
117
|
+
p.add_argument("--external-per-host", type=_bounded_int(1, 100), default=5, metavar="N",
|
|
118
|
+
help="External URLs checked per host (default 5)")
|
|
119
|
+
p.add_argument("--extract-budget", type=_bounded_float(0.1, 60), default=2.0,
|
|
120
|
+
metavar="SECONDS", help="Time limit for each --extract expression on one "
|
|
121
|
+
"page (default 2)")
|
|
122
|
+
p.add_argument("--allow-private-network", action="store_true",
|
|
123
|
+
help="Allow loopback/private/link-local addresses (local development only)")
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
# --- output files ------------------------------------------------------------------------
|
|
127
|
+
|
|
128
|
+
def _out_dir(raw: str, *, create: bool) -> Path:
|
|
129
|
+
"""``raw`` resolved inside the current directory; no ``..`` escape, no symlinked
|
|
130
|
+
component. Created (mode 0700) if missing and ``create``."""
|
|
131
|
+
root = Path.cwd().resolve()
|
|
132
|
+
target = (root / raw) if not Path(raw).is_absolute() else Path(raw)
|
|
133
|
+
if not os.path.normpath(target).startswith(str(root) + os.sep) and \
|
|
134
|
+
os.path.normpath(target) != str(root):
|
|
135
|
+
raise OutputError(f"--out {raw!r} must be inside the current directory")
|
|
136
|
+
rel = Path(os.path.normpath(target)).relative_to(root)
|
|
137
|
+
current = root
|
|
138
|
+
for part in rel.parts:
|
|
139
|
+
current = current / part
|
|
140
|
+
if current.is_symlink():
|
|
141
|
+
raise OutputError(f"--out: {current} is a symlink; refusing to write through it")
|
|
142
|
+
if current.exists() and not current.is_dir():
|
|
143
|
+
raise OutputError(f"--out: {current} exists and is not a directory")
|
|
144
|
+
if not create:
|
|
145
|
+
return root.joinpath(*rel.parts)
|
|
146
|
+
current = root
|
|
147
|
+
for part in rel.parts:
|
|
148
|
+
current = current / part
|
|
149
|
+
if not current.exists():
|
|
150
|
+
current.mkdir(mode=0o700)
|
|
151
|
+
if current.is_symlink() or not current.is_dir():
|
|
152
|
+
raise OutputError(f"--out: {current} is a symlink or not a directory")
|
|
153
|
+
if not current.resolve().is_relative_to(root):
|
|
154
|
+
raise OutputError(f"--out {raw!r} resolves outside the current directory")
|
|
155
|
+
return current
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _write(directory: Path, name: str, text: str) -> Path:
|
|
159
|
+
target = directory / name
|
|
160
|
+
if target.is_symlink():
|
|
161
|
+
raise OutputError(f"{target} is a symlink; refusing to write through it")
|
|
162
|
+
tmp = directory / f".tmp-{secrets.token_hex(8)}"
|
|
163
|
+
flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0)
|
|
164
|
+
fd = os.open(tmp, flags, 0o600)
|
|
165
|
+
try:
|
|
166
|
+
with os.fdopen(fd, "w", encoding="utf-8", newline="") as fh:
|
|
167
|
+
fh.write(text)
|
|
168
|
+
os.replace(tmp, target)
|
|
169
|
+
except BaseException:
|
|
170
|
+
try:
|
|
171
|
+
os.unlink(tmp)
|
|
172
|
+
except OSError:
|
|
173
|
+
pass
|
|
174
|
+
raise
|
|
175
|
+
return target
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def _write_outputs(directory: Path, report: dict, fmt: str) -> list[Path]:
|
|
179
|
+
if fmt == "csv":
|
|
180
|
+
return [_write(directory, "pages.csv", to_csv_pages(report)),
|
|
181
|
+
_write(directory, "issues.csv", to_csv_issues(report))]
|
|
182
|
+
if fmt == "sarif":
|
|
183
|
+
return [_write(directory, "crawl.sarif",
|
|
184
|
+
json.dumps(to_sarif_report(report), indent=2, ensure_ascii=False)
|
|
185
|
+
+ "\n")]
|
|
186
|
+
return [_write(directory, "crawl.json",
|
|
187
|
+
json.dumps(report, indent=1, ensure_ascii=False) + "\n")]
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
# --- summary -------------------------------------------------------------------------------
|
|
191
|
+
|
|
192
|
+
def summary_lines(report: dict) -> list[str]:
|
|
193
|
+
s = report["summary"]
|
|
194
|
+
statuses = " ".join(f"{k}x{v}" for k, v in s["status_counts"].items()) or "none"
|
|
195
|
+
budget = report["budget"]["exhausted"]
|
|
196
|
+
return [
|
|
197
|
+
(f"omnirank crawl: {clean(report['start_url'], 300)} (public read-only scan; "
|
|
198
|
+
"robots.txt obeyed for user-agent OmniRank)"),
|
|
199
|
+
f" pages fetched: {s['pages_fetched']} statuses: {statuses}",
|
|
200
|
+
" budget: " + (f"STOPPED early ({budget}); counts cover only what was fetched"
|
|
201
|
+
if budget else "complete"),
|
|
202
|
+
(f" redirects: {s['redirects']} (chains {s['redirect_chains']}, loops "
|
|
203
|
+
f"{s['redirect_loops']}) broken links: {s['broken_links']} blocked by robots: "
|
|
204
|
+
f"{s['blocked_by_robots']}"),
|
|
205
|
+
(f" sitemap URLs: {s['sitemap_urls']} (orphans {s['orphans']}, not linked "
|
|
206
|
+
f"{s['sitemap_not_linked']}, not indexable {s['sitemap_url_not_ok']}) crawled but "
|
|
207
|
+
f"not in sitemap: {s['crawled_not_in_sitemap']}"),
|
|
208
|
+
(f" duplicates: exact groups {s['exact_duplicate_groups']}, near pairs "
|
|
209
|
+
f"{s['near_duplicate_pairs']}, titles {s['duplicate_title_groups']}, descriptions "
|
|
210
|
+
f"{s['duplicate_description_groups']}"),
|
|
211
|
+
(f" hreflang: invalid {s['hreflang_invalid']}, non-reciprocal "
|
|
212
|
+
f"{s['hreflang_non_reciprocal']}, bad target {s['hreflang_bad_target']} "
|
|
213
|
+
f"soft 404 (heuristic): {s['soft_404']}"),
|
|
214
|
+
(f" images: missing alt {s['images_missing_alt']}, missing width/height "
|
|
215
|
+
f"{s['images_missing_dimensions']} max depth {s['max_depth']}, unreachable "
|
|
216
|
+
f"{s['unreachable']}"),
|
|
217
|
+
]
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def run_crawl(args: argparse.Namespace) -> int:
|
|
221
|
+
def fail(message: str, code: int = 2) -> int:
|
|
222
|
+
print(f"omnirank: {clean(message, 600)}", file=sys.stderr)
|
|
223
|
+
return code
|
|
224
|
+
|
|
225
|
+
try:
|
|
226
|
+
_out_dir(args.out, create=False) # refuse a bad path before any request
|
|
227
|
+
extractors = [parse_extractor(spec) for spec in args.extract]
|
|
228
|
+
cfg = CrawlConfig(start_url=args.url, max_urls=args.max, max_depth=args.depth,
|
|
229
|
+
delay=args.delay, concurrency=args.concurrency,
|
|
230
|
+
max_redirects=args.max_redirects,
|
|
231
|
+
max_page_bytes=args.max_page_bytes,
|
|
232
|
+
max_total_bytes=args.max_total_bytes,
|
|
233
|
+
max_seconds=args.max_seconds, timeout=args.timeout,
|
|
234
|
+
check_external=args.check_external,
|
|
235
|
+
external_per_host=args.external_per_host)
|
|
236
|
+
except (OutputError, ExtractError, ValueError, OSError) as exc:
|
|
237
|
+
return fail(str(exc))
|
|
238
|
+
|
|
239
|
+
if args.render and not args.render_trusted_site:
|
|
240
|
+
return fail(TRUSTED_HINT)
|
|
241
|
+
policy = _make_policy(args.allow_private_network, max_bytes=args.max_page_bytes,
|
|
242
|
+
timeout=args.timeout)
|
|
243
|
+
renderer = None
|
|
244
|
+
if args.render:
|
|
245
|
+
try:
|
|
246
|
+
renderer = playwright_renderer(timeout=args.timeout)
|
|
247
|
+
except RenderUnavailable as exc:
|
|
248
|
+
return fail(str(exc))
|
|
249
|
+
except Exception as exc: # noqa: BLE001 - a browser that will not start
|
|
250
|
+
return fail(f"the browser for --render did not start: {exc}")
|
|
251
|
+
aborted = None
|
|
252
|
+
try:
|
|
253
|
+
result = crawl(cfg, transport=_make_transport(policy), policy=policy,
|
|
254
|
+
renderer=renderer, extractors=extractors, sleep=_sleep,
|
|
255
|
+
extract_budget=args.extract_budget)
|
|
256
|
+
except CrawlError as exc:
|
|
257
|
+
return fail(str(exc))
|
|
258
|
+
except CrawlAborted as exc:
|
|
259
|
+
result, aborted = exc.result, exc.result.aborted
|
|
260
|
+
except Exception as exc: # noqa: BLE001 - never a traceback for a crawl failure
|
|
261
|
+
return fail(f"the crawl stopped by an unexpected error before any page was "
|
|
262
|
+
f"recorded ({type(exc).__name__}: {exc})", 1)
|
|
263
|
+
finally:
|
|
264
|
+
if renderer is not None:
|
|
265
|
+
try:
|
|
266
|
+
renderer.close()
|
|
267
|
+
except Exception: # noqa: BLE001, S110 - closing a broken browser must not mask results
|
|
268
|
+
pass
|
|
269
|
+
|
|
270
|
+
try:
|
|
271
|
+
report = build_report(result)
|
|
272
|
+
except Exception as exc: # noqa: BLE001 - report the failure, not a traceback
|
|
273
|
+
return fail(f"the crawl finished but the report could not be built "
|
|
274
|
+
f"({type(exc).__name__}: {exc})", 1)
|
|
275
|
+
try:
|
|
276
|
+
written = _write_outputs(_out_dir(args.out, create=True), report, args.format)
|
|
277
|
+
except (OutputError, OSError) as exc:
|
|
278
|
+
return fail(f"could not write the report: {exc}")
|
|
279
|
+
for line in summary_lines(report):
|
|
280
|
+
print(line)
|
|
281
|
+
for path in written:
|
|
282
|
+
print(f" report: {path}")
|
|
283
|
+
if aborted:
|
|
284
|
+
return fail(f"the crawl stopped by an unexpected error ({aborted}); the report "
|
|
285
|
+
"covers what was crawled before it", 1)
|
|
286
|
+
|
|
287
|
+
start = result.records.get(result.start_url)
|
|
288
|
+
if start is None:
|
|
289
|
+
why = ("disallowed by robots.txt" if result.start_url in result.blocked_by_robots
|
|
290
|
+
else "not fetched (budget)")
|
|
291
|
+
return fail(f"the start page {result.start_url} was {why}", 1)
|
|
292
|
+
if start["status"] == 0 or start["status"] >= 400:
|
|
293
|
+
detail = start["error"] or f"HTTP {start['status']}"
|
|
294
|
+
return fail(f"the start page {result.start_url} could not be crawled ({detail})", 1)
|
|
295
|
+
return 0
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
"""Sitemap discovery for the crawl: robots.txt ``Sitemap:`` lines plus ``/sitemap.xml``.
|
|
2
|
+
|
|
3
|
+
Parsed only after ``packs.xmlsafe.check_untrusted`` (no DOCTYPE/ENTITY, UTF-8/16 only).
|
|
4
|
+
A ``<sitemapindex>`` is followed one level (at most ``MAX_CHILDREN`` child sitemaps).
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import xml.etree.ElementTree as ET
|
|
9
|
+
from collections.abc import Callable
|
|
10
|
+
from dataclasses import dataclass, field
|
|
11
|
+
|
|
12
|
+
from ..packs.xmlsafe import MAX_XML_BYTES, check_untrusted, local
|
|
13
|
+
from .text import clean
|
|
14
|
+
from .urls import normalize, same_site
|
|
15
|
+
|
|
16
|
+
MAX_CHILDREN = 50
|
|
17
|
+
MAX_SITEMAP_URLS = 50_000
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass
|
|
21
|
+
class SitemapResult:
|
|
22
|
+
urls: list[str] = field(default_factory=list)
|
|
23
|
+
offsite: int = 0
|
|
24
|
+
fetched: list[str] = field(default_factory=list)
|
|
25
|
+
problems: list[dict] = field(default_factory=list)
|
|
26
|
+
|
|
27
|
+
def to_dict(self) -> dict:
|
|
28
|
+
return {"fetched": list(self.fetched), "url_count": len(self.urls),
|
|
29
|
+
"offsite_ignored": self.offsite, "problems": list(self.problems)}
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _locs(root: ET.Element, parent: str) -> list[str]:
|
|
33
|
+
out = []
|
|
34
|
+
for item in root:
|
|
35
|
+
if local(item.tag) != parent:
|
|
36
|
+
continue
|
|
37
|
+
for child in item:
|
|
38
|
+
if local(child.tag) == "loc" and (child.text or "").strip():
|
|
39
|
+
out.append(child.text.strip())
|
|
40
|
+
return out
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def collect(get: Callable, listed: list[str], default: str, site_host: str,
|
|
44
|
+
allowed: Callable[[str], bool]) -> SitemapResult:
|
|
45
|
+
"""``get(url, max_bytes)`` returns a fetcher Response. ``listed`` are the robots.txt
|
|
46
|
+
``Sitemap:`` URLs; ``default`` (``/sitemap.xml``) is tried too and a 404 there is not
|
|
47
|
+
a problem (a site need not have one at that path)."""
|
|
48
|
+
result = SitemapResult()
|
|
49
|
+
seen_urls: set[str] = set()
|
|
50
|
+
queue = [(s, 0, False) for s in listed] + [(default, 0, True)]
|
|
51
|
+
visited: set[str] = set()
|
|
52
|
+
while queue:
|
|
53
|
+
src, level, is_default = queue.pop(0)
|
|
54
|
+
url = normalize(src)
|
|
55
|
+
if url is None or url in visited:
|
|
56
|
+
continue
|
|
57
|
+
visited.add(url)
|
|
58
|
+
if not same_site(url, site_host):
|
|
59
|
+
result.problems.append({"url": clean(src, 300), "problem": "offsite-sitemap"})
|
|
60
|
+
continue
|
|
61
|
+
if not allowed(url):
|
|
62
|
+
result.problems.append({"url": url, "problem": "blocked-by-robots"})
|
|
63
|
+
continue
|
|
64
|
+
resp = get(url, MAX_XML_BYTES)
|
|
65
|
+
if is_default and resp.status == 404:
|
|
66
|
+
continue
|
|
67
|
+
result.fetched.append(url)
|
|
68
|
+
if not 200 <= resp.status < 300:
|
|
69
|
+
result.problems.append({"url": url, "problem": f"http-{resp.status}"})
|
|
70
|
+
continue
|
|
71
|
+
if resp.truncated:
|
|
72
|
+
result.problems.append({"url": url, "problem": "too-large",
|
|
73
|
+
"detail": f"over {MAX_XML_BYTES} bytes"})
|
|
74
|
+
continue
|
|
75
|
+
problem, detail = check_untrusted(resp.body)
|
|
76
|
+
if problem:
|
|
77
|
+
result.problems.append({"url": url, "problem": problem, "detail": detail})
|
|
78
|
+
continue
|
|
79
|
+
try:
|
|
80
|
+
root = ET.fromstring(resp.body)
|
|
81
|
+
except (ET.ParseError, ValueError) as exc:
|
|
82
|
+
result.problems.append({"url": url, "problem": "malformed",
|
|
83
|
+
"detail": clean(exc, 200)})
|
|
84
|
+
continue
|
|
85
|
+
if local(root.tag) == "sitemapindex":
|
|
86
|
+
if level == 0:
|
|
87
|
+
queue.extend((c, 1, False) for c in _locs(root, "sitemap")[:MAX_CHILDREN])
|
|
88
|
+
else:
|
|
89
|
+
result.problems.append({"url": url, "problem": "nested-index-ignored"})
|
|
90
|
+
continue
|
|
91
|
+
for loc in _locs(root, "url"):
|
|
92
|
+
page = normalize(loc)
|
|
93
|
+
if page is None or not same_site(page, site_host):
|
|
94
|
+
result.offsite += 1
|
|
95
|
+
continue
|
|
96
|
+
if page not in seen_urls and len(result.urls) < MAX_SITEMAP_URLS:
|
|
97
|
+
seen_urls.add(page)
|
|
98
|
+
result.urls.append(page)
|
|
99
|
+
return result
|
omnirank/crawl/text.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
"""Text hygiene for anything taken from a fetched page."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from ..mcp_server import _strip_controls
|
|
5
|
+
|
|
6
|
+
MAX_FIELD = 1000
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def clean(value: object, limit: int = MAX_FIELD) -> str:
|
|
10
|
+
"""Control characters and bidi overrides removed (the MCP server's rule), whitespace
|
|
11
|
+
collapsed to single spaces, cut to ``limit`` characters."""
|
|
12
|
+
text = _strip_controls(str(value))
|
|
13
|
+
text = " ".join(text.split())
|
|
14
|
+
return text if len(text) <= limit else text[:limit] + "…"
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def words(text: str) -> list[str]:
|
|
18
|
+
"""Whitespace-separated tokens holding at least one letter or digit (Unicode-safe:
|
|
19
|
+
Bengali vowel signs are not word breaks)."""
|
|
20
|
+
return [w for w in text.split() if any(c.isalnum() for c in w)]
|