sbombox 0.1.1__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.
Files changed (32) hide show
  1. sbombox-0.1.1/.gitignore +40 -0
  2. sbombox-0.1.1/PKG-INFO +83 -0
  3. sbombox-0.1.1/README.md +56 -0
  4. sbombox-0.1.1/pyproject.toml +41 -0
  5. sbombox-0.1.1/src/sbombox_cli/__init__.py +16 -0
  6. sbombox-0.1.1/src/sbombox_cli/api_client.py +222 -0
  7. sbombox-0.1.1/src/sbombox_cli/auth.py +200 -0
  8. sbombox-0.1.1/src/sbombox_cli/ci_auth.py +121 -0
  9. sbombox-0.1.1/src/sbombox_cli/ci_detect.py +227 -0
  10. sbombox-0.1.1/src/sbombox_cli/commands/__init__.py +1 -0
  11. sbombox-0.1.1/src/sbombox_cli/commands/check.py +72 -0
  12. sbombox-0.1.1/src/sbombox_cli/commands/ci.py +109 -0
  13. sbombox-0.1.1/src/sbombox_cli/commands/compliance.py +47 -0
  14. sbombox-0.1.1/src/sbombox_cli/commands/config_cmd.py +40 -0
  15. sbombox-0.1.1/src/sbombox_cli/commands/fix.py +41 -0
  16. sbombox-0.1.1/src/sbombox_cli/commands/generate.py +97 -0
  17. sbombox-0.1.1/src/sbombox_cli/commands/init.py +133 -0
  18. sbombox-0.1.1/src/sbombox_cli/commands/list.py +75 -0
  19. sbombox-0.1.1/src/sbombox_cli/commands/login.py +41 -0
  20. sbombox-0.1.1/src/sbombox_cli/commands/projects.py +45 -0
  21. sbombox-0.1.1/src/sbombox_cli/commands/push.py +90 -0
  22. sbombox-0.1.1/src/sbombox_cli/commands/score.py +54 -0
  23. sbombox-0.1.1/src/sbombox_cli/commands/share.py +29 -0
  24. sbombox-0.1.1/src/sbombox_cli/commands/status.py +54 -0
  25. sbombox-0.1.1/src/sbombox_cli/commands/upgrade.py +49 -0
  26. sbombox-0.1.1/src/sbombox_cli/config.py +95 -0
  27. sbombox-0.1.1/src/sbombox_cli/main.py +98 -0
  28. sbombox-0.1.1/src/sbombox_cli/update_check.py +111 -0
  29. sbombox-0.1.1/tests/conftest.py +4 -0
  30. sbombox-0.1.1/tests/test_ci.py +169 -0
  31. sbombox-0.1.1/tests/test_inspect_commands.py +84 -0
  32. sbombox-0.1.1/tests/test_versioning.py +43 -0
@@ -0,0 +1,40 @@
1
+ # --- Python ---
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+ *.so
6
+ .Python
7
+ build/
8
+ develop-eggs/
9
+ dist/
10
+ downloads/
11
+ eggs/
12
+ .eggs/
13
+ lib/
14
+ lib64/
15
+ parts/
16
+ sdist/
17
+ var/
18
+ wheels/
19
+ *.egg-info/
20
+ .installed.cfg
21
+ *.egg
22
+ MANIFEST
23
+
24
+ # --- Virtual environments ---
25
+ .env
26
+ .env.*
27
+ !.env.example
28
+ .venv
29
+ env/
30
+ venv/
31
+ ENV/
32
+
33
+ # --- Tooling caches ---
34
+ .mypy_cache/
35
+ .ruff_cache/
36
+ .pytest_cache/
37
+ .coverage
38
+ reports/
39
+ release/
40
+ .DS_Store
sbombox-0.1.1/PKG-INFO ADDED
@@ -0,0 +1,83 @@
1
+ Metadata-Version: 2.5
2
+ Name: sbombox
3
+ Version: 0.1.1
4
+ Summary: SBOMBox CLI - generate, score, and manage SBOMs from the command line
5
+ Project-URL: Homepage, https://sbombox.com
6
+ Project-URL: Documentation, https://sbombox.com/docs/cli
7
+ Project-URL: Source, https://github.com/sbombox-hq/cli
8
+ Project-URL: Issues, https://github.com/sbombox-hq/cli/issues
9
+ Author-email: sia-sbombox <sia@sbombox.com>
10
+ Maintainer-email: sia-sbombox <sia@sbombox.com>
11
+ License-Expression: Apache-2.0
12
+ Requires-Python: >=3.12
13
+ Requires-Dist: httpx>=0.27
14
+ Requires-Dist: keyring>=25.0
15
+ Requires-Dist: rich>=13.0
16
+ Requires-Dist: ruamel-yaml>=0.18
17
+ Requires-Dist: sbombox-core
18
+ Requires-Dist: typer>=0.12
19
+ Provides-Extra: dev
20
+ Requires-Dist: cyclonedx-bom>=7.0; extra == 'dev'
21
+ Requires-Dist: mypy>=1.10; extra == 'dev'
22
+ Requires-Dist: pytest>=8.0; extra == 'dev'
23
+ Requires-Dist: ruff>=0.4; extra == 'dev'
24
+ Provides-Extra: sigstore
25
+ Requires-Dist: sbombox-core[sigstore]; extra == 'sigstore'
26
+ Description-Content-Type: text/markdown
27
+
28
+ # SBOMBox CLI
29
+
30
+ Generate, score, check and upload software bills of materials (SBOMs) from the command line. Works offline for everything except signing in and uploading.
31
+
32
+ ## Install
33
+
34
+ ```sh
35
+ curl -fsSL https://sbombox.com/install.sh | sh
36
+ ```
37
+
38
+ The installer sets up the CLI and an SBOM generator (syft). If you already have a generator, install the CLI on its own:
39
+
40
+ ```sh
41
+ uv tool install sbombox
42
+ ```
43
+
44
+ Requires Python 3.12 or newer.
45
+
46
+ ## Quick start
47
+
48
+ ```sh
49
+ sbombox generate --dir . --output sbom.json # make an SBOM for this project
50
+ sbombox score sbom.json # quality score from 0 to 10
51
+ sbombox compliance sbom.json --profile ntia # check against a ruleset
52
+ sbombox fix sbom.json --output sbom.fixed.json # repair common defects
53
+ ```
54
+
55
+ To upload to SBOMBox:
56
+
57
+ ```sh
58
+ sbombox login
59
+ sbombox push sbom.json
60
+ ```
61
+
62
+ In CI, use the [GitHub Action](https://github.com/sbombox-hq/action) or run `sbombox ci` to let pipelines upload with their OIDC identity instead of a stored token. `sbombox check --fail-under 7` makes a quick local or pre-commit gate.
63
+
64
+ ## Commands
65
+
66
+ | | |
67
+ |---|---|
68
+ | Set up | `login`, `logout`, `whoami`, `init`, `projects`, `ci` |
69
+ | Create and assess | `generate`, `check`, `score`, `compliance`, `list`, `fix`, `share` |
70
+ | Publish | `push`, `status` |
71
+ | Configure | `upgrade`, `config` |
72
+
73
+ Run `sbombox <command> --help` for options.
74
+
75
+ Compliance rulesets: NTIA minimum elements (`ntia-2021`), CISA (`cisa-2025`, `cisa-2026`), EU CRA readiness (`cra-readiness`), BSI TR-03183-2 (`bsi-tr-03183-2@2.1.0` and earlier), FSCT v3 (`fsct-v3`) and OpenChain Telco (`openchain-telco`).
76
+
77
+ ## Links
78
+
79
+ - Docs: [sbombox.com/docs/cli](https://sbombox.com/docs/cli)
80
+ - Source and issues: [github.com/sbombox-hq/cli](https://github.com/sbombox-hq/cli)
81
+ - Security reports: see [SECURITY.md](https://github.com/sbombox-hq/cli/blob/main/SECURITY.md)
82
+
83
+ Licensed under Apache-2.0.
@@ -0,0 +1,56 @@
1
+ # SBOMBox CLI
2
+
3
+ Generate, score, check and upload software bills of materials (SBOMs) from the command line. Works offline for everything except signing in and uploading.
4
+
5
+ ## Install
6
+
7
+ ```sh
8
+ curl -fsSL https://sbombox.com/install.sh | sh
9
+ ```
10
+
11
+ The installer sets up the CLI and an SBOM generator (syft). If you already have a generator, install the CLI on its own:
12
+
13
+ ```sh
14
+ uv tool install sbombox
15
+ ```
16
+
17
+ Requires Python 3.12 or newer.
18
+
19
+ ## Quick start
20
+
21
+ ```sh
22
+ sbombox generate --dir . --output sbom.json # make an SBOM for this project
23
+ sbombox score sbom.json # quality score from 0 to 10
24
+ sbombox compliance sbom.json --profile ntia # check against a ruleset
25
+ sbombox fix sbom.json --output sbom.fixed.json # repair common defects
26
+ ```
27
+
28
+ To upload to SBOMBox:
29
+
30
+ ```sh
31
+ sbombox login
32
+ sbombox push sbom.json
33
+ ```
34
+
35
+ In CI, use the [GitHub Action](https://github.com/sbombox-hq/action) or run `sbombox ci` to let pipelines upload with their OIDC identity instead of a stored token. `sbombox check --fail-under 7` makes a quick local or pre-commit gate.
36
+
37
+ ## Commands
38
+
39
+ | | |
40
+ |---|---|
41
+ | Set up | `login`, `logout`, `whoami`, `init`, `projects`, `ci` |
42
+ | Create and assess | `generate`, `check`, `score`, `compliance`, `list`, `fix`, `share` |
43
+ | Publish | `push`, `status` |
44
+ | Configure | `upgrade`, `config` |
45
+
46
+ Run `sbombox <command> --help` for options.
47
+
48
+ Compliance rulesets: NTIA minimum elements (`ntia-2021`), CISA (`cisa-2025`, `cisa-2026`), EU CRA readiness (`cra-readiness`), BSI TR-03183-2 (`bsi-tr-03183-2@2.1.0` and earlier), FSCT v3 (`fsct-v3`) and OpenChain Telco (`openchain-telco`).
49
+
50
+ ## Links
51
+
52
+ - Docs: [sbombox.com/docs/cli](https://sbombox.com/docs/cli)
53
+ - Source and issues: [github.com/sbombox-hq/cli](https://github.com/sbombox-hq/cli)
54
+ - Security reports: see [SECURITY.md](https://github.com/sbombox-hq/cli/blob/main/SECURITY.md)
55
+
56
+ Licensed under Apache-2.0.
@@ -0,0 +1,41 @@
1
+ [project]
2
+ name = "sbombox"
3
+ version = "0.1.1"
4
+ description = "SBOMBox CLI - generate, score, and manage SBOMs from the command line"
5
+ readme = "README.md"
6
+ requires-python = ">=3.12"
7
+ license = "Apache-2.0"
8
+ authors = [{ name = "sia-sbombox", email = "sia@sbombox.com" }]
9
+ maintainers = [{ name = "sia-sbombox", email = "sia@sbombox.com" }]
10
+ dependencies = [
11
+ "sbombox-core",
12
+ "typer>=0.12",
13
+ "rich>=13.0",
14
+ "httpx>=0.27",
15
+ "keyring>=25.0",
16
+ "ruamel.yaml>=0.18",
17
+ ]
18
+
19
+ [project.optional-dependencies]
20
+ sigstore = ["sbombox-core[sigstore]"]
21
+ # cyclonedx-bom provides cyclonedx-py, the generator the end-to-end `sbombox check` tests run.
22
+ dev = ["pytest>=8.0", "ruff>=0.4", "mypy>=1.10", "cyclonedx-bom>=7.0"]
23
+
24
+ [project.scripts]
25
+ sbombox = "sbombox_cli.main:app"
26
+
27
+ [project.urls]
28
+ Homepage = "https://sbombox.com"
29
+ Documentation = "https://sbombox.com/docs/cli"
30
+ Source = "https://github.com/sbombox-hq/cli"
31
+ Issues = "https://github.com/sbombox-hq/cli/issues"
32
+
33
+ [build-system]
34
+ requires = ["hatchling"]
35
+ build-backend = "hatchling.build"
36
+
37
+ [tool.hatch.build.targets.wheel]
38
+ packages = ["src/sbombox_cli"]
39
+
40
+ [tool.uv.sources]
41
+ sbombox-core = { workspace = true }
@@ -0,0 +1,16 @@
1
+ """SBOMBox CLI package.
2
+
3
+ Command-line interface for generating, scoring, and managing SBOMs. Built on
4
+ Typer + Rich; the heavy lifting is delegated to :mod:`sbombox_core`.
5
+ """
6
+
7
+ from importlib.metadata import PackageNotFoundError, version
8
+
9
+ try:
10
+ # Single source of truth: the version in packages/cli/pyproject.toml, as
11
+ # installed. Never hardcode it here, or the two drift apart.
12
+ __version__ = version("sbombox")
13
+ except PackageNotFoundError: # pragma: no cover - running from a source tree without install
14
+ __version__ = "0.0.0+unknown"
15
+
16
+ __all__ = ["__version__"]
@@ -0,0 +1,222 @@
1
+ """HTTP API client for the SBOMBox backend.
2
+
3
+ Uses ``httpx`` with automatic retries and structured error handling.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ from pathlib import Path
9
+ from typing import Any, Dict, List, Optional
10
+
11
+ import httpx
12
+
13
+ from sbombox_cli.config import CliConfig
14
+
15
+ # Exit codes -----------------------------------------------------------------
16
+
17
+ EXIT_OK = 0
18
+ EXIT_POLICY_FAIL = 1
19
+ EXIT_USAGE = 2
20
+ EXIT_NETWORK = 3
21
+ EXIT_GENERATION = 4
22
+ EXIT_AUTH = 5
23
+ EXIT_UPGRADE = 6
24
+
25
+ _MAX_RETRIES = 3
26
+ _BACKOFF_FACTOR = 0.5
27
+
28
+
29
+ def user_agent() -> str:
30
+ """``sbombox-cli/<version> (<ci>)`` - lets the server's audit log tell CLI
31
+ and CI traffic apart, and shows which CI systems people actually use."""
32
+ from sbombox_cli import __version__
33
+ from sbombox_cli.ci_detect import detect_ci
34
+
35
+ return f"sbombox-cli/{__version__} ({detect_ci().ci_name})"
36
+
37
+
38
+ def _problem_detail(response: httpx.Response) -> str:
39
+ try:
40
+ body = response.json()
41
+ except ValueError:
42
+ return ""
43
+ return str(body.get("detail") or "") if isinstance(body, dict) else ""
44
+
45
+
46
+ class ApiError(Exception):
47
+ """Raised when an API request fails."""
48
+
49
+ def __init__(self, message: str, exit_code: int = EXIT_NETWORK) -> None:
50
+ super().__init__(message)
51
+ self.exit_code = exit_code
52
+
53
+
54
+ class ApiClient:
55
+ """Thin wrapper around ``httpx.Client`` with auth + retry logic."""
56
+
57
+ def __init__(self, config: CliConfig) -> None:
58
+ self._config = config
59
+ self._client = self._build_client()
60
+
61
+ # -- lifecycle ------------------------------------------------------------
62
+
63
+ def _build_client(self) -> httpx.Client:
64
+ """Create an ``httpx.Client`` with auth headers and retry transport."""
65
+ headers: Dict[str, str] = {"Accept": "application/json", "User-Agent": user_agent()}
66
+ if self._config.token:
67
+ headers["Authorization"] = f"Bearer {self._config.token}"
68
+
69
+ transport = httpx.HTTPTransport(retries=_MAX_RETRIES)
70
+ return httpx.Client(
71
+ base_url=self._config.api_url,
72
+ headers=headers,
73
+ transport=transport,
74
+ timeout=30.0,
75
+ )
76
+
77
+ def close(self) -> None:
78
+ """Close the underlying HTTP client."""
79
+ self._client.close()
80
+
81
+ def __enter__(self) -> ApiClient:
82
+ return self
83
+
84
+ def __exit__(self, *exc: Any) -> None:
85
+ self.close()
86
+
87
+ # -- helpers --------------------------------------------------------------
88
+
89
+ def _request(
90
+ self,
91
+ method: str,
92
+ path: str,
93
+ *,
94
+ json: Any = None,
95
+ params: Optional[Dict[str, Any]] = None,
96
+ ) -> Any:
97
+ """Execute an HTTP request and return parsed JSON.
98
+
99
+ Raises
100
+ ------
101
+ ApiError
102
+ On network failures or non-2xx responses.
103
+ """
104
+ try:
105
+ resp = self._client.request(method, path, json=json, params=params)
106
+ resp.raise_for_status()
107
+ if resp.status_code == 204:
108
+ return None
109
+ return resp.json()
110
+ except httpx.HTTPStatusError as exc:
111
+ status = exc.response.status_code
112
+ if status == 426:
113
+ raise ApiError(_problem_detail(exc.response) or "This CLI version is no longer supported. "
114
+ "Run `sbombox upgrade`.", exit_code=EXIT_UPGRADE) from exc
115
+ if status in (401, 403):
116
+ raise ApiError(f"Authentication failed: {exc}", exit_code=EXIT_AUTH) from exc
117
+ detail = ""
118
+ try:
119
+ body = exc.response.json()
120
+ detail = body.get("detail") or body.get("title") or ""
121
+ except ValueError:
122
+ pass
123
+ message = f"API error {status}" + (f": {detail}" if detail else f": {exc}")
124
+ raise ApiError(message, exit_code=EXIT_NETWORK) from exc
125
+ except httpx.RequestError as exc:
126
+ raise ApiError(f"Network error: {exc}", exit_code=EXIT_NETWORK) from exc
127
+
128
+ # -- public API -----------------------------------------------------------
129
+
130
+ def upload_sbom(
131
+ self,
132
+ project_id: str,
133
+ sbom_path: Path,
134
+ *,
135
+ branch: str = "main",
136
+ version_label: str = "",
137
+ sbom_format: str | None = None,
138
+ ci: Optional[Dict[str, str]] = None,
139
+ ) -> Dict[str, Any]:
140
+ """Upload an SBOM document to a project.
141
+
142
+ SBOMs are nested under their project (``/v1/sboms/projects/<id>/sboms/``)
143
+ and sent as JSON so the server can hash and store the exact bytes.
144
+ """
145
+ payload: Dict[str, Any] = {
146
+ "content": sbom_path.read_text(encoding="utf-8"),
147
+ "branch": branch,
148
+ }
149
+ if version_label:
150
+ payload["version_label"] = version_label
151
+ if sbom_format:
152
+ payload["format"] = sbom_format
153
+ if ci:
154
+ payload["ci"] = ci
155
+ return self._request("POST", f"/v1/sboms/projects/{project_id}/sboms/", json=payload)
156
+
157
+ def get_project(self, project_id: str) -> Dict[str, Any]:
158
+ """Retrieve project metadata."""
159
+ return self._request("GET", f"/v1/projects/{project_id}/")
160
+
161
+ def list_projects(self, *, limit: int = 50) -> List[Dict[str, Any]]:
162
+ """List projects across every organization visible to the token."""
163
+ orgs = self._request("GET", "/v1/orgs/")
164
+ projects: List[Dict[str, Any]] = []
165
+ for org in orgs.get("results") or []:
166
+ data = self._request(
167
+ "GET", f"/v1/orgs/{org['slug']}/projects/", params={"limit": limit}
168
+ )
169
+ projects.extend(data.get("results") or [])
170
+ if len(projects) >= limit:
171
+ break
172
+ return projects[:limit]
173
+
174
+ def latest_sbom(self, project_id: str) -> Dict[str, Any]:
175
+ """Return the most recent SBOM for a project, or an empty dict."""
176
+ listing = self._request("GET", f"/v1/sboms/projects/{project_id}/sboms/")
177
+ results = listing.get("results") if isinstance(listing, dict) else listing
178
+ return (results or [{}])[0]
179
+
180
+ def get_score(self, project_id: str, sbom_id: Optional[str] = None) -> Dict[str, Any]:
181
+ """Retrieve the latest score run for a project's SBOM."""
182
+ if not sbom_id:
183
+ sbom_id = self.latest_sbom(project_id).get("id")
184
+ if not sbom_id:
185
+ return {}
186
+ data = self._request(
187
+ "GET", f"/v1/sboms/projects/{project_id}/sboms/{sbom_id}/scores/"
188
+ )
189
+ results = data.get("results") if isinstance(data, dict) else data
190
+ return (results or [{}])[0]
191
+
192
+ def get_vulnerabilities(
193
+ self,
194
+ project_id: str,
195
+ *,
196
+ severity: Optional[str] = None,
197
+ ) -> List[Dict[str, Any]]:
198
+ """List vulnerability findings for a project."""
199
+ params: Dict[str, Any] = {}
200
+ if severity:
201
+ params["severity"] = severity
202
+ data = self._request(
203
+ "GET", f"/v1/vulns/projects/{project_id}/vulnerabilities/", params=params
204
+ )
205
+ results = data.get("results") if isinstance(data, dict) else data
206
+ return results or []
207
+
208
+ def get_trust_rules(self, project_id: str) -> Dict[str, Any]:
209
+ """Return the project's CI (OIDC) trust rules."""
210
+ data = self._request("GET", f"/v1/projects/{project_id}/trust-rules/")
211
+ rules = data.get("trust_rules") if isinstance(data, dict) else None
212
+ return rules if isinstance(rules, dict) else {}
213
+
214
+ def set_trust_rules(self, project_id: str, trust_rules: Dict[str, Any]) -> Dict[str, Any]:
215
+ """Replace the project's CI trust rules (project admin only)."""
216
+ return self._request(
217
+ "PATCH", f"/v1/projects/{project_id}/trust-rules/", json={"trust_rules": trust_rules}
218
+ )
219
+
220
+ def whoami(self) -> Dict[str, Any]:
221
+ """Return information about the authenticated user."""
222
+ return self._request("GET", "/v1/me/")
@@ -0,0 +1,200 @@
1
+ """OAuth device-flow authentication for the SBOMBox CLI.
2
+
3
+ Supports token storage via OS keyring with a fallback to a ``0600`` file
4
+ at ``~/.sbombox/token.json``.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import stat
11
+ import time
12
+ from pathlib import Path
13
+ from typing import Any, Dict, Optional
14
+
15
+ import httpx
16
+
17
+ _KEYRING_SERVICE = "sbombox-cli"
18
+ _KEYRING_USERNAME = "sbombox-user"
19
+ #: Public OAuth client registered for the device-code grant. The server grants
20
+ #: this client's full scope set when ``scope`` is omitted.
21
+ _CLIENT_ID = "sbombox-cli"
22
+ _TOKEN_DIR = Path.home() / ".sbombox"
23
+ _TOKEN_FILE = _TOKEN_DIR / "token.json"
24
+
25
+ _POLL_INTERVAL = 5 # seconds
26
+ _DEFAULT_TIMEOUT = 30.0
27
+
28
+
29
+ # -- token storage ------------------------------------------------------------
30
+
31
+
32
+ def _save_token_to_keyring(token: str) -> bool:
33
+ """Attempt to store token in OS keyring. Return True on success."""
34
+ try:
35
+ import keyring as kr
36
+
37
+ kr.set_password(_KEYRING_SERVICE, _KEYRING_USERNAME, token)
38
+ return True
39
+ except Exception:
40
+ return False
41
+
42
+
43
+ def _load_token_from_keyring() -> Optional[str]:
44
+ """Retrieve token from OS keyring. Return None on failure."""
45
+ try:
46
+ import keyring as kr
47
+
48
+ return kr.get_password(_KEYRING_SERVICE, _KEYRING_USERNAME)
49
+ except Exception:
50
+ return None
51
+
52
+
53
+ def _delete_token_from_keyring() -> bool:
54
+ """Remove token from OS keyring. Return True on success."""
55
+ try:
56
+ import keyring as kr
57
+
58
+ kr.delete_password(_KEYRING_SERVICE, _KEYRING_USERNAME)
59
+ return True
60
+ except Exception:
61
+ return False
62
+
63
+
64
+ def _save_token_to_file(token: str) -> None:
65
+ """Store token in ``~/.sbombox/token.json`` with 0600 permissions."""
66
+ _TOKEN_DIR.mkdir(parents=True, exist_ok=True)
67
+ payload = json.dumps({"token": token})
68
+ _TOKEN_FILE.write_text(payload, encoding="utf-8")
69
+ _TOKEN_FILE.chmod(stat.S_IRUSR | stat.S_IWUSR) # 0600
70
+
71
+
72
+ def _load_token_from_file() -> Optional[str]:
73
+ """Load token from file fallback. Return None if missing."""
74
+ if not _TOKEN_FILE.is_file():
75
+ return None
76
+ try:
77
+ data = json.loads(_TOKEN_FILE.read_text(encoding="utf-8"))
78
+ return data.get("token")
79
+ except (json.JSONDecodeError, OSError):
80
+ return None
81
+
82
+
83
+ def _delete_token_file() -> None:
84
+ """Remove the token file if it exists."""
85
+ if _TOKEN_FILE.is_file():
86
+ _TOKEN_FILE.unlink()
87
+
88
+
89
+ # -- public API ---------------------------------------------------------------
90
+
91
+
92
+ def store_token(token: str) -> None:
93
+ """Persist token - keyring first, file fallback."""
94
+ if not _save_token_to_keyring(token):
95
+ _save_token_to_file(token)
96
+
97
+
98
+ def load_token() -> Optional[str]:
99
+ """Load token - keyring first, file fallback."""
100
+ tok = _load_token_from_keyring()
101
+ if tok:
102
+ return tok
103
+ return _load_token_from_file()
104
+
105
+
106
+ def clear_token() -> None:
107
+ """Remove stored token from both keyring and file."""
108
+ _delete_token_from_keyring()
109
+ _delete_token_file()
110
+
111
+
112
+ def device_flow(api_url: str) -> str:
113
+ """Execute the OAuth device-authorization flow.
114
+
115
+ Parameters
116
+ ----------
117
+ api_url:
118
+ Base URL of the SBOMBox API (e.g. ``https://api.sbombox.com``).
119
+
120
+ Returns
121
+ -------
122
+ str
123
+ The access token on success.
124
+
125
+ Raises
126
+ ------
127
+ SystemExit
128
+ If the flow fails or is aborted.
129
+ """
130
+ import typer
131
+
132
+ # Step 1: request device + user codes ------------------------------------
133
+ try:
134
+ resp = httpx.post(
135
+ f"{api_url}/oauth/device-authorization",
136
+ json={"client_id": _CLIENT_ID},
137
+ timeout=_DEFAULT_TIMEOUT,
138
+ )
139
+ resp.raise_for_status()
140
+ data: Dict[str, Any] = resp.json()
141
+ except httpx.RequestError as exc:
142
+ typer.echo(f"Error: could not reach auth endpoint: {exc}", err=True)
143
+ raise typer.Exit(code=5) from exc
144
+ except httpx.HTTPStatusError as exc:
145
+ typer.echo(f"Error: auth endpoint returned {exc.response.status_code}", err=True)
146
+ raise typer.Exit(code=5) from exc
147
+
148
+ user_code: str = data["user_code"]
149
+ verification_uri: str = data["verification_uri"]
150
+ device_code: str = data["device_code"]
151
+ interval: int = data.get("interval", _POLL_INTERVAL)
152
+ expires_in: int = data.get("expires_in", 900)
153
+
154
+ # Step 2: display instructions -------------------------------------------
155
+ typer.echo(f"\nOpen this URL in your browser:\n\n {verification_uri}\n")
156
+ typer.echo(f"Enter code: {user_code}\n")
157
+ typer.echo("Waiting for authorization…")
158
+
159
+ # Step 3: poll for token -------------------------------------------------
160
+ deadline = time.monotonic() + expires_in
161
+ while time.monotonic() < deadline:
162
+ time.sleep(interval)
163
+ try:
164
+ token_resp = httpx.post(
165
+ f"{api_url}/oauth/token",
166
+ json={
167
+ "grant_type": "urn:ietf:params:oauth:grant-type:device_code",
168
+ "device_code": device_code,
169
+ # Public clients identify themselves in the body: there is no
170
+ # secret to put in an HTTP Basic header.
171
+ "client_id": _CLIENT_ID,
172
+ },
173
+ timeout=_DEFAULT_TIMEOUT,
174
+ )
175
+ except httpx.RequestError:
176
+ continue
177
+
178
+ if token_resp.status_code == 200:
179
+ token_data = token_resp.json()
180
+ access_token: str = token_data["access_token"]
181
+ store_token(access_token)
182
+ typer.echo("\nAuthorization successful!")
183
+ return access_token
184
+
185
+ # Handle slow_down / authorization_pending
186
+ if token_resp.status_code == 400:
187
+ err = token_resp.json().get("error", "")
188
+ if err == "slow_down":
189
+ interval += 5
190
+ elif err == "authorization_pending":
191
+ continue
192
+ else:
193
+ typer.echo(f"\nAuth error: {err}", err=True)
194
+ raise typer.Exit(code=5)
195
+ else:
196
+ typer.echo(f"\nUnexpected auth response: {token_resp.status_code}", err=True)
197
+ raise typer.Exit(code=5)
198
+
199
+ typer.echo("\nTimed out waiting for authorization.", err=True)
200
+ raise typer.Exit(code=5)