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.
Files changed (183) hide show
  1. omnirank/__init__.py +14 -0
  2. omnirank/__main__.py +6 -0
  3. omnirank/adapters/__init__.py +202 -0
  4. omnirank/adapters/astro.py +338 -0
  5. omnirank/adapters/base.py +372 -0
  6. omnirank/adapters/html.py +561 -0
  7. omnirank/adapters/jsx.py +340 -0
  8. omnirank/adapters/nextjs.py +692 -0
  9. omnirank/aeo/__init__.py +9 -0
  10. omnirank/aeo/extract.py +383 -0
  11. omnirank/aeo/propose.py +84 -0
  12. omnirank/aeo/rules.py +964 -0
  13. omnirank/aeo/runner.py +148 -0
  14. omnirank/applicability.py +98 -0
  15. omnirank/apply/__init__.py +23 -0
  16. omnirank/apply/engine.py +1254 -0
  17. omnirank/apply/journal.py +139 -0
  18. omnirank/apply/patch.py +144 -0
  19. omnirank/audit.py +185 -0
  20. omnirank/bands.py +106 -0
  21. omnirank/brief/__init__.py +0 -0
  22. omnirank/brief/analyze.py +197 -0
  23. omnirank/brief/constants.py +89 -0
  24. omnirank/brief/cost.py +62 -0
  25. omnirank/brief/egress.py +23 -0
  26. omnirank/brief/fetchpages.py +239 -0
  27. omnirank/brief/render.py +151 -0
  28. omnirank/brief/runner.py +369 -0
  29. omnirank/brief/serp.py +274 -0
  30. omnirank/brief/text.py +181 -0
  31. omnirank/cli.py +844 -0
  32. omnirank/clock.py +22 -0
  33. omnirank/cms/__init__.py +1 -0
  34. omnirank/cms/runner.py +170 -0
  35. omnirank/cms/wordpress.py +495 -0
  36. omnirank/cms/wordpress_apply.py +508 -0
  37. omnirank/cms/wordpress_plan.py +280 -0
  38. omnirank/config.py +81 -0
  39. omnirank/connect/__init__.py +4 -0
  40. omnirank/connect/bing.py +284 -0
  41. omnirank/connect/cloud_setup.py +43 -0
  42. omnirank/connect/confirm.py +242 -0
  43. omnirank/connect/constants.py +226 -0
  44. omnirank/connect/doctor.py +270 -0
  45. omnirank/connect/ga4.py +749 -0
  46. omnirank/connect/ga4_ai.py +123 -0
  47. omnirank/connect/google_auth.py +657 -0
  48. omnirank/connect/gsc.py +630 -0
  49. omnirank/connect/gsc_reports.py +169 -0
  50. omnirank/connect/http.py +310 -0
  51. omnirank/connect/indexnow.py +373 -0
  52. omnirank/connect/naver.py +536 -0
  53. omnirank/connect/runner.py +515 -0
  54. omnirank/connect/runner_ga4_ai.py +59 -0
  55. omnirank/connect/runner_more.py +489 -0
  56. omnirank/connect/runner_regional.py +260 -0
  57. omnirank/connect/secrets.py +190 -0
  58. omnirank/connect/urlcheck.py +41 -0
  59. omnirank/connect/yandex.py +350 -0
  60. omnirank/crawl/__init__.py +11 -0
  61. omnirank/crawl/analyze.py +493 -0
  62. omnirank/crawl/crawler.py +491 -0
  63. omnirank/crawl/custom.py +175 -0
  64. omnirank/crawl/export.py +67 -0
  65. omnirank/crawl/fetcher.py +212 -0
  66. omnirank/crawl/parse.py +102 -0
  67. omnirank/crawl/render.py +148 -0
  68. omnirank/crawl/robotsgate.py +198 -0
  69. omnirank/crawl/runner.py +295 -0
  70. omnirank/crawl/sitemap.py +99 -0
  71. omnirank/crawl/text.py +20 -0
  72. omnirank/crawl/urls.py +100 -0
  73. omnirank/crawlers.py +564 -0
  74. omnirank/data/ai_crawlers.json +269 -0
  75. omnirank/data/ai_referrers.json +42 -0
  76. omnirank/fetch.py +107 -0
  77. omnirank/fixes/__init__.py +92 -0
  78. omnirank/fixes/base.py +232 -0
  79. omnirank/fixes/canonical.py +243 -0
  80. omnirank/fixes/schema.py +126 -0
  81. omnirank/formats.py +134 -0
  82. omnirank/framework.py +223 -0
  83. omnirank/gates/__init__.py +48 -0
  84. omnirank/gates/aeo.py +114 -0
  85. omnirank/gates/contradictions.py +280 -0
  86. omnirank/gates/crawler_policy.py +85 -0
  87. omnirank/gates/geo.py +152 -0
  88. omnirank/gates/hygiene.py +81 -0
  89. omnirank/gates/jsonld.py +282 -0
  90. omnirank/gates/onpage.py +177 -0
  91. omnirank/gates/perf.py +115 -0
  92. omnirank/gates/security.py +264 -0
  93. omnirank/gates/seo.py +118 -0
  94. omnirank/gates/site.py +248 -0
  95. omnirank/geo_artifacts.py +199 -0
  96. omnirank/html.py +79 -0
  97. omnirank/keywords/__init__.py +5 -0
  98. omnirank/keywords/constants.py +69 -0
  99. omnirank/keywords/engine.py +384 -0
  100. omnirank/keywords/report.py +143 -0
  101. omnirank/keywords/runner.py +160 -0
  102. omnirank/keywords/source.py +60 -0
  103. omnirank/keywords/text.py +45 -0
  104. omnirank/locator.py +480 -0
  105. omnirank/logs/__init__.py +0 -0
  106. omnirank/logs/analyze.py +127 -0
  107. omnirank/logs/bots.py +69 -0
  108. omnirank/logs/ipranges.py +191 -0
  109. omnirank/logs/parse.py +452 -0
  110. omnirank/logs/paths.py +22 -0
  111. omnirank/logs/privacy.py +105 -0
  112. omnirank/logs/runner.py +179 -0
  113. omnirank/mcp_server.py +1480 -0
  114. omnirank/netguard.py +525 -0
  115. omnirank/packs/__init__.py +6 -0
  116. omnirank/packs/backlinks.py +535 -0
  117. omnirank/packs/blog.py +544 -0
  118. omnirank/packs/blog_cross.py +468 -0
  119. omnirank/packs/crawlers.py +23 -0
  120. omnirank/packs/entity.py +492 -0
  121. omnirank/packs/feeds.py +150 -0
  122. omnirank/packs/frontmatter.py +59 -0
  123. omnirank/packs/gsc.py +421 -0
  124. omnirank/packs/local.py +879 -0
  125. omnirank/packs/mdscan.py +326 -0
  126. omnirank/packs/miniyaml.py +378 -0
  127. omnirank/packs/model.py +46 -0
  128. omnirank/packs/product.py +979 -0
  129. omnirank/packs/refresh.py +165 -0
  130. omnirank/packs/runner.py +277 -0
  131. omnirank/packs/sitescan.py +294 -0
  132. omnirank/packs/textsafe.py +79 -0
  133. omnirank/packs/xmlsafe.py +92 -0
  134. omnirank/page.py +42 -0
  135. omnirank/registry.py +302 -0
  136. omnirank/report.py +251 -0
  137. omnirank/report_cmd/__init__.py +7 -0
  138. omnirank/report_cmd/delta.py +58 -0
  139. omnirank/report_cmd/files.py +64 -0
  140. omnirank/report_cmd/model.py +208 -0
  141. omnirank/report_cmd/notify.py +195 -0
  142. omnirank/report_cmd/pdf.py +83 -0
  143. omnirank/report_cmd/portfolio.py +342 -0
  144. omnirank/report_cmd/render.py +379 -0
  145. omnirank/report_cmd/runner.py +267 -0
  146. omnirank/robots.py +172 -0
  147. omnirank/scanner/__init__.py +10 -0
  148. omnirank/scanner/badge.py +90 -0
  149. omnirank/scanner/cache.py +69 -0
  150. omnirank/scanner/cli.py +96 -0
  151. omnirank/scanner/engine.py +289 -0
  152. omnirank/scanner/limits.py +98 -0
  153. omnirank/scanner/server.py +143 -0
  154. omnirank/scanner/service.py +328 -0
  155. omnirank/schema/__init__.py +13 -0
  156. omnirank/schema/catalog.py +679 -0
  157. omnirank/schema/catalog_specs.py +350 -0
  158. omnirank/schema/core.py +306 -0
  159. omnirank/schema/extract.py +396 -0
  160. omnirank/schema/gate.py +121 -0
  161. omnirank/schema/runner.py +213 -0
  162. omnirank/schema/validate.py +504 -0
  163. omnirank/schema/vocab.py +305 -0
  164. omnirank/schemas/omnirank.config.schema.json +268 -0
  165. omnirank/track/__init__.py +0 -0
  166. omnirank/track/ai_prompts.py +207 -0
  167. omnirank/track/analysis.py +197 -0
  168. omnirank/track/constants.py +155 -0
  169. omnirank/track/cost.py +229 -0
  170. omnirank/track/discover.py +277 -0
  171. omnirank/track/discover_cli.py +309 -0
  172. omnirank/track/discover_constants.py +95 -0
  173. omnirank/track/engines.py +216 -0
  174. omnirank/track/estimate_view.py +212 -0
  175. omnirank/track/history.py +261 -0
  176. omnirank/track/runner.py +586 -0
  177. omnirank/track/stats.py +138 -0
  178. omnirank/track/storage.py +128 -0
  179. omnirank-0.5.0.dist-info/METADATA +47 -0
  180. omnirank-0.5.0.dist-info/RECORD +183 -0
  181. omnirank-0.5.0.dist-info/WHEEL +5 -0
  182. omnirank-0.5.0.dist-info/entry_points.txt +2 -0
  183. omnirank-0.5.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,64 @@
1
+ """Confined, symlink-safe file writes for report output.
2
+
3
+ The output path is resolved against a root directory; ``..`` escapes, absolute paths outside
4
+ the root, symlinked path components and a final symlink are refused, and names that look like
5
+ secrets, keys or lockfiles are never written (a report must not overwrite them).
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import os
10
+ from pathlib import Path
11
+
12
+ DENY_NAMES = frozenset({"credentials.json", "package-lock.json", "yarn.lock", "pnpm-lock.yaml",
13
+ "poetry.lock", "cargo.lock", "gemfile.lock", "composer.lock",
14
+ "uv.lock", "pipfile.lock", "go.sum", "known_hosts",
15
+ "authorized_keys"})
16
+ DENY_SUFFIXES = (".pem", ".key", ".p12", ".pfx", ".lock", ".keystore", ".jks")
17
+ DENY_PREFIXES = (".env", "id_rsa", "id_ed25519", "id_ecdsa", "id_dsa", ".npmrc", ".netrc")
18
+
19
+
20
+ class WriteRefused(Exception):
21
+ """The output path is not a safe place to write."""
22
+
23
+
24
+ def _denied(name: str) -> bool:
25
+ low = name.lower()
26
+ return (low in DENY_NAMES or low.endswith(DENY_SUFFIXES) or low.startswith(DENY_PREFIXES))
27
+
28
+
29
+ def checked_path(root: str | Path, rel: str | Path) -> Path:
30
+ """The absolute target for ``rel`` under ``root`` after every safety check (nothing is
31
+ created)."""
32
+ raw = str(rel)
33
+ if not raw or "\x00" in raw:
34
+ raise WriteRefused("empty or invalid output path")
35
+ base = Path(os.path.normpath(Path(root).absolute()))
36
+ target = Path(os.path.normpath((base / raw) if not os.path.isabs(raw) else raw))
37
+ if target != base and base not in target.parents:
38
+ raise WriteRefused(f"{raw!r} is outside the project root {base}; refusing to write it")
39
+ if target == base:
40
+ raise WriteRefused("the output path is the root directory")
41
+ if _denied(target.name):
42
+ raise WriteRefused(f"{target.name!r} looks like a secret, key or lockfile; "
43
+ "refusing to write it")
44
+ cur = base
45
+ for part in target.relative_to(base).parts:
46
+ cur = cur / part
47
+ if cur.is_symlink():
48
+ raise WriteRefused(f"{cur} is a symlink; refusing to write through it")
49
+ return target
50
+
51
+
52
+ def write_text(root: str | Path, rel: str | Path, text: str) -> Path:
53
+ target = checked_path(root, rel)
54
+ target.parent.mkdir(parents=True, exist_ok=True)
55
+ flags = os.O_WRONLY | os.O_CREAT | os.O_TRUNC | getattr(os, "O_NOFOLLOW", 0)
56
+ try:
57
+ fd = os.open(target, flags, 0o644)
58
+ except OSError as exc:
59
+ raise WriteRefused(f"cannot write {target}: {exc.strerror or exc}") from None
60
+ try:
61
+ os.write(fd, text.encode("utf-8"))
62
+ finally:
63
+ os.close(fd)
64
+ return target
@@ -0,0 +1,208 @@
1
+ """Load and validate sweep reports (``Report.to_dict()`` JSON) from a file or a directory.
2
+
3
+ A report may come from a file somebody else produced, so every field is checked, every
4
+ string is cleaned of terminal control characters and length-capped, and the size and the
5
+ number of findings are bounded. Nothing here fetches anything.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import unicodedata
11
+ from dataclasses import dataclass, field
12
+ from pathlib import Path
13
+
14
+ MAX_REPORT_BYTES = 20_000_000
15
+ MAX_FINDINGS = 50_000
16
+ MAX_TEXT = 2000
17
+ SEVERITIES = ("error", "warning", "info")
18
+ _BIDI = frozenset(chr(c) for c in (*range(0x202A, 0x202F), *range(0x2066, 0x206A)))
19
+ _FINDING_STR = ("id", "severity", "layer", "url", "gate", "observed", "expected", "fix")
20
+
21
+
22
+ class ReportError(Exception):
23
+ """The input is not a usable sweep report."""
24
+
25
+
26
+ def clean(value: object, limit: int = MAX_TEXT) -> str:
27
+ """Printable text: control characters (ANSI escapes, NUL, bell) and bidi overrides
28
+ removed, newlines and tabs turned into spaces, truncated to ``limit`` characters.
29
+ Letters of any script, including Bengali and joiners, are kept."""
30
+ text = value if isinstance(value, str) else str(value)
31
+ kept = "".join(" " if c in "\n\r\t" else c for c in text
32
+ if c not in _BIDI and (c in "\n\r\t" or unicodedata.category(c) != "Cc"))
33
+ if len(kept) > limit:
34
+ kept = kept[: max(0, limit - 1)] + "…"
35
+ return kept
36
+
37
+
38
+ def _is_int(v: object) -> bool:
39
+ return isinstance(v, int) and not isinstance(v, bool)
40
+
41
+
42
+ def validate(raw: object) -> dict:
43
+ if not isinstance(raw, dict):
44
+ raise ReportError("not a sweep report: the top level is not a JSON object")
45
+ site, score, findings = raw.get("site"), raw.get("score"), raw.get("findings")
46
+ if not isinstance(site, str) or not isinstance(score, dict) or not isinstance(findings, list):
47
+ raise ReportError("not a sweep report: needs string 'site', object 'score' and "
48
+ "list 'findings'")
49
+ if len(findings) > MAX_FINDINGS:
50
+ raise ReportError(f"report has more than {MAX_FINDINGS} findings; refusing it")
51
+ clean_score: dict[str, int] = {}
52
+ for layer, value in score.items():
53
+ if not isinstance(layer, str) or not _is_int(value) or not 0 <= value <= 100:
54
+ raise ReportError(f"score {layer!r} is not an integer from 0 to 100")
55
+ clean_score[clean(layer, 40)] = value
56
+ out_findings = []
57
+ for f in findings:
58
+ if not isinstance(f, dict) or any(not isinstance(f.get(k), str) for k in _FINDING_STR):
59
+ raise ReportError("a finding is missing one of: " + ", ".join(_FINDING_STR))
60
+ if f["severity"] not in SEVERITIES:
61
+ raise ReportError(f"unknown finding severity {clean(f['severity'], 30)!r}")
62
+ item = {k: clean(f[k]) for k in _FINDING_STR}
63
+ item["fixTier"] = clean(f.get("fixTier", ""), 40) if isinstance(
64
+ f.get("fixTier"), str) else ""
65
+ out_findings.append(item)
66
+ ne = raw.get("notEvaluated", [])
67
+ if not isinstance(ne, list):
68
+ raise ReportError("'notEvaluated' is not a list")
69
+ out_ne = []
70
+ for e in ne:
71
+ if not isinstance(e, dict) or not isinstance(e.get("gate"), str) \
72
+ or not isinstance(e.get("reason"), str):
73
+ raise ReportError("a notEvaluated entry needs string 'gate' and 'reason'")
74
+ out_ne.append({"gate": clean(e["gate"], 80), "reason": clean(e["reason"], 80),
75
+ "target": clean(e.get("url") or e.get("site") or "", 500)})
76
+ stats = raw.get("stats") if isinstance(raw.get("stats"), dict) else {}
77
+ checked = stats.get("urlsChecked")
78
+ return {
79
+ "site": clean(site, 500),
80
+ "kind": clean(raw.get("kind", "audit") if isinstance(raw.get("kind"), str) else "audit",
81
+ 40),
82
+ "generatedAt": clean(raw.get("generatedAt", ""), 40)
83
+ if isinstance(raw.get("generatedAt"), str) else "",
84
+ "score": clean_score,
85
+ "urlsChecked": checked if _is_int(checked) and checked >= 0 else None,
86
+ "findings": out_findings,
87
+ "notEvaluated": out_ne,
88
+ }
89
+
90
+
91
+ def load_report(path: str | Path) -> dict:
92
+ p = Path(path)
93
+ try:
94
+ size = p.stat().st_size
95
+ except OSError as exc:
96
+ raise ReportError(f"cannot read {clean(p, 300)}: {exc.strerror or exc}") from None
97
+ if not p.is_file():
98
+ raise ReportError(f"{clean(p, 300)} is not a file")
99
+ if size > MAX_REPORT_BYTES:
100
+ raise ReportError(f"{clean(p, 300)} is larger than {MAX_REPORT_BYTES} bytes")
101
+ try:
102
+ raw = json.loads(p.read_text(encoding="utf-8"))
103
+ except (RecursionError, MemoryError):
104
+ raise ReportError(f"{clean(p, 300)} is nested or large beyond what can be read "
105
+ "safely; refusing it") from None
106
+ except (ValueError, OSError) as exc:
107
+ raise ReportError(f"{clean(p, 300)} is not valid JSON: {clean(exc, 200)}") from None
108
+ try:
109
+ return validate(raw)
110
+ except RecursionError:
111
+ raise ReportError(f"{clean(p, 300)} is nested too deeply; refusing it") from None
112
+
113
+
114
+ @dataclass
115
+ class PairInfo:
116
+ """Which files were read, which were skipped and why (directory mode)."""
117
+ current: dict
118
+ previous: dict | None
119
+ current_path: Path | None = None
120
+ previous_path: Path | None = None
121
+ skipped: list[tuple[Path, str]] = field(default_factory=list)
122
+ newest_broken: bool = False
123
+
124
+ def warnings(self) -> list[str]:
125
+ out = [f"skipped {clean(p.name, 120)}: {clean(why, 200)}" for p, why in self.skipped]
126
+ if self.newest_broken:
127
+ out.append("the NEWEST report could not be used; the comparison below is "
128
+ "NOT of the latest run")
129
+ return out
130
+
131
+
132
+ def _scan(directory: Path) -> list[tuple[Path, str | None]]:
133
+ """Every ``*.json`` oldest first, each with a reason it is unusable (or None)."""
134
+ base = directory / ".omnirank" / "reports"
135
+ search = base if base.is_dir() else directory
136
+ root = directory.resolve()
137
+ found: list[tuple[Path, str | None]] = []
138
+ try:
139
+ names = sorted(search.glob("*.json"))
140
+ except OSError:
141
+ return found
142
+ for f in names:
143
+ try:
144
+ if not f.is_file():
145
+ found.append((f, "not a regular file"))
146
+ elif not f.resolve().is_relative_to(root):
147
+ found.append((f, "resolves outside the directory"))
148
+ else:
149
+ found.append((f, None))
150
+ except OSError as exc:
151
+ found.append((f, clean(exc.strerror or exc, 100)))
152
+ return found
153
+
154
+
155
+ def candidates(directory: Path) -> list[Path]:
156
+ """Usable report files in a directory, oldest first by name."""
157
+ return [f for f, why in _scan(directory) if why is None]
158
+
159
+
160
+ def load_pair_info(source: str | Path, previous: str | Path | None) -> PairInfo:
161
+ src = Path(source)
162
+ if not src.is_dir():
163
+ prev = load_report(previous) if previous else None
164
+ return PairInfo(load_report(src), prev, src, Path(previous) if previous else None)
165
+ valid: list[tuple[Path, dict]] = []
166
+ skipped: list[tuple[Path, str]] = []
167
+ newest_broken = False
168
+ for index, (f, why) in enumerate(reversed(_scan(src))):
169
+ if why is None:
170
+ try:
171
+ valid.append((f, load_report(f)))
172
+ except ReportError as exc:
173
+ why = str(exc)
174
+ if why is not None:
175
+ skipped.append((f, why))
176
+ if index == 0:
177
+ newest_broken = True
178
+ if len(valid) == 2:
179
+ break
180
+ if not valid:
181
+ raise ReportError(f"no usable report JSON found in {clean(src, 300)} (looked in "
182
+ ".omnirank/reports and the directory itself)"
183
+ + (f"; skipped {len(skipped)} file(s)" if skipped else ""))
184
+ cur_path, cur = valid[0]
185
+ if previous:
186
+ return PairInfo(cur, load_report(previous), cur_path, Path(previous), skipped,
187
+ newest_broken)
188
+ prev_path, prev = valid[1] if len(valid) > 1 else (None, None)
189
+ return PairInfo(cur, prev, cur_path, prev_path, skipped, newest_broken)
190
+
191
+
192
+ def load_pair(source: str | Path, previous: str | Path | None) -> tuple[dict, dict | None]:
193
+ """The current report and (if any) the previous one."""
194
+ info = load_pair_info(source, previous)
195
+ return info.current, info.previous
196
+
197
+
198
+ def to_raw(report: dict) -> dict:
199
+ """The validated form back in the on-disk shape ``validate`` accepts (round trip)."""
200
+ return {
201
+ "site": report["site"], "kind": report["kind"], "generatedAt": report["generatedAt"],
202
+ "score": report["score"],
203
+ "stats": {"urlsChecked": report["urlsChecked"]} if report["urlsChecked"] is not None
204
+ else {},
205
+ "findings": report["findings"],
206
+ "notEvaluated": [{"gate": e["gate"], "reason": e["reason"], "url": e["target"]}
207
+ for e in report["notEvaluated"]],
208
+ }
@@ -0,0 +1,195 @@
1
+ """Regression notifications: GitHub issue and Slack webhook (the only network code here).
2
+
3
+ * Both are WRITES: they go through ``connect.confirm`` (the request is printed, dry run by
4
+ default, ``--send`` plus a prompt or ``--yes``, refusal on a non-terminal, action log).
5
+ * Credentials come from the environment only (``GITHUB_TOKEN``, ``OMNIRANK_SLACK_WEBHOOK``),
6
+ are registered with ``redact()`` and never appear in output, logs or URLs we print.
7
+ * Requests go through the shared ``ApiClient``: exact host allow-list, no redirects, no
8
+ retries (a retried POST could open a second issue).
9
+ * Text from audited pages is untrusted: Markdown puts it in code spans (no @mentions, no
10
+ HTML), Slack text is entity-escaped (no ``<!channel>``).
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import re
15
+ from collections.abc import Callable
16
+
17
+ import httpx
18
+
19
+ from ..connect.confirm import WriteAction
20
+ from ..connect.http import ApiClient
21
+ from ..connect.secrets import env_secret
22
+ from .delta import Delta
23
+ from .model import clean
24
+ from .render import md_code, md_text
25
+
26
+ MAX_BODY = 60_000 # GitHub rejects issue bodies above 65,536 characters
27
+ MAX_LISTED = 25
28
+ MAX_SLACK = 3000
29
+ GITHUB_HOST = "api.github.com"
30
+ SLACK_HOST = "hooks.slack.com"
31
+ ENV_GITHUB = "GITHUB_TOKEN"
32
+ ENV_REPO = "GITHUB_REPOSITORY"
33
+ ENV_SLACK = "OMNIRANK_SLACK_WEBHOOK"
34
+ _REPO = re.compile(r"[A-Za-z0-9_.-]{1,100}/[A-Za-z0-9_.-]{1,100}")
35
+ _WEBHOOK = re.compile(r"https://hooks\.slack\.com/services/[A-Za-z0-9_-]{1,40}/"
36
+ r"[A-Za-z0-9_-]{1,40}/[A-Za-z0-9_-]{1,60}")
37
+
38
+ # Tests (and nothing else) may set this to build the httpx client used for sends.
39
+ HTTP_FACTORY: Callable[[], httpx.Client] | None = None
40
+
41
+
42
+ class NotifyError(Exception):
43
+ pass
44
+
45
+
46
+ def should_notify(d: Delta) -> bool:
47
+ return d.previous is not None and d.has_regression
48
+
49
+
50
+ def validate_repo(value: str) -> str:
51
+ if not isinstance(value, str) or not _REPO.fullmatch(value) \
52
+ or any(part in (".", "..") for part in value.split("/")):
53
+ raise NotifyError("repository must look like owner/name (letters, digits, . _ -)")
54
+ return value
55
+
56
+
57
+ def validate_webhook(value: str) -> str:
58
+ if not isinstance(value, str) or not _WEBHOOK.fullmatch(value):
59
+ raise NotifyError("the Slack webhook must be exactly "
60
+ "https://hooks.slack.com/services/<T>/<B>/<token>")
61
+ return value
62
+
63
+
64
+ def webhook_from_env() -> str:
65
+ value = env_secret(ENV_SLACK)
66
+ if value is None:
67
+ raise NotifyError(f"{ENV_SLACK} is not set; export the Slack incoming-webhook URL "
68
+ "in that environment variable (it is never read from a file or flag)")
69
+ return validate_webhook(value)
70
+
71
+
72
+ def repo_from_env() -> str:
73
+ import os
74
+ return validate_repo(os.environ.get(ENV_REPO, "").strip())
75
+
76
+
77
+ def issue_title(d: Delta) -> str:
78
+ n = len(d.regressions)
79
+ what = f"{n} new finding(s)" if n else "score drop"
80
+ return clean(f"OmniRank monitor: regression ({what}) on {d.current['site']}", 200)
81
+
82
+
83
+ RESERVE = 450 # room kept for the score table, the footer and the truncation line
84
+ FOOTER = ("Opened by a scheduled run. Findings are automated checks on sampled "
85
+ "URLs, not a ranking or citation guarantee.")
86
+
87
+
88
+ def issue_body(d: Delta) -> str:
89
+ """Markdown issue body. The size cap is applied per ITEM: an item (all its lines) is
90
+ added whole or not at all, so a code span is never cut open and untrusted text can
91
+ never become live Markdown. Omitted items are counted in a closing line."""
92
+ cur, prev = d.current, d.previous
93
+ head = [f"# Regression detected on {md_code(cur['site'])}", ""]
94
+ if prev is None:
95
+ head.append("No previous run to compare with.")
96
+ else:
97
+ head.append(f"Compared with the previous run: {len(d.new_findings)} new finding(s), "
98
+ f"{len(d.resolved)} resolved.")
99
+ budget = MAX_BODY - RESERVE
100
+ used = len("\n".join(head)) + 1
101
+ omitted = 0
102
+ out: list[str] = list(head)
103
+
104
+ def add_items(blocks: list[str]) -> None:
105
+ nonlocal used, omitted
106
+ for i, block in enumerate(blocks):
107
+ if i >= MAX_LISTED or used + len(block) + 1 > budget:
108
+ omitted += len(blocks) - i
109
+ return
110
+ out.append(block)
111
+ used += len(block) + 1
112
+
113
+ out += ["", "## New regressions", ""]
114
+ reg = d.regressions
115
+ if not reg:
116
+ out.append("None. The score of at least one layer dropped (below).")
117
+ add_items([(f"- **{f['severity']}** {md_code(f['id'])} · {md_text(f['layer'])} · "
118
+ f"{md_code(f['url'])}\n - observed: {md_code(f['observed'])}\n"
119
+ f" - fix: {md_code(f['fix'])}") for f in reg])
120
+ out += ["", "## Score changes", "", "| Layer | Before | After | Change |",
121
+ "| --- | ---: | ---: | ---: |"]
122
+ changed = [(layer, c) for layer, c in sorted(d.score_changes.items()) if c]
123
+ for layer, change in changed[:20]:
124
+ out.append(f"| {md_text(layer)} | {prev['score'][layer] if prev else ''} | "
125
+ f"{cur['score'][layer]} | {change:+d} |")
126
+ if not changed:
127
+ out.append("| (no layer score changed) | | | |")
128
+ if d.new_not_evaluated:
129
+ out += ["", "## Newly not evaluated", "",
130
+ "These gates could not run this time. They did not pass.", ""]
131
+ add_items([f"- {md_code(e['gate'])} {md_code(e['reason'])} {md_code(e['target'])}"
132
+ for e in d.new_not_evaluated])
133
+ if omitted:
134
+ out += ["", (f"truncated: {omitted} more item(s) not shown (size limit); "
135
+ "see the full report.")]
136
+ out += ["", "---", FOOTER]
137
+ body = "\n".join(out) + "\n"
138
+ if len(body) > MAX_BODY: # pathological: even the fixed parts do not fit
139
+ body = "\n".join([*head, "", ("truncated: the details do not fit in an issue body; "
140
+ "see the full report."), "", "---", FOOTER])[:MAX_BODY] + "\n"
141
+ return body
142
+
143
+
144
+ def _slack_escape(text: object) -> str:
145
+ return clean(text, 300).replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
146
+
147
+
148
+ def slack_text(d: Delta) -> str:
149
+ lines = [(f"Regression on {_slack_escape(d.current['site'])}: "
150
+ f"{len(d.regressions)} new error/warning finding(s).")]
151
+ for f in d.regressions[:10]:
152
+ lines.append(f"- {f['severity']} {_slack_escape(f['id'])} "
153
+ f"{_slack_escape(f['url'])}")
154
+ for layer, change in sorted(d.score_drops.items()):
155
+ lines.append(f"- {_slack_escape(layer)} score {change:+d}")
156
+ return "\n".join(lines)[:MAX_SLACK]
157
+
158
+
159
+ def github_action(repo: str, title: str, body: str) -> WriteAction:
160
+ repo = validate_repo(repo)
161
+ return WriteAction(
162
+ connector="github", action="open-issue", method="POST",
163
+ url=f"https://{GITHUB_HOST}/repos/{repo}/issues",
164
+ summary=f"Open a GitHub issue in {repo}: {clean(title, 120)}",
165
+ body={"title": title, "body": body}, scopes=("issues: write",))
166
+
167
+
168
+ def slack_action(webhook: str, text: str) -> WriteAction:
169
+ return WriteAction(connector="slack", action="post-message", method="POST",
170
+ url=validate_webhook(webhook),
171
+ summary="Post a regression notice to a Slack incoming webhook",
172
+ body={"text": text})
173
+
174
+
175
+ def _http() -> httpx.Client | None:
176
+ return HTTP_FACTORY() if HTTP_FACTORY else None
177
+
178
+
179
+ def execute_github(action: WriteAction, http: httpx.Client | None = None) -> dict:
180
+ token = env_secret(ENV_GITHUB)
181
+ if token is None:
182
+ raise NotifyError(f"{ENV_GITHUB} is not set; in GitHub Actions pass "
183
+ "`env: GITHUB_TOKEN: ${{ github.token }}` with `issues: write`")
184
+ client = ApiClient(lambda: token, http=http or _http(), allowed_hosts=[GITHUB_HOST],
185
+ max_retries=0,
186
+ extra_headers={"Accept": "application/vnd.github+json",
187
+ "X-GitHub-Api-Version": "2022-11-28"},
188
+ auth_hint="the token needs `issues: write` on this repository")
189
+ out = client.request("POST", action.url, json_body=action.body)
190
+ return {k: out[k] for k in ("number", "html_url") if k in out}
191
+
192
+
193
+ def execute_slack(action: WriteAction, http: httpx.Client | None = None) -> dict:
194
+ client = ApiClient(None, http=http or _http(), allowed_hosts=[SLACK_HOST], max_retries=0)
195
+ return client.request("POST", action.url, json_body=action.body, auth=False, raw=True)
@@ -0,0 +1,83 @@
1
+ """PDF output without a new dependency: only through a converter that happens to be installed.
2
+
3
+ A PDF cannot be produced with the standard library. ``weasyprint`` or ``wkhtmltopdf`` is
4
+ used if found on PATH; the command is an argv list run without a shell, every path is made
5
+ absolute (so it can never look like an option) and NUL bytes are refused. With neither
6
+ installed the caller exits 2 with guidance: the HTML report is print-optimized, so any
7
+ browser's "Save as PDF" gives the same result.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import shutil
12
+ import subprocess
13
+ from collections.abc import Callable
14
+ from pathlib import Path
15
+
16
+ from .model import clean
17
+
18
+ TIMEOUT_SECONDS = 120
19
+
20
+ GUIDANCE = ("no PDF converter found on PATH. Install weasyprint or wkhtmltopdf and re-run, "
21
+ "or run `omnirank report --format html` and print the page to PDF from a "
22
+ "browser (the HTML is print-optimized, with no external assets).")
23
+
24
+
25
+ class PdfError(Exception):
26
+ pass
27
+
28
+
29
+ class PdfUnavailable(PdfError):
30
+ def __init__(self) -> None:
31
+ super().__init__(GUIDANCE)
32
+
33
+
34
+ _CONVERTERS: tuple[tuple[str, Callable[[str, str, str], list[str]]], ...] = (
35
+ ("weasyprint", lambda exe, i, o: [exe, i, o]),
36
+ ("wkhtmltopdf", lambda exe, i, o: [exe, "--quiet", "--disable-javascript", i, o]),
37
+ )
38
+
39
+
40
+ def _abs(p: str | Path) -> str:
41
+ s = str(p)
42
+ if "\x00" in s or "\n" in s or "\r" in s:
43
+ raise PdfError("refusing a path with NUL or newline characters")
44
+ return str(Path(s).resolve())
45
+
46
+
47
+ def build_argv(exe: str, html: str | Path, out: str | Path, *, name: str | None = None) -> list[str]:
48
+ exe_s = str(exe)
49
+ if "\x00" in exe_s:
50
+ raise PdfError("refusing a converter path with a NUL character")
51
+ base = name or Path(exe_s).name
52
+ for cname, build in _CONVERTERS:
53
+ if cname == base:
54
+ return build(exe_s, _abs(html), _abs(out))
55
+ raise PdfError(f"unsupported converter {clean(base, 40)!r}")
56
+
57
+
58
+ def convert(html: str | Path, out: str | Path, *,
59
+ which: Callable[[str], str | None] | None = None,
60
+ run: Callable | None = None) -> str:
61
+ """Convert ``html`` to ``out``; returns the converter's name."""
62
+ which = which or shutil.which
63
+ run = run or subprocess.run
64
+ for name, _ in _CONVERTERS:
65
+ exe = which(name)
66
+ if not exe:
67
+ continue
68
+ argv = build_argv(exe, html, out, name=name)
69
+ try:
70
+ proc = run(argv, shell=False, capture_output=True, timeout=TIMEOUT_SECONDS,
71
+ check=False, stdin=subprocess.DEVNULL)
72
+ except subprocess.TimeoutExpired:
73
+ raise PdfError(f"{name} did not finish within {TIMEOUT_SECONDS}s") from None
74
+ except OSError as exc:
75
+ raise PdfError(f"could not run {name}: {clean(exc, 200)}") from None
76
+ if proc.returncode != 0:
77
+ err = proc.stderr.decode("utf-8", "replace") if isinstance(
78
+ proc.stderr, bytes) else str(proc.stderr)
79
+ raise PdfError(f"{name} failed (exit {proc.returncode}): {clean(err, 300)}")
80
+ if not Path(out).is_file():
81
+ raise PdfError(f"{name} reported success but wrote no file")
82
+ return name
83
+ raise PdfUnavailable()