authentify-sdk 0.2.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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 4Sure Technologies LLC
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,131 @@
1
+ Metadata-Version: 2.4
2
+ Name: authentify-sdk
3
+ Version: 0.2.0
4
+ Summary: Typed Python client for the Authentify API: authorize AI agent actions before they run
5
+ Author: 4Sure Technologies LLC
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://authentify.bz
8
+ Project-URL: Documentation, https://authentify.bz/api-docs
9
+ Project-URL: API spec, https://authentify.bz/openapi.json
10
+ Keywords: authentify,ai agents,authorization,audit,human in the loop
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Intended Audience :: Developers
14
+ Requires-Python: >=3.9
15
+ Description-Content-Type: text/markdown
16
+ License-File: LICENSE
17
+ Requires-Dist: requests>=2.28
18
+ Dynamic: license-file
19
+
20
+ # authentify-sdk
21
+
22
+ Typed Python client for the [Authentify](https://authentify.bz) API. Your agent asks Authentify before it acts; Authentify answers allow, deny or escalate, and seals the decision in a tamper-evident audit log.
23
+
24
+ A port of the TypeScript SDK ([`@authentify2026/sdk`](https://www.npmjs.com/package/@authentify2026/sdk)) covering authorization, OAuth 2.1 token management, consent sessions, outcome reports, agent creation and audit logs. It doesn't cover every endpoint: billing, SLA and rules-engine management are left out. See the [API reference](https://authentify.bz/api-docs), the [OpenAPI spec](https://authentify.bz/openapi.json) and the [integration guide](https://authentify.bz/integration).
25
+
26
+ ## Install
27
+
28
+ ```bash
29
+ pip install authentify-sdk
30
+ ```
31
+
32
+ Requires Python 3.9 or later.
33
+
34
+ ## Usage
35
+
36
+ ### x-api-key mode (simplest -- a long-lived key, no token refresh to think about)
37
+
38
+ ```python
39
+ import os
40
+ from authentify import AuthentifyClient
41
+
42
+ client = AuthentifyClient(
43
+ api_key=os.environ["AUTHENTIFY_API_KEY"],
44
+ environment="sandbox", # or "production"
45
+ )
46
+
47
+ result = client.authorize({
48
+ "action": "approve_claim",
49
+ "resource": {"id": "claim_123", "type": "insurance_claim"},
50
+ "context": {"claimantTier": "gold"},
51
+ })
52
+
53
+ if result["decision"] == "allow":
54
+ ... # run the action
55
+ elif result["decision"] == "escalate":
56
+ ... # hold it: your approvers are asked to decide (see below)
57
+ else:
58
+ ... # stop: the action is not authorized
59
+ ```
60
+
61
+ ### OAuth 2.1 mode (short-lived tokens, minted and refreshed automatically)
62
+
63
+ ```python
64
+ client = AuthentifyClient(
65
+ client_id=os.environ["AUTHENTIFY_KEY_ID"],
66
+ client_secret=os.environ["AUTHENTIFY_KEY_SECRET"],
67
+ environment="production",
68
+ )
69
+
70
+ # No manual token handling required -- authorize() mints and refreshes
71
+ # the underlying OAuth token for you.
72
+ client.authorize({"action": "read_document", "resource": {"id": "document_123", "type": "document"}})
73
+ ```
74
+
75
+ Want a token scoped to less than the agent's full permissions, or bound to a specific end user's consent? Call `mint_token()` directly:
76
+
77
+ ```python
78
+ token = client.mint_token(scope="READ", end_user_id="retail-cust-42")
79
+ ```
80
+
81
+ ### When a request needs a person
82
+
83
+ An escalated request is on hold until your approvers decide. Approvals are cast by people, not by code: an approver decides in the Authentify dashboard (signed in to a login linked to their approver record) or through the single-use links Authentify emails them. An API key can't approve or reject, so one key can never meet an approval quorum on its own.
84
+
85
+ Your backend learns the outcome with `get_authorization_request()`, using your account-level API key (an agent's own key is refused):
86
+
87
+ ```python
88
+ account = AuthentifyClient(api_key=os.environ["AUTHENTIFY_ACCOUNT_KEY"], environment="production")
89
+ status = account.get_authorization_request(result["authorizationRequestId"])
90
+ status["approvalStatus"] # "pending", "approved" or "rejected"
91
+ ```
92
+
93
+ `approve_authorization_request()` and `reject_authorization_request()` are deprecated for that reason. Since 0.2.0 they raise `AuthentifyError` (status 403) straight away, without calling the API.
94
+
95
+ ### Reporting what happened
96
+
97
+ ```python
98
+ client.report_outcome(result["authorizationRequestId"], {"status": "succeeded"})
99
+ ```
100
+
101
+ ### Consent sessions
102
+
103
+ ```python
104
+ session = account.create_consent_session({
105
+ "agent_id": "YOUR_AGENT_ID",
106
+ "customer_id": "YOUR_CUSTOMER_ID",
107
+ "end_user_id": "retail-cust-42",
108
+ "scope": ["READ", "TRANSFER"],
109
+ })
110
+
111
+ # session["widget_url"] -- send your retail customer here, or render
112
+ # @authentify2026/consent-widget client-side with session["session_id"].
113
+ ```
114
+
115
+ ## Errors
116
+
117
+ Any non-2xx response raises `authentify.AuthentifyError`, with `status`, `code` and the response `body`.
118
+
119
+ ## Smoke-testing against a sandbox account
120
+
121
+ ```python
122
+ from authentify import AuthentifyClient
123
+
124
+ client = AuthentifyClient(api_key="YOUR_SANDBOX_KEY", environment="sandbox")
125
+ result = client.authorize({"action": "READ", "resource": {"id": "test-123"}})
126
+ print(result["decision"]) # expect "allow" for an unrestricted agent
127
+
128
+ integrity = client.get_audit_integrity()
129
+ assert integrity["verifiedCount"] == integrity["totalCount"]
130
+ print("audit chain intact:", integrity["brokenAtId"] is None)
131
+ ```
@@ -0,0 +1,112 @@
1
+ # authentify-sdk
2
+
3
+ Typed Python client for the [Authentify](https://authentify.bz) API. Your agent asks Authentify before it acts; Authentify answers allow, deny or escalate, and seals the decision in a tamper-evident audit log.
4
+
5
+ A port of the TypeScript SDK ([`@authentify2026/sdk`](https://www.npmjs.com/package/@authentify2026/sdk)) covering authorization, OAuth 2.1 token management, consent sessions, outcome reports, agent creation and audit logs. It doesn't cover every endpoint: billing, SLA and rules-engine management are left out. See the [API reference](https://authentify.bz/api-docs), the [OpenAPI spec](https://authentify.bz/openapi.json) and the [integration guide](https://authentify.bz/integration).
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ pip install authentify-sdk
11
+ ```
12
+
13
+ Requires Python 3.9 or later.
14
+
15
+ ## Usage
16
+
17
+ ### x-api-key mode (simplest -- a long-lived key, no token refresh to think about)
18
+
19
+ ```python
20
+ import os
21
+ from authentify import AuthentifyClient
22
+
23
+ client = AuthentifyClient(
24
+ api_key=os.environ["AUTHENTIFY_API_KEY"],
25
+ environment="sandbox", # or "production"
26
+ )
27
+
28
+ result = client.authorize({
29
+ "action": "approve_claim",
30
+ "resource": {"id": "claim_123", "type": "insurance_claim"},
31
+ "context": {"claimantTier": "gold"},
32
+ })
33
+
34
+ if result["decision"] == "allow":
35
+ ... # run the action
36
+ elif result["decision"] == "escalate":
37
+ ... # hold it: your approvers are asked to decide (see below)
38
+ else:
39
+ ... # stop: the action is not authorized
40
+ ```
41
+
42
+ ### OAuth 2.1 mode (short-lived tokens, minted and refreshed automatically)
43
+
44
+ ```python
45
+ client = AuthentifyClient(
46
+ client_id=os.environ["AUTHENTIFY_KEY_ID"],
47
+ client_secret=os.environ["AUTHENTIFY_KEY_SECRET"],
48
+ environment="production",
49
+ )
50
+
51
+ # No manual token handling required -- authorize() mints and refreshes
52
+ # the underlying OAuth token for you.
53
+ client.authorize({"action": "read_document", "resource": {"id": "document_123", "type": "document"}})
54
+ ```
55
+
56
+ Want a token scoped to less than the agent's full permissions, or bound to a specific end user's consent? Call `mint_token()` directly:
57
+
58
+ ```python
59
+ token = client.mint_token(scope="READ", end_user_id="retail-cust-42")
60
+ ```
61
+
62
+ ### When a request needs a person
63
+
64
+ An escalated request is on hold until your approvers decide. Approvals are cast by people, not by code: an approver decides in the Authentify dashboard (signed in to a login linked to their approver record) or through the single-use links Authentify emails them. An API key can't approve or reject, so one key can never meet an approval quorum on its own.
65
+
66
+ Your backend learns the outcome with `get_authorization_request()`, using your account-level API key (an agent's own key is refused):
67
+
68
+ ```python
69
+ account = AuthentifyClient(api_key=os.environ["AUTHENTIFY_ACCOUNT_KEY"], environment="production")
70
+ status = account.get_authorization_request(result["authorizationRequestId"])
71
+ status["approvalStatus"] # "pending", "approved" or "rejected"
72
+ ```
73
+
74
+ `approve_authorization_request()` and `reject_authorization_request()` are deprecated for that reason. Since 0.2.0 they raise `AuthentifyError` (status 403) straight away, without calling the API.
75
+
76
+ ### Reporting what happened
77
+
78
+ ```python
79
+ client.report_outcome(result["authorizationRequestId"], {"status": "succeeded"})
80
+ ```
81
+
82
+ ### Consent sessions
83
+
84
+ ```python
85
+ session = account.create_consent_session({
86
+ "agent_id": "YOUR_AGENT_ID",
87
+ "customer_id": "YOUR_CUSTOMER_ID",
88
+ "end_user_id": "retail-cust-42",
89
+ "scope": ["READ", "TRANSFER"],
90
+ })
91
+
92
+ # session["widget_url"] -- send your retail customer here, or render
93
+ # @authentify2026/consent-widget client-side with session["session_id"].
94
+ ```
95
+
96
+ ## Errors
97
+
98
+ Any non-2xx response raises `authentify.AuthentifyError`, with `status`, `code` and the response `body`.
99
+
100
+ ## Smoke-testing against a sandbox account
101
+
102
+ ```python
103
+ from authentify import AuthentifyClient
104
+
105
+ client = AuthentifyClient(api_key="YOUR_SANDBOX_KEY", environment="sandbox")
106
+ result = client.authorize({"action": "READ", "resource": {"id": "test-123"}})
107
+ print(result["decision"]) # expect "allow" for an unrestricted agent
108
+
109
+ integrity = client.get_audit_integrity()
110
+ assert integrity["verifiedCount"] == integrity["totalCount"]
111
+ print("audit chain intact:", integrity["brokenAtId"] is None)
112
+ ```
@@ -0,0 +1,30 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77.0"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "authentify-sdk"
7
+ version = "0.2.0"
8
+ description = "Typed Python client for the Authentify API: authorize AI agent actions before they run"
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ license = "MIT"
12
+ license-files = ["LICENSE"]
13
+ authors = [{ name = "4Sure Technologies LLC" }]
14
+ keywords = ["authentify", "ai agents", "authorization", "audit", "human in the loop"]
15
+ classifiers = [
16
+ "Programming Language :: Python :: 3",
17
+ "Operating System :: OS Independent",
18
+ "Intended Audience :: Developers",
19
+ ]
20
+ dependencies = [
21
+ "requests>=2.28",
22
+ ]
23
+
24
+ [project.urls]
25
+ Homepage = "https://authentify.bz"
26
+ Documentation = "https://authentify.bz/api-docs"
27
+ "API spec" = "https://authentify.bz/openapi.json"
28
+
29
+ [tool.setuptools.packages.find]
30
+ where = ["src"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,4 @@
1
+ from .client import AuthentifyClient
2
+ from .errors import AuthentifyError
3
+
4
+ __all__ = ["AuthentifyClient", "AuthentifyError"]
@@ -0,0 +1,246 @@
1
+ """Typed client for the Authentify API. A direct port of
2
+ sdk/typescript/src/client.ts's logic and comments -- keep the two in
3
+ sync when either changes.
4
+
5
+ Construct with either:
6
+ AuthentifyClient(api_key=..., environment=...) # x-api-key mode
7
+ AuthentifyClient(client_id=..., client_secret=..., environment=...) # OAuth 2.1 mode
8
+
9
+ In OAuth mode, access tokens are minted lazily on first use and
10
+ transparently re-minted before they expire -- callers never touch token
11
+ lifecycle themselves. See POST /v1/oauth/token in /api-docs for the
12
+ underlying grant.
13
+ """
14
+
15
+ import time
16
+ import warnings
17
+ from typing import Any, Dict, NoReturn, Optional
18
+ from urllib.parse import quote
19
+
20
+ import requests
21
+
22
+ from .errors import AuthentifyError
23
+ from .types import (
24
+ ApproveRejectParams,
25
+ AuditIntegrityResponse,
26
+ AuthorizationRequestStatus,
27
+ AuthorizeParams,
28
+ AuthorizeResponse,
29
+ CreateAgentParams,
30
+ CreateConsentSessionParams,
31
+ CreateConsentSessionResponse,
32
+ Environment,
33
+ OAuthTokenResponse,
34
+ ReportOutcomeParams,
35
+ )
36
+
37
+ DEFAULT_BASE_URL = "https://www.authentify.bz/api/v1"
38
+ # Re-mint this many seconds before the cached token's expires_in window
39
+ # closes, so a call in flight never races an about-to-expire token.
40
+ TOKEN_REFRESH_MARGIN_SECONDS = 30
41
+ APPROVALS_NEED_A_PERSON = (
42
+ "Approvals are cast by a person, not an API key: approvers decide in the "
43
+ "Authentify dashboard or through their emailed links. Call "
44
+ "get_authorization_request() for the outcome."
45
+ )
46
+
47
+
48
+ class AuthentifyClient:
49
+ def __init__(
50
+ self,
51
+ *,
52
+ api_key: Optional[str] = None,
53
+ client_id: Optional[str] = None,
54
+ client_secret: Optional[str] = None,
55
+ environment: Environment = "sandbox",
56
+ base_url: Optional[str] = None,
57
+ ):
58
+ is_oauth = client_id is not None or client_secret is not None
59
+ if is_oauth and api_key is not None:
60
+ raise ValueError("Pass either api_key, or client_id/client_secret -- not both.")
61
+ if is_oauth and (client_id is None or client_secret is None):
62
+ raise ValueError("OAuth mode requires both client_id and client_secret.")
63
+ if not is_oauth and api_key is None:
64
+ raise ValueError("Pass either api_key, or client_id and client_secret.")
65
+
66
+ self._is_oauth = is_oauth
67
+ self._api_key = api_key
68
+ self._client_id = client_id
69
+ self._client_secret = client_secret
70
+ self._environment: Environment = environment
71
+ self._base_url = base_url or DEFAULT_BASE_URL
72
+ self._cached_token: Optional[Dict[str, Any]] = None
73
+
74
+ def mint_token(self, scope: Optional[str] = None, end_user_id: Optional[str] = None) -> OAuthTokenResponse:
75
+ """Mints (or returns the still-valid cached) OAuth access token.
76
+ Exposed directly for callers who want to manage token lifecycle
77
+ themselves; every other method on this client calls it internally
78
+ when constructed in OAuth mode."""
79
+ if not self._is_oauth:
80
+ raise RuntimeError("mint_token() requires the client to be constructed with client_id/client_secret")
81
+
82
+ form = {
83
+ "grant_type": "client_credentials",
84
+ "client_id": self._client_id,
85
+ "client_secret": self._client_secret,
86
+ }
87
+ if scope:
88
+ form["scope"] = scope
89
+ if end_user_id:
90
+ form["end_user_id"] = end_user_id
91
+
92
+ res = requests.post(self._url("/oauth/token"), data=form)
93
+ body = self._safe_json(res)
94
+ if not res.ok:
95
+ raise AuthentifyError(res.status_code, body)
96
+
97
+ token: OAuthTokenResponse = body
98
+ self._cached_token = {
99
+ "token": token["access_token"],
100
+ "expires_at": time.time() + (token["expires_in"] - TOKEN_REFRESH_MARGIN_SECONDS),
101
+ }
102
+ return token
103
+
104
+ def authorize(self, params: AuthorizeParams) -> AuthorizeResponse:
105
+ """POST /api/v2/authorize -- the canonical per-call authorization
106
+ gate. Accepts either x-api-key or an OAuth-minted Bearer token;
107
+ OAuth tokens are minted/refreshed automatically when this client
108
+ uses OAuth mode."""
109
+ return self._request("POST", "/authorize", params, auth="authorize", version="v2")
110
+
111
+ def approve_authorization_request(
112
+ self, approval_request_id: str, params: Optional[ApproveRejectParams] = None
113
+ ) -> NoReturn:
114
+ """Deprecated. Approval votes can't be cast with an API key: the
115
+ server refuses them, by design, so one key can never meet an
116
+ approval quorum alone. Approvers vote from the dashboard (signed in
117
+ to a login linked to their operator) or through their emailed
118
+ single-use links. To learn the outcome, call
119
+ get_authorization_request(). Raises AuthentifyError (403) without
120
+ calling the API."""
121
+ warnings.warn(APPROVALS_NEED_A_PERSON, DeprecationWarning, stacklevel=2)
122
+ raise AuthentifyError(403, {"error": APPROVALS_NEED_A_PERSON})
123
+
124
+ def reject_authorization_request(
125
+ self, approval_request_id: str, params: Optional[ApproveRejectParams] = None
126
+ ) -> NoReturn:
127
+ """Deprecated. See approve_authorization_request()."""
128
+ warnings.warn(APPROVALS_NEED_A_PERSON, DeprecationWarning, stacklevel=2)
129
+ raise AuthentifyError(403, {"error": APPROVALS_NEED_A_PERSON})
130
+
131
+ def get_authorization_request(self, authorization_request_id: str) -> AuthorizationRequestStatus:
132
+ """GET /api/v2/authorization-requests/{id} -- the current state of
133
+ one authorization request, including whether a person has approved
134
+ or rejected it (approvalStatus) and each vote. Use it to learn the
135
+ outcome of an escalated request. Needs your account-level API key:
136
+ an agent-bound key or an agent access token is refused (403)."""
137
+ return self._request(
138
+ "GET",
139
+ f"/authorization-requests/{quote(authorization_request_id, safe='')}",
140
+ None,
141
+ auth="raw_key",
142
+ version="v2",
143
+ )
144
+
145
+ def report_outcome(self, authorization_request_id: str, params: ReportOutcomeParams) -> Any:
146
+ """POST /api/v2/authorization-requests/{id}/outcome -- report back
147
+ what actually happened after acting on an authorize() decision
148
+ (the authorization_request_id it returned). Self-reported by the
149
+ caller; Authentify does not independently verify execution on
150
+ your own infrastructure."""
151
+ return self._request(
152
+ "POST",
153
+ f"/authorization-requests/{authorization_request_id}/outcome",
154
+ params,
155
+ auth="raw_key",
156
+ version="v2",
157
+ )
158
+
159
+ def create_consent_session(self, params: CreateConsentSessionParams) -> CreateConsentSessionResponse:
160
+ """POST /consent-sessions -- creates a widget session for a
161
+ specific agent + customer + end user. Unlike every other method
162
+ here, this endpoint always wants the *raw* API key value via
163
+ Authorization: Bearer <raw key> -- it hashes and looks up the key
164
+ directly, it does not accept an OAuth-minted JWT or an x-api-key
165
+ header. In OAuth mode, that raw value is the client_secret this
166
+ client was constructed with."""
167
+ raw_key = self._client_secret if self._is_oauth else self._api_key
168
+ res = requests.post(
169
+ self._url("/consent-sessions"),
170
+ headers={"Content-Type": "application/json", "Authorization": f"Bearer {raw_key}"},
171
+ json=params,
172
+ )
173
+ body = self._safe_json(res)
174
+ if not res.ok:
175
+ raise AuthentifyError(res.status_code, body)
176
+ return body
177
+
178
+ # The methods below (agent CRUD, audit logs/integrity) are
179
+ # dashboard-session-authenticated on the backend
180
+ # (requireCustomerSession()), which accepts a session cookie, a
181
+ # dashboard session Bearer token, or a raw *account-level* x-api-key --
182
+ # never an agent-bound key (403) and never an OAuth-minted agent-scoped
183
+ # JWT. Construct a separate client with your account-level key for
184
+ # these (and for get_authorization_request and create_consent_session); an agent's
185
+ # client can only call authorize() and report_outcome().
186
+
187
+ def create_agent(self, params: CreateAgentParams) -> Any:
188
+ """POST /agents -- create a new agent."""
189
+ return self._request("POST", "/agents", params, auth="raw_key")
190
+
191
+ def list_agents(self, customer_id: str) -> Any:
192
+ """GET /agents?customer_id=...&environment=..."""
193
+ return self._request("GET", f"/agents?customer_id={customer_id}", None, auth="raw_key")
194
+
195
+ def get_audit_logs(self, customer_id: str, days: Optional[int] = None) -> Any:
196
+ """GET /audit-logs?customer_id=...&days=..."""
197
+ path = f"/audit-logs?customer_id={customer_id}"
198
+ if days is not None:
199
+ path += f"&days={days}"
200
+ return self._request("GET", path, None, auth="raw_key")
201
+
202
+ def get_audit_integrity(self) -> AuditIntegrityResponse:
203
+ """GET /audit-integrity -- verifies the tamper-evident hash chain."""
204
+ return self._request("GET", "/audit-integrity", None, auth="raw_key")
205
+
206
+ def _url(self, path: str, version: str = "v1") -> str:
207
+ # base_url is constructed pointing at /api/v1 (default or
208
+ # customer-overridden). V2 calls swap that one path segment
209
+ # rather than requiring a second constructor option -- v1 and v2
210
+ # always live on the same host/deployment.
211
+ base = self._base_url.replace("/api/v1", "/api/v2") if version == "v2" and self._base_url.endswith("/api/v1") else self._base_url
212
+ separator = "&" if "?" in path else "?"
213
+ return f"{base}{path}{separator}environment={self._environment}"
214
+
215
+ def _raw_key(self) -> str:
216
+ return self._client_secret if self._is_oauth else self._api_key
217
+
218
+ def _authorize_headers(self) -> Dict[str, str]:
219
+ if self._is_oauth:
220
+ if self._cached_token is None or self._cached_token["expires_at"] <= time.time():
221
+ self.mint_token()
222
+ return {"Authorization": f"Bearer {self._cached_token['token']}"}
223
+ return {"x-api-key": self._api_key}
224
+
225
+ def _request(
226
+ self,
227
+ method: str,
228
+ path: str,
229
+ body: Optional[Dict[str, Any]],
230
+ *,
231
+ auth: str,
232
+ version: str = "v1",
233
+ ) -> Any:
234
+ headers = self._authorize_headers() if auth == "authorize" else {"x-api-key": self._raw_key()}
235
+ res = requests.request(method, self._url(path, version), headers=headers, json=body)
236
+ response_body = self._safe_json(res)
237
+ if not res.ok:
238
+ raise AuthentifyError(res.status_code, response_body)
239
+ return response_body
240
+
241
+ @staticmethod
242
+ def _safe_json(res: requests.Response) -> Any:
243
+ try:
244
+ return res.json()
245
+ except ValueError:
246
+ return {}
@@ -0,0 +1,20 @@
1
+ """Error type raised for any non-2xx response from the Authentify API."""
2
+
3
+ from typing import Any, Optional
4
+
5
+
6
+ class AuthentifyError(Exception):
7
+ """Thrown for any non-2xx response, so callers get one consistent
8
+ shape instead of parsing each endpoint's own error body."""
9
+
10
+ def __init__(self, status: int, body: Any):
11
+ body_obj = body if isinstance(body, dict) else {}
12
+ message = (
13
+ body_obj.get("error_description")
14
+ or body_obj.get("error")
15
+ or f"Authentify API request failed with status {status}"
16
+ )
17
+ super().__init__(message)
18
+ self.status: int = status
19
+ self.code: Optional[str] = body_obj.get("error") if isinstance(body_obj.get("error"), str) else None
20
+ self.body: Any = body
@@ -0,0 +1,106 @@
1
+ """Type hints mirroring sdk/typescript/src/types.ts -- compile-time/IDE
2
+ support only, not runtime-enforced (Python has no built-in equivalent
3
+ to TypeScript's structural typing without a validation library)."""
4
+
5
+ from typing import Any, Dict, List, Literal, Optional, TypedDict
6
+
7
+ Environment = Literal["sandbox", "production"]
8
+
9
+
10
+ class MintTokenParams(TypedDict, total=False):
11
+ scope: str
12
+ """Space-delimited subset of the agent's allowed_actions -- narrows, never widens."""
13
+ end_user_id: str
14
+ """Binds the token to a specific consumer's existing consent grant."""
15
+
16
+
17
+ class OAuthTokenResponse(TypedDict):
18
+ access_token: str
19
+ token_type: Literal["Bearer"]
20
+ expires_in: int
21
+
22
+
23
+ class CreateConsentSessionParams(TypedDict, total=False):
24
+ agent_id: str
25
+ customer_id: str
26
+ end_user_id: str
27
+ scope: List[str]
28
+ expires_in: int
29
+ require_auth: bool
30
+
31
+
32
+ class CreateConsentSessionResponse(TypedDict):
33
+ session_id: str
34
+ expires_at: str
35
+ widget_url: str
36
+
37
+
38
+ class ApproveRejectParams(TypedDict, total=False):
39
+ operator_id: str
40
+ signature: str
41
+ """Non-empty attestation string, e.g. the operator's typed full name."""
42
+ decision_reason: str
43
+ ip_address: str
44
+ device_fingerprint: str
45
+
46
+
47
+ class ReportOutcomeParams(TypedDict, total=False):
48
+ status: Literal["succeeded", "failed", "not_attempted"]
49
+ detail: Dict[str, Any]
50
+
51
+
52
+ class CreateAgentParams(TypedDict, total=False):
53
+ customer_id: str
54
+ agent_name: str
55
+ allowed_actions: List[str]
56
+ entity_scope: str
57
+ """'*' (default), an exact entity ID, or a prefix ending in '*' (e.g. 'acct_*')."""
58
+ rate_limit: int
59
+ model_id: str
60
+
61
+
62
+ class AuditIntegrityResponse(TypedDict):
63
+ totalCount: int
64
+ verifiedCount: int
65
+ integrityPercent: float
66
+ brokenAt: Optional[str]
67
+ brokenAtId: Optional[str]
68
+
69
+
70
+ # --- Canonical domain-neutral authorization (POST /api/v2/authorize) ---
71
+ # Every domain supplies an action, a resource, and optional opaque context.
72
+ # The server preserves context as supplied.
73
+
74
+ class ResourceRef(TypedDict, total=False):
75
+ id: str
76
+ type: str
77
+
78
+
79
+ class Signals(TypedDict, total=False):
80
+ domain: str
81
+ industryContext: str
82
+ signal1: str
83
+ signal2: str
84
+
85
+
86
+ class AuthorizeParams(TypedDict, total=False):
87
+ action: str
88
+ resource: ResourceRef
89
+ context: Dict[str, Any]
90
+ end_user_id: str
91
+ signals: Signals
92
+ """Optional UTP classification evidence; never overrides authorization policy."""
93
+
94
+
95
+ AuthorizationOutcome = Literal["allow", "deny", "escalate"]
96
+
97
+ # Loosely typed like AuthorizeResponse in types.ts -- extra keys are
98
+ # expected and preserved (the response is forward-compatible), so this
99
+ # is a plain Dict[str, Any] at the call sites rather than a closed TypedDict.
100
+ AuthorizeResponse = Dict[str, Any]
101
+
102
+ # GET /api/v2/authorization-requests/{id}. Same loose typing as
103
+ # AuthorizeResponse. Keys most callers need: "decision", "approvalStatus"
104
+ # (None when no person was asked, else "pending" / "approved" /
105
+ # "rejected"), "requiredApproverCount", "actualApproverCount", "votes".
106
+ AuthorizationRequestStatus = Dict[str, Any]
@@ -0,0 +1,131 @@
1
+ Metadata-Version: 2.4
2
+ Name: authentify-sdk
3
+ Version: 0.2.0
4
+ Summary: Typed Python client for the Authentify API: authorize AI agent actions before they run
5
+ Author: 4Sure Technologies LLC
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://authentify.bz
8
+ Project-URL: Documentation, https://authentify.bz/api-docs
9
+ Project-URL: API spec, https://authentify.bz/openapi.json
10
+ Keywords: authentify,ai agents,authorization,audit,human in the loop
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Intended Audience :: Developers
14
+ Requires-Python: >=3.9
15
+ Description-Content-Type: text/markdown
16
+ License-File: LICENSE
17
+ Requires-Dist: requests>=2.28
18
+ Dynamic: license-file
19
+
20
+ # authentify-sdk
21
+
22
+ Typed Python client for the [Authentify](https://authentify.bz) API. Your agent asks Authentify before it acts; Authentify answers allow, deny or escalate, and seals the decision in a tamper-evident audit log.
23
+
24
+ A port of the TypeScript SDK ([`@authentify2026/sdk`](https://www.npmjs.com/package/@authentify2026/sdk)) covering authorization, OAuth 2.1 token management, consent sessions, outcome reports, agent creation and audit logs. It doesn't cover every endpoint: billing, SLA and rules-engine management are left out. See the [API reference](https://authentify.bz/api-docs), the [OpenAPI spec](https://authentify.bz/openapi.json) and the [integration guide](https://authentify.bz/integration).
25
+
26
+ ## Install
27
+
28
+ ```bash
29
+ pip install authentify-sdk
30
+ ```
31
+
32
+ Requires Python 3.9 or later.
33
+
34
+ ## Usage
35
+
36
+ ### x-api-key mode (simplest -- a long-lived key, no token refresh to think about)
37
+
38
+ ```python
39
+ import os
40
+ from authentify import AuthentifyClient
41
+
42
+ client = AuthentifyClient(
43
+ api_key=os.environ["AUTHENTIFY_API_KEY"],
44
+ environment="sandbox", # or "production"
45
+ )
46
+
47
+ result = client.authorize({
48
+ "action": "approve_claim",
49
+ "resource": {"id": "claim_123", "type": "insurance_claim"},
50
+ "context": {"claimantTier": "gold"},
51
+ })
52
+
53
+ if result["decision"] == "allow":
54
+ ... # run the action
55
+ elif result["decision"] == "escalate":
56
+ ... # hold it: your approvers are asked to decide (see below)
57
+ else:
58
+ ... # stop: the action is not authorized
59
+ ```
60
+
61
+ ### OAuth 2.1 mode (short-lived tokens, minted and refreshed automatically)
62
+
63
+ ```python
64
+ client = AuthentifyClient(
65
+ client_id=os.environ["AUTHENTIFY_KEY_ID"],
66
+ client_secret=os.environ["AUTHENTIFY_KEY_SECRET"],
67
+ environment="production",
68
+ )
69
+
70
+ # No manual token handling required -- authorize() mints and refreshes
71
+ # the underlying OAuth token for you.
72
+ client.authorize({"action": "read_document", "resource": {"id": "document_123", "type": "document"}})
73
+ ```
74
+
75
+ Want a token scoped to less than the agent's full permissions, or bound to a specific end user's consent? Call `mint_token()` directly:
76
+
77
+ ```python
78
+ token = client.mint_token(scope="READ", end_user_id="retail-cust-42")
79
+ ```
80
+
81
+ ### When a request needs a person
82
+
83
+ An escalated request is on hold until your approvers decide. Approvals are cast by people, not by code: an approver decides in the Authentify dashboard (signed in to a login linked to their approver record) or through the single-use links Authentify emails them. An API key can't approve or reject, so one key can never meet an approval quorum on its own.
84
+
85
+ Your backend learns the outcome with `get_authorization_request()`, using your account-level API key (an agent's own key is refused):
86
+
87
+ ```python
88
+ account = AuthentifyClient(api_key=os.environ["AUTHENTIFY_ACCOUNT_KEY"], environment="production")
89
+ status = account.get_authorization_request(result["authorizationRequestId"])
90
+ status["approvalStatus"] # "pending", "approved" or "rejected"
91
+ ```
92
+
93
+ `approve_authorization_request()` and `reject_authorization_request()` are deprecated for that reason. Since 0.2.0 they raise `AuthentifyError` (status 403) straight away, without calling the API.
94
+
95
+ ### Reporting what happened
96
+
97
+ ```python
98
+ client.report_outcome(result["authorizationRequestId"], {"status": "succeeded"})
99
+ ```
100
+
101
+ ### Consent sessions
102
+
103
+ ```python
104
+ session = account.create_consent_session({
105
+ "agent_id": "YOUR_AGENT_ID",
106
+ "customer_id": "YOUR_CUSTOMER_ID",
107
+ "end_user_id": "retail-cust-42",
108
+ "scope": ["READ", "TRANSFER"],
109
+ })
110
+
111
+ # session["widget_url"] -- send your retail customer here, or render
112
+ # @authentify2026/consent-widget client-side with session["session_id"].
113
+ ```
114
+
115
+ ## Errors
116
+
117
+ Any non-2xx response raises `authentify.AuthentifyError`, with `status`, `code` and the response `body`.
118
+
119
+ ## Smoke-testing against a sandbox account
120
+
121
+ ```python
122
+ from authentify import AuthentifyClient
123
+
124
+ client = AuthentifyClient(api_key="YOUR_SANDBOX_KEY", environment="sandbox")
125
+ result = client.authorize({"action": "READ", "resource": {"id": "test-123"}})
126
+ print(result["decision"]) # expect "allow" for an unrestricted agent
127
+
128
+ integrity = client.get_audit_integrity()
129
+ assert integrity["verifiedCount"] == integrity["totalCount"]
130
+ print("audit chain intact:", integrity["brokenAtId"] is None)
131
+ ```
@@ -0,0 +1,12 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/authentify/__init__.py
5
+ src/authentify/client.py
6
+ src/authentify/errors.py
7
+ src/authentify/types.py
8
+ src/authentify_sdk.egg-info/PKG-INFO
9
+ src/authentify_sdk.egg-info/SOURCES.txt
10
+ src/authentify_sdk.egg-info/dependency_links.txt
11
+ src/authentify_sdk.egg-info/requires.txt
12
+ src/authentify_sdk.egg-info/top_level.txt
@@ -0,0 +1 @@
1
+ requests>=2.28