opencra-cli 0.1.0__tar.gz

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.
@@ -0,0 +1,249 @@
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[codz]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py.cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ # Pipfile.lock
96
+
97
+ # UV
98
+ # Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ # uv.lock
102
+
103
+ # poetry
104
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
105
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
106
+ # commonly ignored for libraries.
107
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
108
+ # poetry.lock
109
+ # poetry.toml
110
+
111
+ # pdm
112
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
113
+ # pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.
114
+ # https://pdm-project.org/en/latest/usage/project/#working-with-version-control
115
+ # pdm.lock
116
+ # pdm.toml
117
+ .pdm-python
118
+ .pdm-build/
119
+
120
+ # pixi
121
+ # Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.
122
+ # pixi.lock
123
+ # Pixi creates a virtual environment in the .pixi directory, just like venv module creates one
124
+ # in the .venv directory. It is recommended not to include this directory in version control.
125
+ .pixi
126
+
127
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
128
+ __pypackages__/
129
+
130
+ # Celery stuff
131
+ celerybeat-schedule
132
+ celerybeat.pid
133
+
134
+ # Redis
135
+ *.rdb
136
+ *.aof
137
+ *.pid
138
+
139
+ # RabbitMQ
140
+ mnesia/
141
+ rabbitmq/
142
+ rabbitmq-data/
143
+
144
+ # ActiveMQ
145
+ activemq-data/
146
+
147
+ # SageMath parsed files
148
+ *.sage.py
149
+
150
+ # Environments
151
+ .env
152
+ .envrc
153
+ .venv
154
+ env/
155
+ venv/
156
+ ENV/
157
+ env.bak/
158
+ venv.bak/
159
+
160
+ # Spyder project settings
161
+ .spyderproject
162
+ .spyproject
163
+
164
+ # Rope project settings
165
+ .ropeproject
166
+
167
+ # mkdocs documentation
168
+ /site
169
+
170
+ # mypy
171
+ .mypy_cache/
172
+ .dmypy.json
173
+ dmypy.json
174
+
175
+ # Pyre type checker
176
+ .pyre/
177
+
178
+ # pytype static type analyzer
179
+ .pytype/
180
+
181
+ # Cython debug symbols
182
+ cython_debug/
183
+
184
+ # PyCharm
185
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
186
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
187
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
188
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
189
+ # .idea/
190
+
191
+ # Abstra
192
+ # Abstra is an AI-powered process automation framework.
193
+ # Ignore directories containing user credentials, local state, and settings.
194
+ # Learn more at https://abstra.io/docs
195
+ .abstra/
196
+
197
+ # Visual Studio Code
198
+ # Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore
199
+ # that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
200
+ # and can be added to the global gitignore or merged into this file. However, if you prefer,
201
+ # you could uncomment the following to ignore the entire vscode folder
202
+ # .vscode/
203
+ # Temporary file for partial code execution
204
+ tempCodeRunnerFile.py
205
+
206
+ # Ruff stuff:
207
+ .ruff_cache/
208
+
209
+ # PyPI configuration file
210
+ .pypirc
211
+
212
+ # Marimo
213
+ marimo/_static/
214
+ marimo/_lsp/
215
+ __marimo__/
216
+
217
+ # Streamlit
218
+ .streamlit/secrets.toml
219
+
220
+ # Environment variables & secrets (CRITICAL)
221
+ .env
222
+ .env.*
223
+ !.env.example
224
+
225
+ # IDEs & Editor settings
226
+ .vscode/
227
+ .idea/
228
+
229
+ # Local OS metadata
230
+ .DS_Store
231
+ Thumbs.db
232
+
233
+ # SQLite / Local Databases
234
+ *.db
235
+ *.sqlite3
236
+ crashield.db
237
+
238
+ # OpenCRA CLI output test files
239
+ *.cyclonedx.json
240
+ *.spdx.json
241
+ cra-report.pdf
242
+ *.pdf-fallback.txt
243
+
244
+ # Node / frontend
245
+ node_modules/
246
+ apps/web/dist/
247
+
248
+ # uv
249
+ .python-version
@@ -0,0 +1,13 @@
1
+ Metadata-Version: 2.5
2
+ Name: opencra-cli
3
+ Version: 0.1.0
4
+ Summary: OpenCRA command-line scanner — Syft wrapper, OSV + CISA KEV matching.
5
+ License: Apache-2.0
6
+ Requires-Python: >=3.12
7
+ Requires-Dist: httpx>=0.27
8
+ Requires-Dist: jinja2>=3.1
9
+ Requires-Dist: opencra-shared
10
+ Requires-Dist: rich>=13.9
11
+ Requires-Dist: typer>=0.15
12
+ Provides-Extra: pdf
13
+ Requires-Dist: weasyprint>=63.0; extra == 'pdf'
@@ -0,0 +1,3 @@
1
+ """OpenCRA CLI — Syft wrapper, OSV + CISA KEV matching."""
2
+
3
+ __version__ = "0.1.0"
@@ -0,0 +1,257 @@
1
+ """OpenCRA Typer CLI."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ from datetime import datetime, timezone
7
+ from enum import Enum
8
+ from pathlib import Path
9
+
10
+ import typer
11
+ from opencra_shared.models import FailOn, OutputFormat, ScanResult
12
+ from rich.console import Console
13
+
14
+ from opencra_cli import __version__
15
+ from opencra_cli.db import Cache, default_db_path
16
+ from opencra_cli.kev import KevError, load_index, refresh
17
+ from opencra_cli.match import merge_matches
18
+ from opencra_cli.nvd import cvss_from_nvd, enrich_cve
19
+ from opencra_cli.osv import ping as osv_ping
20
+ from opencra_cli.osv import query_batch
21
+ from opencra_cli.pdf import PDF_HINT, export_report, weasyprint_status
22
+ from opencra_cli.render import format_payload, print_table, result_to_json, write_output
23
+ from opencra_cli.syft import SyftError, resolve_syft, scan_to_document, syft_version, version_ok
24
+ from opencra_cli.sync import ingest
25
+
26
+ app = typer.Typer(
27
+ name="opencra",
28
+ help="CRA Article 14 reporting readiness for your SBOM. A KEV hit is a candidate, not awareness.",
29
+ no_args_is_help=True,
30
+ )
31
+ console = Console()
32
+ err_console = Console(stderr=True)
33
+
34
+
35
+ class FailOnOpt(str, Enum):
36
+ none = "none"
37
+ kev = "kev"
38
+ critical = "critical"
39
+ high = "high"
40
+
41
+
42
+ class FormatOpt(str, Enum):
43
+ table = "table"
44
+ json = "json"
45
+ cyclonedx = "cyclonedx"
46
+ spdx = "spdx"
47
+
48
+
49
+ class EnrichOpt(str, Enum):
50
+ none = "none"
51
+ nvd = "nvd"
52
+
53
+
54
+ def _configure_logging(verbose: bool, quiet: bool) -> None:
55
+ level = logging.WARNING
56
+ if verbose:
57
+ level = logging.DEBUG
58
+ if quiet:
59
+ level = logging.ERROR
60
+ logging.basicConfig(level=level, format="%(levelname)s %(name)s: %(message)s")
61
+
62
+
63
+ def _exit(code: int, message: str | None = None) -> None:
64
+ if message:
65
+ err_console.print(f"[red]{message}[/red]")
66
+ raise typer.Exit(code)
67
+
68
+
69
+ def _run_scan(
70
+ target: str,
71
+ *,
72
+ offline: bool,
73
+ enrich: EnrichOpt,
74
+ syft_bin: str | None,
75
+ cache: Cache,
76
+ ) -> ScanResult:
77
+ document = scan_to_document(target, syft_bin=syft_bin)
78
+ skipped = [c for c in document.components if not c.purl]
79
+ valid_purls = sorted({c.purl for c in document.components if c.purl})
80
+ warnings: list[str] = []
81
+ if skipped:
82
+ warnings.append(
83
+ f"Skipped {len(skipped)} component(s) with invalid or missing PURLs "
84
+ "(they were not sent to OSV)."
85
+ )
86
+
87
+ kev_index = load_index(cache, offline=offline)
88
+ osv_by_purl = query_batch(valid_purls, cache, offline=offline)
89
+ matches = merge_matches(document.components, osv_by_purl, kev_index)
90
+
91
+ if enrich is EnrichOpt.nvd and not offline:
92
+ for match in matches:
93
+ if match.cve_id and match.cvss_v3 is None:
94
+ payload = enrich_cve(match.cve_id)
95
+ if payload:
96
+ match.cvss_v3 = cvss_from_nvd(payload)
97
+
98
+ return ScanResult(
99
+ target=target,
100
+ scanned_at=datetime.now(timezone.utc),
101
+ sbom=document,
102
+ matches=matches,
103
+ skipped_components=skipped,
104
+ offline=offline,
105
+ warnings=warnings,
106
+ )
107
+
108
+
109
+ @app.command()
110
+ def scan(
111
+ target: str = typer.Argument(
112
+ ".", help="Path, image, Syft target, or CycloneDX JSON file."
113
+ ),
114
+ format: FormatOpt = typer.Option(FormatOpt.table, "--format", help="Output format."),
115
+ output: Path | None = typer.Option(None, "--output", help="Write formatted output to PATH."),
116
+ export_pdf: Path | None = typer.Option(
117
+ None, "--export-pdf", help="Write a community PDF (falls back to HTML/Markdown)."
118
+ ),
119
+ fail_on: FailOnOpt = typer.Option(
120
+ FailOnOpt.kev, "--fail-on", help="Exit 1 when threshold is met. Default: kev."
121
+ ),
122
+ offline: bool = typer.Option(False, "--offline", help="Use SQLite caches only. No network."),
123
+ enrich: EnrichOpt = typer.Option(EnrichOpt.none, "--enrich"),
124
+ sync_cloud: bool = typer.Option(False, "--sync-cloud", help="POST results to CRA-Shield."),
125
+ syft_bin: str | None = typer.Option(None, "--syft-bin", help="Path to the Syft binary."),
126
+ quiet: bool = typer.Option(False, "--quiet"),
127
+ verbose: bool = typer.Option(False, "--verbose"),
128
+ ) -> None:
129
+ """Generate or ingest an SBOM and match components against OSV + CISA KEV."""
130
+ _configure_logging(verbose, quiet)
131
+ try:
132
+ with Cache() as cache:
133
+ result = _run_scan(
134
+ target,
135
+ offline=offline,
136
+ enrich=enrich,
137
+ syft_bin=syft_bin,
138
+ cache=cache,
139
+ )
140
+ cache.save_scan(target, result_to_json(result), result.sbom.model_dump(mode="json"))
141
+ except SyftError as exc:
142
+ _exit(exc.exit_code, str(exc))
143
+ except KevError as exc:
144
+ _exit(2, str(exc))
145
+
146
+ fmt = OutputFormat(format.value)
147
+ if fmt is OutputFormat.TABLE and not quiet:
148
+ print_table(result, console)
149
+ elif fmt is not OutputFormat.TABLE:
150
+ payload = format_payload(result, fmt)
151
+ if output:
152
+ write_output(result, fmt, output)
153
+ if not quiet:
154
+ console.print(f"Wrote {fmt.value} to {output}")
155
+ else:
156
+ console.print(payload)
157
+ elif output:
158
+ write_output(result, OutputFormat.JSON, output)
159
+
160
+ if export_pdf:
161
+ written = export_report(result, export_pdf)
162
+ if not quiet:
163
+ if written.suffix == ".pdf":
164
+ console.print(f"Wrote PDF to {written}")
165
+ else:
166
+ console.print(
167
+ f"[yellow]PDF engine unavailable.[/yellow] Wrote {written} instead.\n{PDF_HINT}"
168
+ )
169
+
170
+ if sync_cloud:
171
+ response = ingest(result)
172
+ if not quiet:
173
+ console.print(response.get("message") or response)
174
+
175
+ threshold = FailOn(fail_on.value)
176
+ if result.fails(threshold):
177
+ _exit(1, f"Scan failed --fail-on {threshold.value}.")
178
+
179
+
180
+ @app.command()
181
+ def doctor(
182
+ syft_bin: str | None = typer.Option(None, "--syft-bin"),
183
+ ) -> None:
184
+ """Check Syft, network, cache, and PDF engine. Friendly, not a stack trace."""
185
+ console.print(f"[bold]OpenCRA[/bold] {__version__}")
186
+ try:
187
+ path = resolve_syft(syft_bin)
188
+ label, parsed = syft_version(syft_bin)
189
+ ok = version_ok(parsed)
190
+ status = "[green]ok[/green]" if ok else "[yellow]old[/yellow]"
191
+ console.print(f"Syft: {status} {path} ({label})")
192
+ if not ok:
193
+ console.print(" Install Syft >= 1.0.0 for CycloneDX 1.6 output.")
194
+ except SyftError as exc:
195
+ console.print(f"Syft: [red]missing[/red]\n{exc}")
196
+
197
+ cache_path = default_db_path()
198
+ console.print(f"Cache: {cache_path} ({'exists' if cache_path.exists() else 'will be created'})")
199
+ with Cache() as cache:
200
+ fetched = cache.get_kev_fetched_at()
201
+ console.print(f"KEV cache: {fetched.isoformat() if fetched else 'empty'}")
202
+
203
+ console.print(f"OSV: {'reachable' if osv_ping() else 'unreachable (offline scans still work)'}")
204
+ pdf_ok, pdf_reason = weasyprint_status()
205
+ console.print(f"PDF engine: {'ok' if pdf_ok else 'fallback'} — {pdf_reason}")
206
+ console.print(
207
+ "[dim]A KEV match is a CRA candidate. Clocks start only after human awareness.[/dim]"
208
+ )
209
+
210
+
211
+ @app.command("kev")
212
+ def kev_cmd(
213
+ action: str = typer.Argument("refresh", help="Only 'refresh' is supported."),
214
+ ) -> None:
215
+ """Download or refresh the CISA KEV catalog into the local cache."""
216
+ if action != "refresh":
217
+ _exit(2, "Usage: opencra kev refresh")
218
+ try:
219
+ with Cache() as cache:
220
+ count, fetched = refresh(cache)
221
+ except KevError as exc:
222
+ _exit(2, str(exc))
223
+ console.print(f"Cached {count} CISA KEV entries ({fetched.isoformat()}).")
224
+
225
+
226
+ @app.command()
227
+ def report(
228
+ last: bool = typer.Option(False, "--last", help="Re-render the most recent local scan."),
229
+ export_pdf: Path | None = typer.Option(None, "--export-pdf"),
230
+ format: FormatOpt = typer.Option(FormatOpt.table, "--format"),
231
+ ) -> None:
232
+ """Show the last cached scan without invoking Syft."""
233
+ if not last:
234
+ _exit(2, "Pass --last to print the most recent scan.")
235
+ with Cache() as cache:
236
+ raw = cache.last_scan()
237
+ if raw is None:
238
+ _exit(2, "No cached scans. Run `opencra scan .` first.")
239
+ result = ScanResult.model_validate(raw)
240
+ fmt = OutputFormat(format.value)
241
+ if fmt is OutputFormat.TABLE:
242
+ print_table(result, console)
243
+ else:
244
+ console.print(format_payload(result, fmt))
245
+ if export_pdf:
246
+ written = export_report(result, export_pdf)
247
+ console.print(f"Wrote report to {written}")
248
+
249
+
250
+ @app.callback()
251
+ def main() -> None:
252
+ """OpenCRA CLI."""
253
+ return
254
+
255
+
256
+ if __name__ == "__main__":
257
+ app()
@@ -0,0 +1,176 @@
1
+ """Local SQLite cache at ~/.opencra/cache.db with WAL mode."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import sqlite3
8
+ from datetime import datetime, timedelta, timezone
9
+ from pathlib import Path
10
+ from typing import Any
11
+
12
+ OSV_TTL = timedelta(hours=12)
13
+
14
+
15
+ def default_db_path() -> Path:
16
+ override = os.environ.get("OPENCRA_CACHE")
17
+ if override:
18
+ return Path(override).expanduser()
19
+ return Path.home() / ".opencra" / "cache.db"
20
+
21
+
22
+ class Cache:
23
+ def __init__(self, path: Path | None = None) -> None:
24
+ self.path = path or default_db_path()
25
+ self.path.parent.mkdir(parents=True, exist_ok=True)
26
+ self.conn = sqlite3.connect(self.path)
27
+ self.conn.row_factory = sqlite3.Row
28
+ self.conn.execute("PRAGMA journal_mode=WAL;")
29
+ self.conn.execute("PRAGMA foreign_keys=ON;")
30
+ self._init()
31
+
32
+ def close(self) -> None:
33
+ self.conn.close()
34
+
35
+ def __enter__(self) -> Cache:
36
+ return self
37
+
38
+ def __exit__(self, *args: object) -> None:
39
+ self.close()
40
+
41
+ def _init(self) -> None:
42
+ self.conn.executescript(
43
+ """
44
+ CREATE TABLE IF NOT EXISTS kev_meta (
45
+ id INTEGER PRIMARY KEY CHECK (id = 1),
46
+ fetched_at TEXT NOT NULL,
47
+ catalog_json TEXT NOT NULL
48
+ );
49
+ CREATE TABLE IF NOT EXISTS osv_cache (
50
+ purl TEXT PRIMARY KEY,
51
+ fetched_at TEXT NOT NULL,
52
+ vulns_json TEXT NOT NULL
53
+ );
54
+ CREATE TABLE IF NOT EXISTS scans (
55
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
56
+ target TEXT NOT NULL,
57
+ scanned_at TEXT NOT NULL,
58
+ serial_number TEXT,
59
+ sbom_json TEXT NOT NULL,
60
+ result_json TEXT NOT NULL
61
+ );
62
+ CREATE TABLE IF NOT EXISTS components (
63
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
64
+ scan_id INTEGER NOT NULL,
65
+ purl TEXT,
66
+ name TEXT NOT NULL,
67
+ version TEXT,
68
+ FOREIGN KEY (scan_id) REFERENCES scans(id)
69
+ );
70
+ CREATE TABLE IF NOT EXISTS matches (
71
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
72
+ scan_id INTEGER NOT NULL,
73
+ purl TEXT NOT NULL,
74
+ osv_id TEXT,
75
+ cve_id TEXT,
76
+ severity TEXT,
77
+ in_kev INTEGER NOT NULL DEFAULT 0,
78
+ summary TEXT,
79
+ FOREIGN KEY (scan_id) REFERENCES scans(id)
80
+ );
81
+ """
82
+ )
83
+ self.conn.commit()
84
+
85
+ def get_kev_catalog(self) -> dict[str, Any] | None:
86
+ row = self.conn.execute("SELECT catalog_json FROM kev_meta WHERE id = 1").fetchone()
87
+ if not row:
88
+ return None
89
+ return json.loads(row["catalog_json"])
90
+
91
+ def get_kev_fetched_at(self) -> datetime | None:
92
+ row = self.conn.execute("SELECT fetched_at FROM kev_meta WHERE id = 1").fetchone()
93
+ if not row:
94
+ return None
95
+ return datetime.fromisoformat(row["fetched_at"])
96
+
97
+ def save_kev_catalog(self, payload: dict[str, Any]) -> None:
98
+ now = datetime.now(timezone.utc).isoformat()
99
+ self.conn.execute(
100
+ """
101
+ INSERT INTO kev_meta (id, fetched_at, catalog_json)
102
+ VALUES (1, ?, ?)
103
+ ON CONFLICT(id) DO UPDATE SET fetched_at = excluded.fetched_at,
104
+ catalog_json = excluded.catalog_json
105
+ """,
106
+ (now, json.dumps(payload)),
107
+ )
108
+ self.conn.commit()
109
+
110
+ def get_osv(self, purl: str) -> list[dict[str, Any]] | None:
111
+ row = self.conn.execute(
112
+ "SELECT fetched_at, vulns_json FROM osv_cache WHERE purl = ?",
113
+ (purl,),
114
+ ).fetchone()
115
+ if not row:
116
+ return None
117
+ fetched = datetime.fromisoformat(row["fetched_at"])
118
+ if datetime.now(timezone.utc) - fetched > OSV_TTL:
119
+ return None
120
+ return json.loads(row["vulns_json"])
121
+
122
+ def save_osv(self, purl: str, vulns: list[dict[str, Any]]) -> None:
123
+ now = datetime.now(timezone.utc).isoformat()
124
+ self.conn.execute(
125
+ """
126
+ INSERT INTO osv_cache (purl, fetched_at, vulns_json)
127
+ VALUES (?, ?, ?)
128
+ ON CONFLICT(purl) DO UPDATE SET fetched_at = excluded.fetched_at,
129
+ vulns_json = excluded.vulns_json
130
+ """,
131
+ (purl, now, json.dumps(vulns)),
132
+ )
133
+ self.conn.commit()
134
+
135
+ def save_scan(self, target: str, result_json: dict[str, Any], sbom_json: dict[str, Any]) -> int:
136
+ scanned_at = result_json.get("scanned_at") or datetime.now(timezone.utc).isoformat()
137
+ serial = (result_json.get("sbom") or {}).get("serial_number")
138
+ cur = self.conn.execute(
139
+ """
140
+ INSERT INTO scans (target, scanned_at, serial_number, sbom_json, result_json)
141
+ VALUES (?, ?, ?, ?, ?)
142
+ """,
143
+ (target, scanned_at, serial, json.dumps(sbom_json), json.dumps(result_json)),
144
+ )
145
+ scan_id = int(cur.lastrowid or 0)
146
+ for component in (result_json.get("sbom") or {}).get("components") or []:
147
+ self.conn.execute(
148
+ "INSERT INTO components (scan_id, purl, name, version) VALUES (?, ?, ?, ?)",
149
+ (scan_id, component.get("purl"), component.get("name"), component.get("version")),
150
+ )
151
+ for match in result_json.get("matches") or []:
152
+ self.conn.execute(
153
+ """
154
+ INSERT INTO matches (scan_id, purl, osv_id, cve_id, severity, in_kev, summary)
155
+ VALUES (?, ?, ?, ?, ?, ?, ?)
156
+ """,
157
+ (
158
+ scan_id,
159
+ match.get("purl"),
160
+ match.get("osv_id"),
161
+ match.get("cve_id"),
162
+ match.get("severity"),
163
+ 1 if match.get("in_kev") else 0,
164
+ match.get("summary"),
165
+ ),
166
+ )
167
+ self.conn.commit()
168
+ return scan_id
169
+
170
+ def last_scan(self) -> dict[str, Any] | None:
171
+ row = self.conn.execute(
172
+ "SELECT result_json FROM scans ORDER BY id DESC LIMIT 1"
173
+ ).fetchone()
174
+ if not row:
175
+ return None
176
+ return json.loads(row["result_json"])