Commit c3971bdb93

c3971bdb9305aaa887385bfb9397796672d925b3

parent: e16a11592d

Unsigned

Alicia Sykes <alicia@omg.lol> · 2026-04-19 19:38 UTC

Quick script to find non-updated listings

Layout: unified · split

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