audithon 0.1.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.
audithon/__init__.py ADDED
@@ -0,0 +1,10 @@
1
+ """Audithon Python SDK — cliente oficial para la API v1."""
2
+
3
+ from .client import (
4
+ AudithonClient,
5
+ AudithonError,
6
+ DEFAULT_BASE_URL,
7
+ )
8
+
9
+ __all__ = ["AudithonClient", "AudithonError", "DEFAULT_BASE_URL"]
10
+ __version__ = "0.1.0"
audithon/client.py ADDED
@@ -0,0 +1,228 @@
1
+ """Cliente Python para la API de Audithon (sin dependencias externas).
2
+
3
+ Autenticación: API key ``aud_...`` creada en Account Settings → CI/CD → API Keys.
4
+ Solo audita sitios propios o para los que tengas autorización expresa.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import time
11
+ import urllib.error
12
+ import urllib.parse
13
+ import urllib.request
14
+ from typing import Any, Dict, Iterable, List, Optional
15
+
16
+ DEFAULT_BASE_URL = "https://audithon.dev"
17
+ DEFAULT_TIMEOUT_SECONDS = 150.0
18
+
19
+
20
+ class AudithonError(Exception):
21
+ """Error de la API (o de red/timeout) con status, code y body."""
22
+
23
+ def __init__(
24
+ self,
25
+ message: str,
26
+ *,
27
+ status: int = 0,
28
+ code: Optional[str] = None,
29
+ body: Any = None,
30
+ ) -> None:
31
+ super().__init__(message)
32
+ self.status = status
33
+ self.code = code
34
+ self.body = body
35
+
36
+
37
+ class AudithonClient:
38
+ """Cliente para auditorías, Quality Gate, reportes y specs de Playwright."""
39
+
40
+ def __init__(
41
+ self,
42
+ api_key: str,
43
+ base_url: str = DEFAULT_BASE_URL,
44
+ timeout: float = DEFAULT_TIMEOUT_SECONDS,
45
+ ) -> None:
46
+ if not api_key:
47
+ raise AudithonError(
48
+ "api_key is required. Create one in Account Settings -> CI/CD -> API Keys."
49
+ )
50
+ self.api_key = api_key
51
+ self.base_url = base_url.rstrip("/")
52
+ if self.base_url.endswith("/api/v1"):
53
+ self.base_url = self.base_url[: -len("/api/v1")]
54
+ self.timeout = timeout
55
+
56
+ def _request(
57
+ self,
58
+ path: str,
59
+ *,
60
+ method: str = "GET",
61
+ body: Optional[Dict[str, Any]] = None,
62
+ query: Optional[Dict[str, Any]] = None,
63
+ response_type: str = "json",
64
+ ) -> Any:
65
+ url = f"{self.base_url}/api/v1{path if path.startswith('/') else '/' + path}"
66
+ if query:
67
+ params = {
68
+ key: str(value)
69
+ for key, value in query.items()
70
+ if value is not None
71
+ }
72
+ if params:
73
+ url = f"{url}?{urllib.parse.urlencode(params)}"
74
+
75
+ data = json.dumps(body).encode("utf-8") if body is not None else None
76
+ headers = {
77
+ "x-api-key": self.api_key,
78
+ "Accept": "text/plain" if response_type == "text" else "application/json",
79
+ }
80
+ if data is not None:
81
+ headers["Content-Type"] = "application/json"
82
+
83
+ request = urllib.request.Request(url, data=data, headers=headers, method=method)
84
+ try:
85
+ with urllib.request.urlopen(request, timeout=self.timeout) as response:
86
+ raw = response.read().decode("utf-8")
87
+ status = response.status
88
+ except urllib.error.HTTPError as error:
89
+ raw = error.read().decode("utf-8", errors="replace")
90
+ parsed: Any = raw
91
+ try:
92
+ parsed = json.loads(raw) if raw else None
93
+ except json.JSONDecodeError:
94
+ parsed = raw
95
+ message = (
96
+ parsed.get("message") or parsed.get("error")
97
+ if isinstance(parsed, dict)
98
+ else f"Audithon request failed with HTTP {error.code}."
99
+ )
100
+ code = None
101
+ if isinstance(parsed, dict):
102
+ code = parsed.get("code") or parsed.get("error")
103
+ raise AudithonError(
104
+ str(message),
105
+ status=error.code,
106
+ code=code,
107
+ body=parsed,
108
+ ) from error
109
+ except urllib.error.URLError as error:
110
+ reason = getattr(error, "reason", error)
111
+ if isinstance(reason, TimeoutError):
112
+ raise AudithonError(
113
+ f"Audithon request timed out after {self.timeout}s.",
114
+ code="TIMEOUT",
115
+ ) from error
116
+ raise AudithonError(f"Audithon request failed: {reason}") from error
117
+ except TimeoutError as error:
118
+ raise AudithonError(
119
+ f"Audithon request timed out after {self.timeout}s.",
120
+ code="TIMEOUT",
121
+ ) from error
122
+
123
+ if response_type == "text":
124
+ return raw
125
+ if not raw:
126
+ return None
127
+ try:
128
+ return json.loads(raw)
129
+ except json.JSONDecodeError:
130
+ return raw
131
+
132
+ def create_audit(
133
+ self,
134
+ url: str,
135
+ *,
136
+ wait_seconds: int = 90,
137
+ mode: str = "public",
138
+ scope_paths: Optional[Iterable[str]] = None,
139
+ checks: Optional[List[Dict[str, Any]]] = None,
140
+ check_ids: Optional[List[str]] = None,
141
+ webhook_url: Optional[str] = None,
142
+ simulation_preset: Optional[str] = None,
143
+ **extra: Any,
144
+ ) -> Dict[str, Any]:
145
+ """Encola una auditoría y espera el resultado (90 s por defecto)."""
146
+ if not url:
147
+ raise AudithonError("create_audit requires a url.")
148
+ body: Dict[str, Any] = {
149
+ "url": url,
150
+ "mode": mode,
151
+ "waitSeconds": wait_seconds,
152
+ # El llamador declara que el target es propio o que está autorizado.
153
+ "authorizationConfirmed": True,
154
+ }
155
+ if scope_paths is not None:
156
+ body["scopePaths"] = list(scope_paths)
157
+ if checks is not None:
158
+ body["checks"] = checks
159
+ if check_ids is not None:
160
+ body["checkIds"] = check_ids
161
+ if webhook_url is not None:
162
+ body["webhookUrl"] = webhook_url
163
+ if simulation_preset is not None:
164
+ body["simulationPreset"] = simulation_preset
165
+ body.update(extra)
166
+ return self._request(
167
+ "/audits",
168
+ method="POST",
169
+ body=body,
170
+ query={"wait": wait_seconds},
171
+ )
172
+
173
+ def get_audit(self, audit_id: str) -> Dict[str, Any]:
174
+ return self._request(f"/audits/{urllib.parse.quote(audit_id)}")
175
+
176
+ def wait_for_audit(
177
+ self,
178
+ audit_id: str,
179
+ *,
180
+ timeout_seconds: int = 180,
181
+ poll_interval_seconds: float = 3.0,
182
+ ) -> Dict[str, Any]:
183
+ """Espera hasta que la auditoría esté ``completed`` o ``failed``."""
184
+ deadline = time.monotonic() + timeout_seconds
185
+ last: Optional[Dict[str, Any]] = None
186
+ while time.monotonic() < deadline:
187
+ last = self.get_audit(audit_id)
188
+ if last.get("status") in ("completed", "failed"):
189
+ return last
190
+ time.sleep(poll_interval_seconds)
191
+ raise AudithonError(
192
+ f"Audit {audit_id} did not finish within {timeout_seconds}s "
193
+ f"(last status: {last.get('status') if last else 'unknown'}).",
194
+ code="AUDIT_TIMEOUT",
195
+ body=last,
196
+ )
197
+
198
+ def evaluate_gate(
199
+ self,
200
+ audit_id: str,
201
+ *,
202
+ min_score_threshold: int = 75,
203
+ fail_on_secret_leak: bool = True,
204
+ fail_on_denial_of_wallet: bool = True,
205
+ fail_on_severe_performance_regression: bool = True,
206
+ ) -> Dict[str, Any]:
207
+ return self._request(
208
+ "/gates/evaluate",
209
+ method="POST",
210
+ body={
211
+ "auditId": audit_id,
212
+ "minScoreThreshold": min_score_threshold,
213
+ "failOnSecretLeak": fail_on_secret_leak,
214
+ "failOnDenialOfWallet": fail_on_denial_of_wallet,
215
+ "failOnSeverePerformanceRegression": fail_on_severe_performance_regression,
216
+ },
217
+ )
218
+
219
+ def get_report_markdown(self, audit_id: str) -> str:
220
+ """Informe Markdown (requiere plan Pro)."""
221
+ return self._request(
222
+ f"/audits/{urllib.parse.quote(audit_id)}/report.md",
223
+ response_type="text",
224
+ )
225
+
226
+ def get_playwright_tests(self, audit_id: str) -> Dict[str, Any]:
227
+ """Spec de Playwright generada para la auditoría."""
228
+ return self._request(f"/audits/{urllib.parse.quote(audit_id)}/tests")
@@ -0,0 +1,88 @@
1
+ Metadata-Version: 2.4
2
+ Name: audithon
3
+ Version: 0.1.0
4
+ Summary: Official Python client for the Audithon audit and Quality Gate API.
5
+ Author-email: Audithon <hello@audithon.dev>
6
+ License: MIT
7
+ Project-URL: Homepage, https://audithon.dev
8
+ Project-URL: Documentation, https://audithon.dev/docs
9
+ Project-URL: Source, https://github.com/cjtore/Audithon
10
+ Keywords: audithon,audit,security,quality-gate,ci,ai-generated
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: License :: OSI Approved :: MIT License
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Topic :: Software Development :: Quality Assurance
15
+ Classifier: Topic :: Security
16
+ Requires-Python: >=3.9
17
+ Description-Content-Type: text/markdown
18
+ License-File: LICENSE
19
+ Dynamic: license-file
20
+
21
+ # audithon (Python SDK)
22
+
23
+ Official Python client for the [Audithon](https://audithon.dev) audit and Quality Gate API.
24
+ Zero dependencies (standard library only), Python 3.9+.
25
+
26
+ ## Install
27
+
28
+ ```bash
29
+ pip install audithon
30
+ ```
31
+
32
+ While the package is not yet published to PyPI, install it from this folder:
33
+
34
+ ```bash
35
+ pip install /path/to/Audithon/sdk/python
36
+ ```
37
+
38
+ ## Usage
39
+
40
+ ```python
41
+ import os
42
+ from audithon import AudithonClient, AudithonError
43
+
44
+ client = AudithonClient(api_key=os.environ["AUDITHON_API_KEY"])
45
+
46
+ # Encola una auditoría y espera el resultado (hasta 90 s por defecto).
47
+ audit = client.create_audit(
48
+ "https://your-app.example.com",
49
+ scope_paths=["/login", "/checkout"],
50
+ )
51
+ print(audit["scoreBreakdown"]["global"], len(audit["findings"]))
52
+
53
+ gate = client.evaluate_gate(audit["auditId"], min_score_threshold=75)
54
+ if not gate["passed"]:
55
+ raise SystemExit(gate["blockingReasons"])
56
+
57
+ # Reporte Markdown (Pro) y spec de Playwright (objeto con specContent)
58
+ markdown = client.get_report_markdown(audit["auditId"])
59
+ spec = client.get_playwright_tests(audit["auditId"])
60
+ print(spec["fileName"])
61
+ ```
62
+
63
+ Async/polled audits:
64
+
65
+ ```python
66
+ queued = client.create_audit(url, wait_seconds=0)
67
+ completed = client.wait_for_audit(queued["auditId"], timeout_seconds=180)
68
+ ```
69
+
70
+ Error handling:
71
+
72
+ ```python
73
+ try:
74
+ client.create_audit("https://your-app.example.com")
75
+ except AudithonError as error:
76
+ if error.code == "RATE_LIMITED":
77
+ print(error.status, error.body.get("retryAfterSeconds"))
78
+ ```
79
+
80
+ ## Notes
81
+
82
+ - API key creation: **Account Settings → CI/CD → API Keys** (Free plan includes keys).
83
+ - `create_audit` declares `authorizationConfirmed=True`: only audit apps you own or are
84
+ explicitly authorized to audit.
85
+ - Stored checks (`check_ids`) need a signed-in session; with an API key use inline `checks`.
86
+ - The SDK is read-only: it never deploys or mutates your app.
87
+
88
+ MIT licensed.
@@ -0,0 +1,7 @@
1
+ audithon/__init__.py,sha256=Mi4nzcx2-d8UPTjxI1n6mlxm8OJ9jZQQEjmkhkgvDuk,237
2
+ audithon/client.py,sha256=jDF8PfjMxx9M5h66-_hjN9fsGMkjtZAIvVs4f5Zvyrg,7910
3
+ audithon-0.1.0.dist-info/licenses/LICENSE,sha256=focvj591hYSRR44lEDghsh9e-6h_DGWtm6Fx9X1vcFQ,1065
4
+ audithon-0.1.0.dist-info/METADATA,sha256=cDFzlHzbAa3nS1PLvfAuMHIH3u4i5yLeHMvZRYIGKaE,2624
5
+ audithon-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
6
+ audithon-0.1.0.dist-info/top_level.txt,sha256=X-nx3H8uug2RZpUNR5uHtTM2H88cYOgLPwN5FdK0uJM,9
7
+ audithon-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Audithon
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ audithon