stackparity 1.0.0__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 (212) hide show
  1. stackparity/__init__.py +17 -0
  2. stackparity/_engine/agents/investigator.py +294 -0
  3. stackparity/_engine/agents/memory_agent.py +37 -0
  4. stackparity/_engine/agents/pipeline_agent.py +152 -0
  5. stackparity/_engine/agents/remediation_agent.py +248 -0
  6. stackparity/_engine/agents/runtime.py +177 -0
  7. stackparity/_engine/agents/specialists.py +709 -0
  8. stackparity/_engine/agents/suspicious_change_agent.py +1275 -0
  9. stackparity/_engine/cli/__init__.py +2 -0
  10. stackparity/_engine/cli/main.py +1252 -0
  11. stackparity/_engine/cli/remediate.py +461 -0
  12. stackparity/_engine/cli/term.py +44 -0
  13. stackparity/_engine/config/__init__.py +0 -0
  14. stackparity/_engine/config/constants.py +88 -0
  15. stackparity/_engine/config/loader.py +155 -0
  16. stackparity/_engine/config/settings.py +108 -0
  17. stackparity/_engine/containers/__init__.py +12 -0
  18. stackparity/_engine/containers/discovery.py +143 -0
  19. stackparity/_engine/containers/models.py +72 -0
  20. stackparity/_engine/containers/trivy_image_scanner.py +165 -0
  21. stackparity/_engine/core/__init__.py +0 -0
  22. stackparity/_engine/core/capabilities.py +107 -0
  23. stackparity/_engine/core/finding_schema.py +305 -0
  24. stackparity/_engine/core/git_manager.py +206 -0
  25. stackparity/_engine/core/http.py +64 -0
  26. stackparity/_engine/core/models.py +109 -0
  27. stackparity/_engine/core/netpolicy.py +242 -0
  28. stackparity/_engine/core/plugins.py +43 -0
  29. stackparity/_engine/core/repository_inspector.py +243 -0
  30. stackparity/_engine/core/safe_env.py +48 -0
  31. stackparity/_engine/core/scan_orchestrator.py +289 -0
  32. stackparity/_engine/core/scan_state.py +58 -0
  33. stackparity/_engine/core/url_validator.py +135 -0
  34. stackparity/_engine/ecosystems/__init__.py +1 -0
  35. stackparity/_engine/ecosystems/registry.py +138 -0
  36. stackparity/_engine/evidence/__init__.py +1 -0
  37. stackparity/_engine/evidence/store.py +65 -0
  38. stackparity/_engine/explainability/__init__.py +0 -0
  39. stackparity/_engine/explainability/evidence_formatter.py +30 -0
  40. stackparity/_engine/explainability/explanation_engine.py +132 -0
  41. stackparity/_engine/explainability/explanation_validator.py +54 -0
  42. stackparity/_engine/explainability/prompt_templates.py +18 -0
  43. stackparity/_engine/graph/__init__.py +0 -0
  44. stackparity/_engine/graph/dependency_tracer.py +86 -0
  45. stackparity/_engine/graph/graph_builder.py +165 -0
  46. stackparity/_engine/graph/graph_diff.py +57 -0
  47. stackparity/_engine/graph/graph_exporter.py +194 -0
  48. stackparity/_engine/graph/graph_validator.py +46 -0
  49. stackparity/_engine/graph/impact_analyzer.py +23 -0
  50. stackparity/_engine/graph/tree_view.py +185 -0
  51. stackparity/_engine/intel/__init__.py +0 -0
  52. stackparity/_engine/intel/epss.py +53 -0
  53. stackparity/_engine/llm/__init__.py +1 -0
  54. stackparity/_engine/llm/client.py +138 -0
  55. stackparity/_engine/monitor/__init__.py +0 -0
  56. stackparity/_engine/monitor/watch.py +171 -0
  57. stackparity/_engine/non_cve/__init__.py +7 -0
  58. stackparity/_engine/non_cve/base.py +62 -0
  59. stackparity/_engine/non_cve/iac.py +144 -0
  60. stackparity/_engine/non_cve/sast.py +272 -0
  61. stackparity/_engine/non_cve/supply_chain.py +147 -0
  62. stackparity/_engine/orchestration/__init__.py +1 -0
  63. stackparity/_engine/orchestration/pipeline.py +279 -0
  64. stackparity/_engine/orchestration/supervisor.py +167 -0
  65. stackparity/_engine/pipeline_analysis/__init__.py +0 -0
  66. stackparity/_engine/pipeline_analysis/analyzer.py +90 -0
  67. stackparity/_engine/pipeline_analysis/ci.py +189 -0
  68. stackparity/_engine/pipeline_analysis/ci_adapters/__init__.py +24 -0
  69. stackparity/_engine/pipeline_analysis/ci_adapters/azure_pipelines.py +221 -0
  70. stackparity/_engine/pipeline_analysis/ci_adapters/base.py +239 -0
  71. stackparity/_engine/pipeline_analysis/ci_adapters/circleci.py +176 -0
  72. stackparity/_engine/pipeline_analysis/ci_adapters/github_actions.py +356 -0
  73. stackparity/_engine/pipeline_analysis/ci_adapters/gitlab_ci.py +268 -0
  74. stackparity/_engine/pipeline_analysis/ci_adapters/jenkins.py +180 -0
  75. stackparity/_engine/pipeline_analysis/ci_adapters/registry.py +80 -0
  76. stackparity/_engine/pipeline_analysis/ci_models.py +72 -0
  77. stackparity/_engine/pipeline_analysis/dockerfile.py +235 -0
  78. stackparity/_engine/pipeline_analysis/eol.py +62 -0
  79. stackparity/_engine/pipeline_analysis/models.py +37 -0
  80. stackparity/_engine/policy/__init__.py +0 -0
  81. stackparity/_engine/policy/engine.py +216 -0
  82. stackparity/_engine/policy/resources/default.yaml +56 -0
  83. stackparity/_engine/policy/resources/strict.yaml +35 -0
  84. stackparity/_engine/reachability/__init__.py +0 -0
  85. stackparity/_engine/reachability/app_reachability.py +186 -0
  86. stackparity/_engine/reachability/scanners.py +215 -0
  87. stackparity/_engine/remediation/__init__.py +0 -0
  88. stackparity/_engine/remediation/adapters.py +198 -0
  89. stackparity/_engine/remediation/apply_local.py +309 -0
  90. stackparity/_engine/remediation/code_fixes.py +383 -0
  91. stackparity/_engine/remediation/compat.py +156 -0
  92. stackparity/_engine/remediation/container_plan.py +127 -0
  93. stackparity/_engine/remediation/delivery.py +31 -0
  94. stackparity/_engine/remediation/export.py +44 -0
  95. stackparity/_engine/remediation/lifecycle.py +623 -0
  96. stackparity/_engine/remediation/local_trial.py +358 -0
  97. stackparity/_engine/remediation/patchers.py +215 -0
  98. stackparity/_engine/remediation/planner.py +285 -0
  99. stackparity/_engine/remediation/pr_template_engine.py +234 -0
  100. stackparity/_engine/remediation/reachability_impact.py +147 -0
  101. stackparity/_engine/remediation/versions.py +92 -0
  102. stackparity/_engine/remediation/whatif.py +64 -0
  103. stackparity/_engine/remediation/worktree_pr.py +434 -0
  104. stackparity/_engine/reporting/__init__.py +0 -0
  105. stackparity/_engine/reporting/counts.py +63 -0
  106. stackparity/_engine/reporting/fix_pdf.py +343 -0
  107. stackparity/_engine/reporting/fix_report.py +135 -0
  108. stackparity/_engine/reporting/json_exporter.py +61 -0
  109. stackparity/_engine/reporting/report_generator.py +200 -0
  110. stackparity/_engine/reporting/sarif.py +71 -0
  111. stackparity/_engine/reporting/vex.py +57 -0
  112. stackparity/_engine/reporting/view.py +166 -0
  113. stackparity/_engine/risk_analysis/__init__.py +0 -0
  114. stackparity/_engine/risk_analysis/contextual_scorer.py +253 -0
  115. stackparity/_engine/risk_analysis/evidence_collector.py +62 -0
  116. stackparity/_engine/risk_analysis/evidence_normalizer.py +37 -0
  117. stackparity/_engine/risk_analysis/finding_correlator.py +90 -0
  118. stackparity/_engine/risk_analysis/function_impact.py +184 -0
  119. stackparity/_engine/risk_analysis/production_context.py +252 -0
  120. stackparity/_engine/risk_analysis/risk_rules.py +81 -0
  121. stackparity/_engine/risk_analysis/risk_scorer.py +390 -0
  122. stackparity/_engine/sandbox/__init__.py +0 -0
  123. stackparity/_engine/sandbox/runner.py +142 -0
  124. stackparity/_engine/sbom/__init__.py +0 -0
  125. stackparity/_engine/sbom/adapters/__init__.py +19 -0
  126. stackparity/_engine/sbom/adapters/builtin.py +29 -0
  127. stackparity/_engine/sbom/adapters/syft.py +26 -0
  128. stackparity/_engine/sbom/adapters/trivy.py +76 -0
  129. stackparity/_engine/sbom/builtin_generator.py +227 -0
  130. stackparity/_engine/sbom/cyclonedx_validator.py +166 -0
  131. stackparity/_engine/sbom/exporters.py +153 -0
  132. stackparity/_engine/sbom/fusion/__init__.py +5 -0
  133. stackparity/_engine/sbom/fusion/engine.py +315 -0
  134. stackparity/_engine/sbom/fusion/hashes.py +47 -0
  135. stackparity/_engine/sbom/fusion/ledger.py +96 -0
  136. stackparity/_engine/sbom/fusion/registries.py +271 -0
  137. stackparity/_engine/sbom/fusion/resolver.py +143 -0
  138. stackparity/_engine/sbom/fusion/writer.py +114 -0
  139. stackparity/_engine/sbom/lockfile_analyzer.py +114 -0
  140. stackparity/_engine/sbom/merge.py +71 -0
  141. stackparity/_engine/sbom/package_extractors/common.py +104 -0
  142. stackparity/_engine/sbom/package_extractors/manifests.py +101 -0
  143. stackparity/_engine/sbom/package_extractors/npm.py +206 -0
  144. stackparity/_engine/sbom/package_extractors/others.py +267 -0
  145. stackparity/_engine/sbom/package_extractors/python.py +143 -0
  146. stackparity/_engine/sbom/quality_analyzer.py +191 -0
  147. stackparity/_engine/sbom/scanner_engine.py +98 -0
  148. stackparity/_engine/sbom/syft_runner.py +100 -0
  149. stackparity/_engine/sbom/tool_locator.py +69 -0
  150. stackparity/_engine/sbom/trivy_runner.py +82 -0
  151. stackparity/_engine/storage/__init__.py +0 -0
  152. stackparity/_engine/storage/cache.py +56 -0
  153. stackparity/_engine/storage/database.py +295 -0
  154. stackparity/_engine/storage/memory.py +146 -0
  155. stackparity/_engine/suspicious_changes/__init__.py +12 -0
  156. stackparity/_engine/suspicious_changes/analyzer.py +1022 -0
  157. stackparity/_engine/suspicious_changes/change_correlation.py +861 -0
  158. stackparity/_engine/suspicious_changes/lifecycle_script_detector.py +263 -0
  159. stackparity/_engine/suspicious_changes/lockfile_change_detector.py +316 -0
  160. stackparity/_engine/suspicious_changes/manifest_diff_detector.py +251 -0
  161. stackparity/_engine/suspicious_changes/package_risk.py +78 -0
  162. stackparity/_engine/suspicious_changes/popular_packages.py +94 -0
  163. stackparity/_engine/suspicious_changes/registry_detector.py +354 -0
  164. stackparity/_engine/suspicious_changes/suspicious_models.py +57 -0
  165. stackparity/_engine/suspicious_changes/typosquatting_detector.py +298 -0
  166. stackparity/_engine/tools/__init__.py +1 -0
  167. stackparity/_engine/tools/builtin.py +93 -0
  168. stackparity/_engine/tools/registry.py +66 -0
  169. stackparity/_engine/ui/__init__.py +0 -0
  170. stackparity/_engine/ui/components/__init__.py +0 -0
  171. stackparity/_engine/ui/components/common.py +238 -0
  172. stackparity/_engine/ui/components/live_progress.py +157 -0
  173. stackparity/_engine/ui/components/memory_panel.py +82 -0
  174. stackparity/_engine/ui/pages/__init__.py +0 -0
  175. stackparity/_engine/ui/pages/agents_page.py +76 -0
  176. stackparity/_engine/ui/pages/architecture_page.py +44 -0
  177. stackparity/_engine/ui/pages/fixes_page.py +98 -0
  178. stackparity/_engine/ui/pages/graph_page.py +203 -0
  179. stackparity/_engine/ui/pages/health_page.py +117 -0
  180. stackparity/_engine/ui/pages/monitor_page.py +67 -0
  181. stackparity/_engine/ui/pages/pipeline_page.py +219 -0
  182. stackparity/_engine/ui/pages/remediation_page.py +409 -0
  183. stackparity/_engine/ui/pages/reports_page.py +54 -0
  184. stackparity/_engine/ui/pages/sbom_page.py +210 -0
  185. stackparity/_engine/ui/pages/scan_page.py +131 -0
  186. stackparity/_engine/ui/pages/suspicious_page.py +551 -0
  187. stackparity/_engine/ui/pages/vulns_page.py +201 -0
  188. stackparity/_engine/ui/state.py +116 -0
  189. stackparity/_engine/ui/theme.py +201 -0
  190. stackparity/_engine/ui/visualizations/__init__.py +0 -0
  191. stackparity/_engine/ui/visualizations/graphs.py +373 -0
  192. stackparity/_engine/vulnerability/__init__.py +0 -0
  193. stackparity/_engine/vulnerability/cvss.py +58 -0
  194. stackparity/_engine/vulnerability/kev_client.py +47 -0
  195. stackparity/_engine/vulnerability/nvd_client.py +74 -0
  196. stackparity/_engine/vulnerability/osv_client.py +139 -0
  197. stackparity/_engine/vulnerability/remediation_engine.py +50 -0
  198. stackparity/_engine/vulnerability/verification.py +94 -0
  199. stackparity/_engine/vulnerability/version_matcher.py +299 -0
  200. stackparity/_engine/vulnerability/vulnerability_correlator.py +303 -0
  201. stackparity/_engine/vulnerability/vulnerability_models.py +64 -0
  202. stackparity/cli.py +30 -0
  203. stackparity/dashboard_app.py +95 -0
  204. stackparity/web_dist/assets/index-DRJYw2Du.css +1 -0
  205. stackparity/web_dist/assets/index-Q6LLpbEi.js +495 -0
  206. stackparity/web_dist/index.html +13 -0
  207. stackparity/web_server.py +533 -0
  208. stackparity-1.0.0.dist-info/METADATA +204 -0
  209. stackparity-1.0.0.dist-info/RECORD +212 -0
  210. stackparity-1.0.0.dist-info/WHEEL +4 -0
  211. stackparity-1.0.0.dist-info/entry_points.txt +2 -0
  212. stackparity-1.0.0.dist-info/licenses/LICENSE +201 -0
@@ -0,0 +1,251 @@
1
+ """
2
+ Manifest and Repository Git Diff Investigator (Phase 1.1)
3
+ Analyzes Git diffs between two commits (base -> head).
4
+
5
+ Detects:
6
+ 1. Added, removed, and modified dependencies in manifests and lockfiles.
7
+ 2. Unexpected version changes (floating 'latest', '*', unbounded ranges).
8
+ 3. Manifest-lockfile inconsistencies (lockfile changed without manifest, or vice versa).
9
+ 4. Modifications to security-sensitive source files (auth, server entry, CI/CD, build scripts).
10
+
11
+ Produces strict OBSERVED_CHANGE evidence with exact commit provenance and line-level diff excerpts.
12
+ Never executes untrusted code.
13
+ """
14
+ from __future__ import annotations
15
+
16
+ import json
17
+ import re
18
+ from pathlib import Path
19
+ from typing import Any, Dict, List, Optional, Set, Tuple
20
+
21
+ from core import git_manager as gm
22
+
23
+ SECURITY_SENSITIVE_PATTERNS = [
24
+ (r"^\.github/workflows/.*\.ya?ml$", "CI/CD Pipeline Definition"),
25
+ (r"^Dockerfile.*", "Container Build Specification"),
26
+ (r"^docker-compose.*\.ya?ml$", "Container Composition Specification"),
27
+ (r"^Gruntfile\.js$|^gulpfile\.js$|^webpack\.config\.js$", "Build Configuration Script"),
28
+ (r"^server\.js$|^app\.js$|^index\.js$", "Application Entry Point"),
29
+ (r".*auth.*\.js$|.*session.*\.js$|.*login.*\.js$", "Authentication & Session Handling"),
30
+ (r".*dao.*\.js$|.*db.*\.js$|.*database.*", "Database Access & Persistence Layer"),
31
+ (r"^\.env.*|.*config.*\.js$", "Environment & Secret Configuration"),
32
+ ]
33
+
34
+
35
+ def _parse_dependencies(content: Optional[str]) -> Dict[str, str]:
36
+ """Parse dependencies from package.json text safely."""
37
+ if not content:
38
+ return {}
39
+ try:
40
+ data = json.loads(content)
41
+ deps = {}
42
+ for sec in ("dependencies", "devDependencies", "peerDependencies", "optionalDependencies"):
43
+ s = data.get(sec, {})
44
+ if isinstance(s, dict):
45
+ for k, v in s.items():
46
+ if isinstance(v, str):
47
+ deps[k] = v
48
+ return deps
49
+ except Exception:
50
+ return {}
51
+
52
+
53
+ def _is_floating_version(constraint: str) -> bool:
54
+ clean = constraint.strip().lower()
55
+ return clean in ("latest", "*") or clean.startswith((">=", ">")) and "<" not in clean
56
+
57
+
58
+ def _is_major_bump(old_v: str, new_v: str) -> bool:
59
+ """Check if version update crosses a major semantic version boundary."""
60
+ clean_old = re.sub(r"^[~^v>=<\s]+", "", old_v).strip()
61
+ clean_new = re.sub(r"^[~^v>=<\s]+", "", new_v).strip()
62
+ old_parts = clean_old.split(".")
63
+ new_parts = clean_new.split(".")
64
+ if old_parts and new_parts and old_parts[0].isdigit() and new_parts[0].isdigit():
65
+ return int(new_parts[0]) != int(old_parts[0])
66
+ return False
67
+
68
+
69
+ def inspect_git_diff_range(
70
+ repo_dir: Path,
71
+ base_commit: str,
72
+ head_commit: str
73
+ ) -> List[Dict[str, Any]]:
74
+ """Compare base_commit and head_commit, producing OBSERVED_CHANGE findings."""
75
+ findings: List[Dict[str, Any]] = []
76
+
77
+ if not gm.commit_exists(repo_dir, base_commit):
78
+ return findings
79
+ if not gm.commit_exists(repo_dir, head_commit):
80
+ return findings
81
+
82
+ head_info = gm.commit_info(repo_dir, head_commit)
83
+ changed = gm.changed_files(repo_dir, base_commit, head_commit)
84
+
85
+ changed_paths = {path for _, path in changed}
86
+
87
+ # 1. Inspect manifest (package.json) dependency diffs
88
+ manifest_paths = [p for p in changed_paths if p.endswith("package.json") and "node_modules" not in p]
89
+
90
+ for m_path in manifest_paths:
91
+ base_text = gm.show_file(repo_dir, base_commit, m_path)
92
+ head_text = gm.show_file(repo_dir, head_commit, m_path)
93
+
94
+ base_deps = _parse_dependencies(base_text)
95
+ head_deps = _parse_dependencies(head_text)
96
+
97
+ # Added dependencies
98
+ added = set(head_deps.keys()) - set(base_deps.keys())
99
+ for pkg in sorted(added):
100
+ spec = head_deps[pkg]
101
+ diff_snip = gm.diff_text(repo_dir, base_commit, head_commit, m_path)
102
+ # Find line where added
103
+ lines = (head_text or "").splitlines()
104
+ line_no = next((idx for idx, l in enumerate(lines, start=1) if f'"{pkg}"' in l), 1)
105
+
106
+ is_floating = _is_floating_version(spec)
107
+ findings.append({
108
+ "id": f"DIFF-DEP-ADDED-{pkg.upper().replace('@', '').replace('/', '_')}",
109
+ "category": "Dependency Change",
110
+ "title": f"Dependency '{pkg}@{spec}' Added in Commit {head_commit[:8]}",
111
+ "severity": "HIGH" if is_floating else "LOW",
112
+ "confidence": "HIGH",
113
+ "status": "OBSERVED",
114
+ "affected_file": m_path,
115
+ "line_number": line_no,
116
+ "commit_reference": head_info,
117
+ "change_origin": "INTRODUCED_IN_RANGE",
118
+ "evidence_type": "OBSERVED_CHANGE",
119
+ "evidence": f'+ "{pkg}": "{spec}"',
120
+ "technical_explanation": (
121
+ f"Commit {head_commit[:8]} introduced new dependency '{pkg}' with version constraint '{spec}' "
122
+ f"in manifest '{m_path}'."
123
+ + (" WARNING: Constraint uses unpinned floating version allowing arbitrary upstream update injection." if is_floating else "")
124
+ ),
125
+ "potential_impact": "Expands dependency attack surface; floating versions risk automatic adoption of compromised releases.",
126
+ "recommended_action": f"Audit provenance and pin '{pkg}' to a deterministic semantic version.",
127
+ "references": []
128
+ })
129
+
130
+ # Removed dependencies
131
+ removed = set(base_deps.keys()) - set(head_deps.keys())
132
+ for pkg in sorted(removed):
133
+ spec = base_deps[pkg]
134
+ findings.append({
135
+ "id": f"DIFF-DEP-REMOVED-{pkg.upper().replace('@', '').replace('/', '_')}",
136
+ "category": "Dependency Change",
137
+ "title": f"Dependency '{pkg}' Removed in Commit {head_commit[:8]}",
138
+ "severity": "INFO",
139
+ "confidence": "HIGH",
140
+ "status": "OBSERVED",
141
+ "affected_file": m_path,
142
+ "line_number": 1,
143
+ "commit_reference": head_info,
144
+ "change_origin": "INTRODUCED_IN_RANGE",
145
+ "evidence_type": "OBSERVED_CHANGE",
146
+ "evidence": f'- "{pkg}": "{spec}"',
147
+ "technical_explanation": f"Commit {head_commit[:8]} removed dependency '{pkg}' (previously '{spec}') from '{m_path}'.",
148
+ "potential_impact": "Dependency removed from manifest.",
149
+ "recommended_action": "Verify removal was intended and clean up any residual configuration.",
150
+ "references": []
151
+ })
152
+
153
+ # Modified versions
154
+ common = set(base_deps.keys()) & set(head_deps.keys())
155
+ for pkg in sorted(common):
156
+ old_v = base_deps[pkg]
157
+ new_v = head_deps[pkg]
158
+ if old_v != new_v:
159
+ is_floating = _is_floating_version(new_v)
160
+ is_major = _is_major_bump(old_v, new_v)
161
+ lines = (head_text or "").splitlines()
162
+ line_no = next((idx for idx, l in enumerate(lines, start=1) if f'"{pkg}"' in l), 1)
163
+
164
+ if is_floating:
165
+ sev = "HIGH"
166
+ title = f"Dependency '{pkg}' Changed to Floating Constraint '{new_v}' in {head_commit[:8]}"
167
+ exp = f"Commit {head_commit[:8]} modified dependency '{pkg}' from '{old_v}' to unpinned floating '{new_v}'."
168
+ elif is_major:
169
+ sev = "MEDIUM"
170
+ title = f"Dependency '{pkg}' Upgraded Major Version from '{old_v}' to '{new_v}' in {head_commit[:8]}"
171
+ exp = f"Commit {head_commit[:8]} upgraded dependency '{pkg}' across a major version boundary from '{old_v}' to '{new_v}'."
172
+ else:
173
+ sev = "LOW"
174
+ title = f"Dependency '{pkg}' Updated from '{old_v}' to '{new_v}' in {head_commit[:8]}"
175
+ exp = f"Commit {head_commit[:8]} routine semver update for '{pkg}' from '{old_v}' to '{new_v}' within the same release series."
176
+
177
+ findings.append({
178
+ "id": f"DIFF-DEP-MODIFIED-{pkg.upper().replace('@', '').replace('/', '_')}",
179
+ "category": "Dependency Change",
180
+ "title": title,
181
+ "severity": sev,
182
+ "confidence": "HIGH",
183
+ "status": "OBSERVED",
184
+ "affected_file": m_path,
185
+ "line_number": line_no,
186
+ "commit_reference": head_info,
187
+ "change_origin": "INTRODUCED_IN_RANGE",
188
+ "evidence_type": "OBSERVED_CHANGE",
189
+ "evidence": f'- "{pkg}": "{old_v}"\n+ "{pkg}": "{new_v}"',
190
+ "technical_explanation": exp,
191
+ "potential_impact": "Major or floating version jumps may introduce breaking changes or tampered releases; routine semver updates carry minimal operational risk.",
192
+ "recommended_action": "Verify package integrity and inspect changelog if version jumps are unexpected.",
193
+ "references": []
194
+ })
195
+
196
+ # 2. Manifest vs Lockfile Inconsistency in the commit range
197
+ lockfile_paths = [p for p in changed_paths if p.endswith("package-lock.json") and "node_modules" not in p]
198
+ if manifest_paths and not lockfile_paths:
199
+ findings.append({
200
+ "id": f"DIFF-INCONSISTENCY-MANIFEST-WITHOUT-LOCK-{head_commit[:8]}",
201
+ "category": "Repository Diff",
202
+ "title": f"Manifest Modified Without Updating Lockfile in Commit {head_commit[:8]}",
203
+ "severity": "MEDIUM",
204
+ "confidence": "HIGH",
205
+ "status": "OBSERVED",
206
+ "affected_file": manifest_paths[0],
207
+ "line_number": 1,
208
+ "commit_reference": head_info,
209
+ "change_origin": "INTRODUCED_IN_RANGE",
210
+ "evidence_type": "OBSERVED_CHANGE",
211
+ "evidence": f"Manifests changed: {', '.join(manifest_paths)}; Lockfiles changed: none",
212
+ "technical_explanation": (
213
+ f"Commit {head_commit[:8]} updated dependencies in package manifest(s) ({', '.join(manifest_paths)}) "
214
+ "but did not update the companion package-lock.json. This leads to non-deterministic local installs "
215
+ "versus CI builds."
216
+ ),
217
+ "potential_impact": "Build discrepancy between developer environments and automated CI runners.",
218
+ "recommended_action": "Run 'npm install' or 'npm package-lock-only' and commit the synchronized lockfile.",
219
+ "references": []
220
+ })
221
+
222
+ # 3. Security-sensitive source file modifications
223
+ for status, path in changed:
224
+ for pattern, desc in SECURITY_SENSITIVE_PATTERNS:
225
+ if re.match(pattern, path, re.IGNORECASE):
226
+ diff_text = gm.diff_text(repo_dir, base_commit, head_commit, path, max_chars=500)
227
+ findings.append({
228
+ "id": f"DIFF-SENSITIVE-FILE-{path.upper().replace('/', '_').replace('.', '_')}",
229
+ "category": "Repository Diff",
230
+ "title": f"Security-Sensitive File Modified: '{path}' ({desc})",
231
+ "severity": "LOW" if status == "M" else "MEDIUM",
232
+ "confidence": "HIGH",
233
+ "status": "OBSERVED",
234
+ "affected_file": path,
235
+ "line_number": 1,
236
+ "commit_reference": head_info,
237
+ "change_origin": "INTRODUCED_IN_RANGE",
238
+ "evidence_type": "OBSERVED_CHANGE",
239
+ "evidence": f"Git status: {status}\n{diff_text[:300]}",
240
+ "technical_explanation": (
241
+ f"Commit {head_commit[:8]} modified security-sensitive file '{path}' ({desc}). "
242
+ "Critical architectural components (authentication, CI/CD, build hooks, server root) "
243
+ "require focused peer review during supply chain auditing."
244
+ ),
245
+ "potential_impact": "Alterations to authentication, authorization, build gates or deployment workflows.",
246
+ "recommended_action": "Conduct targeted code review on modified lines in this security-sensitive component.",
247
+ "references": []
248
+ })
249
+ break
250
+
251
+ return findings
@@ -0,0 +1,78 @@
1
+ """Advanced package risk signals derived from fused metadata (no extra network calls).
2
+
3
+ Signals are *indicators*, not verdicts, and each states what it does and does not prove:
4
+
5
+ PKG-INT lockfile digest differs from the registry's digest for the same version (possible tampered lockfile / republished artifact)
6
+ PKG-INST direct dependency runs code at install time and publishes no build provenance (install scripts are the classic malware vector)
7
+ PKG-NEW direct dependency version published very recently (typical window for hijacked-maintainer releases)
8
+ PKG-DEP direct dependency is deprecated / yanked (no fixes will follow)
9
+ PKG-CONF package is unknown to the public registry but resolved from a registry (dependency-confusion candidate if it is an internal name)
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import calendar
14
+ import time
15
+ from typing import Any
16
+
17
+ from core.models import Component
18
+ from pipeline_analysis.models import PipelineFinding
19
+
20
+ NEW_DAYS = 7
21
+
22
+
23
+ def _age_days(published: str | None, now_ts: str) -> float | None:
24
+ if not published:
25
+ return None
26
+ try:
27
+ t = calendar.timegm(time.strptime(published[:19], "%Y-%m-%dT%H:%M:%S"))
28
+ n = calendar.timegm(time.strptime(now_ts, "%Y-%m-%dT%H:%M:%SZ"))
29
+ return (n - t) / 86400
30
+ except (ValueError, TypeError):
31
+ return None
32
+
33
+
34
+ def _f(rule, title, sev, c: Component, why, fix, strength="high", **extra) -> PipelineFinding:
35
+ return PipelineFinding(kind="package_risk", rule_id=rule, category="package", ecosystem=c.ecosystem or "", title=title, severity=sev, file=(c.locations or [""])[0], line=0,
36
+ snippet=f"{c.name}@{c.version}", subject=f"{c.name}@{c.version}", why=why, remediation=fix, evidence_strength=strength, extra={"package": c.name, "version": c.version, **extra})
37
+
38
+
39
+ def assess(components: list[Component], scan_ts: str) -> dict[str, Any]:
40
+ out: list[PipelineFinding] = []
41
+ attested = total_meta = 0
42
+ for c in components:
43
+ if c.is_self or c.type in ("file", "container") or not c.ecosystem or not c.version:
44
+ continue
45
+ direct = bool(c.direct_declared)
46
+ if c.integrity.get("lookup") or c.integrity.get("status") in ("verified", "mismatch", "absent", "unverifiable"):
47
+ total_meta += 1
48
+ if c.integrity.get("attested"):
49
+ attested += 1
50
+ if c.integrity.get("status") == "mismatch":
51
+ out.append(_f("PKG-INT", f"Lockfile digest of {c.name}@{c.version} differs from the registry", "HIGH", c,
52
+ "The digest pinned in the lockfile is not the digest the registry publishes today for this exact version: the lockfile may have been altered, or the package version was re-published.",
53
+ "Do not install. Compare the lockfile history (`git log -p`) for this entry, regenerate it from a trusted environment, and check the package's release history.",
54
+ lockfile=c.integrity.get("lockfile", {}).get("file"), algorithm=c.integrity.get("algorithm")))
55
+ if direct and c.install_script and not c.integrity.get("attested"):
56
+ age = _age_days(c.published_at, scan_ts)
57
+ sev = "MEDIUM" if (age is not None and age < 30) else "LOW"
58
+ out.append(_f("PKG-INST", f"{c.name} runs install-time scripts and publishes no build provenance", sev, c,
59
+ "Install scripts execute arbitrary code on every developer machine and CI runner at `npm install` time, and no signed build attestation links this release to its source.",
60
+ "Review the script (`npm view <pkg>@<version> scripts`), install with `--ignore-scripts` where possible, and prefer releases with provenance.", strength="medium"))
61
+ age = _age_days(c.published_at, scan_ts)
62
+ if direct and age is not None and 0 <= age < NEW_DAYS:
63
+ out.append(_f("PKG-NEW", f"{c.name}@{c.version} was published {age:.1f} day(s) before the scan", "LOW", c,
64
+ "Very new releases have had little community review; hijacked-maintainer attacks are typically discovered within days.", "Consider waiting a few days (a minimum release-age policy) before adopting new versions.", strength="medium",
65
+ published=c.published_at))
66
+ if direct and (c.deprecated or c.integrity.get("yanked")):
67
+ out.append(_f("PKG-DEP", f"{c.name}@{c.version} is " + ("yanked" if c.integrity.get("yanked") else "deprecated"), "MEDIUM" if c.integrity.get("yanked") else "LOW", c,
68
+ "The maintainers withdrew or deprecated this version; it will not receive security fixes.", "Move to the recommended replacement or a maintained fork."))
69
+ if direct and c.integrity.get("lookup") == "not_found" and c.source_type in ("registry", None) and c.ecosystem in ("npm", "PyPI"):
70
+ out.append(_f("PKG-CONF", f"{c.name} is not found on the public {c.ecosystem} registry", "MEDIUM", c,
71
+ "The lockfile resolves this name from a registry, but the public registry does not know it. If it is an internal package, anyone can publish the same name publicly and a misconfigured client may install theirs (dependency confusion).",
72
+ "Scope internal packages (`@org/name`) and pin the registry for that scope; reserve the name on the public registry.", strength="medium"))
73
+ for n, f in enumerate(sorted(out, key=lambda x: ["CRITICAL", "HIGH", "MEDIUM", "LOW", "INFO"].index(x.severity)), 1):
74
+ f.finding_id = f"PKG-{n:03d}"
75
+ f.scan_timestamp = scan_ts
76
+ ordered = sorted(out, key=lambda x: x.finding_id)
77
+ return {"findings": [f.model_dump() for f in ordered], "provenance": {"attested": attested, "with_registry_data": total_meta,
78
+ "note": "attestation presence only (npm provenance / deps.dev SLSA); signatures are not cryptographically verified here"}}
@@ -0,0 +1,94 @@
1
+ """Curated reference lists of widely used packages per ecosystem (built-in, versioned, hand-maintained).
2
+
3
+ These are a *reference set for name comparison*, not a trust list: absence from the list says nothing about a package.
4
+ Extend or replace via ``load_extra_reference`` (JSON file mapping ecosystem -> [names]).
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import json
9
+ from pathlib import Path
10
+
11
+ REFERENCE_VERSION = "builtin-2026.1"
12
+
13
+ _NPM = """
14
+ react react-dom react-router react-router-dom redux react-redux next vue vuex vue-router nuxt angular svelte
15
+ express koa fastify hapi body-parser cookie-parser cors helmet morgan compression multer passport jsonwebtoken bcrypt bcryptjs
16
+ lodash underscore moment dayjs date-fns axios request request-promise node-fetch got superagent needle
17
+ webpack webpack-cli webpack-dev-server rollup vite parcel babel-core babel-loader babel-preset-env eslint prettier typescript ts-node tslint
18
+ jest mocha chai sinon karma jasmine supertest nyc istanbul cypress puppeteer playwright selenium-webdriver
19
+ chalk commander yargs inquirer minimist optimist debug colors cli-color ora boxen figlet
20
+ async bluebird q rxjs uuid nanoid shortid moment-timezone numeral validator joi yup ajv
21
+ mongoose mongodb mysql mysql2 pg sequelize knex redis ioredis sqlite3 typeorm prisma
22
+ socket.io ws cheerio jquery bootstrap tailwindcss sass less node-sass postcss autoprefixer
23
+ dotenv cross-env rimraf mkdirp glob fs-extra del gulp grunt nodemon pm2 concurrently
24
+ semver inherits readable-stream through2 safe-buffer string_decoder util events buffer process
25
+ yaml js-yaml xml2js csv-parse marked handlebars ejs pug mustache underscore.string
26
+ aws-sdk firebase stripe twilio nodemailer sendgrid winston bunyan pino log4js
27
+ core-js regenerator-runtime tslib object-assign qs ms mime mime-types iconv-lite
28
+ object.assign safer-buffer through through2 isarray core-util-is process-nextick-args util-deprecate
29
+ @angular/core @angular/common @angular/cli @babel/core @babel/preset-env @types/node @types/react @types/jest @nestjs/core @nestjs/common
30
+ """.split()
31
+
32
+ _PYPI = """
33
+ requests urllib3 numpy pandas scipy matplotlib seaborn scikit-learn tensorflow torch keras pillow opencv-python
34
+ flask django fastapi starlette uvicorn gunicorn jinja2 werkzeug click itsdangerous markupsafe
35
+ sqlalchemy psycopg2 psycopg2-binary pymysql pymongo redis celery kombu boto3 botocore awscli s3transfer
36
+ setuptools wheel pip virtualenv six packaging pyparsing python-dateutil pytz tzdata certifi idna chardet charset-normalizer
37
+ pyyaml toml tomli simplejson ujson orjson cryptography pyopenssl paramiko bcrypt pynacl pycparser cffi
38
+ pytest pytest-cov mock nose tox coverage flake8 pylint black isort mypy pydantic attrs
39
+ beautifulsoup4 lxml html5lib scrapy selenium httpx aiohttp websockets grpcio protobuf
40
+ jsonschema pyjwt oauthlib requests-oauthlib python-dotenv tqdm colorama tabulate rich typer docopt
41
+ networkx sympy statsmodels xgboost lightgbm transformers openai anthropic streamlit gradio
42
+ django-rest-framework djangorestframework django-cors-headers whitenoise pillow-simd
43
+ """.split()
44
+
45
+ _MAVEN = """
46
+ org.springframework:spring-core org.springframework:spring-web org.springframework.boot:spring-boot-starter
47
+ com.google.guava:guava org.apache.commons:commons-lang3 commons-io:commons-io commons-codec:commons-codec
48
+ com.fasterxml.jackson.core:jackson-databind com.fasterxml.jackson.core:jackson-core org.slf4j:slf4j-api
49
+ ch.qos.logback:logback-classic org.apache.logging.log4j:log4j-core org.apache.logging.log4j:log4j-api
50
+ junit:junit org.junit.jupiter:junit-jupiter org.mockito:mockito-core org.hibernate:hibernate-core
51
+ com.google.code.gson:gson org.apache.httpcomponents:httpclient mysql:mysql-connector-java org.projectlombok:lombok
52
+ """.split()
53
+
54
+ _GO = """
55
+ github.com/gin-gonic/gin github.com/gorilla/mux github.com/stretchr/testify github.com/sirupsen/logrus
56
+ github.com/spf13/cobra github.com/spf13/viper github.com/pkg/errors github.com/golang/protobuf google.golang.org/grpc
57
+ golang.org/x/net golang.org/x/crypto golang.org/x/text golang.org/x/sys github.com/go-sql-driver/mysql github.com/lib/pq
58
+ github.com/labstack/echo github.com/gofiber/fiber github.com/google/uuid go.uber.org/zap gorm.io/gorm
59
+ """.split()
60
+
61
+ _CRATES = """
62
+ serde serde_json tokio rand clap regex syn quote proc-macro2 log env_logger anyhow thiserror chrono reqwest
63
+ hyper futures lazy_static once_cell itertools bytes libc rayon actix-web axum rocket diesel sqlx
64
+ """.split()
65
+
66
+ _PACKAGIST = """
67
+ laravel/framework symfony/console symfony/http-foundation guzzlehttp/guzzle monolog/monolog phpunit/phpunit
68
+ doctrine/orm doctrine/dbal composer/composer psr/log nesbot/carbon vlucas/phpdotenv league/flysystem twig/twig
69
+ """.split()
70
+
71
+ _NUGET = """
72
+ Newtonsoft.Json Microsoft.Extensions.Logging Microsoft.EntityFrameworkCore Serilog AutoMapper Dapper
73
+ xunit NUnit Moq FluentAssertions RestSharp Polly StackExchange.Redis System.Text.Json Microsoft.AspNetCore.App
74
+ """.split()
75
+
76
+ _RUBYGEMS = """
77
+ rails rack sinatra rspec nokogiri puma devise activerecord rake bundler json thor minitest sidekiq redis pg mysql2
78
+ """.split()
79
+
80
+ POPULAR: dict[str, list[str]] = {
81
+ "npm": _NPM, "PyPI": _PYPI, "Maven": _MAVEN, "Go": _GO, "crates.io": _CRATES,
82
+ "Packagist": _PACKAGIST, "NuGet": _NUGET, "RubyGems": _RUBYGEMS,
83
+ }
84
+
85
+ # npm scopes that are well known and legitimately host many packages
86
+ TRUSTED_NPM_SCOPES = {"@types", "@babel", "@angular", "@nestjs", "@aws-sdk", "@azure", "@google-cloud", "@mui", "@emotion",
87
+ "@testing-library", "@jest", "@vue", "@reduxjs", "@storybook", "@typescript-eslint", "@eslint"}
88
+
89
+
90
+ def load_extra_reference(path: str | Path) -> None:
91
+ data = json.loads(Path(path).read_text(encoding="utf-8"))
92
+ for eco, names in data.items():
93
+ POPULAR.setdefault(eco, [])
94
+ POPULAR[eco] = sorted(set(POPULAR[eco]) | set(names))