codefactory-cli 0.20.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. codefactory/__init__.py +3 -0
  2. codefactory/__main__.py +5 -0
  3. codefactory/accept.py +68 -0
  4. codefactory/analyzers/__init__.py +55 -0
  5. codefactory/analyzers/generic.py +392 -0
  6. codefactory/analyzers/parallel.py +113 -0
  7. codefactory/analyzers/python.py +279 -0
  8. codefactory/analyzers/python_parse.py +402 -0
  9. codefactory/analyzers/treewalk.py +299 -0
  10. codefactory/analyzers/ts_helper.js +483 -0
  11. codefactory/analyzers/typescript.py +118 -0
  12. codefactory/apple.py +80 -0
  13. codefactory/audit.py +227 -0
  14. codefactory/baseline.py +58 -0
  15. codefactory/brief.py +330 -0
  16. codefactory/cache.py +93 -0
  17. codefactory/checks.py +608 -0
  18. codefactory/cli.py +782 -0
  19. codefactory/config.py +157 -0
  20. codefactory/coverage.py +104 -0
  21. codefactory/deps.py +182 -0
  22. codefactory/diff.py +197 -0
  23. codefactory/efficiency.py +250 -0
  24. codefactory/flags.py +263 -0
  25. codefactory/graph.py +95 -0
  26. codefactory/hotspots.py +344 -0
  27. codefactory/infra.py +242 -0
  28. codefactory/intent.py +106 -0
  29. codefactory/layers.py +143 -0
  30. codefactory/org.py +131 -0
  31. codefactory/owners.py +72 -0
  32. codefactory/patch.py +81 -0
  33. codefactory/paths.py +93 -0
  34. codefactory/plan.py +476 -0
  35. codefactory/privacy.py +221 -0
  36. codefactory/profile.py +667 -0
  37. codefactory/rerank.py +161 -0
  38. codefactory/review.py +1504 -0
  39. codefactory/rules.py +50 -0
  40. codefactory/sarif.py +661 -0
  41. codefactory/sbom.py +78 -0
  42. codefactory/security.py +537 -0
  43. codefactory/similar.py +199 -0
  44. codefactory/skill.py +144 -0
  45. codefactory/skill_template/SKILL.md +68 -0
  46. codefactory/skill_template/__init__.py +0 -0
  47. codefactory/sqlgraph.py +109 -0
  48. codefactory/suppress.py +92 -0
  49. codefactory/taint.py +439 -0
  50. codefactory/trace.py +72 -0
  51. codefactory/viewer/__init__.py +19 -0
  52. codefactory/viewer/dashboard.html +43 -0
  53. codefactory/viewer/factory.css +61 -0
  54. codefactory/viewer/factory.js +665 -0
  55. codefactory/viewer/template.html +47 -0
  56. codefactory_cli-0.20.1.dist-info/METADATA +250 -0
  57. codefactory_cli-0.20.1.dist-info/RECORD +61 -0
  58. codefactory_cli-0.20.1.dist-info/WHEEL +5 -0
  59. codefactory_cli-0.20.1.dist-info/entry_points.txt +2 -0
  60. codefactory_cli-0.20.1.dist-info/licenses/LICENSE +21 -0
  61. codefactory_cli-0.20.1.dist-info/top_level.txt +1 -0
codefactory/review.py ADDED
@@ -0,0 +1,1504 @@
1
+ """`codefactory review`: a technical review of a repository, written without an AI, in the structure of a principal
2
+ engineer's review (executive summary, system map, findings by severity, what works, testing and release gaps, open
3
+ questions, review limits). Every finding cites file:line evidence. `--for-ai` adds an evidence pack: the findings plus
4
+ the riskiest code, so an AI can make the judgement calls by reading a few thousand tokens instead of the whole repo.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import re
10
+ import subprocess
11
+ from collections import Counter, defaultdict
12
+ from concurrent.futures import ThreadPoolExecutor
13
+ from dataclasses import dataclass, field
14
+ from fnmatch import fnmatch
15
+ from pathlib import Path
16
+
17
+ from . import hotspots, rerank
18
+ from .apple import scan as apple_scan
19
+ from .audit import current_secrets
20
+ from .audit import scan as audit_scan
21
+ from .brief import View
22
+ from .checks import scan_repo, scan_sources, source_files, test_reach
23
+ from .config import load_config
24
+ from .coverage import measured
25
+ from .infra import scan as infra_scan
26
+ from .paths import is_script, is_test, walk
27
+ from .plan import make_plan
28
+ from .privacy import scan as privacy_scan
29
+ from .profile import detect as detect_profile
30
+ from .profile import markdown as profile_markdown
31
+ from .security import SINK_KINDS, function_at, surface, writes
32
+
33
+ SEV = ["Critical", "High", "Medium", "Low"]
34
+ POINTS = {"Critical": 30, "High": 10, "Medium": 3, "Low": 1}
35
+ CAPS = {"Medium": 24, "Low": 6} # many small issues shouldn't outweigh one serious one
36
+ TS_EXT = (".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".mts", ".cts")
37
+ OTHER_CODE = {
38
+ ".swift": "Swift",
39
+ ".kt": "Kotlin",
40
+ ".java": "Java",
41
+ ".go": "Go",
42
+ ".rs": "Rust",
43
+ ".rb": "Ruby",
44
+ ".cs": "C#",
45
+ ".m": "Objective-C",
46
+ ".mm": "Objective-C++",
47
+ ".cpp": "C++",
48
+ ".c": "C",
49
+ ".php": "PHP",
50
+ ".scala": "Scala",
51
+ ".dart": "Dart",
52
+ ".sql": "SQL",
53
+ ".tf": "Terraform",
54
+ ".sh": "shell",
55
+ }
56
+
57
+
58
+ @dataclass
59
+ class Finding:
60
+ title: str
61
+ severity: str
62
+ area: str
63
+ evidence: list[str]
64
+ impact: str
65
+ fix: str
66
+ effort: str
67
+ more: int = 0
68
+ data: dict = field(default_factory=dict)
69
+
70
+
71
+ def _ev(items, n: int = 6) -> tuple[list[str], int]:
72
+ shown = [f"`{e.at()}` {e.text}" if hasattr(e, "at") else e for e in items[:n]]
73
+ return shown, max(0, len(items) - n)
74
+
75
+
76
+ # endpoints that have to work without being signed in: signing in, signing up, resetting a password, confirming an email
77
+ SIGN_IN = re.compile(r"log_?in|log_?out|sign_?in|sign_?up|signup|regist(?:er|ration)|password|reset|forgot|confirm|"
78
+ r"verify|webauthn|totp|two_?factor|2fa|oauth|callback|magic_?link|unsubscribe|check_token|login_link",
79
+ re.I) # fmt: skip
80
+ CLIENT_APPS = {"React", "React Native", "Expo", "Vue", "Svelte"} # a UI process serves one user
81
+
82
+
83
+ def _n(n: int, word: str) -> str:
84
+ return f"{n} {word}" + ("" if n == 1 else "s")
85
+
86
+
87
+ def _effort(count: int, files: int) -> str:
88
+ return "S" if count <= 3 and files <= 2 else "M" if count <= 15 and files <= 8 else "L"
89
+
90
+
91
+ class Review:
92
+ def __init__(self, g: dict, root: Path, online: bool = False):
93
+ self.g, self.root, self.v = g, root, View(g)
94
+ self.repo = scan_repo(root)
95
+ pool = ThreadPoolExecutor(max_workers=1) # git log runs while the checks below read files
96
+ history = pool.submit(hotspots.analyze, root, g)
97
+ sources = source_files(root, g) # parsed or not: line checks need no parser
98
+ self.scan = scan_sources(root, sources)
99
+ extra, self.history_note = audit_scan(root, current_secrets(self.scan["secret"]))
100
+ self.scan.update(extra) # CI, Docker, mobile config and git history: same shape, same silencing
101
+ self.scan.update(privacy_scan(root, sources)) # personal data, Apple privacy rules
102
+ self.scan.update(apple_scan(root, sources)) # Swift crashes, cycles, main-thread I/O
103
+ self.scan.update(infra_scan(root, set(load_config(root).ignore))) # shell, Make, YAML, HTML, Pkl, patches
104
+ self.online, self.vulns, self.deps_note = online, [], ""
105
+ self._apply_silence(load_config(root).silence)
106
+ self.surface = surface(root, g, self.v)
107
+ self.profile = detect_profile(root, g, self.surface, sources=sources) # what kind of project: findings are ranked for it
108
+ self.history = history.result() # where change happens: findings there are worth fixing first
109
+ pool.shutdown()
110
+ self.hot = self.history.by_path()
111
+ self.rank_changes: list[rerank.Change] = []
112
+ self.writers = writes(self.v)
113
+ static = test_reach(self.v)
114
+ self.coverage = measured(root, g["functions"])
115
+ if self.coverage: # what ran, where the report knows; the static estimate for files it doesn't cover
116
+ seen = self.coverage.seen
117
+ self.reached = self.coverage.covered | {fid for fid in static if self.v.fn.get(fid, {}).get("file") not in seen}
118
+ else:
119
+ self.reached = static
120
+ self.tasks = make_plan(g, {path: fh.commits for path, fh in self.history.history.files.items()})
121
+ self.findings: list[Finding] = []
122
+ self.by_kind = defaultdict(list)
123
+ for f in g["flags"]:
124
+ self.by_kind[f["kind"]].append(f)
125
+ self.code_fns = [f for f in g["functions"] if f["kind"] != "module" and not is_test(f["file"])]
126
+ self._strengths: list[str] | None = None
127
+
128
+ def add(self, *a, **k) -> None:
129
+ self.findings.append(Finding(*a, **k))
130
+
131
+ def changes(self, path: str) -> int:
132
+ """Commits that changed this file in the last 12 months."""
133
+ fh = self.history.history.files.get(path)
134
+ return fh.commits if fh else 0
135
+
136
+ def _changed(self, path: str) -> str:
137
+ n = self.changes(path)
138
+ return f" · changed {n}× in 12 months" if n >= 3 else ""
139
+
140
+ def where(self, flag: dict) -> str:
141
+ fn = self.v.fn.get(flag["target"])
142
+ return (
143
+ f"`{fn['file']}:{flag.get('line') or fn['line']}` {fn['qualname'] if fn['kind'] != 'module' else ''}".rstrip()
144
+ if fn
145
+ else f"`{flag['target']}`"
146
+ )
147
+
148
+ # ---- findings ----------------------------------------------------------------------------------------------
149
+ def security(self) -> None:
150
+ s = self.scan
151
+ if s["secret"].hits:
152
+ ev, more = _ev(s["secret"].hits)
153
+ self.add(
154
+ "Credentials committed in source",
155
+ "Critical",
156
+ "Security",
157
+ ev,
158
+ "Anyone with read access to the repository (or its history, forks and CI logs) can use them.",
159
+ "Rotate each credential now, remove it from the code (and history), and load it from the environment "
160
+ "or a secret store at runtime.",
161
+ "S",
162
+ more,
163
+ )
164
+ tracked = self._tracked(self.repo["env_files"])
165
+ if tracked:
166
+ self.add(
167
+ "Environment files committed",
168
+ "High",
169
+ "Security",
170
+ [f"`{f}`" for f in tracked],
171
+ "Environment files usually hold secrets and per-machine settings.",
172
+ "Remove them from git, add `.env*` to .gitignore (keep a `.env.example`), and rotate anything in them.",
173
+ "S",
174
+ )
175
+ if s["sql_built"].hits:
176
+ ev = [
177
+ f"`{e.at()}` {e.text}"
178
+ + (
179
+ f" (interpolates: {', '.join(s['sql_built'].data.get(e.at(), []))})"
180
+ if s["sql_built"].data.get(e.at())
181
+ else ""
182
+ )
183
+ + self._reached_by(e)
184
+ for e in s["sql_built"].hits[:6]
185
+ ]
186
+ self.add(
187
+ "SQL assembled from strings",
188
+ self._by_reach("Medium", s["sql_built"].hits),
189
+ "Security",
190
+ ev,
191
+ "If any interpolated value can come from a user, a file or the network, this is SQL injection. "
192
+ "Constants and whitelisted identifiers are safe, but nothing enforces that they stay so.",
193
+ "Pass values as bound parameters (`?` / `%s`); for table or column names, check them against a fixed "
194
+ "list right where the SQL is built.",
195
+ _effort(len(s["sql_built"].hits), len({e.file for e in s["sql_built"].hits})),
196
+ max(0, len(s["sql_built"].hits) - 6),
197
+ )
198
+ for key, title, sev, impact, fix in [
199
+ (
200
+ "eval",
201
+ "Dynamic code execution (eval / exec / pickle / unsafe YAML)",
202
+ "High",
203
+ "Running text as code: if that text can be influenced from outside, it's remote code execution.",
204
+ "Replace with explicit parsing (JSON, a lookup table); never unpickle or yaml.load untrusted data "
205
+ "(use SafeLoader).",
206
+ ),
207
+ (
208
+ "shell",
209
+ "Shell commands built at runtime",
210
+ "High",
211
+ "A shell interprets its input: values with spaces, quotes or `;` change the command.",
212
+ "Pass arguments as a list without a shell (subprocess.run([...]), execFile/spawn), never a formatted string.",
213
+ ),
214
+ (
215
+ "tls_off",
216
+ "TLS certificate checks turned off",
217
+ "High",
218
+ "Connections can be intercepted and altered without any error.",
219
+ "Remove the override; if a private CA is needed, configure it as a trusted root instead.",
220
+ ),
221
+ (
222
+ "raw_html",
223
+ "Raw HTML injected into pages",
224
+ "Medium",
225
+ "HTML from data that isn't fully trusted is cross-site scripting.",
226
+ "Render as text, or sanitize with a maintained library (e.g. DOMPurify) right before inserting.",
227
+ ),
228
+ (
229
+ "plain_http",
230
+ "Plain-HTTP URLs in code",
231
+ "Low",
232
+ "Traffic to these hosts can be read and changed in transit.",
233
+ "Use https:// where the host supports it.",
234
+ ),
235
+ ]:
236
+ hits = s[key].hits
237
+ if hits:
238
+ ev, more = _ev(hits)
239
+ if key in SINK_KINDS:
240
+ ev = [line + self._reached_by(e) for line, e in zip(ev, hits, strict=False)]
241
+ sev = self._by_reach(sev, hits)
242
+ self.add(title, sev, "Security", ev, impact, fix, _effort(len(hits), len({e.file for e in hits})), more)
243
+ self.endpoints()
244
+ self.flows()
245
+ self.config_findings()
246
+ self.dependencies()
247
+
248
+ def flows(self) -> None:
249
+ """Proven data flows (Python): a request value traced, variable by variable, into a dangerous call."""
250
+ flows = self.by_kind["taint"]
251
+ if not flows:
252
+ return
253
+ worst = any(f.get("detail") in ("sql", "shell", "code") for f in flows)
254
+ self.add(
255
+ f"Request data reaches dangerous calls ({len(flows)} proven flows)",
256
+ "Critical" if worst else "High",
257
+ "Security",
258
+ [f"{self.where(f)}: {f['message'].split(': ', 1)[-1]}" for f in flows[:8]],
259
+ "Traced through the code, not guessed from a pattern: whoever sends the request controls what reaches the "
260
+ "call (injection into SQL or a shell, code execution, files outside the intended folder, requests to internal "
261
+ "hosts, redirects to any site).",
262
+ "Convert or validate the value where it enters (int(), an allow-list), or use the safe form of the call: bound "
263
+ "SQL parameters, a command as an argument list without a shell, a fixed base URL or folder.",
264
+ _effort(len(flows), len({self._file(f) for f in flows})),
265
+ max(0, len(flows) - 8),
266
+ )
267
+
268
+ def config_findings(self) -> None:
269
+ """Configuration, crypto, CI, containers, mobile settings and git history (the rest of a security audit)."""
270
+ s = self.scan
271
+ pr = s["gha_pr_target"]
272
+ dangerous = [e for e in pr.hits if pr.data.get(e.file) == "checkout"]
273
+ if dangerous:
274
+ self.add(
275
+ "Workflow runs a fork's code with this repository's secrets",
276
+ "Critical",
277
+ "Security",
278
+ [f"`{e.at()}` {e.text}" for e in dangerous],
279
+ "`pull_request_target` runs with write access and secrets; checking out the pull request's code lets "
280
+ "anyone who opens a PR run it with both.",
281
+ "Use `pull_request` for anything that builds or tests PR code; keep `pull_request_target` for "
282
+ "labelling and commenting, without checking the PR out.",
283
+ "S",
284
+ )
285
+ for key, title, sev, impact, fix in CONFIG_CHECKS:
286
+ hits = s[key].hits
287
+ if hits:
288
+ ev, more = _ev(hits)
289
+ self.add(title, sev, "Security", ev, impact, fix, _effort(len(hits), len({e.file for e in hits})), more)
290
+ for key, title, sev, area, impact, fix in APPLE_CHECKS + INFRA_CHECKS:
291
+ hits = s[key].hits
292
+ if hits:
293
+ ev, more = _ev(hits)
294
+ self.add(title, sev, area, ev, impact, fix, _effort(len(hits), len({e.file for e in hits})), more)
295
+
296
+ def dependencies(self) -> None:
297
+ if not self.online:
298
+ return
299
+ from .deps import packages, vulnerabilities
300
+
301
+ pkgs = packages(self.root)
302
+ if not pkgs:
303
+ self.deps_note = "no lockfile found, so dependencies weren't checked for known vulnerabilities"
304
+ return
305
+ try:
306
+ self.vulns = vulnerabilities(pkgs)
307
+ except (OSError, ValueError) as e:
308
+ self.deps_note = f"OSV.dev couldn't be reached ({type(e).__name__}): dependencies not checked"
309
+ return
310
+ self.deps_note = f"{len(pkgs)} pinned dependencies checked against OSV.dev"
311
+ if not self.vulns:
312
+ return
313
+ rank = ["CRITICAL", "HIGH", "MODERATE", "MEDIUM", "LOW", ""]
314
+ by_pkg: dict = {}
315
+ for vuln in self.vulns:
316
+ by_pkg.setdefault(vuln.package, []).append(vuln)
317
+ shipped = {p: vs for p, vs in by_pkg.items() if not p.dev}
318
+ worst = min((vuln.severity for vs in (shipped or by_pkg).values() for vuln in vs), key=rank.index)
319
+ sev = {"CRITICAL": "Critical", "HIGH": "High", "MODERATE": "Medium", "MEDIUM": "Medium", "LOW": "Low"}.get(
320
+ worst, "Medium"
321
+ )
322
+ if not shipped: # only development tools: not in what users run
323
+ sev = {"Critical": "High", "High": "Medium", "Medium": "Low"}.get(sev, "Low")
324
+
325
+ def line(pkg, vs) -> str:
326
+ vs = sorted(vs, key=lambda x: rank.index(x.severity))
327
+ sevs = ", ".join(f"{n} {s.lower()}" for s in rank if s and (n := sum(1 for x in vs if x.severity == s)))
328
+ fixed = sorted({f for x in vs for f in x.fixed.split(", ") if f})
329
+ return (
330
+ f"`{pkg.name}@{pkg.version}` ({pkg.source}{', dev only' if pkg.dev else ''}): "
331
+ + (f"{len(vs)} vulnerability" if len(vs) == 1 else f"{len(vs)} vulnerabilities")
332
+ + (f" ({sevs})" if sevs else "")
333
+ + (f", e.g. {vs[0].id}: {vs[0].summary}" if vs[0].summary else f", e.g. {vs[0].id}")
334
+ + (f"; fixed in {', '.join(fixed[:3])}" if fixed else "")
335
+ )
336
+
337
+ ordered = sorted(by_pkg.items(), key=lambda kv: (kv[0].dev, min(rank.index(x.severity) for x in kv[1])))
338
+ self.add(
339
+ f"Dependencies with known vulnerabilities ({len(self.vulns)} in {len(by_pkg)} packages"
340
+ + (", all development-only" if not shipped else "")
341
+ + ")",
342
+ sev,
343
+ "Security",
344
+ [line(p, vs) for p, vs in ordered[:8]],
345
+ "Published vulnerabilities in the exact versions installed. Whether each is exploitable depends on how the "
346
+ "package is used, but attackers scan for these first.",
347
+ "Upgrade to a fixed version (`npm audit fix`, `pip install -U`, `cargo update`…); where there's no fix, "
348
+ "check whether the vulnerable feature is used.",
349
+ _effort(len(by_pkg), len(by_pkg)),
350
+ max(0, len(by_pkg) - 8),
351
+ )
352
+
353
+ # -- the attack surface --------------------------------------------------------------------------------------
354
+ def _reached_by(self, hit) -> str:
355
+ """` ← POST /orders → create_order → save` when a request reaches the line."""
356
+ if not self.surface.entries:
357
+ return ""
358
+ fid = function_at(self.v, hit.file, hit.line)
359
+ chain = self.surface.chain(fid, self.v) if fid else ""
360
+ return f" ← reached from `{chain}`" if chain else " (no endpoint reaches it)"
361
+
362
+ def _by_reach(self, sev: str, hits) -> str:
363
+ """Severity from reachability: a risky line a request reaches is evidence (one level up); when the code has
364
+ endpoints and none reaches it, it's a lead (one level down). Without endpoints (a library, a client app), as is."""
365
+ if not self.surface.entries:
366
+ return sev
367
+ reached = any(self.surface.chain(f, self.v) for e in hits if (f := function_at(self.v, e.file, e.line)))
368
+ order = ["Low", "Medium", "High", "Critical"]
369
+ i = order.index(sev) + (1 if reached else -1)
370
+ return order[max(0, min(len(order) - 1, i))]
371
+
372
+ def _writing_entries(self) -> list[tuple]:
373
+ """(entry, the first function it reaches that changes data) for endpoints that change data."""
374
+ out_edges: dict[str, list[str]] = {}
375
+ for e in self.g["edges"]:
376
+ if e["kind"] in ("call", "ref"):
377
+ out_edges.setdefault(e["src"], []).append(e["dst"])
378
+ found, seen_routes = [], set()
379
+ for entry in self.surface.entries:
380
+ key = (entry.method, entry.path, entry.fn)
381
+ if key in seen_routes:
382
+ continue
383
+ seen_routes.add(key)
384
+ seen, q = {entry.fn}, [entry.fn]
385
+ while q:
386
+ cur = q.pop(0)
387
+ if cur in self.writers:
388
+ found.append((entry, cur))
389
+ break
390
+ for nxt in out_edges.get(cur, ()):
391
+ if nxt not in seen:
392
+ seen.add(nxt)
393
+ q.append(nxt)
394
+ return found
395
+
396
+ def endpoints(self) -> None:
397
+ entries = self.surface.entries
398
+ if not entries:
399
+ return
400
+ writing = self._writing_entries()
401
+ open_writes = [(e, w) for e, w in writing if not e.auth and not SIGN_IN.search(f"{e.path} {e.fn}")]
402
+ if not open_writes:
403
+ return
404
+ authed = [e for e in entries if e.auth]
405
+ exp, why = self.surface.exposure, self.surface.exposure_evidence
406
+ if authed:
407
+ sev, impact = (
408
+ "High",
409
+ (
410
+ f"Other endpoints check who's asking ({len(authed)} of {len(entries)}), these don't: likely a missing check, "
411
+ "so anyone who can reach the server can change this data."
412
+ ),
413
+ )
414
+ elif exp == "local":
415
+ sev, impact = (
416
+ "Low",
417
+ (
418
+ f"No endpoint checks who's asking, and the server listens only on this machine ({why}): fine for a local "
419
+ "tool, as long as it never listens on the network."
420
+ ),
421
+ )
422
+ elif exp == "configurable":
423
+ sev, impact = (
424
+ "Medium",
425
+ (
426
+ f"No endpoint checks who's asking. The server listens locally by default but can be opened to the network "
427
+ f"({why}): then anyone on that network can change data."
428
+ ),
429
+ )
430
+ else:
431
+ sev, impact = (
432
+ ("High" if exp == "open" else "Medium"),
433
+ (
434
+ "No endpoint checks who's asking"
435
+ + (f", and the server listens on every interface ({why})" if exp == "open" else "")
436
+ + ": anyone who can reach it can change data."
437
+ ),
438
+ )
439
+ self.add(
440
+ f"Endpoints that change data without an auth check ({len(open_writes)})",
441
+ sev,
442
+ "Security",
443
+ [
444
+ f"`{e.method} {e.path}` (`{e.file}:{e.line}`) → changes data in `{self.v.fn[w]['qualname']}` "
445
+ f"(`{', '.join(self.v.fn[w]['io'][:2])}`)"
446
+ for e, w in open_writes[:8]
447
+ ],
448
+ impact + " Pattern-based: an auth check done elsewhere (a gateway, a proxy, an unusual decorator) isn't seen.",
449
+ "Require authentication on each (a dependency, decorator or middleware), or document why it's open and "
450
+ "`codefactory accept` it.",
451
+ _effort(len(open_writes), len({e.file for e, _ in open_writes})),
452
+ max(0, len(open_writes) - 8),
453
+ )
454
+
455
+ def surface_line(self) -> str:
456
+ entries = self.surface.entries
457
+ if not entries:
458
+ return ""
459
+ frameworks = sorted({e.framework for e in entries})
460
+ authed = sum(1 for e in entries if e.auth)
461
+ writing = len(self._writing_entries())
462
+ exp = {
463
+ "local": "listens only on this machine",
464
+ "configurable": "listens locally by default, can be opened to the network",
465
+ "open": "listens on every interface",
466
+ "unknown": "listening address not found",
467
+ }[self.surface.exposure]
468
+ return (
469
+ f"- **Attack surface:** {_n(len(entries), 'HTTP endpoint')} ({', '.join(frameworks)}); {authed} check auth; "
470
+ f"{writing} change data; {exp}."
471
+ )
472
+
473
+ def reliability(self) -> None:
474
+ s = self.scan
475
+ sw = s["swallowed"].hits
476
+ if len(sw) >= 3:
477
+ ev, more = _ev(sw)
478
+ self.add(
479
+ f"{_n(len(sw), 'error')} silently swallowed",
480
+ "High" if len(sw) >= 10 else "Medium",
481
+ "Reliability",
482
+ ev,
483
+ "Failures leave no trace: users see something half-done, and nobody can tell why.",
484
+ "Route every caught error through one helper that records it (a log, a local error file, crash "
485
+ "reporting) and only then recovers; keep empty catches for genuinely expected cases, with a comment.",
486
+ _effort(len(sw), len({e.file for e in sw})),
487
+ more,
488
+ )
489
+ fw = self.repo["frameworks"]
490
+ if fw & {"React", "React Native", "Expo", "Next.js"} and not s["error_boundary"].hits:
491
+ self.add(
492
+ "No error boundary around the UI",
493
+ "Medium",
494
+ "Reliability",
495
+ [f"React-based ({', '.join(sorted(fw))}); no ErrorBoundary / componentDidCatch found in the source"],
496
+ "One rendering error blanks the whole app with nothing recorded.",
497
+ "Add an error boundary at the root (and around risky screens) that shows a recovery screen and records "
498
+ "the error.",
499
+ "S",
500
+ )
501
+ nt = [e for e in s["fetch_no_timeout"].hits if not is_script(e.file)]
502
+ if nt:
503
+ s["fetch_no_timeout"].hits = nt
504
+ ev, more = _ev(nt)
505
+ self.add(
506
+ "Network calls without a timeout",
507
+ "Medium",
508
+ "Reliability",
509
+ ev,
510
+ "A slow or hanging server stalls the caller indefinitely.",
511
+ "Give every request a deadline (AbortSignal.timeout(ms) / requests' timeout=) and handle it.",
512
+ _effort(len(s["fetch_no_timeout"].hits), len({e.file for e in s["fetch_no_timeout"].hits})),
513
+ more,
514
+ )
515
+ ms = s["module_state"].hits
516
+ if fw & CLIENT_APPS: # one user per process: module singletons are a normal design; exported mutable bindings aren't
517
+ ms = s["module_state"].hits = [e for e in ms if e.text.startswith("export")]
518
+ if len(ms) >= 3:
519
+ ev, more = _ev(ms)
520
+ self.add(
521
+ f"Module-level mutable state ({len(ms)} places)",
522
+ "Medium" if len(ms) >= 6 else "Low",
523
+ "Reliability",
524
+ ev,
525
+ "State held in module variables is shared by everything that imports it, survives no reload, and "
526
+ "makes order of calls matter in ways tests rarely cover.",
527
+ "Keep it in an owner with a clear lifecycle (a store, a context, a class instance, the database) and "
528
+ "pass it explicitly.",
529
+ _effort(len(ms), len({e.file for e in ms})),
530
+ more,
531
+ )
532
+ reads = [f for f in self.by_kind["io_in_loop"] if f["severity"] == "warn" and not self._script(f)]
533
+ if reads:
534
+ self.add(
535
+ f"Queries or requests inside loops (N+1) in {_n(len(reads), 'place')}",
536
+ "Medium",
537
+ "Performance",
538
+ [f"{self.where(f)}: {f['message'].split(':')[0]}" for f in reads[:6]],
539
+ "Cost grows with the data: one round trip per item instead of one for all.",
540
+ "Load everything a loop needs with one batched query (WHERE id IN (…), a JOIN) or request before the "
541
+ "loop (`codefactory plan` lists each with steps).",
542
+ _effort(len(reads), len(reads)),
543
+ max(0, len(reads) - 6),
544
+ )
545
+ product = [f for f in self.by_kind["io_in_loop"] if not self._script(f) and not is_test(self._file(f))]
546
+ writes = [f for f in product if f.get("detail") == "write"] # loops that can grow; fixed ones are fine as is
547
+ files = [f for f in product if f.get("detail") in ("file", "process")]
548
+ if writes:
549
+ self.add(
550
+ f"Writes inside loops in {_n(len(writes), 'place')}",
551
+ "Low",
552
+ "Performance",
553
+ [self.where(f) for f in writes[:6]],
554
+ "One write per item: fine for a few, slow for many, and partial if it fails halfway outside a transaction.",
555
+ "Wrap each loop in one transaction (or have the caller do so); for loops that can grow, write all rows "
556
+ "with one multi-row INSERT/UPDATE.",
557
+ "M",
558
+ max(0, len(writes) - 6),
559
+ )
560
+ if files:
561
+ self.add(
562
+ f"File or program operations inside loops in {_n(len(files), 'place')}",
563
+ "Low",
564
+ "Performance",
565
+ [self.where(f) for f in files[:6]],
566
+ "One file read, write, copy or directory walk (or program run) per item: normal when each item is its "
567
+ "own file, slow when it's the same file or folder every time.",
568
+ "Where it's the same file or folder each round, read it once before the loop and look items up in memory.",
569
+ "S",
570
+ max(0, len(files) - 6),
571
+ )
572
+
573
+ def architecture(self) -> None:
574
+ cycles = {frozenset([f["target"], *f.get("related", [])]) for f in self.by_kind["cycle"]}
575
+ if cycles:
576
+ biggest = max(len(c) for c in cycles)
577
+ load_order = any(f["severity"] == "high" for f in self.by_kind["cycle"]) # modules that run on import
578
+ self.add(
579
+ f"{'Import' if load_order else 'Dependency'} loops ({len(cycles)})",
580
+ ("High" if biggest >= 3 else "Medium") if load_order else ("Medium" if biggest >= 3 else "Low"),
581
+ "Architecture",
582
+ [" → ".join(sorted(c)) for c in list(cycles)[:4]],
583
+ "Files in a loop load in a fragile order and can't be understood, tested or moved alone."
584
+ if load_order
585
+ else "Classes in a loop work at runtime, but can't be understood, tested, reused or moved apart.",
586
+ "Move what both sides need into a module that imports neither, or pass the dependency in.",
587
+ _effort(len(cycles), biggest),
588
+ )
589
+ lv = self.by_kind["layer_violation"]
590
+ if lv:
591
+ self.add(
592
+ f"Layer rule violations ({len(lv)})",
593
+ "High",
594
+ "Architecture",
595
+ [f["message"] for f in lv[:6]],
596
+ "The architecture factory.toml describes isn't the one the code has.",
597
+ "Move the code into an allowed layer or invert the dependency.",
598
+ _effort(len(lv), len(lv)),
599
+ max(0, len(lv) - 6),
600
+ )
601
+ rank = {name: i for i, name in enumerate(self.g["layers"])}
602
+ layer_of = {f["id"]: f["layer"] for f in self.g["files"]}
603
+ back = Counter()
604
+ for e in self.g["edges"]:
605
+ if e["kind"] == "import":
606
+ a, b = layer_of.get(e["src"]), layer_of.get(e["dst"])
607
+ if a and b and "tests" not in (a, b) and rank.get(b, 0) < rank.get(a, 0):
608
+ back[(a, b)] += 1
609
+ if back:
610
+ self.add(
611
+ "Dependencies against the layer order",
612
+ "Low",
613
+ "Architecture",
614
+ [f"{a} imports {b} ({n} files)" for (a, b), n in back.most_common(5)],
615
+ "A lower layer reaching up into a higher one blurs who depends on whom.",
616
+ "Check each is intended; if not, move the shared piece down or pass it in. Make the rule explicit in "
617
+ "factory.toml ([rules] forbid).",
618
+ "S",
619
+ )
620
+ copies = [t for t in self.tasks if self._copied(t)]
621
+ if copies:
622
+ saved = sum(int(m.group(1)) for t in copies if (m := re.search(r"~(\d+) lines", t["title"])))
623
+ self.add(
624
+ f"Copied logic in {_n(len(copies), 'group')} (~{saved} lines)",
625
+ "Medium" if len(copies) >= 3 else "Low",
626
+ "Maintainability",
627
+ [f"{t['title']}: " + ", ".join(f"`{w['file']}:{w['line']}`" for w in t["where"][:3]) for t in copies[:6]],
628
+ "A fix applied to one copy silently misses the others.",
629
+ "Merge each group into one function in the lowest layer its callers share (`codefactory plan` has "
630
+ "per-group steps).",
631
+ _effort(len(copies), len(copies) * 2),
632
+ max(0, len(copies) - 6),
633
+ )
634
+ # the hardest to follow first: branches (decisions) weigh more than length, so a long but flat table of
635
+ # options or a big layout ranks below a shorter function full of conditions
636
+ # ...and among those, the ones in files that keep changing: a tangled function nobody touches costs little
637
+ long = sorted(
638
+ (f for f in self.code_fns if f["loc"] > 80),
639
+ key=lambda f: -(f.get("branches", 0) * 4 + f["loc"] / 10) * (1 + self.changes(f["file"]) / 4),
640
+ )
641
+ if long:
642
+ self.add(
643
+ f"Very long functions ({_n(len(long), 'function')} over 80 lines)",
644
+ "Low",
645
+ "Maintainability",
646
+ [
647
+ f"`{f['file']}:{f['line']}` {f['qualname']}: {f['loc']} lines"
648
+ + (f", {f['branches']} decision points" if f.get("branches") else "")
649
+ + self._changed(f["file"])
650
+ for f in long[:6]
651
+ ],
652
+ "Hard to read, test and change safely; often several responsibilities in one place.",
653
+ "Extract the parts that have names of their own.",
654
+ "M",
655
+ max(0, len(long) - 6),
656
+ )
657
+ unused = [f for f in self.by_kind["unused"] if not is_test(self._file(f))]
658
+ if unused:
659
+ self.add(
660
+ f"Unused code ({_n(len(unused), 'function')})",
661
+ "Low",
662
+ "Maintainability",
663
+ [self.where(f) for f in unused[:6]],
664
+ "Dead code costs reading time and keeps dependencies alive.",
665
+ "Verify (frameworks may call by name), then delete.",
666
+ "S",
667
+ max(0, len(unused) - 6),
668
+ )
669
+ # only where the lists plausibly grow: the function loads data itself or through what it calls. A search in
670
+ # a loop over a handful of UI items or a fixed table costs nothing, and listing 50 of them hides the few
671
+ # that matter
672
+ loads = self._loads_data()
673
+ scans = [f for f in self.by_kind["quadratic_scan"] if not self._script(f) and f["target"] in loads]
674
+ if scans:
675
+ self.add(
676
+ f"Array searches inside loops over loaded data ({len(scans)})",
677
+ "Low",
678
+ "Performance",
679
+ [self.where(f) for f in scans[:5]],
680
+ "O(n²) on data that comes from storage or the network: fine at today's size, slow as it grows.",
681
+ "Build a Map/Set (dict/set) from the list once before the loop, and look items up in it.",
682
+ "M",
683
+ max(0, len(scans) - 5),
684
+ )
685
+
686
+ def testing(self) -> None:
687
+ tests = [f for f in self.g["files"] if is_test(f["id"])]
688
+ code = [f for f in self.code_fns]
689
+ if not tests:
690
+ self.add(
691
+ "No automated tests",
692
+ "High",
693
+ "Testing",
694
+ ["no test files found (tests/, __tests__/, *.test.*, test_*.py)"],
695
+ "Every change is verified by hand, if at all; refactoring is risky.",
696
+ "Start with tests for the most-used and data-writing functions listed in this report.",
697
+ "L",
698
+ )
699
+ return
700
+ pct = round(100 * sum(1 for f in code if f["id"] in self.reached) / max(1, len(code)))
701
+ self.test_pct = pct
702
+ callers = {f["id"]: {self.v.fn[e["src"]]["file"] for e in self.v.callers[f["id"]] if e["src"] in self.v.fn} for f in code}
703
+ risky = [
704
+ f
705
+ for f in code
706
+ if f["id"] not in self.reached and (f.get("io") or len(callers[f["id"]]) >= 8) and not is_script(f["file"])
707
+ ]
708
+ # writes first (a wrong one loses data), then I/O, then code that keeps changing, then the most depended-on
709
+ risky.sort(
710
+ key=lambda f: (
711
+ -bool(rerank.WRITE_WORDS.search(" ".join(f.get("io", [])))),
712
+ -bool(f.get("io")),
713
+ -min(self.changes(f["file"]), 10),
714
+ -len(callers[f["id"]]),
715
+ )
716
+ )
717
+ if risky:
718
+ self.add(
719
+ f"Important code no test reaches ({_n(len(risky), 'function')})",
720
+ "Medium",
721
+ "Testing",
722
+ [
723
+ f"`{f['file']}:{f['line']}` {f['qualname']}"
724
+ + (f": does I/O ({', '.join(f['io'][:2])})" if f.get("io") else "")
725
+ + (f", called from {len(callers[f['id']])} files" if len(callers[f["id"]]) >= 2 else "")
726
+ + self._changed(f["file"])
727
+ for f in risky[:8]
728
+ ],
729
+ f"Tests reach {pct}% of functions, but not these: code that talks to storage or the network, or that "
730
+ "much of the app depends on." + self._coverage_note(),
731
+ "Add tests that call these (against a real or in-memory store), starting with the ones that write data.",
732
+ _effort(len(risky), len({f["file"] for f in risky})),
733
+ max(0, len(risky) - 8),
734
+ )
735
+ if self.repo["ci"] and "tests" not in self.repo["ci_steps"]:
736
+ self.add(
737
+ "CI doesn't run the tests",
738
+ "Medium",
739
+ "Delivery",
740
+ [f"`{c}`" for c in self.repo["ci"]],
741
+ "Tests that don't run on every change stop being trusted.",
742
+ "Add the test command to CI.",
743
+ "S",
744
+ )
745
+
746
+ def custom(self) -> None:
747
+ """The team's own rules from factory.toml, one finding per rule."""
748
+ by_rule: dict[str, list[dict]] = {}
749
+ for f in self.by_kind["custom"]:
750
+ by_rule.setdefault(f.get("detail") or "custom", []).append(f)
751
+ for rule, flags in sorted(by_rule.items()):
752
+ sev = {"high": "High", "warn": "Medium", "info": "Low"}[
753
+ min((f["severity"] for f in flags), key=["high", "warn", "info"].index)
754
+ ]
755
+ message = flags[0]["message"].split("] ", 1)[-1]
756
+ self.add(f"Custom rule {rule} ({len(flags)})", sev, "Custom", [self.where(f) for f in flags[:6]], message,
757
+ "See the rule in factory.toml.", _effort(len(flags), len({self._file(f) for f in flags})),
758
+ max(0, len(flags) - 6)) # fmt: skip
759
+
760
+ def _by_owner(self) -> list[str]:
761
+ """Findings per owning team, from CODEOWNERS: who has the most to act on."""
762
+ from .owners import load
763
+
764
+ owners = load(self.root)
765
+ if not owners:
766
+ return []
767
+ counts: dict[str, Counter] = {}
768
+ files = [(self._file(f), f["severity"]) for f in self.g["flags"]]
769
+ files += [(e.file, "warn") for k, c in self.scan.items() if k in SECURITY_KEYS for e in c.hits]
770
+ for file, sev in files:
771
+ for who in owners.of(file) or ["(no owner)"]:
772
+ counts.setdefault(who, Counter())[sev] += 1
773
+ rows = sorted(counts.items(), key=lambda kv: (-kv[1]["high"], -kv[1]["warn"], -sum(kv[1].values())))
774
+ out = [f"### By owner ({owners.source})", "", "| Owner | High | Warn | Info |", "|---|---|---|---|"]
775
+ out += [f"| {who} | {c['high']} | {c['warn']} | {c['info']} |" for who, c in rows[:15]]
776
+ return [*out, ""]
777
+
778
+ def delivery(self) -> None:
779
+ r = self.repo
780
+ if not r["ci"]:
781
+ self.add(
782
+ "No continuous integration",
783
+ "High",
784
+ "Delivery",
785
+ ["no CI configuration found (" + ", ".join(c for c in CI_HINT) + ")"],
786
+ "Nothing checks a change before it ships.",
787
+ "Add a CI workflow that installs from the lockfile and runs "
788
+ "typecheck, lint and tests on every pull request and push to the main branch.",
789
+ "S",
790
+ )
791
+ elif not r["ci_on_push"]:
792
+ self.add(
793
+ "CI doesn't run on pushes to the main branch",
794
+ "Low",
795
+ "Delivery",
796
+ [f"`{c}`" for c in r["ci"]],
797
+ "Direct pushes skip every check.",
798
+ "Also trigger on push to the main branch.",
799
+ "S",
800
+ )
801
+ if r["manifests"] and not r["locks"] and any(m == "package.json" for m in r["manifests"]):
802
+ self.add(
803
+ "No lockfile",
804
+ "High",
805
+ "Dependencies",
806
+ [", ".join(r["manifests"])],
807
+ "Every install can resolve different versions: builds aren't reproducible.",
808
+ "Commit the lockfile your package manager writes, and install with it in CI (npm ci / pnpm i --frozen-lockfile).",
809
+ "S",
810
+ )
811
+ if r["floating"]:
812
+ self.add(
813
+ "Dependencies on moving targets",
814
+ "Medium",
815
+ "Dependencies",
816
+ r["floating"][:8],
817
+ "`*`, `latest` or a git branch changes under you without a code change.",
818
+ "Pin versions (or commits).",
819
+ "S",
820
+ )
821
+ if r["unpinned_py"]:
822
+ self.add(
823
+ "Unpinned Python requirements",
824
+ "Medium",
825
+ "Dependencies",
826
+ r["unpinned_py"][:8],
827
+ "Installs drift over time.",
828
+ "Pin with == (or use a lock tool: uv, pip-tools, poetry).",
829
+ "S",
830
+ )
831
+ if r["manifests"] and not r["runtime_pin"]:
832
+ self.add(
833
+ "Runtime version not pinned",
834
+ "Low",
835
+ "Delivery",
836
+ ["no engines / .nvmrc / .python-version / requires-python"],
837
+ "Developers, CI and production can run different Node/Python versions.",
838
+ "Declare the version (package.json engines + .nvmrc, or requires-python + .python-version).",
839
+ "S",
840
+ )
841
+ if not r["readme"]:
842
+ self.add(
843
+ "No README",
844
+ "Medium",
845
+ "Docs",
846
+ ["no README at the repository root"],
847
+ "A new engineer can't run or change it from the repo alone.",
848
+ "Add one: what it is, how to run, test and ship.",
849
+ "S",
850
+ )
851
+ elif not r.get("readme_run"):
852
+ self.add(
853
+ "README doesn't say how to run it",
854
+ "Low",
855
+ "Docs",
856
+ [f"`{r['readme']}`"],
857
+ "Setup knowledge lives in people's heads.",
858
+ "Add install, run and test commands.",
859
+ "S",
860
+ )
861
+
862
+ # ---- helpers -----------------------------------------------------------------------------------------------
863
+ def _file(self, flag: dict) -> str:
864
+ fn = self.v.fn.get(flag["target"])
865
+ return fn["file"] if fn else flag["target"]
866
+
867
+ def _script(self, flag: dict) -> bool:
868
+ return is_script(self._file(flag))
869
+
870
+ def _tracked(self, names: list[str]) -> list[str]:
871
+ if not names:
872
+ return []
873
+ try:
874
+ out = subprocess.run(["git", "ls-files", *names], cwd=self.root, capture_output=True, text=True, timeout=20)
875
+ return out.stdout.split() if out.returncode == 0 else names
876
+ except (OSError, subprocess.SubprocessError):
877
+ return names
878
+
879
+ # ---- report ------------------------------------------------------------------------------------------------
880
+ def run(self) -> None:
881
+ self.test_pct = None
882
+ self.security()
883
+ self.reliability()
884
+ self.architecture()
885
+ self.testing()
886
+ self.delivery()
887
+ self.custom()
888
+ if self.surface.entries:
889
+ self.profile.open_writes = sum(1 for e, _ in self._writing_entries() if not e.auth)
890
+ self.rank_changes = rerank.rerank(self.findings, self.profile)
891
+ for f in self.findings: # findings in hotspots: the same severity, but worth doing first
892
+ hot = sorted({p for e in f.evidence for p in re.findall(r"`([^`\s]+?):\d+`", e) if p in self.hot},
893
+ key=lambda p: -self.hot[p].score) # fmt: skip
894
+ if hot:
895
+ f.data["hotspot"] = hot
896
+ self.findings.sort(key=lambda f: (SEV.index(f.severity), not f.data.get("hotspot"), -len(f.evidence) - f.more))
897
+
898
+ def health(self) -> tuple[str, list[Finding]]:
899
+ score = 100
900
+ for sev in SEV:
901
+ pts = sum(POINTS[sev] for f in self.findings if f.severity == sev)
902
+ score -= min(CAPS.get(sev, pts), pts)
903
+ grade = "Strong" if score >= 85 else "Adequate" if score >= 65 else "Fragile" if score >= 40 else "At risk"
904
+ return grade, [f for f in self.findings if f.severity in ("Critical", "High")]
905
+
906
+ def stores(self) -> list[str]:
907
+ sinks = " ".join(" ".join(f.get("io", [])) for f in self.g["functions"])
908
+ deps = self.repo["deps"]
909
+ out = []
910
+ if "expo-sqlite" in deps:
911
+ out.append("SQLite (expo-sqlite)")
912
+ elif re.search(r"sqlite3|getAllAsync|runAsync", sinks):
913
+ out.append("SQLite")
914
+ for pat, name in (
915
+ (r"psycopg|asyncpg|pg\b", "PostgreSQL"),
916
+ (r"duckdb", "DuckDB"),
917
+ (r"pyarrow|fastparquet|\.parquet|to_parquet|read_parquet", "Parquet files"),
918
+ (r"sqlalchemy", "SQLAlchemy"),
919
+ (r"mysql|pymysql", "MySQL"),
920
+ (r"elasticsearch|opensearch", "Elasticsearch"),
921
+ (r"boto3|@aws-sdk/client-s3", "Amazon S3 / AWS"),
922
+ (r"pymongo|mongoose", "MongoDB"),
923
+ (r"redis", "Redis"),
924
+ (r"AsyncStorage", "AsyncStorage"),
925
+ (r"SecureStore|getItemAsync", "secure key store"),
926
+ (r"prisma", "Prisma ORM"),
927
+ (r"objects\.", "Django ORM"),
928
+ (r"readFile|writeFile|read_text|write_text|AsStringAsync", "local files"),
929
+ ):
930
+ if re.search(pat, sinks) or any(re.search(pat, d) for d in deps):
931
+ out.append(name)
932
+ return out
933
+
934
+ def markdown(self, for_ai: bool = False) -> str:
935
+ g, r = self.g, self.repo
936
+ name = g["root"].replace("\\", "/").rstrip("/").split("/")[-1]
937
+ code_files = [f for f in g["files"] if not is_test(f["id"])]
938
+ lines_total = sum(f["loc"] for f in code_files)
939
+ entry = [f for f in code_files if not self.v.importers.get(f["id"])]
940
+ layers = [(name, sum(1 for f in code_files if f["layer"] == name)) for name in g["layers"] if name != "tests"]
941
+ hosts = self.scan["hosts"].data
942
+ grade, drivers = self.health()
943
+ frameworks = r["frameworks"]
944
+ fw = (
945
+ "Expo / React Native"
946
+ if "Expo" in frameworks
947
+ else "React Native"
948
+ if "React Native" in frameworks
949
+ else ", ".join(sorted(frameworks)) or g["language"]
950
+ )
951
+ article = "an" if fw[:1].lower() in "aeiou" else "a"
952
+ out = [
953
+ f"# Technical review: {name}",
954
+ "",
955
+ f"_Generated by codefactory {self._version()} from static analysis (no code was run, no AI). Every finding "
956
+ "cites file:line; verify before acting on anything marked as a hint._",
957
+ "",
958
+ "## 1. Executive summary",
959
+ "",
960
+ f"- **What it is:** {article} {fw} codebase ({g['language']}): {len(code_files)} source files, "
961
+ f"{lines_total:,} lines, in "
962
+ f"{_n(len(layers), 'layer')} ({', '.join(f'{name} {n}' for name, n in sorted(layers, key=lambda x: -x[1])[:5])}).",
963
+ f"- **Profile:** {self.profile.summary()} (section 2; findings are ranked for it).",
964
+ f"- **Entry points:** {len(entry)} files nothing imports (screens, routes, scripts, configs).",
965
+ f"- **Data:** {', '.join(self.stores()) or 'no data store detected'}.",
966
+ f"- **External services:** {', '.join(sorted(hosts)[:8]) or 'none found in the code'}"
967
+ + (f" (+{len(hosts) - 8} more)" if len(hosts) > 8 else "")
968
+ + ".",
969
+ *([line] if (line := self.surface_line()) else []),
970
+ f"- **Tests:** {len([f for f in g['files'] if is_test(f['id'])])} test files"
971
+ + (f", reaching {self.test_pct}% of functions" if self.test_pct is not None else "")
972
+ + ".",
973
+ f"- **CI:** {', '.join(r['ci']) if r['ci'] else 'none'}"
974
+ + (f" (runs {', '.join(sorted(r['ci_steps']))})" if r["ci_steps"] else "")
975
+ + ".",
976
+ "",
977
+ f"**Overall health: {grade}.** " + self._justify(grade, drivers),
978
+ "",
979
+ "**Top 5 actions, by leverage**",
980
+ "",
981
+ "| # | Action | Effort | Why |",
982
+ "|---|---|---|---|",
983
+ ]
984
+ for i, f in enumerate(self.findings[:5], 1):
985
+ action = re.split(r"[;:]\s|\.\s", f.fix)[0].rstrip(".")
986
+ why = re.split(r"[;:]\s|\.\s", f.impact)[0].rstrip(".")
987
+ out.append(f"| {i} | **{f.title}**: {action} | {f.effort} | {why} |")
988
+ out += ["", "## 2. Project profile", ""] + profile_markdown(self.profile)
989
+ out += ["", "**Ranked for this project**", ""] + rerank.markdown(self.rank_changes)
990
+ out += ["## 3. System map", "", "| Layer | Files | Lines | Calls into |", "|---|---|---|---|"]
991
+ layer_of = {f["id"]: f["layer"] for f in g["files"]}
992
+ fn_file = {f["id"]: f["file"] for f in g["functions"]}
993
+ deps = defaultdict(Counter)
994
+ for e in g["edges"]:
995
+ if e["kind"] == "call":
996
+ a, b = layer_of.get(fn_file.get(e["src"])), layer_of.get(fn_file.get(e["dst"]))
997
+ if a and b and a != b:
998
+ deps[a][b] += e["count"]
999
+ for layer in g["layers"]:
1000
+ members = [f for f in g["files"] if f["layer"] == layer]
1001
+ out.append(
1002
+ f"| {layer} | {len(members)} | {sum(f['loc'] for f in members):,} | "
1003
+ f"{', '.join(f'{k} ({n})' for k, n in deps[layer].most_common(4)) or '-'} |"
1004
+ )
1005
+ out += [
1006
+ "",
1007
+ "**Trust boundaries:** "
1008
+ + "; ".join(
1009
+ filter(
1010
+ None,
1011
+ [
1012
+ f"network ({_n(len(hosts), 'host')}: {', '.join(sorted(hosts)[:5])})" if hosts else "",
1013
+ "the data store" if self.stores() else "",
1014
+ "files the user opens or imports"
1015
+ if re.search(
1016
+ r"DocumentPicker|open\(|readFile|FileReader",
1017
+ " ".join(" ".join(f.get("io", [])) for f in g["functions"]),
1018
+ )
1019
+ else "",
1020
+ ],
1021
+ )
1022
+ )
1023
+ or "none detected.",
1024
+ "",
1025
+ ]
1026
+ hub = sorted(
1027
+ self.code_fns,
1028
+ key=lambda f: -len({self.v.fn[e["src"]]["file"] for e in self.v.callers[f["id"]] if e["src"] in self.v.fn}),
1029
+ )[:5]
1030
+ out += ["**Most depended-on code:** " + ", ".join(f"`{f['file']}:{f['line']}` {f['qualname']}" for f in hub), ""]
1031
+ by_file: dict[str, list[str]] = defaultdict(list)
1032
+ for f in self.findings:
1033
+ for path in f.data.get("hotspot", []):
1034
+ by_file[path].append(f.title.split(" (")[0])
1035
+ out += ["## 4. Where change happens", ""] + hotspots.markdown(self.history, by_file)
1036
+ out += ["## 5. Findings", ""]
1037
+ for sev in SEV:
1038
+ group = [f for f in self.findings if f.severity == sev]
1039
+ out += [f"### {sev}", ""]
1040
+ if not group:
1041
+ out += ["None found.", ""]
1042
+ continue
1043
+ for f in group:
1044
+ out += [f"**{f.title}** · {f.area} · effort {f.effort}", "", "- Evidence:"] + [f" - {e}" for e in f.evidence]
1045
+ if f.more:
1046
+ out.append(f" - … {f.more} more")
1047
+ out += [f"- Impact: {f.impact}", f"- Fix: {f.fix}"]
1048
+ if ranked := f.data.get("ranked"):
1049
+ out.append(f"- Ranked {f.severity} for this project (default {ranked['from']}): {ranked['why']}")
1050
+ if hot := f.data.get("hotspot"):
1051
+ x = self.hot[hot[0]]
1052
+ out.append(
1053
+ f"- In a hotspot: `{x.path}` changed {x.commits} times in 12 months"
1054
+ + (f" ({x.recent} in the last 3)" if x.recent and x.recent != x.commits else "")
1055
+ + (f", and {len(hot) - 1} more hotspot file{'s' if len(hot) > 2 else ''}" if len(hot) > 1 else "")
1056
+ + ": fixing it here pays off soonest."
1057
+ )
1058
+ out.append("")
1059
+ out += self._by_owner()
1060
+ out += ["## 6. What is working", ""] + [f"- {w}" for w in self.strengths()] + [""]
1061
+ out += ["## 7. Testing and release gaps", ""]
1062
+ gaps = [f for f in self.findings if f.area in ("Testing", "Delivery", "Dependencies")]
1063
+ out += [f"- **{f.title}.** {f.fix}" for f in gaps] or ["- None found by these checks."]
1064
+ out += ["", "## 8. Open questions", ""] + [f"- {q}" for q in self.questions()]
1065
+ out += ["", "## Review limits", ""] + [f"- {x}" for x in self.limits()]
1066
+ if for_ai:
1067
+ out += ["", self.evidence_pack()]
1068
+ return "\n".join(out) + "\n"
1069
+
1070
+ def _justify(self, grade: str, drivers: list[Finding]) -> str:
1071
+ crit = [f.title for f in drivers]
1072
+ good = len(self.strengths())
1073
+ if not crit:
1074
+ return f"No critical or high-severity findings; {good} strengths below. The medium items are real debt, not blockers."
1075
+ return (
1076
+ f"Driven by {_n(len(crit), 'critical/high finding')}: {'; '.join(crit[:3])}"
1077
+ + (" …" if len(crit) > 3 else "")
1078
+ + f". {good} things are working well (section 6)."
1079
+ )
1080
+
1081
+ def strengths(self) -> list[str]:
1082
+ if self._strengths is None:
1083
+ self._strengths = self._find_strengths()
1084
+ return self._strengths
1085
+
1086
+ def _find_strengths(self) -> list[str]:
1087
+ r, s, out = self.repo, self.scan, []
1088
+ if not self.by_kind["cycle"]:
1089
+ out.append("No import loops: every module can be loaded and understood on its own.")
1090
+ if not s["secret"].hits:
1091
+ out.append("No credentials found in the source.")
1092
+ if not s["sql_built"].hits and re.search(
1093
+ r"Async|execute", " ".join(" ".join(f.get("io", [])) for f in self.g["functions"])
1094
+ ):
1095
+ out.append("SQL is parameterized: no queries built from strings were found.")
1096
+ if not (s["eval"].hits or s["shell"].hits or s["tls_off"].hits):
1097
+ out.append("No eval, shell-string execution or disabled TLS checks.")
1098
+ if self.test_pct is not None and self.test_pct >= 50:
1099
+ out.append(f"Tests reach {self.test_pct}% of functions.")
1100
+ if r["ci"] and {"tests"} <= r["ci_steps"]:
1101
+ out.append(f"CI runs {', '.join(sorted(r['ci_steps']))}.")
1102
+ if r["locks"]:
1103
+ out.append(f"Reproducible installs: {', '.join(r['locks'])} committed.")
1104
+ if r["runtime_pin"]:
1105
+ out.append(f"Runtime version pinned ({', '.join(r['runtime_pin'])}).")
1106
+ dup_targets = {x["target"] for x in self.by_kind["duplicate"] + self.by_kind["similar"]}
1107
+ copied = sum(f["loc"] for f in self.code_fns if f["id"] in dup_targets)
1108
+ total = max(1, sum(f["loc"] for f in self.code_fns))
1109
+ if copied / total < 0.02:
1110
+ out.append(f"Little copied code ({round(100 * copied / total, 1)}% of function lines).")
1111
+ if len(s["swallowed"].hits) < 3:
1112
+ out.append("Errors are rarely swallowed silently.")
1113
+ if r["readme"] and r.get("readme_run"):
1114
+ out.append(f"{r['readme']} explains how to run it.")
1115
+ return out
1116
+
1117
+ def questions(self) -> list[str]:
1118
+ p = self.profile
1119
+ q = [
1120
+ "What scale is this built for (users, data volume, requests per second), and what are the uptime or latency targets?"
1121
+ if p.server
1122
+ else "How many people use it, and how much data does one of them build up over a year?",
1123
+ (
1124
+ f"It holds {', '.join(p.sensitive)} data: which rules apply (GDPR, HIPAA, PCI DSS, the app stores' privacy "
1125
+ "labels), and is that data ever sent off the device or server?"
1126
+ )
1127
+ if p.sensitive
1128
+ else "Is any of its data sensitive (personal, payment, health) in ways the code doesn't show?",
1129
+ ]
1130
+ if p.kind == "unknown":
1131
+ q.insert(0, "What kind of project is this (app, service, tool, library)? Set it in factory.toml `[profile]` "
1132
+ "so findings are ranked for it.") # fmt: skip
1133
+ if self.scan["hosts"].data:
1134
+ q.append(
1135
+ f"What should happen when {', '.join(sorted(self.scan['hosts'].data)[:3])} "
1136
+ f"{'is' if len(self.scan['hosts'].data) == 1 else 'are'} slow or down?"
1137
+ )
1138
+ if self.stores():
1139
+ q.append(f"How is {self.stores()[0]} backed up and restored, and has a restore been tested?")
1140
+ if self.repo["deploy"]:
1141
+ q.append(
1142
+ f"Who can run {', '.join(f'`{d}`' for d in self.repo['deploy'][:3])}, what checks run first, "
1143
+ "and how is a bad release rolled back?"
1144
+ )
1145
+ if not self.repo["ci"]:
1146
+ q.append("How is the code built and released today?")
1147
+ q.append(
1148
+ "Which findings above are known and accepted? Mark them (`codefactory accept <kind> <file> --why …` or a "
1149
+ "`codefactory: ignore <kind> — why` comment) "
1150
+ "so the next review shows only what's new."
1151
+ )
1152
+ return q
1153
+
1154
+ def _apply_silence(self, rules: list[dict]) -> None:
1155
+ """[[silence]] rules in factory.toml (written by `codefactory accept`) apply to the review's own checks too."""
1156
+ for key, check in self.scan.items():
1157
+ check.hits = [
1158
+ e for e in check.hits
1159
+ if not any(r["kind"] in ("*", key) and (fnmatch(e.file, r["where"]) or fnmatch(f"{e.file}:{e.line}", r["where"]))
1160
+ for r in rules)
1161
+ ] # fmt: skip
1162
+
1163
+ def _coverage_note(self) -> str:
1164
+ if self.coverage:
1165
+ return (
1166
+ f" Measured from {self.coverage.source} ({self.coverage.written}); rerun the tests with coverage to refresh it."
1167
+ )
1168
+ return " Estimated from which functions tests call (no coverage report found: coverage/lcov.info, coverage.json)."
1169
+
1170
+ def _loads_data(self) -> set[str]:
1171
+ """Functions that read from a database, the network or files, themselves or through a function they call."""
1172
+ io = {fid for fid, f in self.v.fn.items() if f.get("io")}
1173
+ out = set(io)
1174
+ for e in self.g["edges"]:
1175
+ if e["kind"] == "call" and e["dst"] in io:
1176
+ out.add(e["src"])
1177
+ return out
1178
+
1179
+ @staticmethod
1180
+ def _copied(task: dict) -> bool:
1181
+ """Copies worth merging: identical or nearly so (≥85%), and not a test restating code it checks (an oracle).
1182
+ Below 85% the pair is usually a deliberate variant (unticking a set vs deleting it, "45 sec" vs "45s")."""
1183
+ if task["kind"] not in ("duplicate", "similar") or any(is_test(w["file"]) for w in task["where"]):
1184
+ return False
1185
+ m = re.search(r"(\d+)% similar", task["title"])
1186
+ return not m or int(m.group(1)) >= 85
1187
+
1188
+ def limits(self) -> list[str]:
1189
+ analyzed = Counter(Path(f["id"]).suffix for f in self.g["files"])
1190
+ seen = {f["id"] for f in self.g["files"]}
1191
+ other = Counter()
1192
+ for rel in walk(self.root, suffixes=tuple(OTHER_CODE)):
1193
+ if rel not in seen:
1194
+ other[OTHER_CODE[Path(rel).suffix]] += 1
1195
+ out = [
1196
+ f"Analyzed {len(self.g['files'])} files ({', '.join(f'{n} {ext}' for ext, n in analyzed.most_common(6))}) "
1197
+ "statically: call graph, imports, structure and text patterns. Nothing was executed."
1198
+ ]
1199
+ if ok := self.scan["swallowed_ok"].hits:
1200
+ kinds = Counter(e.text for e in ok)
1201
+ why = {"explained": "a comment says why", "cleanup": "best-effort cleanup", "fallback": "a fallback value"}
1202
+ out.append(
1203
+ f"{_n(len(ok), 'empty catch block')} treated as deliberate, not reported ("
1204
+ + ", ".join(f"{n}: {why[k]}" for k, n in kinds.most_common())
1205
+ + ")."
1206
+ )
1207
+ if other:
1208
+ from .analyzers.generic import available
1209
+
1210
+ why = (
1211
+ "generated, too large or not parseable"
1212
+ if available()
1213
+ else 'install the language pack to include them: pip install "codefactory[languages]"'
1214
+ )
1215
+ out.append(f"Not analyzed ({why}): " + ", ".join(f"{n} {lang}" for lang, n in other.most_common()) + ".")
1216
+ if any(Path(f["id"]).suffix not in (".py", *TS_EXT) for f in self.g["files"]):
1217
+ out.append(
1218
+ "Languages other than Python and TypeScript/JavaScript are analyzed by tree-sitter, matching calls by "
1219
+ "name: their unused-code and call findings are hints."
1220
+ )
1221
+ out += [
1222
+ "Calls through dynamic dispatch (callbacks in variables, getattr, untyped objects) can be missing, so "
1223
+ "'unused' and 'no test reaches it' are hints.",
1224
+ (
1225
+ f"Dependencies: {self.deps_note}."
1226
+ if self.online
1227
+ else "Dependencies weren't checked for known vulnerabilities: `--online` does it (sends package names "
1228
+ "and versions to OSV.dev, nothing else)."
1229
+ ),
1230
+ *([f"Git history: {self.history_note}."] if self.history_note else []),
1231
+ "Not checked: runtime behaviour, concurrency and transaction semantics, business logic, infrastructure "
1232
+ "beyond Dockerfiles and CI workflows.",
1233
+ "Severity is set by rules, not by knowing the product: re-rank with what you know about users and data.",
1234
+ ]
1235
+ return out
1236
+
1237
+ def evidence_pack(self) -> str:
1238
+ """For an AI reviewer: what to confirm, and the riskiest code to read, in a few thousand tokens."""
1239
+ risky = []
1240
+ wipe = re.compile(
1241
+ r"deleteDatabase|DROP TABLE|\brmSync\b|\bunlink(Sync)?\(|\brmdir|shutil\.rmtree|os\.remove\(|"
1242
+ r"\bdeleteAsync\(|\b\w*(?:file|File|dir|Dir)\w*(?:\(\))?\.delete\(|\bTRUNCATE\b"
1243
+ ) # databases or files
1244
+ rows = re.compile(r"DELETE FROM|\.destroy\(|objects\.\w+\(.*\)\.delete\(|session\.delete\(", re.I)
1245
+ for f in self.code_fns:
1246
+ if f["loc"] < 8 or f["loc"] > 160 or is_script(f["file"]):
1247
+ continue # one-liners have nowhere to hide a failure mode; huge ones won't fit
1248
+ try:
1249
+ lines = (
1250
+ (self.root / f["file"]).read_text(encoding="utf-8", errors="replace").splitlines()[f["line"] - 1 : f["end"]]
1251
+ )
1252
+ except OSError:
1253
+ continue
1254
+ # code only: words in comments ("unlinks", "truncate") aren't operations
1255
+ body = "\n".join(re.sub(r"(^|\s)(//|#).*$", "", ln) for ln in lines)
1256
+ body = re.sub(r"/\*.*?\*/", "", body, flags=re.S)
1257
+ score, reasons = 0, []
1258
+ if wipe.search(body):
1259
+ score += 6
1260
+ reasons.append("deletes a database or files")
1261
+ elif rows.search(body):
1262
+ score += 2
1263
+ reasons.append("deletes rows")
1264
+ swallowed = len(
1265
+ re.findall(
1266
+ r"catch\s*(?:\([^)]*\))?\s*\{\s*(?://[^\n]*)?\s*\}|\.catch\(\s*\(\s*\)\s*=>\s*\{\s*\}\s*\)|except[^:]*:\s*pass",
1267
+ body,
1268
+ )
1269
+ )
1270
+ if swallowed:
1271
+ score += min(6, 2 + swallowed)
1272
+ reasons.append(f"swallows {_n(swallowed, 'error')}")
1273
+ if f.get("io"):
1274
+ score += 1
1275
+ reasons.append("does I/O")
1276
+ if f["id"] not in self.reached:
1277
+ score += 2
1278
+ reasons.append("no test reaches it")
1279
+ if re.search(r"withTransaction|BEGIN|transaction|lock|mutex|Promise\.all", body):
1280
+ score += 1
1281
+ reasons.append("transactions or concurrency")
1282
+ branches = len(re.findall(r"\bif\b|\?\s|\bcatch\b|\bexcept\b|\|\||&&", body))
1283
+ score += min(4, branches // 4)
1284
+ if branches >= 8:
1285
+ reasons.append(f"{branches} branches")
1286
+ if score >= 7:
1287
+ risky.append((score, f, reasons, lines))
1288
+ risky.sort(key=lambda x: -x[0])
1289
+ out = [
1290
+ "---",
1291
+ "",
1292
+ "## Evidence pack for an AI reviewer",
1293
+ "",
1294
+ "You are finishing this review. Everything above was produced by static rules. Your job:",
1295
+ "1. Check the project profile (section 2) against the README: it decides how findings are ranked. If it's "
1296
+ "wrong, say so and suggest the `[profile]` lines for factory.toml.",
1297
+ "2. For each Critical/High/Medium finding: confirm it from the cited lines (open only those), or reject it "
1298
+ "with the reason. Adjust severity using what the code and README say about the product.",
1299
+ "3. Read the risky functions below. For each, decide whether there's a real failure mode (data loss, a "
1300
+ "user locked out, a race between writers, a misleading error) and add findings for the real ones. Weigh "
1301
+ "those in hotspots (section 4) higher: that code changes every week.",
1302
+ "4. Rewrite sections 1 and 5 with your conclusions. Keep file:line evidence. Don't read other files "
1303
+ "unless a finding needs one more caller (`codefactory context <name>` lists them).",
1304
+ "",
1305
+ f"Profile: {self.profile.summary()}."
1306
+ + (f" Hotspots: {', '.join(f'`{x.path}`' for x in self.history.hot[:5])}." if self.history.hot else ""),
1307
+ "",
1308
+ "### Riskiest code (deletes data, does I/O, untested, swallows errors)",
1309
+ "",
1310
+ ]
1311
+ out += self._surface_pack()
1312
+ for _score, f, reasons, lines in risky[:6]:
1313
+ ext = Path(f["file"]).suffix.lstrip(".") or "text"
1314
+ out += (
1315
+ [f"**`{f['file']}:{f['line']}` {f['qualname']}** ({', '.join(reasons)})", "", f"```{ext}"]
1316
+ + lines[:60]
1317
+ + ["```", ""]
1318
+ )
1319
+ if not risky:
1320
+ out.append("No function combines deleting data, I/O and missing tests.")
1321
+ return "\n".join(out)
1322
+
1323
+ def _surface_pack(self) -> list[str]:
1324
+ """The attack surface for the AI: every endpoint with its auth check and what it changes, so it judges
1325
+ authorization (can user A reach user B's data?) and input handling on the paths that matter."""
1326
+ entries = self.surface.entries
1327
+ if not entries:
1328
+ return []
1329
+ writing = {(e.method, e.path): self.v.fn[w]["qualname"] for e, w in self._writing_entries()}
1330
+ out = [
1331
+ "### Attack surface",
1332
+ "",
1333
+ f"Listening: {self.surface.exposure}"
1334
+ + (f" ({self.surface.exposure_evidence})" if self.surface.exposure_evidence else "")
1335
+ + ".",
1336
+ "For each endpoint that changes data, check that it verifies who's asking and that the caller may change "
1337
+ "*that* record (an id from the request must belong to them), and that its inputs are validated.",
1338
+ "",
1339
+ "| Endpoint | Handler | Auth found | Changes data in |",
1340
+ "|---|---|---|---|",
1341
+ ]
1342
+ for e in entries[:40]:
1343
+ out.append(
1344
+ f"| `{e.method} {e.path}` | `{e.file}:{e.line}` | {e.auth or 'none'} | {writing.get((e.method, e.path), '')} |"
1345
+ )
1346
+ if len(entries) > 40:
1347
+ out.append(f"| … {len(entries) - 40} more (`codefactory surface`) | | | |")
1348
+ return [*out, ""]
1349
+
1350
+ @staticmethod
1351
+ def _version() -> str:
1352
+ from . import __version__
1353
+
1354
+ return __version__
1355
+
1356
+
1357
+ CI_HINT = [".github/workflows", ".gitlab-ci.yml", ".circleci", "Jenkinsfile"]
1358
+ SECURITY_KEYS = {"secret", "eval", "shell", "tls_off", "raw_html", "sql_built", "history_secret", "secret_key_literal",
1359
+ "jwt_unverified", "weak_cipher", "weak_hash", "weak_random", "cors_any", "insecure_cookie", "debug_on",
1360
+ "sensitive_storage", "docker_secret", "gha_injection"} # fmt: skip
1361
+
1362
+ INFRA_CHECKS = [
1363
+ ("config_secret", "Credentials in configuration files", "Critical", "Security",
1364
+ "YAML, Makefiles, Pkl, Terraform and other config files are shared, copied into images and pasted into tickets; a "
1365
+ "key in one is as leaked as one in the code.",
1366
+ "Rotate it, then read it from the environment or a secret manager (Pkl: `read(\"env:NAME\")`; Compose and "
1367
+ "Kubernetes: secrets)."),
1368
+ ("compose_secret", "Passwords written into docker-compose", "Medium", "Security",
1369
+ "Everyone with the repository has them, and the same file tends to reach staging and production.",
1370
+ "Use an `.env` file that isn't committed, `${VAR}` substitution, or Compose `secrets:`."),
1371
+ ("k8s_secret", "Kubernetes Secrets committed with their values", "High", "Security",
1372
+ "A Secret's `data` is only base64: anyone with the repository can read it.",
1373
+ "Keep the values out of git: Sealed Secrets, SOPS, External Secrets, or create them at deploy time."),
1374
+ ("shell_pipe", "Downloads piped straight into a shell", "Medium", "Security",
1375
+ "Runs whatever the server sends at that moment, with no checksum: a compromised or spoofed host runs code on "
1376
+ "every machine that runs this.",
1377
+ "Download to a file, check its checksum or signature, then run it; or use a package manager."),
1378
+ ("html_no_sri", "Third-party scripts without integrity hashes", "Medium", "Security",
1379
+ "If the CDN is compromised or the file changes, the page runs the new code with your users' sessions.",
1380
+ "Add `integrity=\"sha384-…\"` and `crossorigin=\"anonymous\"`, or serve the file yourself."),
1381
+ ("html_mixed", "Pages loading scripts, styles or forms over plain HTTP", "Medium", "Security",
1382
+ "Anyone on the network can change them in transit; browsers block most of it on HTTPS pages, so it also breaks.",
1383
+ "Use https:// (or a relative URL)."),
1384
+ ("compose_exposed", "Databases published on every interface (docker-compose)", "Medium", "Security",
1385
+ "`5432:5432` listens on all of the host's addresses, not just this machine: on a server or a laptop on public "
1386
+ "Wi-Fi, the database is reachable by others.",
1387
+ "Bind to localhost (`127.0.0.1:5432:5432`), or don't publish the port and let services talk on the Compose network."),
1388
+ ("compose_privileged", "Privileged containers or the host's network (docker-compose)", "Medium", "Security",
1389
+ "A privileged container (or one on the host network) can reach the host itself: a break-in goes straight through.",
1390
+ "Drop `privileged`/`network_mode: host`; grant only the capabilities it needs (`cap_add`)."),
1391
+ ("k8s_privileged", "Privileged or root containers (Kubernetes)", "Medium", "Security",
1392
+ "A break-in in the container becomes root on the node.",
1393
+ "Set `privileged: false`, `allowPrivilegeEscalation: false`, `runAsNonRoot: true`."),
1394
+ ("k8s_host", "Pods using the node's network, processes or files (Kubernetes)", "Medium", "Security",
1395
+ "hostNetwork, hostPID, hostIPC and hostPath give the pod a view into the node and everything else on it.",
1396
+ "Remove them unless the workload is a node agent that truly needs them."),
1397
+ ("shell_rm_var", "`rm -rf` on a variable that may be empty", "Medium", "Reliability",
1398
+ "If the variable is unset or empty, `rm -rf \"$DIR/\"` deletes from the filesystem root.",
1399
+ "Use `\"${DIR:?}/\"` (fails when empty), or `set -u` at the top of the script."),
1400
+ ("shell_eval", "Shell `eval` of a variable", "Medium", "Security",
1401
+ "Whatever the variable holds is run as shell code: spaces, `;` and `$(…)` in it all execute.",
1402
+ "Call the command directly with its arguments, or use an array."),
1403
+ ("go_server_timeout", "HTTP servers without timeouts (Go)", "Low", "Reliability",
1404
+ "`http.ListenAndServe` and a bare `http.Server` never time out: slow clients hold connections open until the "
1405
+ "server runs out (Slowloris).",
1406
+ "Use an `http.Server` with `ReadHeaderTimeout` (and Read/Write/IdleTimeout)."),
1407
+ ("config_http", "Plain-HTTP URLs in configuration (Pkl, TOML, Terraform…)", "Low", "Security",
1408
+ "Packages, endpoints or registries fetched over HTTP can be swapped in transit.",
1409
+ "Use https://."),
1410
+ ] # fmt: skip
1411
+
1412
+ APPLE_CHECKS = [
1413
+ ("main_thread_io", "Disk or database work on the main thread (Swift)", "Medium", "Performance",
1414
+ "The UI freezes while it runs; long enough and the watchdog kills the app.",
1415
+ "Move it off the main thread (a Task, an actor, a background queue) and update the UI when it's done."),
1416
+ ("swift_retain_cycle", "Possible retain cycles: closures kept by self that capture self strongly", "Medium", "Reliability",
1417
+ "The object and its closure keep each other alive: memory grows, and observers or timers keep firing after the "
1418
+ "screen is gone.",
1419
+ "Capture `[weak self]` (or `[unowned self]` when the lifetime is certain) in closures self keeps."),
1420
+ ("swift_force", "`try!` / `as!` that crash on failure (Swift)", "Low", "Reliability",
1421
+ "An unexpected error or type ends the app instead of being handled.",
1422
+ "Use `try` with `do/catch`, `try?` with a fallback, or `as?` with a guard."),
1423
+ ("entitlement_weakened", "Code-signing protections turned off (entitlements)", "Medium", "Security",
1424
+ "Library validation, executable-memory or debugging protections are off: easier to inject code into the app.",
1425
+ "Remove the entitlement unless a dependency truly needs it, and keep get-task-allow out of release builds."),
1426
+ ] # fmt: skip
1427
+
1428
+ # (check, title, severity, impact, fix) for the configuration, crypto, CI, container, mobile and history checks
1429
+ CONFIG_CHECKS = [
1430
+ ("history_secret", "Credentials in git history (deleted, still leaked)", "High",
1431
+ "Anyone with a clone, a fork or an old CI log has them, even though the current files don't.",
1432
+ "Rotate each one now; rewriting history doesn't help once it has been pushed."),
1433
+ ("ios_usage_missing", "iOS permission used without its usage description", "High",
1434
+ "App Review rejects the app, and iOS terminates it the moment it asks for that permission.",
1435
+ "Add the Info.plist key with a sentence saying why (in Expo: `ios.infoPlist` in app.json, or the library's config "
1436
+ "plugin option)."),
1437
+ ("ios_privacy_manifest", "Required-reason API without a privacy manifest", "High",
1438
+ "Since May 2024 App Store Connect rejects uploads that use these APIs without declaring why.",
1439
+ "Add PrivacyInfo.xcprivacy with NSPrivacyAccessedAPITypes and the approved reason codes (in Expo: "
1440
+ "`ios.privacyManifests` in app.json)."),
1441
+ ("privacy_analytics", "Personal data sent to analytics or crash reporting", "High",
1442
+ "A third party receives it: it needs consent, a privacy-policy entry and App Store privacy labels, and it's hard to "
1443
+ "take back.",
1444
+ "Send an opaque id or a coarse value instead (age band, city), or drop the field."),
1445
+ ("privacy_log", "Personal data written to logs", "Medium",
1446
+ "Logs are copied to consoles, crash reports and log services, kept for long, and readable by more people than the "
1447
+ "data itself.",
1448
+ "Log an id or a redacted value instead (`***@domain`), or nothing."),
1449
+ ("privacy_storage", "Personal data in unencrypted storage", "Medium",
1450
+ "AsyncStorage, localStorage, UserDefaults and SharedPreferences are plain files, included in backups.",
1451
+ "Keep it in the database you protect, or the platform's encrypted store."),
1452
+ ("secret_key_literal", "Signing key written in the code", "High",
1453
+ "Whoever reads the code can forge sessions, tokens or signed links.",
1454
+ "Load it from the environment or a secret store, and rotate the one that was committed."),
1455
+ ("jwt_unverified", "JWT checks turned off", "High",
1456
+ "A token that isn't verified (signature, algorithm or expiry) can be forged or reused.",
1457
+ "Always verify the signature with an explicit algorithm list, and keep expiry checks on."),
1458
+ ("weak_cipher", "Broken encryption mode or cipher (ECB, DES, RC4)", "High",
1459
+ "Patterns in the data survive encryption (ECB), or the cipher can be broken (DES, RC4).",
1460
+ "Use an authenticated mode such as AES-GCM (or a library like libsodium / Fernet)."),
1461
+ ("docker_secret", "Secrets baked into a container image", "High",
1462
+ "Every layer of an image is readable by anyone who can pull it.",
1463
+ "Pass secrets at runtime (environment, mounted secret, build secret), never in ENV/ARG."),
1464
+ ("gha_injection", "Untrusted text run as a shell command in CI", "High",
1465
+ "A PR or issue title or body is pasted into a `run:` script: whoever writes it can run commands with the "
1466
+ "workflow's secrets.",
1467
+ "Pass it through an environment variable (`env: TITLE: ${{ … }}`) and quote it in the script."),
1468
+ ("weak_hash", "MD5 / SHA-1 used for security", "Medium",
1469
+ "Both are broken for passwords and signatures: fast to brute-force, and collisions can be forged.",
1470
+ "Passwords: bcrypt, scrypt or argon2. Signatures and tokens: HMAC-SHA-256 or better."),
1471
+ ("weak_random", "Predictable random numbers for secrets", "Medium",
1472
+ "`random` / `Math.random()` can be predicted from earlier outputs; tokens made with them can be guessed.",
1473
+ "Use `secrets` (Python), `crypto.randomBytes` / `crypto.getRandomValues` (JavaScript)."),
1474
+ ("cors_any", "Any website may call this API (CORS *)", "Medium",
1475
+ "Every site a user visits can read this API's responses in their browser.",
1476
+ "List the origins that need access."),
1477
+ ("insecure_cookie", "Session cookies without Secure / HttpOnly", "Medium",
1478
+ "Cookies can travel over plain HTTP, or be read by injected scripts.",
1479
+ "Set Secure and HttpOnly (and SameSite) on session and auth cookies."),
1480
+ ("debug_on", "Debug mode switched on in code", "Medium",
1481
+ "Debug pages show code, settings and sometimes a console to whoever triggers an error.",
1482
+ "Turn it on from the environment for development only."),
1483
+ ("sensitive_storage", "Tokens or passwords in unencrypted storage", "Medium",
1484
+ "AsyncStorage / localStorage are plain files or readable by any script on the page.",
1485
+ "Use the platform's secure store (Keychain / Keystore via SecureStore, or an HttpOnly cookie on the web)."),
1486
+ ("mobile_cleartext", "App allows unencrypted HTTP", "Medium",
1487
+ "Traffic can be read or changed on public Wi-Fi.",
1488
+ "Remove the exception, or limit it to the hosts that need it."),
1489
+ ("docker_root", "Container runs as root", "Medium",
1490
+ "A break-in through the app gets root inside the container, one step from the host.",
1491
+ "Add a non-root `USER` after installing packages."),
1492
+ ("gha_unpinned", "Third-party CI actions not pinned to a commit", "Low",
1493
+ "A tag can be moved: a compromised action then runs in your CI with its secrets.",
1494
+ "Pin third-party actions to a full commit SHA (keep the tag in a comment)."),
1495
+ ("docker_latest", "Container base image not pinned", "Low",
1496
+ "`latest` or no tag changes under you: builds aren't reproducible and can pick up a bad release.",
1497
+ "Pin a version tag (or a digest)."),
1498
+ ] # fmt: skip
1499
+
1500
+
1501
+ def review_markdown(g: dict, root: Path, for_ai: bool = False, online: bool = False) -> str:
1502
+ r = Review(g, root, online)
1503
+ r.run()
1504
+ return r.markdown(for_ai)