codefactory-cli 0.20.2__py3-none-any.whl → 0.20.3__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.
codefactory/__init__.py CHANGED
@@ -1,3 +1,3 @@
1
1
  """codefactory: see a codebase as a factory floor and find dead code, duplicates, import loops and bottlenecks."""
2
2
 
3
- __version__ = "0.20.2"
3
+ __version__ = "0.20.3"
@@ -18,6 +18,7 @@ from collections import Counter, defaultdict
18
18
  from pathlib import Path
19
19
 
20
20
  from ..graph import Edge, File, Function, Graph, Site
21
+ from ..paths import links_outside
21
22
  from . import parallel
22
23
 
23
24
  # extension -> tree-sitter language. Python and TypeScript/JavaScript have their own analyzers.
@@ -143,8 +144,9 @@ def find_files(root: Path, ignore: list[str], include_js: bool) -> list[tuple[st
143
144
  for name in sorted(filenames):
144
145
  ext = os.path.splitext(name)[1]
145
146
  lang = exts.get(ext) or exts.get(ext.lower())
146
- if lang and not name.endswith((".d.ts", ".min.js")):
147
- out.append((Path(dirpath, name).relative_to(root).as_posix(), lang))
147
+ rel = Path(dirpath, name).relative_to(root).as_posix()
148
+ if lang and not name.endswith((".d.ts", ".min.js")) and not links_outside(root, rel):
149
+ out.append((rel, lang))
148
150
  return out
149
151
 
150
152
 
@@ -11,6 +11,7 @@ from __future__ import annotations
11
11
 
12
12
  import json
13
13
  import os
14
+ import time
14
15
  from collections.abc import Callable
15
16
  from concurrent.futures import ProcessPoolExecutor
16
17
  from pathlib import Path
@@ -28,29 +29,41 @@ def workers() -> int:
28
29
  return max(1, min(32, (os.cpu_count() or 1)))
29
30
 
30
31
 
31
- def _stamp(path: Path) -> str:
32
+ def _stamp(path: Path, now_ns: int = 0) -> str:
33
+ """The file's stamp; "" (never matches) when it changed too recently to trust (see paths.racy)."""
34
+ from ..paths import file_stamp, racy
35
+
32
36
  st = path.stat()
33
- return f"{st.st_size}:{st.st_mtime_ns}"
37
+ return "" if now_ns and racy(st, now_ns) else file_stamp(st)
38
+
34
39
 
40
+ def _cache_file(root: Path, name: str) -> Path | None:
41
+ from ..paths import cache_dir
35
42
 
36
- def _cache_file(root: Path, name: str) -> Path:
37
- return root / ".codefactory" / f"files-{name}.json"
43
+ d = cache_dir(root)
44
+ return d / f"files-{name}.json" if d else None
38
45
 
39
46
 
40
47
  def _load(root: Path, name: str, tool: str) -> dict:
48
+ path = _cache_file(root, name)
49
+ if path is None:
50
+ return {}
41
51
  try:
42
- data = json.loads(_cache_file(root, name).read_text(encoding="utf-8"))
52
+ data = json.loads(path.read_text(encoding="utf-8"))
43
53
  except (OSError, ValueError):
44
54
  return {}
45
55
  return data.get("files", {}) if data.get("tool") == tool else {}
46
56
 
47
57
 
48
58
  def _save(root: Path, name: str, tool: str, files: dict) -> None:
59
+ path = _cache_file(root, name)
60
+ if path is None:
61
+ return # untrusted cache folder
49
62
  try:
50
- d = root / ".codefactory"
63
+ d = path.parent
51
64
  d.mkdir(exist_ok=True)
52
65
  (d / ".gitignore").write_text("# codefactory's cache: never committed\n*\n", encoding="utf-8")
53
- _cache_file(root, name).write_text(json.dumps({"tool": tool, "files": files}), encoding="utf-8")
66
+ path.write_text(json.dumps({"tool": tool, "files": files}), encoding="utf-8")
54
67
  except OSError:
55
68
  pass # a read-only checkout: analyze in full each time
56
69
 
@@ -70,13 +83,14 @@ def run(
70
83
  out: dict[str, dict] = {}
71
84
  stamps: dict[str, str] = {}
72
85
  todo: list[tuple[str, tuple]] = []
86
+ now_ns = time.time_ns()
73
87
  for rel, args in items:
74
88
  try:
75
- stamps[rel] = _stamp(root / rel)
89
+ stamps[rel] = _stamp(root / rel, now_ns)
76
90
  except OSError:
77
91
  continue
78
92
  hit = old.get(rel)
79
- if hit and hit[0] == stamps[rel]:
93
+ if hit and stamps[rel] and hit[0] == stamps[rel]:
80
94
  if hit[1] is not None:
81
95
  out[rel] = hit[1]
82
96
  else:
@@ -12,9 +12,17 @@ const ts = require(tsPath);
12
12
  const ignore = new Set(JSON.parse(ignoreJson || "[]"));
13
13
  const EXT = /\.(tsx?|jsx?|mjs|cjs|mts|cts)$/;
14
14
  const rel = (f) => path.relative(root, f).split(path.sep).join("/");
15
+ const realRoot = fs.realpathSync(root);
16
+ // a link to somewhere outside the repository: not its code (a pull request can commit `a.ts -> ~/.npmrc`)
17
+ const outside = (f) => {
18
+ try {
19
+ const r = path.relative(realRoot, fs.realpathSync(f));
20
+ return r.startsWith("..") || path.isAbsolute(r);
21
+ } catch { return true; }
22
+ };
15
23
  const skipped = (f) => {
16
24
  const parts = rel(f).split("/");
17
- return parts.slice(0, -1).some((p) => ignore.has(p) || (p.startsWith(".") && p !== "." && p !== "..")) || /\.d\.[mc]?ts$|\.min\.[mc]?js$/.test(f) || !EXT.test(f) || rel(f).startsWith("..");
25
+ return parts.slice(0, -1).some((p) => ignore.has(p) || (p.startsWith(".") && p !== "." && p !== "..")) || /\.d\.[mc]?ts$|\.min\.[mc]?js$/.test(f) || !EXT.test(f) || rel(f).startsWith("..") || outside(f);
18
26
  };
19
27
 
20
28
  function walkDir(dir, out) {
@@ -1,8 +1,10 @@
1
1
  """TypeScript / JavaScript analyzer. The parsing and call resolution run in Node (ts_helper.js) with the TypeScript
2
2
  compiler, because only the type checker can tell what `obj.method()` or a function from a React hook really is.
3
3
 
4
- Needs Node on PATH and the `typescript` package: the analyzed repo's own (node_modules/typescript) is used first,
5
- then a global install (npm install -g typescript), or CODEFACTORY_TYPESCRIPT pointing at one.
4
+ Needs Node on PATH and a TypeScript 5.x compiler the user installed: CODEFACTORY_TYPESCRIPT pointing at one, or a
5
+ global install (npm install -g typescript@5). Never the one inside the analyzed repository: its node_modules is the
6
+ repository's code (a pull request could commit one), and codefactory never runs the code it analyzes. The compiler
7
+ only parses and type-checks; module resolution (tsconfig paths, aliases) comes from the project's own files either way.
6
8
  """
7
9
 
8
10
  from __future__ import annotations
@@ -13,6 +15,7 @@ import os
13
15
  import shutil
14
16
  import subprocess
15
17
  import sys
18
+ import time
16
19
  from importlib.resources import files as pkg_files
17
20
  from pathlib import Path
18
21
 
@@ -26,10 +29,15 @@ class TypeScriptUnavailable(RuntimeError):
26
29
 
27
30
 
28
31
  def sources_stamp(root: Path, ignore: list[str]) -> str:
29
- """A fingerprint of every TypeScript/JavaScript file and tsconfig (empty when there are none)."""
32
+ """A fingerprint of every TypeScript/JavaScript file and tsconfig (empty when there are none; "racy" when one
33
+ changed too recently to trust, so the result isn't reused)."""
34
+ from ..paths import file_stamp
35
+ from ..paths import racy as too_recent
36
+
30
37
  skip = set(ignore)
31
38
  h = hashlib.sha1()
32
- found = False
39
+ found = racy = False
40
+ now_ns = time.time_ns()
33
41
  for dirpath, dirnames, filenames in os.walk(root):
34
42
  dirnames[:] = sorted(d for d in dirnames if d not in skip)
35
43
  for f in sorted(filenames):
@@ -39,32 +47,51 @@ def sources_stamp(root: Path, ignore: list[str]) -> str:
39
47
  st = os.stat(os.path.join(dirpath, f))
40
48
  except OSError:
41
49
  continue
42
- h.update(
43
- f"{os.path.relpath(os.path.join(dirpath, f), root)}|{st.st_size}|{st.st_mtime_ns}\n".encode(
44
- "utf-8", "surrogatepass"
45
- )
46
- )
47
- return h.hexdigest() if found else ""
50
+ racy = racy or too_recent(st, now_ns)
51
+ h.update(f"{os.path.relpath(os.path.join(dirpath, f), root)}|{file_stamp(st)}\n".encode("utf-8", "surrogatepass"))
52
+ return ("racy" if racy else h.hexdigest()) if found else ""
53
+
54
+
55
+ def has_api(folder) -> bool:
56
+ """A TypeScript package with the JavaScript compiler API (5.x and earlier). TypeScript 7, the native rewrite, ships
57
+ only an unstable API, so requiring it fails."""
58
+ return (Path(folder) / "lib" / "typescript.js").is_file()
59
+
60
+
61
+ def _outside(folder: Path, root: Path) -> bool:
62
+ """Not inside the analyzed repository (a global install can't be the repository's own code)."""
63
+ try:
64
+ return not folder.resolve().is_relative_to(Path(root).resolve())
65
+ except OSError:
66
+ return False
48
67
 
49
68
 
50
69
  def find_typescript(root: Path, node: str) -> str:
51
70
  env = os.environ.get("CODEFACTORY_TYPESCRIPT")
52
71
  if env:
72
+ if not has_api(env):
73
+ raise TypeScriptUnavailable(f"CODEFACTORY_TYPESCRIPT ({env}) isn't a TypeScript 5.x package (no lib/typescript.js).")
53
74
  return env
54
- local = root / "node_modules" / "typescript"
55
- if (local / "package.json").is_file():
56
- return str(local)
75
+ # a global install: next to node first (no subprocess); then npm, run from the home folder so the analyzed
76
+ # repository's .npmrc (which could set `prefix` to a folder inside it) isn't read
77
+ bin_dir = Path(node).resolve().parent if node else None
78
+ candidates = []
79
+ if bin_dir: # (Linux and macOS: <prefix>/lib/node_modules; Windows: next to node.exe)
80
+ candidates = [bin_dir.parent / "lib" / "node_modules" / "typescript", bin_dir / "node_modules" / "typescript"]
57
81
  try:
58
- npm_root = subprocess.run(
59
- ["npm", "root", "-g"], capture_output=True, text=True, timeout=30, shell=sys.platform == "win32"
60
- ).stdout.strip()
61
- if npm_root and (Path(npm_root) / "typescript" / "package.json").is_file():
62
- return str(Path(npm_root) / "typescript")
63
- except (OSError, subprocess.SubprocessError):
82
+ npm_root = subprocess.run(["npm", "root", "-g"], capture_output=True, text=True, timeout=30, cwd=Path.home(),
83
+ shell=sys.platform == "win32").stdout.strip() # fmt: skip
84
+ if npm_root:
85
+ candidates.append(Path(npm_root) / "typescript")
86
+ except (OSError, subprocess.SubprocessError, RuntimeError): # (RuntimeError: no home folder)
64
87
  pass
88
+ for c in candidates:
89
+ if has_api(c) and _outside(c, root):
90
+ return str(c)
65
91
  raise TypeScriptUnavailable(
66
- "TypeScript files found, but the typescript package isn't installed. Run `npm install` in the repo, "
67
- "or `npm install -g typescript`, or set CODEFACTORY_TYPESCRIPT to its folder."
92
+ "TypeScript files found, but no TypeScript compiler of your own is installed: `npm install -g typescript@5` (or "
93
+ "set CODEFACTORY_TYPESCRIPT to its folder). codefactory never runs the one in the repository's node_modules: "
94
+ "that's the repository's code."
68
95
  )
69
96
 
70
97
 
@@ -76,7 +103,11 @@ def analyze_typescript(root: Path, ignore: list[str], cache: bool = True) -> Gra
76
103
  from .parallel import _tool_hash
77
104
 
78
105
  stamp = f"{stamp}|{_tool_hash()}"
79
- saved = root / ".codefactory" / "typescript.json"
106
+ from ..paths import cache_dir
107
+
108
+ folder = cache_dir(root) if cache and not stamp.startswith("racy") else None # racy: nothing to reuse or keep
109
+ cache = folder is not None
110
+ saved = folder / "typescript.json" if folder else None
80
111
  data = None
81
112
  if cache:
82
113
  try:
codefactory/audit.py CHANGED
@@ -12,8 +12,8 @@ import re
12
12
  import subprocess
13
13
  from pathlib import Path
14
14
 
15
- from .checks import ANY, PATTERNS, PLACEHOLDER, VENDOR_SECRETS, Check, Evidence
16
- from .paths import drop_ignored, is_test, walk
15
+ from .checks import ANY, PATTERNS, PLACEHOLDER, VENDOR_SECRETS, Check, Evidence, redact
16
+ from .paths import drop_ignored, is_test, links_outside, walk
17
17
  from .suppress import MARK
18
18
 
19
19
  # GitHub Actions
@@ -59,6 +59,8 @@ def _excerpt(text: str) -> str:
59
59
  def workflows(root: Path, out: dict[str, Check]) -> None:
60
60
  for path in sorted((root / ".github" / "workflows").glob("*.y*ml")):
61
61
  rel = path.relative_to(root).as_posix()
62
+ if links_outside(root, rel):
63
+ continue
62
64
  try:
63
65
  text = path.read_text(encoding="utf-8", errors="replace")
64
66
  except OSError:
@@ -121,7 +123,7 @@ def dockerfiles(root: Path, files: list[Path], out: dict[str, Check]) -> None:
121
123
  out["docker_latest"].hits.append(Evidence(rel, _line(text, m.start()), f"FROM {image}"))
122
124
  for m in ENV_SECRET.finditer(text):
123
125
  if not re.search(r"\$\{?\w+|changeme|example|<", m.group(0), re.I):
124
- out["docker_secret"].hits.append(Evidence(rel, _line(text, m.start()), _excerpt(m.group(0))))
126
+ out["docker_secret"].hits.append(Evidence(rel, _line(text, m.start()), redact(_excerpt(m.group(0)))))
125
127
 
126
128
 
127
129
  def mobile(root: Path, out: dict[str, Check]) -> None:
@@ -166,6 +168,11 @@ def history(root: Path, current: set[str], out: dict[str, Check], max_lines: int
166
168
  commit, file, seen, read, note = "", "", set(), 0, ""
167
169
  texts: dict[str, str] = {}
168
170
  pats = PATTERNS["secret"]
171
+ import threading
172
+
173
+ watchdog = threading.Timer(timeout, proc.kill) # git stalled or slow: stop it, and say what was read
174
+ watchdog.daemon = True
175
+ watchdog.start()
169
176
  try:
170
177
  for raw in proc.stdout:
171
178
  read += 1
@@ -190,20 +197,31 @@ def history(root: Path, current: set[str], out: dict[str, Check], max_lines: int
190
197
  if value in current or (file, value) in seen or value in _now(root, file, texts):
191
198
  continue # still in the code: the current-files check reports it (or it was marked as intended)
192
199
  seen.add((file, value))
193
- out["history_secret"].hits.append(Evidence(file, 0, f"commit {commit}: {_excerpt(line)}"))
200
+ out["history_secret"].hits.append(Evidence(file, 0, f"commit {commit}: {redact(_excerpt(line))}"))
194
201
  finally:
202
+ timed_out = not watchdog.is_alive() and proc.poll() not in (0, None) and read <= max_lines
203
+ watchdog.cancel()
195
204
  proc.kill()
196
205
  proc.stdout.close()
197
206
  proc.wait(timeout=timeout)
207
+ if timed_out and not note:
208
+ note = f"history read for {timeout} s, then stopped ({read:,} changed lines, the most recent commits)"
198
209
  shallow = subprocess.run(["git", "-C", str(root), "rev-parse", "--is-shallow-repository"], capture_output=True, text=True)
199
210
  if shallow.stdout.strip() == "true":
200
211
  note = (note + "; " if note else "") + "shallow clone: only part of the history was available"
201
212
  return note
202
213
 
203
214
 
204
- def current_secrets(secret_check: Check) -> set[str]:
205
- """The secret values in today's files (history only reports the ones that are gone)."""
206
- return {m.group(0) for e in secret_check.hits for p in PATTERNS["secret"] if (m := p.search(e.text))}
215
+ def current_secrets(secret_check: Check, root: Path | None = None) -> set[str]:
216
+ """The secret values in today's files (history only reports the ones that are gone). Reported text is redacted,
217
+ so the values are read again from each reported line."""
218
+ lines = []
219
+ for e in secret_check.hits:
220
+ try:
221
+ lines.append((root / e.file).read_text(encoding="utf-8", errors="replace").splitlines()[e.line - 1])
222
+ except (OSError, IndexError, TypeError):
223
+ lines.append(e.text)
224
+ return {m.group(0) for line in lines for p in PATTERNS["secret"] if (m := p.search(line))}
207
225
 
208
226
 
209
227
  def find_dockerfiles(root: Path) -> list[Path]:
codefactory/baseline.py CHANGED
@@ -29,10 +29,10 @@ def baseline_path(repo_or_file: Path) -> Path:
29
29
  def write_baseline(graph: dict, path: Path) -> int:
30
30
  fns = {f["id"]: f for f in graph["functions"]}
31
31
  counts = Counter(issue_key(graph, f, fns) for f in graph["flags"])
32
- path.write_text(
33
- json.dumps({"version": 1, "created": date.today().isoformat(), "issues": dict(sorted(counts.items()))}, indent=1) + "\n",
34
- encoding="utf-8",
35
- )
32
+ from .paths import write_file
33
+
34
+ doc = {"version": 1, "created": date.today().isoformat(), "issues": dict(sorted(counts.items()))}
35
+ write_file(path, json.dumps(doc, indent=1) + "\n")
36
36
  return sum(counts.values())
37
37
 
38
38
 
codefactory/cache.py CHANGED
@@ -9,6 +9,7 @@ from __future__ import annotations
9
9
  import hashlib
10
10
  import json
11
11
  import os
12
+ import time
12
13
  from pathlib import Path
13
14
 
14
15
  from . import __version__
@@ -33,7 +34,7 @@ def _parsers() -> str:
33
34
  if node:
34
35
  bin_dir = Path(node).resolve().parent
35
36
  candidates += [str(bin_dir.parent / "lib" / "node_modules" / "typescript"), str(bin_dir / "node_modules" / "typescript")]
36
- ts = next((c for c in candidates if c and (Path(c) / "package.json").is_file()), "")
37
+ ts = next((c for c in candidates if c and (Path(c) / "lib" / "typescript.js").is_file()), "")
37
38
  return f"pack={available()}|node={bool(node)}|ts={ts}"
38
39
 
39
40
 
@@ -51,12 +52,14 @@ def _tool_stamp() -> str:
51
52
  return "\n".join(parts)
52
53
 
53
54
 
54
- def fingerprint(root: Path, ignore: list[str]) -> str:
55
+ def fingerprint(root: Path, ignore: list[str], recent: list | None = None) -> str:
56
+ """Every source file's stamp. `recent` (if given) gets True when a file changed too recently to trust."""
57
+ from .paths import file_stamp, racy
58
+
59
+ now_ns = time.time_ns()
55
60
  skip = set(ignore)
56
61
  h = hashlib.sha1((_tool_stamp() + "\n" + _parsers()).encode("utf-8", "surrogatepass"))
57
62
  source = _source_ext()
58
- local_ts = root / "node_modules" / "typescript" / "package.json" # a project-local compiler appearing counts too
59
- h.update(f"local_ts={local_ts.is_file()}\n".encode())
60
63
  for dirpath, dirnames, filenames in os.walk(root):
61
64
  dirnames[:] = sorted(d for d in dirnames if d not in skip and not d.endswith(".egg-info"))
62
65
  for name in sorted(filenames):
@@ -66,28 +69,46 @@ def fingerprint(root: Path, ignore: list[str]) -> str:
66
69
  st = os.stat(p)
67
70
  except OSError:
68
71
  continue
69
- h.update(f"{os.path.relpath(p, root)}|{st.st_size}|{st.st_mtime_ns}\n".encode("utf-8", "surrogatepass"))
72
+ if recent is not None and not recent and racy(st, now_ns):
73
+ recent.append(True)
74
+ h.update(f"{os.path.relpath(p, root)}|{file_stamp(st)}\n".encode("utf-8", "surrogatepass"))
70
75
  return h.hexdigest()
71
76
 
72
77
 
73
- def _dir(root: Path) -> Path:
74
- return root / ".codefactory"
78
+ def _dir(root: Path) -> Path | None:
79
+ from .paths import cache_dir
80
+
81
+ return cache_dir(root)
75
82
 
76
83
 
77
- def load_cached(root: Path, ignore: list[str]) -> dict | None:
78
- path = _dir(root) / "graph.json"
84
+ def load_cached(root: Path, ignore: list[str], stamp: str | None = None) -> dict | None:
85
+ d = _dir(root)
86
+ if d is None:
87
+ return None
88
+ path = d / "graph.json"
79
89
  try:
80
90
  data = json.loads(path.read_text(encoding="utf-8"))
81
91
  except (OSError, ValueError):
82
92
  return None
83
- return data.get("graph") if data.get("fingerprint") == fingerprint(root, ignore) else None
93
+ return data.get("graph") if data.get("fingerprint") == (stamp or fingerprint(root, ignore)) else None
84
94
 
85
95
 
86
- def save_cache(root: Path, ignore: list[str], graph: dict) -> None:
96
+ def save_cache(root: Path, ignore: list[str], graph: dict, stamp: str | None = None, recent: bool = False) -> None:
97
+ """Keep the graph under `stamp`: the fingerprint taken *before* analysis, so a file edited while it ran makes the
98
+ next run's fingerprint differ instead of being cached as analyzed. `recent`: a file changed in the moments before
99
+ the stamp was taken (see paths.racy): then nothing is kept."""
87
100
  d = _dir(root)
101
+ if d is None:
102
+ return # untrusted cache folder: analyze in full each time
103
+ if stamp is None:
104
+ changed: list = []
105
+ stamp = fingerprint(root, ignore, changed)
106
+ recent = bool(changed)
107
+ if recent:
108
+ return # a same-size edit in the same clock tick would look unchanged
88
109
  try:
89
110
  d.mkdir(exist_ok=True)
90
111
  (d / ".gitignore").write_text("# codefactory's cache: never committed\n*\n", encoding="utf-8")
91
- (d / "graph.json").write_text(json.dumps({"fingerprint": fingerprint(root, ignore), "graph": graph}), encoding="utf-8")
112
+ (d / "graph.json").write_text(json.dumps({"fingerprint": stamp, "graph": graph}), encoding="utf-8")
92
113
  except OSError:
93
114
  pass # read-only checkout: just analyze each time
codefactory/checks.py CHANGED
@@ -16,7 +16,7 @@ from pathlib import Path
16
16
 
17
17
  from .brief import View
18
18
  from .intent import interp_safe, push_skip_explained, safe_names, swallow_intent
19
- from .paths import is_test
19
+ from .paths import is_test, links_outside
20
20
  from .suppress import MARK
21
21
  from .suppress import _parse as parse_mark
22
22
 
@@ -229,6 +229,26 @@ WEAK_CONTEXT_FROM_FUNCTION = ("weak_random", "weak_hash") # a token made in new
229
229
  FUNC_HEADER = re.compile(r"^\s*(?:async\s+)?(?:def|func|function|fun|fn)\s+(\w+)|^\s*(?:export\s+)?(?:public|private|static)\b")
230
230
 
231
231
 
232
+ # the value part of a secret, wherever it's reported (PR comments, SARIF, annotations, the review): enough to find it
233
+ # (its first 4 characters), never enough to use it
234
+ _VENDOR_KEY = re.compile(
235
+ r"\b(?:AKIA[0-9A-Z]{16}|(?:ghp|gho|ghu|ghs)_[A-Za-z0-9]{36}|xox[abpr]-[A-Za-z0-9-]{10,}|sk_live_[A-Za-z0-9]{16,}|"
236
+ r"AIza[0-9A-Za-z_-]{35})"
237
+ )
238
+ _NAMED_VALUE = re.compile(
239
+ r"""(?i)(\b[\w.-]*(?:key|secret|token|passw|pwd|auth|credential|private)[\w.-]*["']?\s*[:=]\s*["']?)"""
240
+ r"""([^\s"',;}]{4})[^\s"',;}]{2,}"""
241
+ )
242
+ _PEM_BODY = re.compile(r"(PRIVATE KEY-----(?:\\r)?(?:\\n)?)[A-Za-z0-9+/=]{8,}")
243
+
244
+
245
+ def redact(text: str) -> str:
246
+ """The text with secret values cut to their first 4 characters: `AKIA…`, `API_KEY = "sk_l…"`."""
247
+ text = _VENDOR_KEY.sub(lambda m: m.group(0)[:4] + "…", text)
248
+ text = _NAMED_VALUE.sub(lambda m: m.group(1) + m.group(2) + "…", text)
249
+ return _PEM_BODY.sub(lambda m: m.group(1) + "…", text)
250
+
251
+
232
252
  def _excerpt(line: str) -> str:
233
253
  t = line.strip()
234
254
  return t if len(t) <= 140 else t[:137] + "…"
@@ -272,7 +292,7 @@ def source_files(root: Path, graph: dict) -> list[str]:
272
292
  for name in filenames:
273
293
  if name.endswith(SRC_EXT) and not name.endswith((".min.js", ".d.ts")):
274
294
  out.add(Path(dirpath, name).relative_to(root).as_posix())
275
- return sorted(out)
295
+ return sorted(f for f in out if not links_outside(root, f))
276
296
 
277
297
 
278
298
  def scan_sources(root: Path, files: list[str]) -> dict[str, Check]:
@@ -352,7 +372,7 @@ def _scan(root: Path, files: list[str]) -> dict[str, Check]:
352
372
  if key == "swallowed" and (why := swallow_intent(line, lines[i - 2] if i > 1 else "")):
353
373
  out["swallowed_ok"].hits.append(Evidence(fid, i, why)) # deliberate: counted, not reported
354
374
  continue
355
- out[key].hits.append(Evidence(fid, i, _excerpt(line)))
375
+ out[key].hits.append(Evidence(fid, i, redact(_excerpt(line)) if key == "secret" else _excerpt(line)))
356
376
  if sql_here and (m := SQL_CALL.search(line)) and hit("sql_built", i):
357
377
  stmt = " ".join(lines[i - 1 : i + 4])
358
378
  if SQL_WORD.search(stmt):
@@ -581,7 +601,10 @@ def scan_repo(root: Path) -> dict:
581
601
  info["env_files"] = [
582
602
  p.name
583
603
  for p in root.glob(".env*")
584
- if p.is_file() and not p.name.endswith((".example", ".sample", ".template", ".dist")) and _holds_secret(p)
604
+ if p.is_file()
605
+ and not p.name.endswith((".example", ".sample", ".template", ".dist"))
606
+ and not links_outside(root, p.name)
607
+ and _holds_secret(p)
585
608
  ]
586
609
  if info["readme"]:
587
610
  t = (root / info["readme"]).read_text(encoding="utf-8", errors="replace").lower()
codefactory/cli.py CHANGED
@@ -16,15 +16,16 @@ from . import __version__
16
16
  from .analyzers import LANGUAGES, analyze
17
17
  from .baseline import baseline_path, compare, read_baseline, write_baseline
18
18
  from .brief import brief_markdown, context_data, context_markdown
19
- from .cache import load_cached, save_cache
19
+ from .cache import fingerprint, load_cached, save_cache
20
20
  from .checks import scan_sources
21
21
  from .config import load_config
22
22
  from .flags import SEVERITY_ORDER, run_flags
23
23
  from .graph import Flag, Graph
24
24
  from .layers import assign_layers
25
+ from .paths import write_file
25
26
  from .plan import make_plan, plan_markdown
26
27
  from .review import review_markdown
27
- from .sarif import build_sarif, github_annotations
28
+ from .sarif import build_sarif, gha_command, github_annotations
28
29
  from .skill import SOURCE as SKILL_SOURCE
29
30
  from .skill import install_hook, install_skill, refresh_skill, skill_outdated, update
30
31
  from .sqlgraph import query_flags, run_query, to_sqlite
@@ -61,13 +62,15 @@ def load_graph(path: Path, languages: list[str] | None = None, cache: bool = Tru
61
62
  raise SystemExit(f"codefactory: {path} is not a folder or a graph .json file")
62
63
  root = path.resolve()
63
64
  ignore = load_config(root).ignore
65
+ stamp, recent = "", []
64
66
  if cache and not languages:
65
- hit = load_cached(root, ignore)
67
+ stamp = fingerprint(root, ignore, recent) # before analysis: what's analyzed is at least this new
68
+ hit = load_cached(root, ignore, stamp)
66
69
  if hit is not None:
67
70
  return hit
68
71
  graph = build(root, languages, cache).to_dict()
69
72
  if cache and not languages:
70
- save_cache(root, ignore, graph)
73
+ save_cache(root, ignore, graph, stamp, bool(recent))
71
74
  return graph
72
75
 
73
76
 
@@ -86,7 +89,7 @@ def _write(path: Path, text: str) -> None:
86
89
  "Pick an existing folder with -o (on Windows, a OneDrive-synced Desktop is under OneDrive\\Desktop)."
87
90
  )
88
91
  try:
89
- path.write_text(text, encoding="utf-8")
92
+ write_file(path, text)
90
93
  except OSError as e:
91
94
  raise SystemExit(f"codefactory: can't save {path}: {e.strerror or e}") from None
92
95
 
@@ -413,7 +416,7 @@ def cmd_diff(a) -> int:
413
416
  elif a.github:
414
417
  for i in result["new"]:
415
418
  kind = {"high": "error", "warn": "warning"}.get(i.severity, "notice")
416
- print(f"::{kind} file={i.file},line={max(1, i.line)},title=codefactory {i.kind}::{i.message}")
419
+ print(gha_command(kind, i.file, max(1, i.line), f"codefactory {i.kind}", i.message))
417
420
  else:
418
421
  print(diff.markdown(result, owners=_owners(root.resolve())), end="")
419
422
  if a.comment:
codefactory/config.py CHANGED
@@ -45,6 +45,11 @@ class Config:
45
45
  profile: dict = field(default_factory=dict) # [profile] corrections to the detected project profile
46
46
 
47
47
 
48
+ NAME = re.compile(r"[A-Za-z0-9_][\w .:/-]{0,79}")
49
+ # catastrophic backtracking's usual shape: a group holding a repeat, repeated itself ((a+)+, (\w*\s?)*, (x{2,})+)
50
+ NESTED = re.compile(r"\((?:[^()\\]|\\.)*(?:[+*]|\{\d*,\d*\})(?:[^()\\]|\\.)*\)(?:[+*]|\{\d*,\d*\})")
51
+
52
+
48
53
  def parse_rule(rule: str) -> tuple[str, str]:
49
54
  left, sep, right = rule.partition("->")
50
55
  if not sep or not left.strip() or not right.strip():
@@ -97,6 +102,8 @@ def load_config(root: Path) -> Config:
97
102
  for q in data.get("queries", []):
98
103
  if not q.get("name") or not q.get("sql"):
99
104
  raise ValueError("Each [[queries]] entry in factory.toml needs a name and sql")
105
+ if not NAME.fullmatch(str(q["name"])): # it becomes a finding kind, shown in pages and comments
106
+ raise ValueError(f"Query name {q['name']!r}: letters, digits, spaces and _ . : / - only (up to 80)")
100
107
  if q.get("severity", "warn") not in ("high", "warn", "info"):
101
108
  raise ValueError(f"Query {q['name']!r}: severity must be high, warn or info")
102
109
  cfg.queries.append({k: q[k] for k in ("name", "sql", "severity", "message") if k in q})
@@ -114,6 +121,11 @@ def load_config(root: Path) -> Config:
114
121
  raise ValueError("Each [[rule]] entry in factory.toml needs an id and a pattern (a regular expression)")
115
122
  if r.get("severity", "warn") not in ("high", "warn", "info"):
116
123
  raise ValueError(f"Rule {r['id']!r}: severity must be high, warn or info")
124
+ if not NAME.fullmatch(str(r["id"])):
125
+ raise ValueError(f"Rule id {r['id']!r}: letters, digits, spaces and _ . : / - only (up to 80)")
126
+ if NESTED.search(str(r["pattern"])): # it runs on every line of every file: a hang would stop every review
127
+ raise ValueError(f"Rule {r['id']!r}: a repeated group that itself repeats, like (a+)+, can take forever on "
128
+ "some lines; write it without the outer repeat") # fmt: skip
117
129
  try:
118
130
  regex = re.compile(r["pattern"])
119
131
  except re.error as e:
@@ -128,10 +140,10 @@ def load_config(root: Path) -> Config:
128
140
 
129
141
 
130
142
  PROFILE_KEYS = {
131
- "kind": ("mobile app", "web app", "web service", "desktop app", "web front-end", "command-line tool",
132
- "data pipeline", "library"),
143
+ "kind": ("mobile app", "web app", "web service", "desktop app", "web front-end", "static website",
144
+ "command-line tool", "data pipeline", "library"),
133
145
  "deployment": ("local-first", "client app", "local server", "LAN server", "network server", "deployed server",
134
- "user's machine", "browser"),
146
+ "user's machine", "browser", "static hosting"),
135
147
  "users": ("single user", "multi-user", "no sign-in"),
136
148
  } # fmt: skip
137
149