lib/review-listings.py

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