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,271 @@
1
+ """Registry clients used to fill metadata the lockfile/scanner did not record and to verify lockfile integrity digests.
2
+
3
+ Each fetcher returns a *record*: {licenses, supplier, description, links[{type,url}], published_at, deprecated, install_script,
4
+ digests[{alg, hex, what}], yanked, url}. Fields a registry does not state are omitted (never defaulted).
5
+ Only public read-only GET requests are made; the scanned repository's code is never run.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import re
10
+ from typing import Any, Callable, Optional
11
+ from urllib.parse import quote
12
+
13
+ from core.http import HttpClient
14
+ from sbom.fusion.hashes import parse_digest
15
+
16
+ DEPSDEV_SYSTEM = {"npm": "npm", "PyPI": "pypi", "Maven": "maven", "Go": "go", "crates.io": "cargo", "NuGet": "nuget"}
17
+ _LINK_TYPE = {"HOMEPAGE": "website", "SOURCE_REPO": "vcs", "ISSUE_TRACKER": "issue-tracker", "DOCUMENTATION": "documentation", "ORIGIN": "distribution"}
18
+ _PYPI_CLASSIFIER = {
19
+ "MIT License": "MIT", "Apache Software License": "Apache-2.0", "ISC License (ISCL)": "ISC", "Mozilla Public License 2.0 (MPL 2.0)": "MPL-2.0",
20
+ "The Unlicense (Unlicense)": "Unlicense", "GNU General Public License v2 (GPLv2)": "GPL-2.0-only", "GNU General Public License v3 (GPLv3)": "GPL-3.0-only",
21
+ "GNU Lesser General Public License v3 (LGPLv3)": "LGPL-3.0-only", "GNU Affero General Public License v3": "AGPL-3.0-only", "Python Software Foundation License": "PSF-2.0",
22
+ }
23
+
24
+
25
+ def _clean_license(v: Any) -> Optional[str]:
26
+ if isinstance(v, dict):
27
+ v = v.get("type") or v.get("name")
28
+ if not isinstance(v, str):
29
+ return None
30
+ v = v.strip()
31
+ if not v or v.lower() in ("non-standard", "other", "unknown", "unlicensed", "see license in license", "none") or len(v) > 120 or "\n" in v:
32
+ return None
33
+ return v
34
+
35
+
36
+ def depsdev(http: HttpClient, eco: str, name: str, version: str) -> dict:
37
+ system = DEPSDEV_SYSTEM[eco]
38
+ url = f"https://api.deps.dev/v3/systems/{system}/packages/{quote(name, safe='')}/versions/{quote(version, safe='')}"
39
+ d = http.get_json(url)
40
+ rec: dict[str, Any] = {"url": url}
41
+ lic = [x for x in (_clean_license(x) for x in d.get("licenses") or []) if x]
42
+ if lic:
43
+ rec["licenses"] = lic
44
+ if d.get("publishedAt"):
45
+ rec["published_at"] = d["publishedAt"]
46
+ if "isDeprecated" in d:
47
+ rec["deprecated"] = bool(d["isDeprecated"])
48
+ links = [{"type": _LINK_TYPE[l["label"]], "url": l["url"]} for l in d.get("links") or [] if l.get("label") in _LINK_TYPE and l.get("url")]
49
+ if links:
50
+ rec["links"] = links
51
+ if d.get("slsaProvenances"):
52
+ rec["provenance_attestations"] = len(d["slsaProvenances"])
53
+ return rec
54
+
55
+
56
+ def npm(http: HttpClient, eco: str, name: str, version: str) -> dict:
57
+ url = f"https://registry.npmjs.org/{quote(name, safe='@')}/{quote(version, safe='')}"
58
+ d = http.get_json(url)
59
+ rec: dict[str, Any] = {"url": url}
60
+ lic = _clean_license(d.get("license"))
61
+ if not lic and isinstance(d.get("licenses"), list):
62
+ lic = " OR ".join(x for x in (_clean_license(x) for x in d["licenses"]) if x) or None
63
+ if lic:
64
+ rec["licenses"] = [lic]
65
+ author = d.get("author")
66
+ pub = (d.get("_npmUser") or {}).get("name") or ((d.get("maintainers") or [{}])[0] or {}).get("name") or (author.get("name") if isinstance(author, dict) else None)
67
+ if pub:
68
+ rec["supplier"] = pub
69
+ if d.get("description"):
70
+ rec["description"] = str(d["description"])[:300]
71
+ links = []
72
+ if d.get("homepage"):
73
+ links.append({"type": "website", "url": d["homepage"]})
74
+ repo = d.get("repository")
75
+ ru = repo.get("url") if isinstance(repo, dict) else repo if isinstance(repo, str) else None
76
+ if ru:
77
+ links.append({"type": "vcs", "url": re.sub(r"^git\+", "", ru)})
78
+ if (d.get("bugs") or {}).get("url") if isinstance(d.get("bugs"), dict) else False:
79
+ links.append({"type": "issue-tracker", "url": d["bugs"]["url"]})
80
+ if links:
81
+ rec["links"] = links
82
+ scripts = d.get("scripts") or {}
83
+ rec["install_script"] = bool(d.get("gypfile") or any(k in scripts for k in ("preinstall", "install", "postinstall")))
84
+ if d.get("deprecated"):
85
+ rec["deprecated"] = True
86
+ dist = d.get("dist") or {}
87
+ if (dist.get("attestations") or {}).get("url"):
88
+ rec["provenance_attestations"] = 1 # npm provenance statement (Sigstore) is published for this version
89
+ dig = []
90
+ for key in ("integrity", "shasum"):
91
+ p = parse_digest(dist.get(key))
92
+ if p:
93
+ dig.append({**p, "what": "tarball"})
94
+ if dig:
95
+ rec["digests"] = dig
96
+ return rec
97
+
98
+
99
+ def pypi(http: HttpClient, eco: str, name: str, version: str) -> dict:
100
+ url = f"https://pypi.org/pypi/{quote(name, safe='')}/{quote(version, safe='')}/json"
101
+ d = http.get_json(url)
102
+ info = d.get("info") or {}
103
+ rec: dict[str, Any] = {"url": url}
104
+ lic = _clean_license(info.get("license_expression")) or None
105
+ if not lic:
106
+ for cl in info.get("classifiers") or []:
107
+ if cl.startswith("License ::") and cl.split(" :: ")[-1] in _PYPI_CLASSIFIER:
108
+ lic = _PYPI_CLASSIFIER[cl.split(" :: ")[-1]]
109
+ break
110
+ if not lic and info.get("license") and len(info["license"]) < 60 and "\n" not in info["license"]:
111
+ lic = _clean_license(info["license"])
112
+ if not lic: # unambiguous label only (e.g. "BSD License" has no single SPDX id, so it is recorded by name)
113
+ for cl in info.get("classifiers") or []:
114
+ if cl.startswith("License :: OSI Approved :: "):
115
+ lic = cl.split(" :: ")[-1]
116
+ break
117
+ if lic:
118
+ rec["licenses"] = [lic]
119
+ pub = info.get("author") or info.get("maintainer")
120
+ if pub:
121
+ rec["supplier"] = pub
122
+ if info.get("summary"):
123
+ rec["description"] = str(info["summary"])[:300]
124
+ links = []
125
+ if info.get("home_page"):
126
+ links.append({"type": "website", "url": info["home_page"]})
127
+ for k, v in (info.get("project_urls") or {}).items():
128
+ t = "vcs" if re.search(r"source|repo|github|code", k, re.I) else "issue-tracker" if re.search(r"issue|bug|tracker", k, re.I) else "documentation" if re.search(r"doc", k, re.I) else "website" if re.search(r"home", k, re.I) else None
129
+ if t and v:
130
+ links.append({"type": t, "url": v})
131
+ if links:
132
+ rec["links"] = links[:5]
133
+ files = d.get("urls") or []
134
+ dig = [{"alg": "sha256", "hex": f["digests"]["sha256"].lower(), "kind": "file", "what": f.get("filename", "")} for f in files if (f.get("digests") or {}).get("sha256")]
135
+ if dig:
136
+ rec["digests"] = dig
137
+ if files:
138
+ rec["published_at"] = files[0].get("upload_time_iso_8601") or files[0].get("upload_time")
139
+ rec["yanked"] = any(f.get("yanked") for f in files)
140
+ return rec
141
+
142
+
143
+ def crates(http: HttpClient, eco: str, name: str, version: str) -> dict:
144
+ url = f"https://crates.io/api/v1/crates/{quote(name, safe='')}/{quote(version, safe='')}"
145
+ v = (http.get_json(url) or {}).get("version") or {}
146
+ rec: dict[str, Any] = {"url": url}
147
+ if v.get("checksum"):
148
+ p = parse_digest(v["checksum"], "sha256")
149
+ if p:
150
+ rec["digests"] = [{**p, "what": "crate"}]
151
+ if v.get("license"):
152
+ rec["licenses"] = [v["license"]]
153
+ if v.get("created_at"):
154
+ rec["published_at"] = v["created_at"]
155
+ if v.get("yanked"):
156
+ rec["yanked"] = True
157
+ rec["deprecated"] = True
158
+ return rec
159
+
160
+
161
+ def maven_central(http: HttpClient, eco: str, name: str, version: str) -> dict:
162
+ if ":" not in name:
163
+ return {}
164
+ g, a = name.split(":", 1)
165
+ base = f"https://repo1.maven.org/maven2/{g.replace('.', '/')}/{a}/{version}/{a}-{version}"
166
+ r = http.request("GET", base + ".jar.sha1")
167
+ h = r.text.strip().split()[0] if r.text.strip() else ""
168
+ p = parse_digest(h)
169
+ return {"url": base + ".jar.sha1", "digests": [{**p, "what": "jar"}]} if p else {}
170
+
171
+
172
+ def go_sum(http: HttpClient, eco: str, name: str, version: str) -> dict:
173
+ """Go checksum database: the authoritative h1 tree hash of a module version (comparable with go.sum)."""
174
+ esc = re.sub(r"[A-Z]", lambda m: "!" + m.group(0).lower(), name)
175
+ url = f"https://sum.golang.org/lookup/{esc}@{version}"
176
+ r = http.request("GET", url)
177
+ for line in r.text.splitlines():
178
+ parts = line.split()
179
+ if len(parts) == 3 and parts[0] == name and parts[1] == version and parts[2].startswith("h1:"):
180
+ p = parse_digest(parts[2])
181
+ if p:
182
+ return {"url": url, "digests": [{**p, "what": "go module tree"}]}
183
+ return {}
184
+
185
+
186
+ def packagist(http: HttpClient, eco: str, name: str, version: str) -> dict:
187
+ url = f"https://repo.packagist.org/p2/{quote(name, safe='/')}.json"
188
+ pk = (http.get_json(url).get("packages") or {}).get(name) or []
189
+ if pk and http is not None: # composer/2.0 "minified" metadata: each entry lists only the keys that changed from the previous one
190
+ full, prev = [], {}
191
+ for e in pk:
192
+ cur = dict(prev)
193
+ for k, val in e.items():
194
+ if val == "__unset":
195
+ cur.pop(k, None)
196
+ else:
197
+ cur[k] = val
198
+ full.append(cur)
199
+ prev = cur
200
+ pk = full
201
+ want = {version, "v" + version, version.lstrip("v")}
202
+ v = next((x for x in pk if str(x.get("version")) in want), None)
203
+ if not v:
204
+ return {}
205
+ rec: dict[str, Any] = {"url": url}
206
+ lic = [x for x in (_clean_license(l) for l in v.get("license") or []) if x]
207
+ if lic:
208
+ rec["licenses"] = lic
209
+ if v.get("description"):
210
+ rec["description"] = str(v["description"])[:300]
211
+ if v.get("time"):
212
+ rec["published_at"] = v["time"]
213
+ links = []
214
+ if v.get("homepage"):
215
+ links.append({"type": "website", "url": v["homepage"]})
216
+ if (v.get("source") or {}).get("url"):
217
+ links.append({"type": "vcs", "url": v["source"]["url"]})
218
+ if (v.get("support") or {}).get("issues"):
219
+ links.append({"type": "issue-tracker", "url": v["support"]["issues"]})
220
+ if links:
221
+ rec["links"] = links
222
+ authors = [a.get("name") for a in v.get("authors") or [] if a.get("name")]
223
+ if authors:
224
+ rec["supplier"] = ", ".join(authors[:2])
225
+ if v.get("abandoned"):
226
+ rec["deprecated"] = True
227
+ sh = (v.get("dist") or {}).get("shasum")
228
+ p = parse_digest(sh) if sh else None
229
+ if p:
230
+ rec["digests"] = [{**p, "what": "dist zip"}]
231
+ return rec
232
+
233
+
234
+ def rubygems(http: HttpClient, eco: str, name: str, version: str) -> dict:
235
+ url = f"https://rubygems.org/api/v2/rubygems/{quote(name, safe='')}/versions/{quote(version, safe='')}.json"
236
+ d = http.get_json(url)
237
+ rec: dict[str, Any] = {"url": url}
238
+ lic = [x for x in (_clean_license(l) for l in d.get("licenses") or []) if x]
239
+ if lic:
240
+ rec["licenses"] = lic
241
+ if d.get("authors"):
242
+ rec["supplier"] = str(d["authors"])[:120]
243
+ if d.get("summary") or d.get("info"):
244
+ rec["description"] = str(d.get("summary") or d.get("info"))[:300]
245
+ if d.get("version_created_at"):
246
+ rec["published_at"] = d["version_created_at"]
247
+ links = [{"type": t, "url": d[k]} for t, k in (("website", "homepage_uri"), ("vcs", "source_code_uri"), ("issue-tracker", "bug_tracker_uri"), ("documentation", "documentation_uri")) if d.get(k)]
248
+ if links:
249
+ rec["links"] = links
250
+ if d.get("yanked"):
251
+ rec["deprecated"] = True
252
+ p = parse_digest(d.get("sha"), "sha256")
253
+ if p:
254
+ rec["digests"] = [{**p, "what": "gem"}]
255
+ return rec
256
+
257
+
258
+ FETCHERS: dict[str, list[tuple[str, Callable]]] = {
259
+ "npm": [("npm-registry", npm), ("deps.dev", depsdev)],
260
+ "PyPI": [("pypi", pypi), ("deps.dev", depsdev)],
261
+ "crates.io": [("crates.io", crates), ("deps.dev", depsdev)],
262
+ "Maven": [("deps.dev", depsdev), ("maven-central", maven_central)],
263
+ "Go": [("deps.dev", depsdev), ("sum.golang.org", go_sum)],
264
+ "Packagist": [("packagist", packagist)],
265
+ "RubyGems": [("rubygems", rubygems)],
266
+ "NuGet": [("deps.dev", depsdev)],
267
+ }
268
+
269
+
270
+ def supported(eco: Optional[str]) -> bool:
271
+ return bool(eco and eco in FETCHERS)
@@ -0,0 +1,143 @@
1
+ """Registry resolver: transitive dependencies for services that have no lockfile.
2
+
3
+ A ``pom.xml``, ``build.gradle`` or pinned ``requirements.txt`` lists only the dependencies a developer typed. Without running Maven, Gradle or pip
4
+ (which would execute repository-controlled code and is forbidden here) the transitive closure is unknown. deps.dev publishes the resolved
5
+ dependency graph of every package version, so for each *pinned* direct dependency we fetch that graph and add the packages and edges as
6
+ ``derived`` dependency records.
7
+
8
+ Honest limits, recorded in the result and in every derived component (``sc-guardian:resolution = registry-resolved``):
9
+ * each direct dependency is resolved on its own; the project's real resolution (version mediation across all dependencies, exclusions,
10
+ BOMs, profiles) can pick different versions
11
+ * a service that has a real lockfile for that ecosystem is never resolved this way - the lockfile is authoritative
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import time
16
+ from concurrent.futures import ThreadPoolExecutor
17
+ from typing import Any, Optional
18
+ from urllib.parse import quote
19
+
20
+ from core.http import HttpClient, NotFound, SourceUnavailable
21
+ from core.models import LockDependency
22
+ from sbom.fusion.registries import DEPSDEV_SYSTEM
23
+ from sbom.package_extractors.common import make_purl, normalize_name
24
+ from storage.cache import Cache
25
+
26
+ TTL = 7 * 24 * 3600
27
+ BACK = {"NPM": "npm", "PYPI": "PyPI", "MAVEN": "Maven", "CARGO": "crates.io", "NUGET": "NuGet", "GO": "Go"}
28
+ RESOLVABLE = {"Maven", "npm", "PyPI", "NuGet", "crates.io"}
29
+ # files that carry exact lock information for an ecosystem: if one exists in a service, nothing is resolved there
30
+ LOCKING_FILES = {
31
+ "npm": {"package-lock.json", "npm-shrinkwrap.json", "yarn.lock", "pnpm-lock.yaml"},
32
+ "PyPI": {"poetry.lock", "uv.lock", "Pipfile.lock"},
33
+ "Maven": {"gradle.lockfile"},
34
+ "NuGet": {"packages.lock.json"},
35
+ "crates.io": {"Cargo.lock"},
36
+ }
37
+ MANIFEST_ONLY_SOURCES = ("package.json", "pyproject.toml", "Cargo.toml", "pom.xml", "build.gradle", "build.gradle.kts", "requirements", ".csproj", ".fsproj", ".vbproj")
38
+
39
+
40
+ def _basename(p: str) -> str:
41
+ return p.replace("\\", "/").rsplit("/", 1)[-1]
42
+
43
+
44
+ def candidates(lock_deps: list[LockDependency]) -> list[LockDependency]:
45
+ """Pinned direct dependencies from manifest-like files in services without an authoritative lockfile for the ecosystem."""
46
+ locked: set[tuple] = set()
47
+ for d in lock_deps:
48
+ if _basename(d.lockfile) in LOCKING_FILES.get(d.ecosystem, ()):
49
+ locked.add((d.service_dir, d.ecosystem))
50
+ out = []
51
+ for d in lock_deps:
52
+ if d.derived or d.ecosystem not in RESOLVABLE or not d.version or (d.service_dir, d.ecosystem) in locked:
53
+ continue
54
+ base = _basename(d.lockfile)
55
+ if not any(base == m or base.startswith(m) or base.endswith(m) for m in MANIFEST_ONLY_SOURCES):
56
+ continue
57
+ if d.direct is False:
58
+ continue
59
+ out.append(d)
60
+ return out
61
+
62
+
63
+ def _fetch(http: HttpClient, cache: Optional[Cache], eco: str, name: str, version: str) -> Optional[dict]:
64
+ key = f"{eco}:{name}@{version}"
65
+ hit = cache.get("depsdev_deps", key, ttl=TTL) if cache else None
66
+ if hit is not None:
67
+ return hit or None
68
+ url = f"https://api.deps.dev/v3/systems/{DEPSDEV_SYSTEM[eco]}/packages/{quote(name, safe='')}/versions/{quote(version, safe='')}:dependencies"
69
+ try:
70
+ d = http.get_json(url)
71
+ except NotFound:
72
+ if cache:
73
+ cache.set("depsdev_deps", key, {})
74
+ return None
75
+ nodes = [{"eco": BACK.get(n["versionKey"]["system"], ""), "name": n["versionKey"]["name"], "version": n["versionKey"]["version"], "relation": n.get("relation", "")}
76
+ for n in d.get("nodes", [])]
77
+ res = {"nodes": nodes, "edges": [[e["fromNode"], e["toNode"]] for e in d.get("edges", [])]}
78
+ if cache:
79
+ cache.set("depsdev_deps", key, res)
80
+ return res
81
+
82
+
83
+ def resolve(lock_deps: list[LockDependency], http: HttpClient, cache: Optional[Cache], limit: int = 150, budget_s: float = 90.0, workers: int = 6) -> dict[str, Any]:
84
+ """Return {derived: [LockDependency], stats}. Also fills ``requires`` of the direct records so the graph gets their edges."""
85
+ cands = candidates(lock_deps)
86
+ stats: dict[str, Any] = {"candidates": len(cands), "resolved": 0, "not_found": 0, "unavailable": 0, "skipped_limit": 0, "skipped_budget": 0, "derived_packages": 0,
87
+ "services": sorted({f"{d.service_dir}:{d.ecosystem}" for d in cands})}
88
+ if not cands:
89
+ return {"derived": [], "stats": stats}
90
+ if len(cands) > limit:
91
+ stats["skipped_limit"] = len(cands) - limit
92
+ cands = cands[:limit]
93
+ t0, down = time.time(), {"n": 0}
94
+
95
+ def work(d: LockDependency):
96
+ if time.time() - t0 > budget_s:
97
+ return d, None, "budget"
98
+ if down["n"] >= 4:
99
+ return d, None, "unavailable"
100
+ try:
101
+ r = _fetch(http, cache, d.ecosystem, d.name, d.version)
102
+ down["n"] = 0
103
+ return d, r, "ok" if r else "not_found"
104
+ except SourceUnavailable:
105
+ down["n"] += 1
106
+ return d, None, "unavailable"
107
+ except Exception:
108
+ return d, None, "unavailable"
109
+
110
+ derived: dict[tuple, LockDependency] = {}
111
+ existing = {(d.service_dir, d.ecosystem, normalize_name(d.ecosystem, d.name), d.version) for d in lock_deps}
112
+ with ThreadPoolExecutor(max_workers=workers) as ex:
113
+ results = list(ex.map(work, cands))
114
+ for d, r, status in results:
115
+ if status != "ok":
116
+ stats["not_found" if status == "not_found" else "skipped_budget" if status == "budget" else "unavailable"] += 1
117
+ continue
118
+ stats["resolved"] += 1
119
+ nodes, edges = r["nodes"], r["edges"]
120
+ out_edges: dict[int, list[int]] = {}
121
+ for a, b in edges:
122
+ out_edges.setdefault(a, []).append(b)
123
+ self_idx = next((i for i, n in enumerate(nodes) if n["relation"] == "SELF"), 0)
124
+ d.requires = sorted(set(d.requires) | {nodes[j]["name"] for j in out_edges.get(self_idx, [])})
125
+ d.meta = {**(d.meta or {}), "requires_resolved_by": "deps.dev"}
126
+ for i, n in enumerate(nodes):
127
+ if i == self_idx or not n["eco"] or not n["version"]:
128
+ continue
129
+ k = (d.service_dir, n["eco"], normalize_name(n["eco"], n["name"]), n["version"])
130
+ reqs = sorted({nodes[j]["name"] for j in out_edges.get(i, [])})
131
+ if k in existing:
132
+ continue # already a declared/locked record: do not duplicate
133
+ cur = derived.get(k)
134
+ if cur:
135
+ cur.requires = sorted(set(cur.requires) | set(reqs))
136
+ cur.meta["resolved_from"] = sorted(set(cur.meta.get("resolved_from", [])) | {d.name})
137
+ continue
138
+ derived[k] = LockDependency(name=n["name"], version=n["version"], ecosystem=n["eco"], purl=make_purl(n["eco"], n["name"], n["version"]), direct=False,
139
+ requires=reqs, lockfile=f"{d.lockfile} (resolved via deps.dev)", service_dir=d.service_dir, record=f"resolved from {d.name}@{d.version}",
140
+ source_type="registry", derived=True, meta={"resolved_from": [d.name]})
141
+ stats["derived_packages"] = len(derived)
142
+ stats["seconds"] = round(time.time() - t0, 1)
143
+ return {"derived": list(derived.values()), "stats": stats}
@@ -0,0 +1,114 @@
1
+ """Write the fused inventory as a CycloneDX document: the canonical document with every fused field added in native CycloneDX form.
2
+
3
+ * licenses -> ``licenses`` (SPDX id when recognised, expression for compound ones, otherwise name)
4
+ * hashes -> ``hashes`` (hex), supplier -> ``supplier.name``, description, scope (required|optional)
5
+ * links -> ``externalReferences`` (website, vcs, issue-tracker, documentation, distribution)
6
+ * provenance and integrity verdicts -> ``properties`` (``sc-guardian:*``) so nothing is hidden in the file
7
+ The original scanner file is never modified; this is a separate, self-describing document.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import copy
12
+ import re
13
+ import time
14
+ import uuid
15
+ from typing import Any
16
+
17
+ from core.models import Component
18
+ from sbom.fusion import ledger
19
+
20
+ _SPDX = {
21
+ "0BSD", "AGPL-3.0-only", "AGPL-3.0-or-later", "Apache-1.1", "Apache-2.0", "Artistic-2.0", "BlueOak-1.0.0", "BSD-2-Clause", "BSD-3-Clause", "BSD-3-Clause-Clear", "BSL-1.0",
22
+ "CC-BY-3.0", "CC-BY-4.0", "CC0-1.0", "CDDL-1.0", "EPL-1.0", "EPL-2.0", "EUPL-1.2", "GPL-2.0-only", "GPL-2.0-or-later", "GPL-3.0-only", "GPL-3.0-or-later", "ISC", "LGPL-2.1-only",
23
+ "LGPL-2.1-or-later", "LGPL-3.0-only", "LGPL-3.0-or-later", "MIT", "MIT-0", "MPL-1.1", "MPL-2.0", "MS-PL", "OFL-1.1", "PSF-2.0", "Python-2.0", "Unlicense", "Zlib", "WTFPL", "Unicode-DFS-2016",
24
+ "GPL-2.0", "GPL-3.0", "LGPL-2.1", "LGPL-3.0", "AGPL-3.0", "BSD-4-Clause", "Apache-1.0", "CC-BY-SA-4.0", "Artistic-1.0", "JSON", "NCSA", "OpenSSL", "Ruby", "X11",
25
+ }
26
+ _EXPR = re.compile(r"\s(OR|AND|WITH)\s|[()]", re.I)
27
+
28
+
29
+ def license_entry(s: str) -> dict:
30
+ s = s.strip()
31
+ if _EXPR.search(s):
32
+ return {"expression": s}
33
+ if s in _SPDX:
34
+ return {"license": {"id": s}}
35
+ for cand in _SPDX: # case-insensitive match, e.g. "mit" or "Apache-2.0 "
36
+ if cand.lower() == s.lower():
37
+ return {"license": {"id": cand}}
38
+ return {"license": {"name": s}}
39
+
40
+
41
+ def _props(c: Component) -> list[dict]:
42
+ out = []
43
+ for f, p in c.provenance.items():
44
+ if f.startswith("_") or not isinstance(p, dict) or not p.get("source"):
45
+ continue
46
+ out.append({"name": f"sc-guardian:provenance:{f}", "value": p["source"]})
47
+ if p.get("confidence") and p["confidence"] != "high":
48
+ out.append({"name": f"sc-guardian:confidence:{f}", "value": p["confidence"]})
49
+ for cf in p.get("conflicts", [])[:3]:
50
+ out.append({"name": f"sc-guardian:conflict:{f}", "value": f"{cf['source']}={cf['value']}"})
51
+ lk = c.integrity.get("lockfile") or {}
52
+ if lk.get("kind") == "tree": # Go h1: digest of the module tree - not a file hash, so not a CycloneDX hash; kept verbatim as a property
53
+ out.append({"name": "sc-guardian:digest:go-h1", "value": f"sha256:{lk.get('hex')}"})
54
+ st = c.integrity.get("status")
55
+ if st:
56
+ out.append({"name": "sc-guardian:integrity", "value": st})
57
+ if c.install_script:
58
+ out.append({"name": "sc-guardian:install-script", "value": "true"})
59
+ if c.deprecated:
60
+ out.append({"name": "sc-guardian:deprecated", "value": "true"})
61
+ if c.published_at:
62
+ out.append({"name": "sc-guardian:published", "value": str(c.published_at)})
63
+ if c.source_type:
64
+ out.append({"name": "sc-guardian:source-type", "value": c.source_type})
65
+ if c.resolved_url:
66
+ out.append({"name": "sc-guardian:resolved", "value": c.resolved_url[:300]})
67
+ if c.resolution != "scanner":
68
+ out.append({"name": "sc-guardian:resolution", "value": c.resolution})
69
+ out.append({"name": "sc-guardian:completeness", "value": str(ledger.completeness(c))})
70
+ return out
71
+
72
+
73
+ def write_fused(doc: dict, components: list[Component], report: dict, requested_tool: str) -> dict:
74
+ d = copy.deepcopy(doc)
75
+ d["serialNumber"] = f"urn:uuid:{uuid.uuid4()}"
76
+ d["version"] = 1
77
+ by_ref = {c.bom_ref: c for c in components}
78
+ for entry in d.get("components") or []:
79
+ c = by_ref.get(entry.get("bom-ref"))
80
+ if not c or c.is_self:
81
+ continue
82
+ if c.licenses:
83
+ entry["licenses"] = [license_entry(x) for x in c.licenses]
84
+ if c.hashes:
85
+ have = {(h.get("alg"), h.get("content")) for h in entry.get("hashes", []) or []}
86
+ entry["hashes"] = list(entry.get("hashes") or []) + [h for h in c.hashes if (h.get("alg"), h.get("content")) not in have]
87
+ if c.supplier and not entry.get("supplier"):
88
+ entry["supplier"] = {"name": c.supplier}
89
+ if c.description and not entry.get("description"):
90
+ entry["description"] = c.description
91
+ if c.scope in ("required", "optional"):
92
+ entry["scope"] = c.scope
93
+ elif c.scope == "dev":
94
+ entry["scope"] = "optional"
95
+ if c.external_refs:
96
+ have = {r.get("url") for r in entry.get("externalReferences", []) or []}
97
+ entry["externalReferences"] = list(entry.get("externalReferences") or []) + [{"type": r["type"], "url": r["url"]} for r in c.external_refs if r["url"] not in have]
98
+ entry["properties"] = [p for p in entry.get("properties", []) or [] if not str(p.get("name", "")).startswith(("sc-guardian:provenance", "sc-guardian:confidence",
99
+ "sc-guardian:conflict", "sc-guardian:integrity", "sc-guardian:completeness",
100
+ "sc-guardian:resolved", "sc-guardian:source-type"))] + _props(c)
101
+ if c.scope == "dev":
102
+ entry["properties"].append({"name": "sc-guardian:dev", "value": "true"})
103
+ md = d.setdefault("metadata", {})
104
+ md["timestamp"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
105
+ tools = md.setdefault("tools", {})
106
+ if isinstance(tools, dict):
107
+ tools.setdefault("components", []).append({"type": "application", "name": "sc-guardian-metadata-fusion", "version": "1.0",
108
+ "description": "Field-level provenance fusion of lockfile, scanner and registry metadata"})
109
+ md.setdefault("properties", []).extend([
110
+ {"name": "sc-guardian:fused-from", "value": requested_tool},
111
+ {"name": "sc-guardian:average-completeness", "value": str(report.get("average_completeness"))},
112
+ {"name": "sc-guardian:integrity-summary", "value": ",".join(f"{k}={v}" for k, v in sorted((report.get("integrity") or {}).items()))},
113
+ ])
114
+ return d
@@ -0,0 +1,114 @@
1
+ """Dispatch manifest/lockfile text to ecosystem parsers. Parser failures are recorded, never raised."""
2
+ from __future__ import annotations
3
+
4
+ import os
5
+ from pathlib import Path
6
+ from typing import Callable, Optional
7
+
8
+ from core.models import InspectionResult, LockDependency
9
+ from core.repository_inspector import safe_read_text
10
+ from sbom.package_extractors import manifests, npm, others, python
11
+
12
+ SIBLINGS = {
13
+ "package-lock.json": {"package_json": "package.json"},
14
+ "npm-shrinkwrap.json": {"package_json": "package.json"},
15
+ "yarn.lock": {"package_json": "package.json"},
16
+ "pnpm-lock.yaml": {"package_json": "package.json"},
17
+ "poetry.lock": {"pyproject": "pyproject.toml"},
18
+ "composer.lock": {"composer_json": "composer.json"},
19
+ }
20
+
21
+ PARSERS: dict[str, Callable] = {
22
+ "package-lock.json": npm.parse_package_lock,
23
+ "npm-shrinkwrap.json": npm.parse_package_lock,
24
+ "yarn.lock": npm.parse_yarn_lock,
25
+ "pnpm-lock.yaml": npm.parse_pnpm_lock,
26
+ "poetry.lock": python.parse_poetry_lock,
27
+ "uv.lock": python.parse_uv_lock,
28
+ "Pipfile.lock": python.parse_pipfile_lock,
29
+ "go.mod": others.parse_go_mod,
30
+ "go.sum": others.parse_go_sum,
31
+ "Cargo.lock": others.parse_cargo_lock,
32
+ "composer.lock": others.parse_composer_lock,
33
+ "packages.lock.json": others.parse_nuget_lock,
34
+ "pom.xml": others.parse_pom,
35
+ "build.gradle": others.parse_gradle,
36
+ "build.gradle.kts": others.parse_gradle,
37
+ "gradle.lockfile": others.parse_gradle_lockfile,
38
+ }
39
+
40
+
41
+ # Fallback parsers for declaration files, used only when a service has no lockfile for that ecosystem.
42
+ MANIFEST_PARSERS: dict[str, Callable] = {
43
+ "package.json": manifests.parse_package_json,
44
+ "pyproject.toml": manifests.parse_pyproject,
45
+ "Cargo.toml": manifests.parse_cargo_toml,
46
+ "composer.json": manifests.parse_composer_json,
47
+ }
48
+
49
+
50
+ def register_parser(name: str, parser: Callable, siblings: Optional[dict[str, str]] = None) -> None:
51
+ """Plugin hook: ``parser(text, path, service_dir, **sibling_texts) -> list[LockDependency]`` for files called ``name``."""
52
+ PARSERS[name] = parser
53
+ if siblings:
54
+ SIBLINGS[name] = siblings
55
+
56
+
57
+ def manifest_parser_for(name: str) -> Optional[Callable]:
58
+ return MANIFEST_PARSERS.get(name)
59
+
60
+
61
+ def parser_for(name: str) -> Optional[Callable]:
62
+ if name in PARSERS:
63
+ return PARSERS[name]
64
+ if name.startswith("requirements") and name.endswith(".txt"):
65
+ return python.parse_requirements
66
+ if name.endswith((".csproj", ".fsproj", ".vbproj")):
67
+ return others.parse_csproj
68
+ return None
69
+
70
+
71
+ def supported_files() -> list[str]:
72
+ return sorted(PARSERS) + ["requirements*.txt", "*.csproj"]
73
+
74
+
75
+ def parse_text(name: str, text: str, path: str, service_dir: str,
76
+ sibling_texts: Optional[dict[str, Optional[str]]] = None) -> list[LockDependency]:
77
+ fn = parser_for(name)
78
+ if fn is None:
79
+ return []
80
+ return fn(text, path, service_dir, **(sibling_texts or {}))
81
+
82
+
83
+ def analyze_repository(root: Path, inspection: InspectionResult) -> tuple[list[LockDependency], list[dict]]:
84
+ """Parse every discovered manifest/lockfile. Returns (dependencies, errors)."""
85
+ deps: list[LockDependency] = []
86
+ errors: list[dict] = []
87
+ locked = {(m.service_dir, m.ecosystem) for m in inspection.manifests if parser_for(m.name) and m.kind == "lockfile"}
88
+ # a workspace lockfile at the repository root also resolves its member packages
89
+ root_locked = {eco for d, eco in locked if d == "." and eco in ("npm", "crates.io")}
90
+ for mf in inspection.manifests:
91
+ fn = parser_for(mf.name)
92
+ if fn is None:
93
+ fallback = manifest_parser_for(mf.name)
94
+ if fallback and ((mf.service_dir, mf.ecosystem) in locked or mf.ecosystem in root_locked):
95
+ continue # the lockfile is authoritative
96
+ if not fallback:
97
+ siblings = [m for m in inspection.manifests if m.service_dir == mf.service_dir and m.ecosystem == mf.ecosystem]
98
+ if not any(parser_for(m.name) for m in siblings):
99
+ errors.append({"file": mf.path, "error": "no built-in parser; its dependencies are not inventoried by the built-in engine"})
100
+ continue
101
+ fn = fallback
102
+ text = safe_read_text(root, mf.path)
103
+ if text is None:
104
+ errors.append({"file": mf.path, "error": "file unreadable, a symlink or over the size limit"})
105
+ continue
106
+ sib = {}
107
+ for kw, sib_name in SIBLINGS.get(mf.name, {}).items():
108
+ rel = mf.path.rsplit("/", 1)[0] + "/" + sib_name if "/" in mf.path else sib_name
109
+ sib[kw] = safe_read_text(root, rel)
110
+ try:
111
+ deps.extend(fn(text, mf.path, mf.service_dir, **sib))
112
+ except Exception as e: # malformed file must never crash the scan
113
+ errors.append({"file": mf.path, "error": f"{type(e).__name__}: {str(e)[:200]}"})
114
+ return deps, errors