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/privacy.py ADDED
@@ -0,0 +1,221 @@
1
+ """Privacy: personal data going where it shouldn't, and Apple's privacy requirements for iOS apps.
2
+
3
+ Personal data (contact details, names, birth dates, location, health readings, device identifiers) written to logs,
4
+ sent to analytics or crash reporting, or stored unencrypted. Matched per line: a log, analytics or storage call whose
5
+ arguments name personal data. Every language.
6
+
7
+ Apple: every protected resource the code uses (camera, photos, location, health, contacts…) needs a usage
8
+ description in Info.plist, or App Review rejects the app and iOS ends it when it asks for permission. Native code
9
+ that uses a "required reason" API (UserDefaults, file timestamps, disk space, system uptime) needs a privacy manifest
10
+ (PrivacyInfo.xcprivacy). Expo apps declare both in app.json (`ios.infoPlist`, `ios.privacyManifests`, or a config
11
+ plugin's permission option), which counts.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import contextlib
17
+ import json
18
+ import re
19
+ from pathlib import Path
20
+
21
+ from .checks import SRC_EXT, Check, Evidence
22
+ from .paths import is_test, walk
23
+
24
+ PERSONAL = re.compile(
25
+ r"\b(?:e_?mail|email_?address|phone(?:_?number)?|mobile_?number|ssn|social_?security|date_?of_?birth|dob|birth_?(?:date|day)|"
26
+ r"(?:home_?|street_?|postal_?|billing_?|shipping_?)address|zip_?code|postcode|first_?name|last_?name|full_?name|"
27
+ r"passport|national_?id|tax_?id|latitude|longitude|lat|lng|coords|coordinates|geolocation|user_?location|heart_?rate|"
28
+ r"blood_?(?:pressure|glucose|type|oxygen)|body_?(?:weight|fat|mass)|bodyweight|medical_?\w+|diagnosis|"
29
+ r"health_?(?:data|record|samples?|info)|menstrual|credit_?card|card_?number|iban|ip_?address|device_?id|idfa|"
30
+ r"advertising_?id|gaid|imei|android_?id)\b",
31
+ re.I,
32
+ )
33
+ LOG = re.compile(
34
+ r"(?:\bconsole\.(?:log|info|warn|error|debug)|\bprint|\bprintln|\bputs|\bNSLog|\bos_log|\blogger\.\w+|"
35
+ r"\blogging\.(?:info|warning|error|debug|critical|exception)|\blog\.(?:info|warn|warning|error|debug|d|i|e|w|v)|"
36
+ r"\bLog\.(?:d|i|e|w|v)|\bfmt\.Print\w*|\bslog\.\w+)\s*\(",
37
+ )
38
+ ANALYTICS = re.compile(
39
+ r"(?:\banalytics\(\)?\.(?:track|identify|logEvent|setUserProperties?|setUserId|screen)|\blogEvent|\bmixpanel\.\w+|"
40
+ r"\bamplitude\.\w+|\bposthog\.\w+|\bsegment\.\w+|\bSentry\.(?:setUser|setContext|setExtra|addBreadcrumb|captureMessage)|"
41
+ r"\bcrashlytics\(\)\.\w+|\bFirebaseAnalytics\.\w+|\bAnalytics\.logEvent|\bBugsnag\.\w+|\bdatadogRum\.\w+)\s*\(",
42
+ )
43
+ STORE = re.compile(
44
+ r"(?:\bAsyncStorage\.setItem|\blocalStorage\.setItem|\bsessionStorage\.setItem|\bUserDefaults\.standard\.set|"
45
+ r"\bdefaults\.set|\bputString|\bSharedPreferences|\bMMKV\.set\w*|\bstorage\.set\w*)\s*\(",
46
+ )
47
+ ANY_SINK = re.compile(f"{ANALYTICS.pattern}|{LOG.pattern}|{STORE.pattern}") # one search to skip lines with no sink
48
+ KEYS = ("privacy_analytics", "privacy_log", "privacy_storage", "ios_usage_missing", "ios_privacy_manifest")
49
+
50
+ # resource -> (Info.plist key, code that uses it, Expo config plugins that add the key themselves)
51
+ USAGE = {
52
+ "camera": (
53
+ "NSCameraUsageDescription",
54
+ r"AVCaptureDevice|UIImagePickerController|launchCameraAsync|expo-camera|vision-camera|CameraView",
55
+ ("expo-camera", "expo-image-picker", "react-native-vision-camera"),
56
+ ),
57
+ "photo library": (
58
+ "NSPhotoLibraryUsageDescription",
59
+ r"PHPhotoLibrary|PHPickerViewController|launchImageLibraryAsync|expo-media-library|MediaLibrary\.",
60
+ ("expo-image-picker", "expo-media-library"),
61
+ ),
62
+ "location": (
63
+ "NSLocationWhenInUseUsageDescription",
64
+ r"CLLocationManager|getCurrentPositionAsync|watchPositionAsync|expo-location|navigator\.geolocation",
65
+ ("expo-location",),
66
+ ),
67
+ "microphone": (
68
+ "NSMicrophoneUsageDescription",
69
+ r"AVAudioRecorder|Audio\.Recording|requestRecordPermission|expo-av|useAudioRecorder",
70
+ ("expo-av", "expo-audio", "expo-camera"),
71
+ ),
72
+ "contacts": ("NSContactsUsageDescription", r"CNContactStore|expo-contacts|Contacts\.getContactsAsync", ("expo-contacts",)),
73
+ "health data": (
74
+ "NSHealthShareUsageDescription",
75
+ r"HKHealthStore|HKQuantityType|react-native-health|healthkit",
76
+ ("react-native-health", "@kingstinct/react-native-healthkit"),
77
+ ),
78
+ "calendar": ("NSCalendarsUsageDescription", r"EKEventStore|expo-calendar|Calendar\.getCalendarsAsync", ("expo-calendar",)),
79
+ "Bluetooth": ("NSBluetoothAlwaysUsageDescription", r"CBCentralManager|CBPeripheralManager|react-native-ble", ()),
80
+ "Face ID": (
81
+ "NSFaceIDUsageDescription",
82
+ r"LAContext|evaluatePolicy|expo-local-authentication|authenticateAsync",
83
+ ("expo-local-authentication",),
84
+ ),
85
+ "motion": ("NSMotionUsageDescription", r"CMMotionActivityManager|CMPedometer|Pedometer\.", ("expo-sensors",)),
86
+ "tracking": (
87
+ "NSUserTrackingUsageDescription",
88
+ r"ATTrackingManager|requestTrackingPermissionsAsync|expo-tracking-transparency",
89
+ ("expo-tracking-transparency",),
90
+ ),
91
+ }
92
+ # Apple's "required reason" API categories, as used from native code
93
+ REQUIRED_REASON = {
94
+ "NSPrivacyAccessedAPICategoryUserDefaults": r"\bUserDefaults\b|\bNSUserDefaults\b|@AppStorage",
95
+ "NSPrivacyAccessedAPICategoryFileTimestamp": (
96
+ r"\.creationDate\b|\.modificationDate\b|NSFileCreationDate|NSFileModificationDate|contentModificationDateKey"
97
+ ),
98
+ "NSPrivacyAccessedAPICategorySystemBootTime": r"systemUptime|mach_absolute_time",
99
+ "NSPrivacyAccessedAPICategoryDiskSpace": r"volumeAvailableCapacity|NSFileSystemFreeSize|systemFreeSize|statfs\(",
100
+ }
101
+ NATIVE = (".swift", ".m", ".mm")
102
+
103
+
104
+ def _argument_text(line: str, call: re.Match) -> str:
105
+ """The text of a call's arguments on this line (up to its closing parenthesis)."""
106
+ depth, out = 1, []
107
+ for ch in line[call.end() :]:
108
+ depth += ch == "("
109
+ depth -= ch == ")"
110
+ if depth == 0:
111
+ break
112
+ out.append(ch)
113
+ text = "".join(out)
114
+
115
+ def values_only(m: re.Match) -> str: # a string's fixed text isn't data; only what's interpolated into it is
116
+ found = re.findall(r"\$?\{([^{}]*)\}|\\\(([^()]*)\)|\$([A-Za-z_][\w.]*)", m.group(0)) # {x} ${x} \(x) $x
117
+ return " ".join(a or b or c for a, b, c in found)
118
+
119
+ return re.sub(r"""(["'`])(?:(?!\1).)*\1""", values_only, text)
120
+
121
+
122
+ def personal_data(root: Path, files: list[str], out: dict[str, Check]) -> None:
123
+ for fid in files:
124
+ if not fid.endswith(SRC_EXT) or is_test(fid):
125
+ continue
126
+ try:
127
+ text = (root / fid).read_text(encoding="utf-8", errors="replace")
128
+ except OSError:
129
+ continue
130
+ if not PERSONAL.search(text) or not ANY_SINK.search(text):
131
+ continue
132
+ for i, line in enumerate(text.splitlines(), 1):
133
+ if len(line) > 1000 or line.lstrip().startswith(("#", "//", "*")) or not ANY_SINK.search(line):
134
+ continue
135
+ for key, pat in (("privacy_analytics", ANALYTICS), ("privacy_log", LOG), ("privacy_storage", STORE)):
136
+ m = pat.search(line)
137
+ if m and (word := PERSONAL.search(_argument_text(line, m))):
138
+ out[key].hits.append(Evidence(fid, i, line.strip()[:140]))
139
+ out[key].data[f"{fid}:{i}"] = word.group(0)
140
+ break
141
+
142
+
143
+ def _declared_keys(root: Path) -> tuple[set[str], set[str], bool]:
144
+ """(usage-description keys declared, Expo config plugins listed, whether a privacy manifest exists)."""
145
+ keys, plugins, manifest = set(), set(), False
146
+ wanted = ("PrivacyInfo.xcprivacy", "Info.plist", "app.json", "app.config.json", "app.config.js", "app.config.ts")
147
+ for rel in walk(root, names=wanted, suffixes=(".entitlements",)):
148
+ path = root / rel
149
+ if path.name == "PrivacyInfo.xcprivacy":
150
+ manifest = True
151
+ elif path.name == "Info.plist" or path.name.endswith(".entitlements"):
152
+ keys |= set(re.findall(r"<key>(NS\w+UsageDescription)</key>", path.read_text(encoding="utf-8", errors="replace")))
153
+ elif path.name in ("app.json", "app.config.json") and path.parent == root:
154
+ try:
155
+ data = json.loads(path.read_text(encoding="utf-8"))
156
+ except ValueError:
157
+ continue
158
+ expo = data.get("expo", data)
159
+ ios = expo.get("ios", {})
160
+ keys |= {k for k in ios.get("infoPlist", {}) if k.endswith("UsageDescription")}
161
+ manifest = manifest or bool(ios.get("privacyManifests"))
162
+ for p in expo.get("plugins", []):
163
+ plugins.add(p[0] if isinstance(p, list) else p)
164
+ elif path.name.startswith("app.config.") and path.parent == root: # JS/TS config: look for the keys as text
165
+ text = path.read_text(encoding="utf-8", errors="replace")
166
+ keys |= set(re.findall(r"(NS\w+UsageDescription)", text))
167
+ manifest = manifest or "privacyManifests" in text
168
+ plugins |= set(re.findall(r"""["'](expo-[\w-]+|react-native-[\w-]+|@[\w-]+/[\w-]+)["']""", text))
169
+ return keys, plugins, manifest
170
+
171
+
172
+ def _first_line(texts: dict[str, str], pattern: str) -> tuple[str, int, str] | None:
173
+ """(file, line number, line) of the first match: one search per file, lines only where it matched."""
174
+ rx = re.compile(pattern)
175
+ for fid, text in texts.items():
176
+ m = rx.search(text)
177
+ if m:
178
+ start = text.rfind("\n", 0, m.start()) + 1
179
+ end = text.find("\n", m.start())
180
+ return fid, text.count("\n", 0, m.start()) + 1, text[start : end if end >= 0 else None]
181
+ return None
182
+
183
+
184
+ def apple(root: Path, files: list[str], out: dict[str, Check]) -> None:
185
+ ios_project = (root / "ios").is_dir() or any(f.endswith(NATIVE) for f in files) or (root / "app.json").is_file()
186
+ if not ios_project:
187
+ return
188
+ texts: dict[str, str] = {}
189
+ for fid in files:
190
+ if fid.endswith(SRC_EXT) and not is_test(fid):
191
+ with contextlib.suppress(OSError):
192
+ texts[fid] = (root / fid).read_text(encoding="utf-8", errors="replace")
193
+ keys, plugins, manifest = _declared_keys(root)
194
+ try:
195
+ deps = set(json.loads((root / "package.json").read_text(encoding="utf-8")).get("dependencies", {}))
196
+ except (OSError, ValueError):
197
+ deps = set()
198
+ for resource, (key, uses, plugin_names) in USAGE.items():
199
+ if key in keys or plugins & set(plugin_names):
200
+ continue
201
+ where = _first_line(texts, uses)
202
+ if where is None and not deps & set(plugin_names):
203
+ continue
204
+ fid, line, text = where or ("package.json", 1, ", ".join(sorted(deps & set(plugin_names))))
205
+ out["ios_usage_missing"].hits.append(Evidence(fid, line, f"{resource}: no {key} ({text.strip()[:100]})"))
206
+ if not manifest:
207
+ for category, uses in REQUIRED_REASON.items():
208
+ hit = _first_line({f: t for f, t in texts.items() if f.endswith(NATIVE)}, uses)
209
+ if hit:
210
+ fid, line, text = hit
211
+ name = category.removeprefix("NSPrivacyAccessedAPICategory")
212
+ out["ios_privacy_manifest"].hits.append(
213
+ Evidence(fid, line, f"{name} API without a privacy manifest: {text.strip()[:100]}")
214
+ )
215
+
216
+
217
+ def scan(root: Path, files: list[str]) -> dict[str, Check]:
218
+ out = {k: Check(k) for k in KEYS}
219
+ personal_data(root, files, out)
220
+ apple(root, files, out)
221
+ return out