lib/review-listings.py

722 lines · 25595 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 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 field."""
226    if entry.service.get("openSource") is True and not entry.service.get("github"):
227        yield _finding(entry, "opensource-github", "warn",
228                       "marked openSource but missing `github` field")
229
230
231@check("androidApp-valid")
232def _android_app_valid(entry: Entry, ctx: Context) -> Iterable[Finding]:
233    """androidApp must be a package name like com.example.app, not a URL."""
234    val = entry.service.get("androidApp")
235    if val and not _PKG_RE.match(val):
236        yield _finding(entry, "androidApp-valid", "warn",
237                       f"androidApp {val} is not a package name (expected com.example.app)")
238
239
240@check("iosApp-reachable")
241def _iosapp_reachable(entry: Entry, ctx: Context) -> Iterable[Finding]:
242    """iOS App Store link must resolve."""
243    url = entry.service.get("iosApp")
244    if url:
245        f = _reachability_finding(entry, "iosApp-reachable", "iosApp", url, "warn", ctx)
246        if f:
247            yield f
248
249
250@check("subreddit-exists")
251def _subreddit_exists(entry: Entry, ctx: Context) -> Iterable[Finding]:
252    """Subreddit page must exist."""
253    name = (entry.service.get("subreddit") or "").strip()
254    if not name:
255        return
256    url = f"https://old.reddit.com/r/{name}"
257    f = _reachability_finding(entry, "subreddit-exists", f"r/{name}", url, "info", ctx)
258    if f:
259        yield f
260
261
262@check("tosdr-valid")
263def _tosdr_valid(entry: Entry, ctx: Context) -> Iterable[Finding]:
264    """tosdrId must still resolve on tosdr.org."""
265    tid = entry.service.get("tosdrId")
266    if not tid:
267        return
268    url = f"https://tosdr.org/en/service/{tid}"
269    ok, status = utils.check_url(url, ctx.session, ctx.timeout)
270    if not ok:
271        detail = f"HTTP {status}" if status else "not reachable"
272        yield _finding(entry, "tosdr-valid", "info",
273                       f"tosdrId {tid} did not validate ({detail})")
274
275
276@check("discord-invite-valid")
277def _discord_invite_valid(entry: Entry, ctx: Context) -> Iterable[Finding]:
278    """Discord invite code must still be valid."""
279    code = (entry.service.get("discordInvite") or "").strip()
280    if not code:
281        return
282    url = f"https://discord.com/api/v10/invites/{code}"
283    ok, status = utils.check_url(url, ctx.session, ctx.timeout)
284    if not ok:
285        detail = f"HTTP {status}" if status else "not reachable"
286        yield _finding(entry, "discord-invite-valid", "info",
287                       f"discord invite {code} invalid or expired ({detail})")
288
289
290@check("github-exists", needs_github=True)
291def _github_exists(entry: Entry, ctx: Context) -> Iterable[Finding]:
292    """GitHub repo must be accessible."""
293    gh = entry.service.get("github")
294    if not gh:
295        return
296    owner, repo = utils.parse_github_field(gh)
297    if not owner:
298        yield _finding(entry, "github-exists", "warn",
299                       f"github field {gh} is not in owner/repo form")
300        return
301    if _get_repo(entry, ctx) is None:
302        yield _finding(entry, "github-exists", "error",
303                       f"repo {owner}/{repo} not accessible (deleted, private, or API error)")
304
305
306@check("github-archived", needs_github=True)
307def _github_archived(entry: Entry, ctx: Context) -> Iterable[Finding]:
308    """GitHub repo must not be archived."""
309    if utils.repo_is_archived(_get_repo(entry, ctx)):
310        yield _finding(entry, "github-archived", "error", "repository is archived on GitHub")
311
312
313@check("github-fork", needs_github=True)
314def _github_fork(entry: Entry, ctx: Context) -> Iterable[Finding]:
315    """GitHub repo should not be a fork."""
316    data = _get_repo(entry, ctx)
317    if utils.repo_is_fork(data):
318        parent = (data.get("parent") or {}).get("full_name")
319        suffix = f" of {parent}" if parent else ""
320        yield _finding(entry, "github-fork", "warn", f"repository is a fork{suffix}")
321
322
323@check("github-activity", needs_github=True)
324def _github_activity(entry: Entry, ctx: Context) -> Iterable[Finding]:
325    """GitHub repo has been pushed to recently (info at 1y, warn at 3y, error at 8y)."""
326    age = utils.repo_pushed_days_ago(_get_repo(entry, ctx))
327    if age is None:
328        return
329    for threshold, sev in ACTIVITY_BANDS:
330        if age >= threshold:
331            yield _finding(entry, "github-activity", sev, f"last push {age} days ago")
332            return
333
334
335@check("github-license", needs_github=True)
336def _github_license(entry: Entry, ctx: Context) -> Iterable[Finding]:
337    """GitHub repo must have a declared license."""
338    data = _get_repo(entry, ctx)
339    if data and not utils.repo_has_license(data):
340        yield _finding(entry, "github-license", "warn", "repository has no declared license")
341
342
343@check("duplicate-url", scope="global")
344def _duplicate_url(entries, ctx: Context) -> Iterable[Finding]:
345    """No two listings share the same homepage URL."""
346    in_scope = {(e.category, e.section, e.name) for e in entries}
347    for url, matches in ctx.url_occurrences.items():
348        if len(matches) <= 1:
349            continue
350        for me in matches:
351            if (me.category, me.section, me.name) not in in_scope:
352                continue
353            others = [e for e in matches if e is not me]
354            shown = ", ".join(f"{e.category} > {e.section}: {e.name}" for e in others[:2])
355            if len(others) > 2:
356                shown += f" (+{len(others) - 2} more)"
357            yield _finding(me, "duplicate-url", "warn",
358                           f"URL {url} also used by {shown}")
359
360
361_interrupted = False
362
363
364def _install_sigint():
365    def handler(signum, frame):
366        global _interrupted
367        if _interrupted:
368            raise KeyboardInterrupt
369        _interrupted = True
370        logging.warning("Interrupt received, finishing in-flight checks (Ctrl-C again to abort)")
371    signal.signal(signal.SIGINT, handler)
372
373
374def build_context(args, data, token):
375    ctx = Context(
376        session=utils.make_session(),
377        token=token,
378        timeout=args.timeout,
379    )
380    for cat, sec, svc in utils.iter_services(data):
381        url = _normalize_url(svc.get("url"))
382        if url:
383            ctx.url_occurrences.setdefault(url, []).append(Entry(cat, sec, svc))
384    return ctx
385
386
387def filter_entries(data, args):
388    for cat, sec, svc in utils.iter_services(data):
389        if args.category and args.category.lower() != cat.lower():
390            continue
391        if args.section and args.section.lower() != sec.lower():
392            continue
393        if args.service and args.service.lower() != svc.get("name", "").lower():
394            continue
395        yield Entry(cat, sec, svc)
396
397
398def _run_one(entry, enabled, ctx):
399    findings = []
400    for name in enabled:
401        spec = CHECKS[name]
402        if spec.scope != "service":
403            continue
404        try:
405            findings.extend(spec.fn(entry, ctx) or [])
406        except Exception as exc:
407            logging.warning("check %s on %s failed: %s", name, entry.name, exc)
408    return findings
409
410
411def _run_global(enabled, entries, ctx):
412    findings = []
413    for name in enabled:
414        spec = CHECKS[name]
415        if spec.scope != "global":
416            continue
417        try:
418            findings.extend(spec.fn(entries, ctx) or [])
419        except Exception as exc:
420            logging.warning("global check %s failed: %s", name, exc)
421    return findings
422
423
424def run_checks(entries, enabled, ctx, workers):
425    findings = []
426    total = len(entries)
427    with ThreadPoolExecutor(max_workers=workers) as ex:
428        futures = {ex.submit(_run_one, e, enabled, ctx): e for e in entries}
429        for i, fut in enumerate(as_completed(futures), start=1):
430            if _interrupted:
431                ex.shutdown(wait=False, cancel_futures=True)
432                break
433            try:
434                findings.extend(fut.result())
435            except Exception as exc:
436                logging.warning("worker error: %s", exc)
437            if i % 25 == 0 or i == total:
438                logging.info("Progress: %d/%d services reviewed", i, total)
439    findings.extend(_run_global(enabled, entries, ctx))
440    return findings
441
442
443def _sev_color(severity, colors):
444    return colors[_SEV_COLOR.get(severity, "yellow")]
445
446
447def _compute_summary(findings, entries, enabled, elapsed):
448    n_services = len(entries)
449    total_checks = n_services * len(enabled)
450    failed = {(f.category, f.section, f.service, f.check) for f in findings}
451    passed_checks = total_checks - len(failed)
452    pass_rate = (passed_checks / total_checks * 100) if total_checks else 100.0
453    services_with_findings = {(f.category, f.section, f.service) for f in findings}
454    return {
455        "services_scanned": n_services,
456        "services_passed": n_services - len(services_with_findings),
457        "total_checks": total_checks,
458        "passed_checks": passed_checks,
459        "pass_rate": round(pass_rate, 1),
460        "findings": len(findings),
461        "errors": sum(1 for f in findings if f.severity == "error"),
462        "warnings": sum(1 for f in findings if f.severity == "warn"),
463        "info": sum(1 for f in findings if f.severity == "info"),
464        "elapsed_seconds": round(elapsed, 2),
465    }
466
467
468_SUMMARY_ROWS = (("errors", "error"), ("warnings", "warn"), ("info", "info"))
469
470
471def _summary(s, colors):
472    parts = ", ".join(
473        colors[_SEV_COLOR[sev]](f"{s[key]} {key}") if s[key] else f"0 {key}"
474        for key, sev in _SUMMARY_ROWS
475    )
476    return "\n".join([
477        colors["bold"]("Summary"),
478        "-------",
479        f"{s['services_scanned']} listings scanned "
480        f"({s['total_checks']} checks, {s['pass_rate']:.1f}% pass rate)",
481        f"{s['findings']} findings ({parts})",
482        f"{s['services_passed']} listings passed all checks",
483        f"Took {s['elapsed_seconds']:.1f}s",
484    ])
485
486
487def _markdown_summary(s):
488    return "\n".join([
489        "### Summary",
490        "",
491        f"- ℹ️ {s['services_scanned']} listings scanned "
492        f"({s['total_checks']} checks, {s['pass_rate']:.1f}% pass rate)",
493        f"- ⚠️ {s['findings']} findings "
494        f"({s['errors']} errors, {s['warnings']} warnings, {s['info']} info)",
495        f"- ✅ {s['services_passed']} listings passed all checks",
496        f"- ⏱️ Triggered at {s['triggered_at']}, took {s['elapsed_seconds']:.1f}s",
497    ])
498
499
500def render_list(findings, colors, summary):
501    lines = []
502    if not findings:
503        lines.append(colors["green"]("✓ All services passed."))
504    grouped: dict = {}
505    for f in findings:
506        grouped.setdefault((f.category, f.section, f.service), []).append(f)
507    for (cat, sec, name), items in grouped.items():
508        lines.append(f"{colors['bold'](name)}  {colors['dim'](f'({cat} > {sec})')}")
509        for f in items:
510            badge = _sev_color(f.severity, colors)(f"[{f.severity.upper():<5}]")
511            lines.append(f"  {badge} {colors['cyan'](f.check.ljust(20))} {f.message}")
512        lines.append("")
513    lines.append(_summary(summary, colors))
514    return "\n".join(lines)
515
516
517def render_json(findings, colors, summary):
518    return json.dumps(
519        {"summary": summary, "findings": [asdict(f) for f in findings]},
520        indent=2,
521    )
522
523
524_MD_URL_RE = re.compile(r"https?://[^\s)\]]+")
525_URL_TRAIL = ".,;:!?"
526
527
528def _md_message(msg, url_limit=42):
529    def shorten(m):
530        url = m.group()
531        trail = ""
532        while url and url[-1] in _URL_TRAIL:
533            trail = url[-1] + trail
534            url = url[:-1]
535        label = url if len(url) <= url_limit else url[:url_limit - 3] + "..."
536        return f"[`{label}`]({url}){trail}"
537    return _MD_URL_RE.sub(shorten, msg)
538
539
540def render_markdown(findings, colors, summary):
541    def cell(s):
542        return str(s).replace("|", "\\|").replace("\n", " ")
543
544    lines = []
545
546    lines += ["# Awesome Privacy Auto Checks", ""]
547
548    need_review = summary["findings"] - summary["errors"]
549    lines += [
550        f"_Ran {summary['total_checks']} checks across {summary['services_scanned']} "
551        f"listings, with a {summary['pass_rate']:.1f}% pass rate._",
552        f"_{summary['errors']} issues require action, plus another {need_review} "
553        f"findings need reviewing._",
554        "",
555    ]
556
557    errors = [f for f in findings if f.severity == "error"]
558    if errors:
559        lines += ["### Critical Issues", ""]
560        for f in errors:
561            lines.append(
562                f"- {_SEV_EMOJI[f.severity]} **{cell(f.service)}** - "
563                f"{_md_message(cell(f.message))}"
564            )
565        lines.append("")
566
567    lines += [
568        "---",
569        "",
570        "### Full Issue List",
571        "",
572        "| Service | Review Required |",
573        "|---|---|",
574    ]
575    grouped: dict = {}
576    for f in findings:
577        grouped.setdefault((f.category, f.section, f.service), []).append(f)
578    for (cat, sec, name), items in grouped.items():
579        review = "<br>".join(
580            f"{_SEV_EMOJI[f.severity]} {_md_message(cell(f.message))}"
581            for f in items
582        )
583        link = f"https://awesome-privacy.xyz/{utils.slugify(cat)}/{utils.slugify(sec)}/{utils.slugify(name)}"
584        lines.append(
585            f"| **{cell(name)}** [↗]({link})<br>"
586            f"<sup>{cell(cat)} > {cell(sec)}</sup> | {review} |"
587        )
588    lines += ["", "---", "", _markdown_summary(summary)]
589    lines += [
590        "",
591        "> [!IMPORTANT]",
592        "> The automated checks can produce false positives, fail to include real issues, and does not "
593        "take the context of the listings into account. Careful human review is needed!",
594        ""
595    ]
596    return "\n".join(lines)
597
598
599def _csv(s):
600    return [x.strip() for x in s.split(",") if x.strip()]
601
602
603def parse_args():
604    p = argparse.ArgumentParser(
605        description="Review all listings in awesome-privacy.yml against our criteria.",
606    )
607    p.add_argument("--save-json", metavar="PATH", help="save a JSON report to this file")
608    p.add_argument("--save-markdown", metavar="PATH",
609                   help="save a markdown report to this file (for GH Actions summaries)")
610    p.add_argument("--category", help="filter to a single category")
611    p.add_argument("--section", help="filter to a single section")
612    p.add_argument("--service", help="filter to a single service")
613    p.add_argument("--only", type=_csv, default=[], help="comma-separated checks to run")
614    p.add_argument("--skip", type=_csv, default=[], help="comma-separated checks to skip")
615    p.add_argument("--severity", choices=["all", "warn", "error"], default="all")
616    p.add_argument("--max-workers", type=int, default=DEFAULT_WORKERS)
617    p.add_argument("--timeout", type=int, default=DEFAULT_TIMEOUT)
618    p.add_argument("--token", help="GitHub token (else $GITHUB_TOKEN)")
619    p.add_argument("--no-color", action="store_true")
620    p.add_argument("--list-checks", action="store_true", help="list available checks and exit")
621    p.add_argument("-v", "--verbose", action="store_true")
622    p.add_argument("-q", "--quiet", action="store_true")
623    return p.parse_args()
624
625
626def resolve_enabled(only, skip):
627    unknown = [n for n in only + skip if n not in CHECKS]
628    if unknown:
629        logging.error("Unknown check(s): %s. Available: %s",
630                      ", ".join(unknown), ", ".join(CHECKS))
631        sys.exit(2)
632    enabled = list(only) if only else list(CHECKS)
633    return [n for n in enabled if n not in skip]
634
635
636def filter_severity(findings, level):
637    if level == "error":
638        return [f for f in findings if f.severity == "error"]
639    if level == "warn":
640        return [f for f in findings if f.severity in ("warn", "error")]
641    return findings
642
643
644def main():
645    _install_sigint()
646    args = parse_args()
647    utils.setup_logging("DEBUG" if args.verbose else "WARNING" if args.quiet else "INFO")
648    colors = utils.make_colors(enabled=False if args.no_color else None)
649
650    if args.list_checks:
651        for name, spec in CHECKS.items():
652            tag = colors["dim"](" (needs GITHUB_TOKEN)") if spec.needs_github else ""
653            print(f"  {colors['cyan'](name.ljust(22))} {spec.doc}{tag}")
654        return
655
656    enabled = resolve_enabled(args.only, args.skip)
657    token = args.token or os.environ.get("GITHUB_TOKEN", "")
658
659    if not token:
660        gh_checks = [n for n in enabled if CHECKS[n].needs_github]
661        if gh_checks:
662            logging.warning(
663                "GITHUB_TOKEN not set, skipping GitHub checks (%s). "
664                "Export GITHUB_TOKEN to enable them.",
665                ", ".join(gh_checks),
666            )
667            enabled = [n for n in enabled if not CHECKS[n].needs_github]
668
669    if not enabled:
670        logging.error("No checks to run after filters.")
671        sys.exit(2)
672
673    try:
674        data = utils.load_yaml()
675    except FileNotFoundError:
676        logging.error("awesome-privacy.yml not found at %s", utils.DATA_PATH)
677        sys.exit(2)
678    except Exception as exc:
679        logging.error("Failed to parse awesome-privacy.yml: %s", exc)
680        sys.exit(2)
681
682    entries = list(filter_entries(data, args))
683    if not entries:
684        logging.error("No services matched filters (category=%s, section=%s, service=%s)",
685                      args.category, args.section, args.service)
686        sys.exit(2)
687
688    ctx = build_context(args, data, token)
689    logging.info("Reviewing %d service(s) with %d check(s): %s",
690                 len(entries), len(enabled), ", ".join(enabled))
691
692    triggered_at = datetime.now(timezone.utc)
693    start = monotonic()
694    findings = run_checks(entries, enabled, ctx, args.max_workers)
695    elapsed = monotonic() - start
696
697    summary = _compute_summary(findings, entries, enabled, elapsed)
698    summary["triggered_at"] = triggered_at.strftime("%Y-%m-%d %H:%M UTC")
699    display = filter_severity(findings, args.severity)
700    display.sort(key=lambda f: (f.category, f.section, f.service, f.check))
701
702    print(render_list(display, colors, summary))
703
704    for path, renderer in (
705        (args.save_json, render_json),
706        (args.save_markdown, render_markdown),
707    ):
708        if not path:
709            continue
710        try:
711            with open(path, "w") as f:
712                f.write(renderer(display, colors, summary) + "\n")
713            logging.info("Wrote %s", path)
714        except OSError as exc:
715            logging.warning("Could not write %s: %s", path, exc)
716
717    fail = summary["pass_rate"] < FAIL_PASS_RATE or summary["errors"] > FAIL_MAX_ERRORS
718    sys.exit(1 if fail else 0)
719
720
721if __name__ == "__main__":
722    main()