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/profile.py ADDED
@@ -0,0 +1,667 @@
1
+ """What kind of project this is, before judging it: the assessment step a security audit starts with.
2
+
3
+ Detected from manifests, the attack surface and the source text, each conclusion with the evidence for it:
4
+
5
+ - kind: mobile app, web app (UI + API), web service, desktop app, web front-end, command-line tool, data pipeline,
6
+ library (and the other roles a repository also plays: a backend with a CLI, an app with scripts)
7
+ - deployment: where it runs and who can reach it: local-first on a device, a client of some backend, a server bound to
8
+ this machine, a LAN, every interface, or deployed (Docker, Vercel, Fly…); a CLI or library on the user's machine
9
+ - users: one person (the device owner, whoever runs it), many accounts with sign-in, or a server with no sign-in found
10
+ - sensitive data: health and fitness, financial, location, contact details, photos and camera, accounts and passwords
11
+
12
+ The review ranks findings with it (`rerank.py`): the same line means different things in a local-first app, a public
13
+ API and a command-line tool. Detection can be wrong, so `[profile]` in factory.toml corrects any part of it.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import json
19
+ import re
20
+ import tomllib
21
+ from dataclasses import dataclass, field
22
+ from pathlib import Path
23
+
24
+ from .paths import NOT_SOURCE, is_test, walk
25
+
26
+ MAX_READ = 400_000 # bytes per file read for sensitive-data detection: past that it's data or generated
27
+ # examples, demos, tests and end-to-end harnesses: they show or check the product, they aren't it
28
+ EXAMPLE_DIR = re.compile(r"(?:^|/)(?:examples?|samples?|demos?|docs?|tests?|e2e|playwright|cypress|fixtures|benchmarks?)/", re.I)
29
+ SKIP_DIRS = {"node_modules", ".git", ".codefactory", ".venv", "venv", "dist", "build", "Pods", ".expo"}
30
+
31
+ # category -> (specific APIs: one use is enough; words: in at least two files; dependencies that mean it on their own).
32
+ # Both are matched on code with comments and strings removed, so prose and patterns about the data don't count.
33
+ SENSITIVE: dict[str, tuple[str, str, tuple[str, ...]]] = {
34
+ "health and fitness": (
35
+ r"\bHealthKit\b|\bHKHealthStore\b|\bHKQuantityType\w*|\bHKWorkout\w*|\bHealthConnect\w*|\bhealth_connect\b",
36
+ r"\bheart_?rate\w*|\bheartRate\w*|\bblood_?(?:pressure|glucose|oxygen)\w*|\bbodyFat\w*|\bbody_?fat\w*|"
37
+ r"\bbody_?weight\w*|\bbodyWeight\w*|\bmenstrua\w*|(?<!Icons\.)\bmedications?\b|\bdiagnos[ie]s\b|"
38
+ r"\bcalories\b|\bworkouts?\b|\bsleep_?(?:stage|score)\w*",
39
+ ("react-native-health", "@kingstinct/react-native-healthkit", "react-native-health-connect", "expo-health"),
40
+ ),
41
+ "financial": (
42
+ r"\bstripe\.\w+|\bStripe\(|\bplaid\w*\.\w+|\bpaymentIntent\w*|\bpayment_intent\w*|\bIBApi\b|\bib_insync\b",
43
+ r"\bbrokerage\w*|\bbuying_?power\b|\baccount_?balance\w*|\bnet_?liquidation\w*|\bcard_?number\b|"
44
+ r"\brouting_?number\b|\biban\b|\bportfolio\w*|\btrades?_?(?:history|log)\b|\bpayees?\b|\bpayeeId\b",
45
+ ("stripe", "@stripe/stripe-js", "@stripe/stripe-react-native", "plaid", "plaid-python", "react-plaid-link",
46
+ "braintree", "paypalrestsdk", "alpaca-trade-api", "alpaca-py", "ib_insync", "ibapi", "robin_stocks",
47
+ "schwab-py", "tda-api", "tastytrade", "ccxt", "coinbase", "yodlee"),
48
+ ),
49
+ "location": (
50
+ r"\bCLLocationManager\b|\bgetCurrentPositionAsync\b|\bwatchPositionAsync\b|navigator\.geolocation|"
51
+ r"\bFusedLocationProvider\w*|\bLocationManager\b",
52
+ r"\buser_?location\w*|\buserLocation\w*|\bcurrent_?position\b|\bcurrentPosition\b",
53
+ ("expo-location", "react-native-geolocation-service", "@react-native-community/geolocation"),
54
+ ),
55
+ "contact details": (
56
+ r"\bCNContactStore\b|\bgetContactsAsync\b|\b(?:email|phone(?:_number)?|first_name|last_name|date_of_birth)\s*"
57
+ r"[:=]\s*(?:models\.\w+Field|Column\(|mapped_column\(|EmailStr|db\.Column)",
58
+ r"\bdate_?of_?birth\b|\bdateOfBirth\b|\bphone_?number\b|\bphoneNumber\b|\bhome_?address\b|\bstreet_?address\b",
59
+ ("expo-contacts", "react-native-contacts"),
60
+ ),
61
+ "photos and camera": (
62
+ r"\bPHPhotoLibrary\b|\bPHPickerViewController\b|\bAVCaptureDevice\b|\blaunchImageLibraryAsync\b|"
63
+ r"\blaunchCameraAsync\b|\bUIImagePickerController\b|\bCameraView\b",
64
+ r"(?!)",
65
+ ("expo-camera", "expo-image-picker", "expo-media-library", "react-native-vision-camera", "react-native-image-picker"),
66
+ ),
67
+ "accounts and passwords": (
68
+ r"\bbcrypt\.\w+|\bargon2\.\w+|\bpasslib\b|\bcheck_password\(|\bset_password\(|\bhash_?password\(|"
69
+ r"\bcreateUserWithEmailAndPassword\b|\bsignInWithPassword\b|\bpbkdf2_hmac\(",
70
+ r"\bpassword_?hash\w*|\bpasswordHash\w*|\bhashed_?password\b",
71
+ ("bcrypt", "bcryptjs", "argon2", "argon2-cffi", "passlib", "next-auth", "@auth/core", "passport",
72
+ "django-allauth", "flask-login", "fastapi-users", "devise", "@clerk/clerk-react", "@clerk/nextjs",
73
+ "firebase-admin", "@supabase/supabase-js", "supabase"),
74
+ ),
75
+ } # fmt: skip
76
+ # generated code and translations: their words are strings for the UI, not data the app handles
77
+ NOT_PRODUCT_TEXT = re.compile(
78
+ r"(?:^|/)(?:i18n|l10n|locales?|translations?|lang|gen|generated)/|\.(?:g|gen|generated|freezed)\.\w+$|"
79
+ r"(?:^|[/_.-])generated[_.-]|strings_\w+\.\w+$",
80
+ re.I,
81
+ )
82
+ # words one of a category's patterns needs (lowercase): a file with none of them can't match, so it isn't searched
83
+ HINTS = { # each a lowercase piece one of the category's patterns can't match without
84
+ "health and fitness": ("health", "hkquantity", "hkworkout", "heart", "blood", "bodyfat", "body_fat", "bodyweight",
85
+ "body_weight", "menstrua", "medication", "diagnos", "calories", "workout", "sleep_stage",
86
+ "sleepstage", "sleep_score", "sleepscore"),
87
+ "financial": ("stripe", "plaid", "paymentintent", "payment_intent", "ibapi", "ib_insync", "brokerage", "buying_power",
88
+ "buyingpower", "account_balance", "accountbalance", "liquidation", "card_number", "cardnumber",
89
+ "routing_number", "routingnumber", "iban", "portfolio", "trade_history", "trades_history", "trade_log",
90
+ "trades_log", "payee"),
91
+ "location": ("cllocationmanager", "getcurrentpositionasync", "watchpositionasync", "geolocation", "fusedlocation",
92
+ "locationmanager", "user_location", "userlocation", "current_position", "currentposition"),
93
+ "contact details": ("cncontact", "getcontactsasync", "email", "phone", "first_name", "last_name", "date_of_birth",
94
+ "dateofbirth", "home_address", "homeaddress", "street_address", "streetaddress"),
95
+ "photos and camera": ("phphotolibrary", "phpicker", "avcapturedevice", "launchimagelibraryasync",
96
+ "launchcameraasync", "uiimagepicker", "cameraview"),
97
+ "accounts and passwords": ("bcrypt", "argon2", "passlib", "pbkdf2", "check_password", "set_password",
98
+ "hash_password", "hashpassword", "password_hash", "passwordhash", "hashed_password",
99
+ "hashedpassword", "createuserwithemailandpassword", "signinwithpassword"),
100
+ } # fmt: skip
101
+ # comments and string literals, removed before looking for words (newlines kept, so line numbers stay right)
102
+ NOT_CODE = re.compile(
103
+ r'"""[\s\S]*?"""|\'\'\'[\s\S]*?\'\'\'|/\*[\s\S]*?\*/|"(?:\\.|[^"\\\n])*"|\'(?:\\.|[^\'\\\n])*\'|`(?:\\.|[^`\\])*`|//[^\n]*|#[^\n]*'
104
+ )
105
+
106
+ AUTH_DEPS = {
107
+ "next-auth", "@auth/core", "passport", "django-allauth", "flask-login", "flask-jwt-extended", "fastapi-users",
108
+ "devise", "@clerk/clerk-react", "@clerk/nextjs", "@clerk/express", "firebase-admin", "@supabase/supabase-js",
109
+ "supabase", "pyjwt", "python-jose", "jsonwebtoken", "jose", "authlib", "djangorestframework-simplejwt",
110
+ } # fmt: skip
111
+ LOCAL_DB = {
112
+ "expo-sqlite": "expo-sqlite", "@op-engineering/op-sqlite": "op-sqlite", "react-native-sqlite-storage": "SQLite",
113
+ "realm": "Realm", "@nozbe/watermelondb": "WatermelonDB", "@react-native-async-storage/async-storage": "AsyncStorage",
114
+ "react-native-mmkv": "MMKV", "dexie": "IndexedDB (Dexie)", "idb": "IndexedDB", "localforage": "localForage",
115
+ "androidx.room": "Room", "room-runtime": "Room", "sqldelight": "SQLDelight", "app.cash.sqldelight": "SQLDelight",
116
+ "realm-kotlin": "Realm", "io.realm.kotlin": "Realm", "objectbox": "ObjectBox", "sqflite": "sqflite", "hive": "Hive",
117
+ "isar": "Isar", "drift": "Drift",
118
+ } # fmt: skip
119
+ TEMPLATING = {
120
+ "spring-boot-starter-thymeleaf", "thymeleaf", "jinja2", "django", "rails", "actionview", "ejs", "pug", "handlebars",
121
+ "express-handlebars", "nunjucks", "freemarker", "twig", "spring-boot-starter-freemarker", "htmx",
122
+ "laravel/framework", "symfony/twig-bundle", "inertiajs/inertia-laravel", "phoenix_live_view", "phoenix_html",
123
+ "rocket_dyn_templates", "askama", "tera", "microsoft.aspnetcore.components.web",
124
+ } # fmt: skip
125
+ WEB_UI = {"react", "vue", "svelte", "@angular/core", "solid-js", "preact", "next", "nuxt", "@sveltejs/kit", "astro"}
126
+ DESKTOP = {"electron": "Electron", "@tauri-apps/api": "Tauri", "pyqt5": "PyQt", "pyqt6": "PyQt", "pyside6": "PySide",
127
+ "wxpython": "wxPython", "kivy": "Kivy"} # fmt: skip
128
+ PIPELINE = {
129
+ "pandas", "polars", "duckdb", "pyspark", "apache-airflow", "dagster", "prefect", "dbt-core", "luigi",
130
+ "great-expectations", "torch", "tensorflow", "jax", "scikit-learn", "xgboost", "lightgbm",
131
+ } # fmt: skip
132
+ CLI_LIBS = {"click", "typer", "fire", "docopt", "commander", "yargs", "oclif", "@oclif/core", "cac", "meow"}
133
+ WORKSPACES = {"packages", "apps", "services", "libs", "modules", "projects", "crates", "plugins"}
134
+ # what a deploy job runs: a cloud CLI or action, not just the word "deploy"
135
+ DEPLOY_ACTIONS = (
136
+ r"aws-actions|google-github-actions|azure/|flyctl|vercel|netlify|wrangler|railway|kubectl|helm |docker push|heroku"
137
+ )
138
+ DEPLOY_FILES = {
139
+ "Dockerfile": "Docker", "docker-compose.yml": "Docker Compose", "compose.yaml": "Docker Compose",
140
+ "vercel.json": "Vercel", "netlify.toml": "Netlify", "fly.toml": "Fly.io", "render.yaml": "Render",
141
+ "Procfile": "Heroku-style Procfile", "app.yaml": "Google App Engine", "serverless.yml": "Serverless",
142
+ "railway.json": "Railway", "wrangler.toml": "Cloudflare Workers", "template.yaml": "AWS SAM",
143
+ } # fmt: skip
144
+
145
+
146
+ @dataclass
147
+ class Profile:
148
+ kind: str = "unknown"
149
+ kind_evidence: list[str] = field(default_factory=list)
150
+ also: list[str] = field(default_factory=list) # other roles the repository plays
151
+ deployment: str = "unknown"
152
+ deployment_evidence: list[str] = field(default_factory=list)
153
+ users: str = "unknown"
154
+ users_evidence: list[str] = field(default_factory=list)
155
+ sensitive: dict[str, list[str]] = field(default_factory=dict) # category -> evidence (file:line text, or a dependency)
156
+ endpoints: int = 0
157
+ open_writes: int = 0
158
+ stores: list[str] = field(default_factory=list)
159
+ corrected: list[str] = field(default_factory=list) # what factory.toml's [profile] overrode
160
+
161
+ @property
162
+ def local_first(self) -> bool:
163
+ return self.deployment == "local-first"
164
+
165
+ @property
166
+ def single_user(self) -> bool:
167
+ return self.users == "single user"
168
+
169
+ @property
170
+ def server(self) -> bool:
171
+ return self.deployment in ("local server", "LAN server", "network server", "deployed server") or self.endpoints > 0
172
+
173
+ @property
174
+ def reachable_by_others(self) -> bool:
175
+ """Someone other than the person running it can send it requests."""
176
+ return self.deployment in ("LAN server", "network server", "deployed server")
177
+
178
+ def summary(self) -> str:
179
+ """One line: "a mobile app, local-first, single user, holding health and fitness data"."""
180
+ parts = [self.kind if self.kind != "unknown" else "a codebase of unknown kind"]
181
+ if self.deployment != "unknown":
182
+ parts.append(self.deployment)
183
+ if self.users != "unknown":
184
+ parts.append(self.users)
185
+ text = ", ".join(parts)
186
+ if self.sensitive:
187
+ text += f", holding {_join(list(self.sensitive))} data"
188
+ article = "an" if text[:1].lower() in "aeiou" else "a"
189
+ return f"{article} {text}" if not text.startswith(("a ", "an ")) else text
190
+
191
+ def to_dict(self) -> dict:
192
+ return {
193
+ "kind": self.kind, "kind_evidence": self.kind_evidence, "also": self.also, "deployment": self.deployment,
194
+ "deployment_evidence": self.deployment_evidence, "users": self.users, "users_evidence": self.users_evidence,
195
+ "sensitive": self.sensitive, "endpoints": self.endpoints, "open_writes": self.open_writes,
196
+ "stores": self.stores, "corrected": self.corrected, "summary": self.summary(),
197
+ } # fmt: skip
198
+
199
+
200
+ def _join(items: list[str]) -> str:
201
+ return items[0] if len(items) == 1 else ", ".join(items[:-1]) + " and " + items[-1]
202
+
203
+
204
+ # ---- manifests -----------------------------------------------------------------------------------------------------
205
+
206
+
207
+ def _manifests(root: Path) -> dict:
208
+ """Dependencies and entry points from every manifest at the root, one folder down, and inside workspace folders
209
+ (`packages/*`, `apps/*`, `services/*`…, where monorepos keep their parts)."""
210
+ out: dict = {"deps": {}, "npm_bin": [], "py_scripts": [], "go_main": [], "rust_bin": False, "flutter": False,
211
+ "pkg_main": [], "py_lib": False, "files": set(), "lib": [], "cli": [], "android": [],
212
+ "swift_lib": False} # fmt: skip
213
+ top = [p for p in sorted(root.iterdir()) if p.is_dir() and p.name not in SKIP_DIRS and not p.name.startswith(".")
214
+ and not EXAMPLE_DIR.search(p.name + "/")] # fmt: skip
215
+ nested = [c for d in top if d.name in WORKSPACES for c in sorted(d.iterdir()) if c.is_dir() and c.name not in SKIP_DIRS]
216
+ for d in [root, *top, *nested[:60]]:
217
+ rel = "" if d == root else d.relative_to(root).as_posix() + "/"
218
+ pkg = d / "package.json"
219
+ if pkg.is_file():
220
+ try:
221
+ data = json.loads(pkg.read_text(encoding="utf-8"))
222
+ except (ValueError, OSError):
223
+ data = {}
224
+ for name in {**data.get("dependencies", {}), **data.get("peerDependencies", {})}:
225
+ out["deps"].setdefault(name, f"{rel}package.json")
226
+ for name in data.get("devDependencies", {}):
227
+ out["deps"].setdefault(name, f"{rel}package.json (dev)")
228
+ if data.get("bin"):
229
+ out["npm_bin"].append(f"{rel}package.json bin")
230
+ if data.get("main") or data.get("exports") or data.get("module"):
231
+ out["pkg_main"].append(f"{rel}package.json")
232
+ py = d / "pyproject.toml"
233
+ if py.is_file():
234
+ try:
235
+ data = tomllib.loads(py.read_text(encoding="utf-8"))
236
+ except (tomllib.TOMLDecodeError, OSError):
237
+ data = {}
238
+ project = data.get("project", {})
239
+ for dep in project.get("dependencies", []):
240
+ out["deps"].setdefault(re.split(r"[\s<>=!~\[;@(]", dep, maxsplit=1)[0].lower(), f"{rel}pyproject.toml")
241
+ for dep in data.get("tool", {}).get("poetry", {}).get("dependencies", {}) or {}:
242
+ out["deps"].setdefault(dep.lower(), f"{rel}pyproject.toml")
243
+ scripts = {**project.get("scripts", {}), **(data.get("tool", {}).get("poetry", {}).get("scripts", {}) or {})}
244
+ out["py_scripts"] += [f"{rel}pyproject.toml [project.scripts] {name}" for name in list(scripts)[:3]]
245
+ out["py_lib"] = out["py_lib"] or bool(project.get("name"))
246
+ for setup in ("setup.cfg", "setup.py"): # older Python packaging: console_scripts entry points
247
+ if (d / setup).is_file() and re.search(r"console_scripts", (d / setup).read_text(encoding="utf-8", errors="replace")):
248
+ out["py_scripts"].append(f"{rel}{setup} console_scripts")
249
+ out["py_lib"] = True
250
+ for req in sorted(d.glob("requirements*.txt")):
251
+ for line in req.read_text(encoding="utf-8", errors="replace").splitlines():
252
+ s = line.split("#")[0].strip()
253
+ if s and not s.startswith("-"):
254
+ out["deps"].setdefault(re.split(r"[\s<>=!~\[;@]", s, maxsplit=1)[0].lower(), f"{rel}{req.name}")
255
+ if (d / "pubspec.yaml").is_file() and "flutter" in (d / "pubspec.yaml").read_text(encoding="utf-8", errors="replace"):
256
+ out["flutter"] = True
257
+ if (d / "Cargo.toml").is_file():
258
+ cargo = (d / "Cargo.toml").read_text(encoding="utf-8", errors="replace")
259
+ out["rust_bin"] = out["rust_bin"] or "[[bin]]" in cargo or (d / "src" / "main.rs").is_file()
260
+ for dep in re.findall(r"^([\w-]+)\s*=", cargo.split("[dependencies]", 1)[-1], re.M):
261
+ out["deps"].setdefault(dep, f"{rel}Cargo.toml")
262
+ if (d / "go.mod").is_file():
263
+ for dep in re.findall(
264
+ r"^\s*([\w./-]+)\s+v[\d.]+", (d / "go.mod").read_text(encoding="utf-8", errors="replace"), re.M
265
+ ):
266
+ out["deps"].setdefault(dep.split("/")[-1].lower(), f"{rel}go.mod")
267
+ _other_manifests(d, rel, out)
268
+ for name in DEPLOY_FILES:
269
+ if (d / name).is_file():
270
+ out["files"].add(f"{rel}{name}")
271
+ for docker in sorted([*d.glob("Dockerfile.*"), *d.glob("docker/Dockerfile*")])[:1]: # Dockerfile.alpine, docker/
272
+ out["files"].add(docker.relative_to(root).as_posix())
273
+ catalog = root / "gradle" / "libs.versions.toml" # Gradle version catalogs: where Android projects list libraries
274
+ if catalog.is_file():
275
+ text = catalog.read_text(encoding="utf-8", errors="replace")
276
+ for group, name in re.findall(r'group\s*=\s*"([\w.-]+)"\s*,\s*name\s*=\s*"([\w.-]+)"', text) + re.findall(
277
+ r'module\s*=\s*"([\w.-]+):([\w.-]+)"', text
278
+ ):
279
+ out["deps"].setdefault(name.lower(), "gradle/libs.versions.toml")
280
+ out["deps"].setdefault(group.lower(), "gradle/libs.versions.toml")
281
+ for p in (root / ".github" / "workflows").glob("*.y*ml"):
282
+ text = p.read_text(encoding="utf-8", errors="replace")
283
+ if re.search(r"docs|pages|site|storybook|book", p.stem, re.I) or "actions/deploy-pages" in text:
284
+ continue # publishes documentation, not the product
285
+ if (
286
+ re.search(r"deploy|release|prod|publish", p.stem, re.I)
287
+ and re.search(DEPLOY_ACTIONS, text, re.I)
288
+ or re.search(
289
+ r"aws-actions/amazon-ecs-deploy|google-github-actions/deploy|azure/webapps-deploy|superfly/flyctl|"
290
+ r"amondnet/vercel-action|netlify/actions|cloudflare/wrangler-action|railwayapp|kubectl apply|helm upgrade",
291
+ text,
292
+ re.I,
293
+ )
294
+ ):
295
+ out["files"].add(f".github/workflows/{p.name} (deploys)")
296
+ return out
297
+
298
+
299
+ def _other_manifests(d: Path, rel: str, out: dict) -> None:
300
+ """Maven, Gradle, RubyGems/Bundler, Composer and .NET: dependencies, and whether it builds an app or a library."""
301
+ read = lambda p: p.read_text(encoding="utf-8", errors="replace") # noqa: E731
302
+ if (d / "pom.xml").is_file():
303
+ pom = read(d / "pom.xml")
304
+ for dep in re.findall(r"<artifactId>([\w.-]+)</artifactId>", pom)[1:]:
305
+ out["deps"].setdefault(dep.lower(), f"{rel}pom.xml")
306
+ if not re.search(r"spring-boot-maven-plugin|<mainClass>|maven-shade-plugin|<packaging>war", pom):
307
+ out["lib"].append(f"{rel}pom.xml (a jar with no main class)")
308
+ elif "<mainClass>" in pom and "spring-boot" not in pom:
309
+ out["cli"].append(f"{rel}pom.xml mainClass")
310
+ for name in ("build.gradle", "build.gradle.kts"):
311
+ if (d / name).is_file():
312
+ gradle = read(d / name)
313
+ for dep in re.findall(r"""['"]([\w.-]+):([\w.-]+):[^'"]*['"]""", gradle):
314
+ out["deps"].setdefault(dep[1].lower(), f"{rel}{name}")
315
+ if re.search(r"com\.android\.application|\bandroid\.application\b", gradle):
316
+ out["android"].append(f"{rel}{name} (com.android.application)")
317
+ elif re.search(r"\bapplication\b\s*(?:\{|$)|mainClass|id\(?\s*['\"]application", gradle, re.M):
318
+ out["cli"].append(f"{rel}{name} application")
319
+ elif re.search(r"java-library|com\.android\.library|`java-library`|kotlin\(\"jvm\"\)|maven-publish", gradle):
320
+ out["lib"].append(f"{rel}{name} (a library build)")
321
+ gemspecs = sorted(d.glob("*.gemspec"))
322
+ if gemspecs:
323
+ spec = read(gemspecs[0])
324
+ (out["cli"] if re.search(r"\.executables\s*=|bindir", spec) else out["lib"]).append(f"{rel}{gemspecs[0].name}")
325
+ if (d / "Gemfile").is_file():
326
+ for dep in re.findall(r"^\s*gem\s+['\"]([\w-]+)", read(d / "Gemfile"), re.M):
327
+ out["deps"].setdefault(dep.lower(), f"{rel}Gemfile")
328
+ if (d / "composer.json").is_file():
329
+ try:
330
+ data = json.loads(read(d / "composer.json"))
331
+ except ValueError:
332
+ data = {}
333
+ for dep in data.get("require", {}):
334
+ out["deps"].setdefault(dep.lower(), f"{rel}composer.json") # the full name: "laravel/framework"
335
+ out["deps"].setdefault(dep.split("/")[-1].lower(), f"{rel}composer.json")
336
+ if data.get("type") == "library":
337
+ out["lib"].append(f"{rel}composer.json (type library)")
338
+ if data.get("bin"):
339
+ out["cli"].append(f"{rel}composer.json bin")
340
+ if (d / "mix.exs").is_file(): # Elixir: {:phoenix, "~> 1.7"}
341
+ for dep in re.findall(r"\{:(\w+),", read(d / "mix.exs")):
342
+ out["deps"].setdefault(dep, f"{rel}mix.exs")
343
+ if (d / "Package.swift").is_file() and re.search(r"\.library\(", read(d / "Package.swift")):
344
+ out["lib"].append(f"{rel}Package.swift (.library product)")
345
+ out["swift_lib"] = True
346
+ for csproj in sorted(d.glob("*.csproj"))[:3]:
347
+ text = read(csproj)
348
+ if "<OutputType>Exe" in text and "Sdk.Web" not in text:
349
+ out["cli"].append(f"{rel}{csproj.name} (Exe)")
350
+ elif "Sdk.Web" not in text and "<OutputType>WinExe" not in text:
351
+ out["lib"].append(f"{rel}{csproj.name} (a class library)")
352
+ for dep in re.findall(r'PackageReference Include="([\w.-]+)"', text):
353
+ out["deps"].setdefault(dep.lower(), f"{rel}{csproj.name}")
354
+
355
+
356
+ # ---- detection -----------------------------------------------------------------------------------------------------
357
+
358
+
359
+ def _source(root: Path, files: list[str]) -> dict[str, str]:
360
+ out = {}
361
+ for fid in files:
362
+ if is_test(fid):
363
+ continue
364
+ try:
365
+ with open(root / fid, "rb") as fh:
366
+ out[fid] = fh.read(MAX_READ).decode("utf-8", errors="replace")
367
+ except OSError:
368
+ continue
369
+ return out
370
+
371
+
372
+ def _swift_files(root: Path, files: list[str]) -> list[str]:
373
+ """Swift files: from the graph, or from disk when Swift wasn't analyzed (no language pack installed)."""
374
+ found = [f for f in files if f.endswith(".swift")]
375
+ if found:
376
+ return found
377
+ out = []
378
+ for rel in walk(root, suffixes=(".swift",), skip=SKIP_DIRS | NOT_SOURCE):
379
+ out.append(rel)
380
+ if len(out) >= 200:
381
+ break
382
+ return sorted(out)
383
+
384
+
385
+ def _head(root: Path, rel: str, size: int = 4000) -> str:
386
+ try:
387
+ with open(root / rel, "rb") as fh:
388
+ return fh.read(size).decode("utf-8", errors="replace")
389
+ except OSError:
390
+ return ""
391
+
392
+
393
+ # contact fields declared in a schema, where their names are strings (Rails schema.rb, SQL, Prisma)
394
+ SCHEMA_CONTACT = re.compile(
395
+ r"""t\.(?:string|citext|text)\s+["'](?:email|phone(?:_number)?|first_name|last_name|date_of_birth|address)["']|"""
396
+ r"CREATE TABLE[^;]{0,800}?\b(?:email|phone(?:_number)?|first_name|last_name|date_of_birth)\b|"
397
+ r"^\s*(?:email|phone|phoneNumber|firstName|lastName|dateOfBirth)\s+String\b|"
398
+ r"\$table->(?:string|text|date|char)\(\s*['\"](?:email|phone(?:_number)?|first_name|last_name|birthdate|"
399
+ r"date_of_birth|address|street|postal_code)['\"]",
400
+ re.I | re.M,
401
+ )
402
+
403
+
404
+ def _schema_contact(root: Path, texts: dict[str, str]) -> list[str]:
405
+ files = [f for f in texts if re.search(r"(?:^|/)(?:schema\.rb|structure\.sql)$|(?:^|/)migrations?/", f)][:400]
406
+ extra = []
407
+ for pattern in (
408
+ "**/schema.prisma",
409
+ "db/*.sql",
410
+ "**/migrations/*.sql",
411
+ "schema.sql",
412
+ "db/schema.rb",
413
+ "*/db/schema.rb",
414
+ "database/migrations/*.php",
415
+ "priv/repo/migrations/*.exs",
416
+ ):
417
+ extra += [p_.relative_to(root).as_posix() for p_ in root.glob(pattern) if not SKIP_DIRS & set(p_.relative_to(root).parts)]
418
+ for fid in files + sorted(set(extra))[:40]:
419
+ text = texts.get(fid) or _head(root, fid, MAX_READ)
420
+ if m := SCHEMA_CONTACT.search(text):
421
+ line_no = text.count("\n", 0, m.start()) + 1
422
+ return [f"`{fid}:{line_no}` {text.splitlines()[line_no - 1].strip()[:100]}"]
423
+ return []
424
+
425
+
426
+ def code_only(text: str) -> str:
427
+ """The text without comments and string literals, line numbers unchanged."""
428
+ return NOT_CODE.sub(lambda m: "\n" * m.group(0).count("\n"), text)
429
+
430
+
431
+ def _first(texts: dict[str, str], code: dict[str, str], pattern: str, min_files: int = 1, limit: int = 3) -> list[str]:
432
+ """`file:line` and the line where the pattern occurs in code (one per file), if it does in at least `min_files`."""
433
+ rx = re.compile(pattern)
434
+ hits = []
435
+ for fid, text in code.items():
436
+ if (m := rx.search(text)) is not None:
437
+ line_no = text.count("\n", 0, m.start()) + 1
438
+ lines = texts[fid].splitlines()
439
+ hits.append(f"`{fid}:{line_no}` {lines[line_no - 1].strip()[:100] if line_no <= len(lines) else ''}")
440
+ return hits[:limit] if len(hits) >= min_files else []
441
+
442
+
443
+ def detect(root: Path, g: dict, surface=None, config: dict | None = None, sources: list[str] | None = None) -> Profile:
444
+ """The profile of the repository at `root` (graph `g`; the attack surface if already computed)."""
445
+ if surface is None:
446
+ from .brief import View
447
+ from .security import surface as find_surface
448
+
449
+ surface = find_surface(root, g, View(g))
450
+ m = _manifests(root)
451
+ deps = m["deps"]
452
+ from .checks import source_files
453
+
454
+ files = sources if sources is not None else source_files(root, g) # parsed or not: no parser needed
455
+ texts = _source(root, files)
456
+ p = Profile()
457
+ p.open_writes = 0
458
+ has = lambda *names: [n for n in names if n in deps] # noqa: E731
459
+
460
+ # what it is
461
+ roles: list[tuple[str, list[str]]] = []
462
+ # endpoints in top-level examples, docs or benchmarks show what a library can do, not what this project serves
463
+ # (only near the top: `org/springframework/samples/petclinic` is a Java package, not an examples folder)
464
+ endpoints = [
465
+ e for e in surface.entries if not re.match(r"(?:[^/]+/)?(?:examples?|samples?|demos?|docs?|benchmarks?)/", e.file)
466
+ ]
467
+ wrapped_mobile: list[str] = []
468
+ mobile = has("expo", "react-native") or (["pubspec.yaml (Flutter)"] if m["flutter"] else [])
469
+ if not mobile:
470
+ apple = [
471
+ f
472
+ for f in _swift_files(root, files)
473
+ if not EXAMPLE_DIR.search(f) and re.search(r"\bimport (?:SwiftUI|UIKit)\b", texts.get(f) or _head(root, f))
474
+ ]
475
+ android = [rel for rel in walk(root, names=("AndroidManifest.xml",), skip=SKIP_DIRS | NOT_SOURCE)
476
+ if not EXAMPLE_DIR.search(rel)][:1] # fmt: skip
477
+ mobile = [f"{apple[0]} (SwiftUI/UIKit)"] if apple else (m["android"] or android)
478
+ wrapper = has("@capacitor/core", "@capacitor/ios", "cordova", "@ionic/core")
479
+ if mobile and (wrapper or (has(*WEB_UI) and len(apple) < 10) or len(endpoints) >= 5 or m["swift_lib"]):
480
+ wrapped_mobile = mobile # a web app's native shell, a server project's client, or a Swift package's demo
481
+ mobile = []
482
+ if mobile:
483
+ roles.append(("mobile app", [f"{x} in {deps[x]}" if x in deps else x for x in mobile]))
484
+ web_ui = [f"{d} in {deps[d]}" for d in has(*WEB_UI)]
485
+ templates = [f"{d} in {deps[d]} (server-rendered pages)" for d in has(*TEMPLATING)]
486
+ frameworks = sorted({e.framework for e in endpoints})
487
+ if endpoints and (web_ui or templates) and not mobile:
488
+ roles.append(("web app", [f"{len(endpoints)} HTTP endpoints ({', '.join(frameworks)})", (web_ui or templates)[0]]))
489
+ elif endpoints:
490
+ roles.append(("web service", [f"{len(endpoints)} HTTP endpoints ({', '.join(frameworks)})"]))
491
+ desktop = has(*DESKTOP)
492
+ if desktop:
493
+ roles.append(("desktop app", [f"{d} in {deps[d]}" for d in desktop[:2]]))
494
+ if web_ui and not endpoints and not mobile and not desktop:
495
+ roles.append(("web front-end", web_ui[:1]))
496
+ cli = m["py_scripts"] + m["npm_bin"] + m["cli"] + [f"{c} in {deps[c]}" for c in has(*CLI_LIBS)]
497
+ if m["rust_bin"] and has("clap", "structopt", "argh"):
498
+ cli.append("Rust binary with clap")
499
+ go_main = [f for f in files if f.endswith(".go") and re.search(r"^package main\b", texts.get(f, ""), re.M)]
500
+ if go_main and not endpoints:
501
+ cli.append(f"`{go_main[0]}` package main")
502
+ argparse = [
503
+ f for f in files if f.endswith(".py") and "argparse.ArgumentParser" in texts.get(f, "") and "__main__" in texts.get(f, "")
504
+ ]
505
+ if argparse and not cli:
506
+ cli.append(f"`{argparse[0]}` argparse")
507
+ if cli:
508
+ roles.append(("command-line tool", cli[:2]))
509
+ pipeline = has(*PIPELINE)
510
+ if pipeline and len(endpoints) <= 5 and not mobile and not web_ui:
511
+ role = ("data pipeline", [f"{x} in {deps[x]}" for x in pipeline[:3]])
512
+ # a few endpoints (an internal tool, a status page) don't make a pipeline repository a web service
513
+ roles.insert(0, role) if roles and roles[0][0] == "web service" else roles.append(role)
514
+ if (
515
+ not roles
516
+ and not m["lib"]
517
+ and not m["py_lib"]
518
+ and not m["pkg_main"]
519
+ and not any(
520
+ (root / x).is_file() for x in ("package.json", "pyproject.toml", "setup.py", "Cargo.toml", "go.mod", "pom.xml")
521
+ )
522
+ ):
523
+ ml = [f for f in files if f.endswith(".py") and re.search(r"^\s*(?:import|from)\s+(?:torch|tensorflow|jax|pandas|polars|"
524
+ r"sklearn|numpy)\b", texts.get(f, ""), re.M) and "__main__" in texts.get(f, "")] # fmt: skip
525
+ if ml: # no manifest at all: scripts that train or transform data
526
+ roles.append(("data pipeline", [f"`{ml[0]}` imports a data or ML library and runs as a script"]))
527
+ if not roles and (m["lib"] or m["py_lib"] or m["pkg_main"] or (not m["rust_bin"] and (root / "Cargo.toml").is_file())):
528
+ roles.append(("library", (m["lib"] + m["pkg_main"])[:1] or ["a package manifest and no app or entry point"]))
529
+ p.endpoints = len(endpoints)
530
+ if wrapped_mobile:
531
+ roles.append(("mobile app", [f"{wrapped_mobile[0]}, a client of the rest"]))
532
+ if roles:
533
+ p.kind, p.kind_evidence = roles[0]
534
+ p.also = [r for r, _ in roles[1:] if r != p.kind]
535
+
536
+ # what it keeps
537
+ p.stores = list(dict.fromkeys(name for dep, name in LOCAL_DB.items() if dep in deps))
538
+ native_db = [
539
+ f
540
+ for f in files
541
+ if f.endswith(".swift") and re.search(r"\b(?:import CoreData|import SwiftData|@Model\b)", texts.get(f, ""))
542
+ ]
543
+ if native_db:
544
+ p.stores.append("Core Data / SwiftData")
545
+ if "Room" not in p.stores and any(
546
+ f.endswith((".kt", ".java")) and re.search(r"@Database\s*\(|\bRoomDatabase\b", texts.get(f, "")) for f in files
547
+ ):
548
+ p.stores.append("Room")
549
+
550
+ # where it runs, who reaches it
551
+ deployed = sorted(m["files"])
552
+ # the main role decides where it runs: an app's (or a tool's) own small server is a part of it, not what it is
553
+ side_server = (p.kind in ("data pipeline", "command-line tool", "library") and len(endpoints) <= 5) or p.kind in (
554
+ "mobile app",
555
+ "desktop app",
556
+ )
557
+ if (endpoints and not side_server) or (deployed and p.kind in ("web app", "web service")):
558
+ if deployed:
559
+ p.deployment = "deployed server"
560
+ p.deployment_evidence = [
561
+ f"{x} ({DEPLOY_FILES.get(x.split('/')[-1], 'Docker' if 'Dockerfile' in x else 'CI deploy')})"
562
+ for x in deployed[:3]
563
+ ]
564
+ else:
565
+ p.deployment = {"local": "local server", "configurable": "LAN server", "open": "network server"}.get(
566
+ surface.exposure, "network server"
567
+ )
568
+ p.deployment_evidence = [surface.exposure_evidence or "HTTP endpoints, and nothing says where it listens"]
569
+ elif p.kind == "mobile app":
570
+ if p.stores:
571
+ p.deployment = "local-first"
572
+ p.deployment_evidence = [f"data kept on the device ({', '.join(p.stores)}), no server in the repository"]
573
+ else:
574
+ p.deployment = "client app"
575
+ p.deployment_evidence = ["no local database and no server in the repository (online features, if any, use "
576
+ "a service elsewhere)"] # fmt: skip
577
+ elif p.kind in ("command-line tool", "library", "data pipeline", "desktop app"):
578
+ p.deployment = "user's machine"
579
+ p.deployment_evidence = [f"a {p.kind}: runs where it's installed"]
580
+ elif p.kind == "web front-end":
581
+ p.deployment = "browser"
582
+ p.deployment_evidence = ["a front-end with no API of its own in the repository"]
583
+
584
+ auth_deps = sorted(AUTH_DEPS & set(deps))
585
+ guarded = [e for e in endpoints if e.auth]
586
+ if auth_deps or guarded:
587
+ p.users = "multi-user"
588
+ p.users_evidence = ([f"{auth_deps[0]} in {deps[auth_deps[0]]}"] if auth_deps else []) + (
589
+ [f"{len(guarded)} of {len(endpoints)} endpoints check who's asking"] if guarded else []
590
+ )
591
+ elif endpoints and not side_server:
592
+ p.users = "no sign-in"
593
+ p.users_evidence = ["no endpoint checks who's asking, and no sign-in library"]
594
+ elif p.kind in ("mobile app", "desktop app") or p.deployment == "local-first":
595
+ p.users = "single user"
596
+ p.users_evidence = ["no sign-in or accounts: whoever holds the device"]
597
+ elif p.kind in ("command-line tool", "library", "data pipeline"):
598
+ p.users = "single user"
599
+ p.users_evidence = ["whoever runs it"]
600
+
601
+ # what it holds
602
+ # cheap first: a file gets the regexes (and has its comments and strings removed) only if its lowercased text
603
+ # contains one of the category's words at all; on 1.7M lines this is most of the profile's time saved
604
+ lowered = {fid: text.lower() for fid, text in texts.items() if not NOT_PRODUCT_TEXT.search(fid)}
605
+ stripped: dict[str, str] = {}
606
+ schema = _schema_contact(root, texts)
607
+ for category, (strong, words, dep_names) in SENSITIVE.items():
608
+ found = [f"{d} in {deps[d]}" for d in dep_names if d in deps][:2]
609
+ hints = HINTS[category]
610
+ code = {
611
+ fid: stripped.setdefault(fid, code_only(texts[fid])) for fid, low in lowered.items() if any(h in low for h in hints)
612
+ }
613
+ found += _first(texts, code, strong) or _first(texts, code, words, min_files=2)
614
+ if category == "contact details" and not found and schema:
615
+ found = schema
616
+ if found:
617
+ p.sensitive[category] = found[:3]
618
+
619
+ _correct(p, config if config is not None else _config(root))
620
+ return p
621
+
622
+
623
+ def _config(root: Path) -> dict:
624
+ from .config import load_config
625
+
626
+ return load_config(root).profile
627
+
628
+
629
+ def _correct(p: Profile, cfg: dict) -> None:
630
+ """Apply factory.toml's [profile]: the team knows better than any detection."""
631
+ for key in ("kind", "deployment", "users"):
632
+ if key in cfg and cfg[key] != getattr(p, key):
633
+ p.corrected.append(f"{key}: {getattr(p, key)} → {cfg[key]}")
634
+ setattr(p, key, cfg[key])
635
+ setattr(p, f"{key}_evidence", ["set in factory.toml [profile]"])
636
+ if "sensitive" in cfg:
637
+ wanted = cfg["sensitive"]
638
+ dropped = [c for c in p.sensitive if c not in wanted]
639
+ added = [c for c in wanted if c not in p.sensitive]
640
+ for c in dropped:
641
+ del p.sensitive[c]
642
+ for c in added:
643
+ p.sensitive[c] = ["set in factory.toml [profile]"]
644
+ if dropped or added:
645
+ p.corrected.append("sensitive: " + ", ".join([f"-{c}" for c in dropped] + [f"+{c}" for c in added]))
646
+
647
+
648
+ def markdown(p: Profile) -> list[str]:
649
+ """The profile as review lines (a list, to splice into a report)."""
650
+ out = [f"**{p.summary()[0].upper() + p.summary()[1:]}.**", ""]
651
+ rows = [
652
+ ("Kind", p.kind + (f" (also: {', '.join(p.also)})" if p.also else ""), p.kind_evidence),
653
+ ("Runs", p.deployment, p.deployment_evidence),
654
+ ("Users", p.users, p.users_evidence),
655
+ ]
656
+ out += ["| | | Evidence |", "|---|---|---|"]
657
+ for label, value, ev in rows:
658
+ out.append(f"| {label} | {value} | {'; '.join(ev[:2]) or '-'} |")
659
+ for category, ev in p.sensitive.items():
660
+ out.append(f"| Holds | {category} | {'; '.join(ev[:2])} |")
661
+ if not p.sensitive:
662
+ out.append("| Holds | no sensitive data found | - |")
663
+ if p.corrected:
664
+ out += ["", f"_Corrected in factory.toml: {'; '.join(p.corrected)}._"]
665
+ out += ["", "_Wrong? Correct it in factory.toml (`[profile]` kind, deployment, users, sensitive) and every review "
666
+ "and pull-request check ranks with it._"] # fmt: skip
667
+ return out