lib/review-listings.py

726 lines · 25752 bytes

  1#!/usr/bin/env python3
  2"""Audit every service in awesome-privacy.yml.
  3
  4Checks:
  5- url-reachable: homepage URL does not 404
  6- https-url: homepage URL uses HTTPS
  7- icon-reachable: icon URL does not 404
  8- description-len: description is 50 to 280 chars (over 420 escalates to warn)
  9- opensource-github: openSource listings include a github, codeberg or git field
 10- duplicate-url: no URL appears in more than one listing
 11- androidApp-valid: androidApp is a package name, not a URL
 12- iosApp-reachable: App Store URL resolves
 13- subreddit-exists: subreddit page exists on reddit.com
 14- tosdr-valid: tosdrId still resolves on tosdr.org
 15- discord-invite-valid: Discord invite code is still valid
 16- github-exists: github repo is accessible (needs token)
 17- github-archived: github repo is not archived (needs token)
 18- github-activity: github repo was pushed recently (needs token)
 19- github-license: github repo has a license (needs token)
 20- github-fork: github repo is not a fork (needs token)
 21
 22Findings have three severities: error (must fix), warn (should review), info (FYI).
 23HTTP 403/406/429 (and 404 on known bot-blocking hosts such as play.google.com) on
 24reachability checks is demoted from error to warn.
 25
 26Exit codes:
 27    1 when pass rate drops below FAIL_PASS_RATE or errors exceed FAIL_MAX_ERRORS (5)
 28    2 you didn't run the script right / something else fucked up
 29    0 everything is amazing
 30
 31Flags:
 32- --save-json PATH: save a JSON report to this file
 33- --save-markdown PATH: save a markdown report to this file (for GH Actions summaries)
 34- --category / --section / --service: narrow to one entry
 35- --only / --skip: pick or drop checks by name
 36- --severity {all,warn,error}: filter findings
 37- --max-workers N: parallel workers (default 8)
 38- --timeout N: HTTP timeout in seconds (default 10)
 39- --token: GitHub token, else $GITHUB_TOKEN
 40- --no-color: disable ANSI colors
 41- --list-checks: list checks and exit
 42- -v / -q: verbose or quiet logging
 43"""
 44
 45import argparse
 46import json
 47import logging
 48import os
 49import re
 50import signal
 51import sys
 52from concurrent.futures import ThreadPoolExecutor, as_completed
 53from dataclasses import asdict, dataclass, field
 54from datetime import datetime, timezone
 55from threading import Lock
 56from time import monotonic
 57from typing import Callable, Iterable
 58from urllib.parse import urlparse
 59
 60sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
 61try:
 62    import utils
 63except ImportError as exc:
 64    print(f"ERROR: missing dependency ({exc}). Run `make install_lib_deps`.", file=sys.stderr)
 65    sys.exit(2)
 66
 67MIN_DESC = 50
 68MAX_DESC = 280
 69MAX_DESC_HARD = 420
 70DEFAULT_WORKERS = 8
 71DEFAULT_TIMEOUT = 10
 72
 73# github-activity age bands (days since last push). Order matters: most severe first.
 74ACTIVITY_BANDS = (
 75    (365 * 8, "error"),
 76    (365 * 3, "warn"),
 77    (365,     "info"),
 78)
 79
 80SEVERITIES = ("error", "warn", "info")
 81_SEV_COLOR = {"error": "red", "warn": "yellow", "info": "cyan"}
 82_SEV_EMOJI = {"error": "🔴", "warn": "🟠", "info": "🟡"}
 83_SOFT_HTTP = {403, 406, 429}
 84_SOFT_404_HOSTS = {"play.google.com"}
 85_PKG_RE = re.compile(r"^[a-zA-Z][a-zA-Z0-9_]*(\.[a-zA-Z][a-zA-Z0-9_]*)+$")
 86
 87FAIL_PASS_RATE = 95.0
 88FAIL_MAX_ERRORS = 5
 89
 90
 91@dataclass
 92class Entry:
 93    category: str
 94    section: str
 95    service: dict
 96
 97    @property
 98    def name(self):
 99        return self.service.get("name", "")
100
101
102@dataclass
103class Finding:
104    category: str
105    section: str
106    service: str
107    check: str
108    severity: str
109    message: str
110
111
112@dataclass
113class Context:
114    session: object
115    token: str
116    timeout: int
117    url_occurrences: dict = field(default_factory=dict)
118    repo_cache: dict = field(default_factory=dict)
119    repo_lock: Lock = field(default_factory=Lock)
120
121
122@dataclass
123class CheckSpec:
124    name: str
125    scope: str
126    needs_github: bool
127    fn: Callable
128    doc: str
129
130
131CHECKS: dict[str, CheckSpec] = {}
132
133
134def check(name, *, scope="service", needs_github=False):
135    def deco(fn):
136        CHECKS[name] = CheckSpec(name, scope, needs_github, fn, (fn.__doc__ or "").strip())
137        return fn
138    return deco
139
140
141def _finding(entry: Entry, check_name: str, severity: str, message: str) -> Finding:
142    return Finding(entry.category, entry.section, entry.name, check_name, severity, message)
143
144
145def _normalize_url(url: str) -> str:
146    return (url or "").strip().rstrip("/").lower()
147
148
149def _get_repo(entry: Entry, ctx: Context):
150    owner, repo = utils.parse_github_field(entry.service.get("github"))
151    if not owner:
152        return None
153    key = f"{owner}/{repo}"
154    with ctx.repo_lock:
155        if key in ctx.repo_cache:
156            return ctx.repo_cache[key]
157    data = utils.fetch_repo(owner, repo, ctx.token, session=ctx.session)
158    with ctx.repo_lock:
159        ctx.repo_cache[key] = data
160    return data
161
162
163def _unreachable(field, url, status, default_sev):
164    """Return (severity, message). Bot-blocking signatures demote error to warn."""
165    host = urlparse(url).netloc.lower()
166    soft = status in _SOFT_HTTP or (status == 404 and host in _SOFT_404_HOSTS)
167    sev = "warn" if default_sev == "error" and soft else default_sev
168    detail = f"{url} returned HTTP {status}" if status else f"{url} could not be reached"
169    return sev, f"{field} is unreachable, {detail}"
170
171
172def _reachability_finding(entry, check_name, field, url, default_sev, ctx):
173    ok, status = utils.check_url(url, ctx.session, ctx.timeout)
174    if ok:
175        return None
176    sev, msg = _unreachable(field, url, status, default_sev)
177    return _finding(entry, check_name, sev, msg)
178
179
180@check("url-reachable")
181def _url_reachable(entry: Entry, ctx: Context) -> Iterable[Finding]:
182    """Homepage URL must not 404."""
183    url = entry.service.get("url")
184    if url:
185        f = _reachability_finding(entry, "url-reachable", "url", url, "error", ctx)
186        if f:
187            yield f
188
189
190@check("https-url")
191def _https_url(entry: Entry, ctx: Context) -> Iterable[Finding]:
192    """Homepage URL must use HTTPS."""
193    url = entry.service.get("url", "")
194    if url and not url.startswith("https://"):
195        yield _finding(entry, "https-url", "warn", f"url is not HTTPS: {url}")
196
197
198@check("icon-reachable")
199def _icon_reachable(entry: Entry, ctx: Context) -> Iterable[Finding]:
200    """Icon URL must not 404."""
201    icon = entry.service.get("icon")
202    if icon:
203        f = _reachability_finding(entry, "icon-reachable", "icon", icon, "warn", ctx)
204        if f:
205            yield f
206
207
208@check("description-len")
209def _description_len(entry: Entry, ctx: Context) -> Iterable[Finding]:
210    """Description length within 50 to 280 characters (over 420 escalates to warn)."""
211    length = len((entry.service.get("description") or "").strip())
212    if length < MIN_DESC:
213        yield _finding(entry, "description-len", "warn",
214                       f"description is {length} chars (min {MIN_DESC})")
215    elif length > MAX_DESC_HARD:
216        yield _finding(entry, "description-len", "warn",
217                       f"description is {length} chars (max {MAX_DESC_HARD})")
218    elif length > MAX_DESC:
219        yield _finding(entry, "description-len", "info",
220                       f"description is {length} chars (target {MIN_DESC} to {MAX_DESC})")
221
222
223@check("opensource-github")
224def _opensource_github(entry: Entry, ctx: Context) -> Iterable[Finding]:
225    """openSource: true services must include a github, codeberg or git field."""
226    svc = entry.service
227    if svc.get("openSource") is True and not (
228        svc.get("github") or svc.get("codeberg") or svc.get("git")
229    ):
230        yield _finding(entry, "opensource-github", "error",
231                       "marked openSource but missing a repository link "
232                       "(`github`, `codeberg` or `git`)")
233
234
235@check("androidApp-valid")
236def _android_app_valid(entry: Entry, ctx: Context) -> Iterable[Finding]:
237    """androidApp must be a package name like com.example.app, not a URL."""
238    val = entry.service.get("androidApp")
239    if val and not _PKG_RE.match(val):
240        yield _finding(entry, "androidApp-valid", "warn",
241                       f"androidApp {val} is not a package name (expected com.example.app)")
242
243
244@check("iosApp-reachable")
245def _iosapp_reachable(entry: Entry, ctx: Context) -> Iterable[Finding]:
246    """iOS App Store link must resolve."""
247    url = entry.service.get("iosApp")
248    if url:
249        f = _reachability_finding(entry, "iosApp-reachable", "iosApp", url, "warn", ctx)
250        if f:
251            yield f
252
253
254@check("subreddit-exists")
255def _subreddit_exists(entry: Entry, ctx: Context) -> Iterable[Finding]:
256    """Subreddit page must exist."""
257    name = (entry.service.get("subreddit") or "").strip()
258    if not name:
259        return
260    url = f"https://old.reddit.com/r/{name}"
261    f = _reachability_finding(entry, "subreddit-exists", f"r/{name}", url, "info", ctx)
262    if f:
263        yield f
264
265
266@check("tosdr-valid")
267def _tosdr_valid(entry: Entry, ctx: Context) -> Iterable[Finding]:
268    """tosdrId must still resolve on tosdr.org."""
269    tid = entry.service.get("tosdrId")
270    if not tid:
271        return
272    url = f"https://tosdr.org/en/service/{tid}"
273    ok, status = utils.check_url(url, ctx.session, ctx.timeout)
274    if not ok:
275        detail = f"HTTP {status}" if status else "not reachable"
276        yield _finding(entry, "tosdr-valid", "info",
277                       f"tosdrId {tid} did not validate ({detail})")
278
279
280@check("discord-invite-valid")
281def _discord_invite_valid(entry: Entry, ctx: Context) -> Iterable[Finding]:
282    """Discord invite code must still be valid."""
283    code = (entry.service.get("discordInvite") or "").strip()
284    if not code:
285        return
286    url = f"https://discord.com/api/v10/invites/{code}"
287    ok, status = utils.check_url(url, ctx.session, ctx.timeout)
288    if not ok:
289        detail = f"HTTP {status}" if status else "not reachable"
290        yield _finding(entry, "discord-invite-valid", "info",
291                       f"discord invite {code} invalid or expired ({detail})")
292
293
294@check("github-exists", needs_github=True)
295def _github_exists(entry: Entry, ctx: Context) -> Iterable[Finding]:
296    """GitHub repo must be accessible."""
297    gh = entry.service.get("github")
298    if not gh:
299        return
300    owner, repo = utils.parse_github_field(gh)
301    if not owner:
302        yield _finding(entry, "github-exists", "warn",
303                       f"github field {gh} is not in owner/repo form")
304        return
305    if _get_repo(entry, ctx) is None:
306        yield _finding(entry, "github-exists", "error",
307                       f"repo {owner}/{repo} not accessible (deleted, private, or API error)")
308
309
310@check("github-archived", needs_github=True)
311def _github_archived(entry: Entry, ctx: Context) -> Iterable[Finding]:
312    """GitHub repo must not be archived."""
313    if utils.repo_is_archived(_get_repo(entry, ctx)):
314        yield _finding(entry, "github-archived", "error", "repository is archived on GitHub")
315
316
317@check("github-fork", needs_github=True)
318def _github_fork(entry: Entry, ctx: Context) -> Iterable[Finding]:
319    """GitHub repo should not be a fork."""
320    data = _get_repo(entry, ctx)
321    if utils.repo_is_fork(data):
322        parent = (data.get("parent") or {}).get("full_name")
323        suffix = f" of {parent}" if parent else ""
324        yield _finding(entry, "github-fork", "warn", f"repository is a fork{suffix}")
325
326
327@check("github-activity", needs_github=True)
328def _github_activity(entry: Entry, ctx: Context) -> Iterable[Finding]:
329    """GitHub repo has been pushed to recently (info at 1y, warn at 3y, error at 8y)."""
330    age = utils.repo_pushed_days_ago(_get_repo(entry, ctx))
331    if age is None:
332        return
333    for threshold, sev in ACTIVITY_BANDS:
334        if age >= threshold:
335            yield _finding(entry, "github-activity", sev, f"last push {age} days ago")
336            return
337
338
339@check("github-license", needs_github=True)
340def _github_license(entry: Entry, ctx: Context) -> Iterable[Finding]:
341    """GitHub repo must have a declared license."""
342    data = _get_repo(entry, ctx)
343    if data and not utils.repo_has_license(data):
344        yield _finding(entry, "github-license", "warn", "repository has no declared license")
345
346
347@check("duplicate-url", scope="global")
348def _duplicate_url(entries, ctx: Context) -> Iterable[Finding]:
349    """No two listings share the same homepage URL."""
350    in_scope = {(e.category, e.section, e.name) for e in entries}
351    for url, matches in ctx.url_occurrences.items():
352        if len(matches) <= 1:
353            continue
354        for me in matches:
355            if (me.category, me.section, me.name) not in in_scope:
356                continue
357            others = [e for e in matches if e is not me]
358            shown = ", ".join(f"{e.category} > {e.section}: {e.name}" for e in others[:2])
359            if len(others) > 2:
360                shown += f" (+{len(others) - 2} more)"
361            yield _finding(me, "duplicate-url", "warn",
362                           f"URL {url} also used by {shown}")
363
364
365_interrupted = False
366
367
368def _install_sigint():
369    def handler(signum, frame):
370        global _interrupted
371        if _interrupted:
372            raise KeyboardInterrupt
373        _interrupted = True
374        logging.warning("Interrupt received, finishing in-flight checks (Ctrl-C again to abort)")
375    signal.signal(signal.SIGINT, handler)
376
377
378def build_context(args, data, token):
379    ctx = Context(
380        session=utils.make_session(),
381        token=token,
382        timeout=args.timeout,
383    )
384    for cat, sec, svc in utils.iter_services(data):
385        url = _normalize_url(svc.get("url"))
386        if url:
387            ctx.url_occurrences.setdefault(url, []).append(Entry(cat, sec, svc))
388    return ctx
389
390
391def filter_entries(data, args):
392    for cat, sec, svc in utils.iter_services(data):
393        if args.category and args.category.lower() != cat.lower():
394            continue
395        if args.section and args.section.lower() != sec.lower():
396            continue
397        if args.service and args.service.lower() != svc.get("name", "").lower():
398            continue
399        yield Entry(cat, sec, svc)
400
401
402def _run_one(entry, enabled, ctx):
403    findings = []
404    for name in enabled:
405        spec = CHECKS[name]
406        if spec.scope != "service":
407            continue
408        try:
409            findings.extend(spec.fn(entry, ctx) or [])
410        except Exception as exc:
411            logging.warning("check %s on %s failed: %s", name, entry.name, exc)
412    return findings
413
414
415def _run_global(enabled, entries, ctx):
416    findings = []
417    for name in enabled:
418        spec = CHECKS[name]
419        if spec.scope != "global":
420            continue
421        try:
422            findings.extend(spec.fn(entries, ctx) or [])
423        except Exception as exc:
424            logging.warning("global check %s failed: %s", name, exc)
425    return findings
426
427
428def run_checks(entries, enabled, ctx, workers):
429    findings = []
430    total = len(entries)
431    with ThreadPoolExecutor(max_workers=workers) as ex:
432        futures = {ex.submit(_run_one, e, enabled, ctx): e for e in entries}
433        for i, fut in enumerate(as_completed(futures), start=1):
434            if _interrupted:
435                ex.shutdown(wait=False, cancel_futures=True)
436                break
437            try:
438                findings.extend(fut.result())
439            except Exception as exc:
440                logging.warning("worker error: %s", exc)
441            if i % 25 == 0 or i == total:
442                logging.info("Progress: %d/%d services reviewed", i, total)
443    findings.extend(_run_global(enabled, entries, ctx))
444    return findings
445
446
447def _sev_color(severity, colors):
448    return colors[_SEV_COLOR.get(severity, "yellow")]
449
450
451def _compute_summary(findings, entries, enabled, elapsed):
452    n_services = len(entries)
453    total_checks = n_services * len(enabled)
454    failed = {(f.category, f.section, f.service, f.check) for f in findings}
455    passed_checks = total_checks - len(failed)
456    pass_rate = (passed_checks / total_checks * 100) if total_checks else 100.0
457    services_with_findings = {(f.category, f.section, f.service) for f in findings}
458    return {
459        "services_scanned": n_services,
460        "services_passed": n_services - len(services_with_findings),
461        "total_checks": total_checks,
462        "passed_checks": passed_checks,
463        "pass_rate": round(pass_rate, 1),
464        "findings": len(findings),
465        "errors": sum(1 for f in findings if f.severity == "error"),
466        "warnings": sum(1 for f in findings if f.severity == "warn"),
467        "info": sum(1 for f in findings if f.severity == "info"),
468        "elapsed_seconds": round(elapsed, 2),
469    }
470
471
472_SUMMARY_ROWS = (("errors", "error"), ("warnings", "warn"), ("info", "info"))
473
474
475def _summary(s, colors):
476    parts = ", ".join(
477        colors[_SEV_COLOR[sev]](f"{s[key]} {key}") if s[key] else f"0 {key}"
478        for key, sev in _SUMMARY_ROWS
479    )
480    return "\n".join([
481        colors["bold"]("Summary"),
482        "-------",
483        f"{s['services_scanned']} listings scanned "
484        f"({s['total_checks']} checks, {s['pass_rate']:.1f}% pass rate)",
485        f"{s['findings']} findings ({parts})",
486        f"{s['services_passed']} listings passed all checks",
487        f"Took {s['elapsed_seconds']:.1f}s",
488    ])
489
490
491def _markdown_summary(s):
492    return "\n".join([
493        "### Summary",
494        "",
495        f"- ℹ️ {s['services_scanned']} listings scanned "
496        f"({s['total_checks']} checks, {s['pass_rate']:.1f}% pass rate)",
497        f"- ⚠️ {s['findings']} findings "
498        f"({s['errors']} errors, {s['warnings']} warnings, {s['info']} info)",
499        f"- ✅ {s['services_passed']} listings passed all checks",
500        f"- ⏱️ Triggered at {s['triggered_at']}, took {s['elapsed_seconds']:.1f}s",
501    ])
502
503
504def render_list(findings, colors, summary):
505    lines = []
506    if not findings:
507        lines.append(colors["green"]("✓ All services passed."))
508    grouped: dict = {}
509    for f in findings:
510        grouped.setdefault((f.category, f.section, f.service), []).append(f)
511    for (cat, sec, name), items in grouped.items():
512        lines.append(f"{colors['bold'](name)}  {colors['dim'](f'({cat} > {sec})')}")
513        for f in items:
514            badge = _sev_color(f.severity, colors)(f"[{f.severity.upper():<5}]")
515            lines.append(f"  {badge} {colors['cyan'](f.check.ljust(20))} {f.message}")
516        lines.append("")
517    lines.append(_summary(summary, colors))
518    return "\n".join(lines)
519
520
521def render_json(findings, colors, summary):
522    return json.dumps(
523        {"summary": summary, "findings": [asdict(f) for f in findings]},
524        indent=2,
525    )
526
527
528_MD_URL_RE = re.compile(r"https?://[^\s)\]]+")
529_URL_TRAIL = ".,;:!?"
530
531
532def _md_message(msg, url_limit=42):
533    def shorten(m):
534        url = m.group()
535        trail = ""
536        while url and url[-1] in _URL_TRAIL:
537            trail = url[-1] + trail
538            url = url[:-1]
539        label = url if len(url) <= url_limit else url[:url_limit - 3] + "..."
540        return f"[`{label}`]({url}){trail}"
541    return _MD_URL_RE.sub(shorten, msg)
542
543
544def render_markdown(findings, colors, summary):
545    def cell(s):
546        return str(s).replace("|", "\\|").replace("\n", " ")
547
548    lines = []
549
550    lines += ["# Awesome Privacy Auto Checks", ""]
551
552    need_review = summary["findings"] - summary["errors"]
553    lines += [
554        f"_Ran {summary['total_checks']} checks across {summary['services_scanned']} "
555        f"listings, with a {summary['pass_rate']:.1f}% pass rate._",
556        f"_{summary['errors']} issues require action, plus another {need_review} "
557        f"findings need reviewing._",
558        "",
559    ]
560
561    errors = [f for f in findings if f.severity == "error"]
562    if errors:
563        lines += ["### Critical Issues", ""]
564        for f in errors:
565            lines.append(
566                f"- {_SEV_EMOJI[f.severity]} **{cell(f.service)}** - "
567                f"{_md_message(cell(f.message))}"
568            )
569        lines.append("")
570
571    lines += [
572        "---",
573        "",
574        "### Full Issue List",
575        "",
576        "| Service | Review Required |",
577        "|---|---|",
578    ]
579    grouped: dict = {}
580    for f in findings:
581        grouped.setdefault((f.category, f.section, f.service), []).append(f)
582    for (cat, sec, name), items in grouped.items():
583        review = "<br>".join(
584            f"{_SEV_EMOJI[f.severity]} {_md_message(cell(f.message))}"
585            for f in items
586        )
587        link = f"https://awesome-privacy.xyz/{utils.slugify(cat)}/{utils.slugify(sec)}/{utils.slugify(name)}"
588        lines.append(
589            f"| **{cell(name)}** [↗]({link})<br>"
590            f"<sup>{cell(cat)} > {cell(sec)}</sup> | {review} |"
591        )
592    lines += ["", "---", "", _markdown_summary(summary)]
593    lines += [
594        "",
595        "> [!IMPORTANT]",
596        "> The automated checks can produce false positives, fail to include real issues, and does not "
597        "take the context of the listings into account. Careful human review is needed!",
598        ""
599    ]
600    return "\n".join(lines)
601
602
603def _csv(s):
604    return [x.strip() for x in s.split(",") if x.strip()]
605
606
607def parse_args():
608    p = argparse.ArgumentParser(
609        description="Review all listings in awesome-privacy.yml against our criteria.",
610    )
611    p.add_argument("--save-json", metavar="PATH", help="save a JSON report to this file")
612    p.add_argument("--save-markdown", metavar="PATH",
613                   help="save a markdown report to this file (for GH Actions summaries)")
614    p.add_argument("--category", help="filter to a single category")
615    p.add_argument("--section", help="filter to a single section")
616    p.add_argument("--service", help="filter to a single service")
617    p.add_argument("--only", type=_csv, default=[], help="comma-separated checks to run")
618    p.add_argument("--skip", type=_csv, default=[], help="comma-separated checks to skip")
619    p.add_argument("--severity", choices=["all", "warn", "error"], default="all")
620    p.add_argument("--max-workers", type=int, default=DEFAULT_WORKERS)
621    p.add_argument("--timeout", type=int, default=DEFAULT_TIMEOUT)
622    p.add_argument("--token", help="GitHub token (else $GITHUB_TOKEN)")
623    p.add_argument("--no-color", action="store_true")
624    p.add_argument("--list-checks", action="store_true", help="list available checks and exit")
625    p.add_argument("-v", "--verbose", action="store_true")
626    p.add_argument("-q", "--quiet", action="store_true")
627    return p.parse_args()
628
629
630def resolve_enabled(only, skip):
631    unknown = [n for n in only + skip if n not in CHECKS]
632    if unknown:
633        logging.error("Unknown check(s): %s. Available: %s",
634                      ", ".join(unknown), ", ".join(CHECKS))
635        sys.exit(2)
636    enabled = list(only) if only else list(CHECKS)
637    return [n for n in enabled if n not in skip]
638
639
640def filter_severity(findings, level):
641    if level == "error":
642        return [f for f in findings if f.severity == "error"]
643    if level == "warn":
644        return [f for f in findings if f.severity in ("warn", "error")]
645    return findings
646
647
648def main():
649    _install_sigint()
650    args = parse_args()
651    utils.setup_logging("DEBUG" if args.verbose else "WARNING" if args.quiet else "INFO")
652    colors = utils.make_colors(enabled=False if args.no_color else None)
653
654    if args.list_checks:
655        for name, spec in CHECKS.items():
656            tag = colors["dim"](" (needs GITHUB_TOKEN)") if spec.needs_github else ""
657            print(f"  {colors['cyan'](name.ljust(22))} {spec.doc}{tag}")
658        return
659
660    enabled = resolve_enabled(args.only, args.skip)
661    token = args.token or os.environ.get("GITHUB_TOKEN", "")
662
663    if not token:
664        gh_checks = [n for n in enabled if CHECKS[n].needs_github]
665        if gh_checks:
666            logging.warning(
667                "GITHUB_TOKEN not set, skipping GitHub checks (%s). "
668                "Export GITHUB_TOKEN to enable them.",
669                ", ".join(gh_checks),
670            )
671            enabled = [n for n in enabled if not CHECKS[n].needs_github]
672
673    if not enabled:
674        logging.error("No checks to run after filters.")
675        sys.exit(2)
676
677    try:
678        data = utils.load_yaml()
679    except FileNotFoundError:
680        logging.error("awesome-privacy.yml not found at %s", utils.DATA_PATH)
681        sys.exit(2)
682    except Exception as exc:
683        logging.error("Failed to parse awesome-privacy.yml: %s", exc)
684        sys.exit(2)
685
686    entries = list(filter_entries(data, args))
687    if not entries:
688        logging.error("No services matched filters (category=%s, section=%s, service=%s)",
689                      args.category, args.section, args.service)
690        sys.exit(2)
691
692    ctx = build_context(args, data, token)
693    logging.info("Reviewing %d service(s) with %d check(s): %s",
694                 len(entries), len(enabled), ", ".join(enabled))
695
696    triggered_at = datetime.now(timezone.utc)
697    start = monotonic()
698    findings = run_checks(entries, enabled, ctx, args.max_workers)
699    elapsed = monotonic() - start
700
701    summary = _compute_summary(findings, entries, enabled, elapsed)
702    summary["triggered_at"] = triggered_at.strftime("%Y-%m-%d %H:%M UTC")
703    display = filter_severity(findings, args.severity)
704    display.sort(key=lambda f: (f.category, f.section, f.service, f.check))
705
706    print(render_list(display, colors, summary))
707
708    for path, renderer in (
709        (args.save_json, render_json),
710        (args.save_markdown, render_markdown),
711    ):
712        if not path:
713            continue
714        try:
715            with open(path, "w") as f:
716                f.write(renderer(display, colors, summary) + "\n")
717            logging.info("Wrote %s", path)
718        except OSError as exc:
719            logging.warning("Could not write %s: %s", path, exc)
720
721    fail = summary["pass_rate"] < FAIL_PASS_RATE or summary["errors"] > FAIL_MAX_ERRORS
722    sys.exit(1 if fail else 0)
723
724
725if __name__ == "__main__":
726    main()