SPB Git

Repository Public

README.md 8.7 KB 176 lines markdown

1# maclustr-identity (Python)23Python SDK for **MacLustr Identity**, the self-hosted identity-verification platform.4Sync and async clients with the same surface, webhook verification, typed objects and exceptions.5Python 3.10+. Single dependency: `httpx`. Ships `py.typed`.67> **Secret keys never leave your server.** `mlid_sk_test_…` and `mlid_sk_live_…` give full access to your8> application's verifications. This package is server-side only: never embed a key in a web page, a mobile app,9> a desktop app, a notebook you share or a public repository. The person being verified only receives the10> session `url`. The client never prints its key (`repr()` hides it).1112## Install1314Nothing is published to PyPI yet. Install from the repository path:1516```bash17pip install /absolute/path/to/maclustr-identity/sdk/python18# or, with uv19uv pip install /absolute/path/to/maclustr-identity/sdk/python20```2122## Quickstart2324```python25import os26from maclustr_identity import MacLustrIdentity, APIConnectionError2728identity = MacLustrIdentity(api_key=os.environ["MLID_SECRET_KEY"])2930# 1. Gate the sensitive action on your server. Fail closed when the service is unreachable.31try:32    verification = identity.is_user_verified(user.id)   # newest valid verification, or None33except APIConnectionError:34    verification = None3536if verification is None:37    # 2. Create a session and send the person to its hosted page.38    session = identity.verification_sessions.create(39        purpose="Raise the transfer limit",40        external_user_id=user.id,                        # opaque id, never an e-mail or a name41        return_url="https://wallet.example/verify/return",42    )43    redirect(session.url)44```4546Async:4748```python49from maclustr_identity import AsyncMacLustrIdentity5051async with AsyncMacLustrIdentity(api_key=os.environ["MLID_SECRET_KEY"]) as identity:52    session = await identity.verification_sessions.create(purpose="Raise the transfer limit", external_user_id="user_42")53    async for v in identity.verifications.list_auto_paging(status="verified"):54        print(v.verification_id, v.assurance_level)55```5657### Client options5859```python60MacLustrIdentity(61    api_key,                                   # required, mlid_sk_test_… or mlid_sk_live_…62    base_url="https://identity.spboucher.ai",  # default63    timeout=30.0,                              # seconds, per attempt64    max_retries=2,                             # after the first attempt65    http_client=None,                          # optional httpx.Client (httpx.AsyncClient for the async client)66)67```6869### Resources7071`MacLustrIdentity` and `AsyncMacLustrIdentity` expose the same methods (awaitable on the async client).7273| Call | HTTP |74|---|---|75| `verification_sessions.create(purpose=…, external_user_id=…, verification_policy=…, return_url=…, locale=…, metadata=…, expires_in_minutes=…)` | `POST /v1/verification-sessions` |76| `verification_sessions.retrieve(id)` | `GET /v1/verification-sessions/{id}` |77| `verification_sessions.list(limit=…, starting_after=…, status=…, external_user_id=…)` / `.list_auto_paging(…)` | `GET /v1/verification-sessions` |78| `verification_sessions.cancel(id)` | `POST /v1/verification-sessions/{id}/cancel` |79| `verifications.retrieve(id)` | `GET /v1/verifications/{id}` |80| `verifications.status(id)` | `GET /v1/verifications/{id}/status` |81| `verifications.list(…)` / `.list_auto_paging(…)` | `GET /v1/verifications` |82| `verifications.revoke(id, reason=…)` | `POST /v1/verifications/{id}/revoke` |83| `verifications.delete_personal_data(id)` | `DELETE /v1/verifications/{id}/personal-data` |84| `webhooks.create(url=…, events=…, description=…)` | `POST /v1/webhooks` |85| `webhooks.list()` | `GET /v1/webhooks` |86| `webhooks.delete(id)` | `DELETE /v1/webhooks/{id}` |87| `webhooks.rotate_secret(id)` | `POST /v1/webhooks/{id}/rotate-secret` |88| `is_user_verified(external_user_id)` | `GET /v1/verifications?external_user_id=…&status=verified` |8990Objects are frozen dataclasses (`VerificationSession`, `CreatedVerificationSession`, `Verification`,91`VerificationStatusSummary`, `PersonalDataDeletion`, `WebhookEndpoint`, `CreatedWebhookEndpoint`,92`RotatedWebhookSecret`, `Page`, `Event`). Each keeps the full JSON in `.raw`. `Verification.is_valid` is true93only for a `verified`, non-expired verification. Timestamps are ISO 8601 strings; `parse_datetime()` converts.9495### Idempotency and retries9697- Every `POST` carries an `Idempotency-Key` generated by the SDK, reused across the retries of that call.98  Pass `idempotency_key="order-42"` to make your own retries safe too. The service deduplicates every keyed99  POST: session creation and cancellation, revocation, webhook creation and secret rotation. A replay returns100  the first response (HTTP header `Idempotent-Replayed: true`); the same key with another body raises101  `ConflictError` (`idempotency_key_reused`).102- Retries happen only on network errors, HTTP 429 and HTTP 5xx, with exponential backoff and jitter103  (0.5 s, 1 s, 2 s… capped at 8 s, each multiplied by a random factor in [0.5, 1]). `Retry-After` is honoured104  on 429 `rate_limited` and 503 `service_unavailable` (capped at 60 s). Quotas (`daily_session_limit`) are not105  retried. 4xx errors are never retried. `webhooks.create` and `webhooks.rotate_secret` are retried like any106  other POST, with the same key: a retry returns the endpoint or the secret of the first attempt107  (`max_retries=0` disables retries for one call).108109### Exceptions110111All inherit `MacLustrIdentityError` (`status`, `type`, `code`, `param`, `request_id`, `message`).112113| Class | When |114|---|---|115| `InvalidRequestError` | 400, 411, 413, 422 (`invalid_cursor`, `payload_too_large`, `length_required`…) |116| `AuthenticationError` | 401 |117| `PermissionDeniedError` | 403 |118| `NotFoundError` | 404 (also for objects of another application or mode) |119| `ConflictError` | 409 |120| `RateLimitError` | 429 (`retry_after` in seconds) |121| `APIServerError` | 5xx (`retry_after` in seconds on 503 `service_unavailable`) |122| `APIConnectionError` | no response (`code`: `connection_failed` or `request_timeout`) |123| `SignatureVerificationError` | webhook signature missing, malformed, expired or not matching |124125## Webhooks126127Deliveries are signed: `MLID-Signature: t=<unix>,v1=<hex>[,v1=<hex>]`, each `v1` being128HMAC-SHA256(secret, `"<t>." + raw body`). During a secret rotation two `v1` values are sent for 24 hours.129Other headers: `MLID-Event-Id`, `MLID-Delivery-Id`, `MLID-Event-Type`.130131```python132from maclustr_identity import Webhook, SignatureVerificationError133134event = Webhook.construct_event(payload, sig_header, secret, tolerance=300)   # payload: the raw bytes135if event.verification is not None:        # decision events136    v = event.verification137    save(v.external_user_id, v.verification_id, v.status, v.assurance_level, v.expires_at)138```139140`payload` must be the raw request body (`await request.body()` in FastAPI, `request.get_data()` in Flask).141Deliveries are at-least-once and unordered: deduplicate on `event.id`. Complete endpoints:142[`examples/fastapi_webhook.py`](examples/fastapi_webhook.py), [`examples/flask_webhook.py`](examples/flask_webhook.py).143144Event types: `verification.created`, `.processing`, `.expired`, `.cancelled` (`event.session` is set) and145`.completed`, `.verified`, `.inconclusive`, `.manual_review`, `.rejected`, `.revoked` (`event.verification` is146set). After `.cancelled`, `.expired` (`event.session_ended_without_decision`) or an `inconclusive` result (for147example reason `review_not_completed`: the manual review was not handled before its deadline) the person may148simply start a new session. An event type or object kind added by a later service version never raises:149`event.object` is then the plain dict and both properties are `None`.150151## Testing your integration152153```python154from maclustr_identity.testing import complete_sandbox_session155156session = identity.verification_sessions.create(purpose="Test", external_user_id="u1")157complete_sandbox_session(session.url, scenario="verified")   # or manual_review | inconclusive | rejected158```159160It records consent and applies a sandbox scenario using the session client secret only (async variant:161`acomplete_sandbox_session`). Sandbox results are flagged `simulated=True` with162`assurance_level="sandbox_simulated"`. Live sessions refuse it.163164## Development165166```bash167uv venv .venv --python 3.12168uv pip install --python .venv/bin/python -e ".[dev]"169.venv/bin/pytest -m "not integration"    # unit tests170.venv/bin/pytest                         # + integration: local backend on http://localhost:8870 and its dispatcher171```172173Integration tests provision two sandbox applications through the backend CLI (`.venv` of the repository,174database `maclustr_identity_sdk`), or use `MLID_SECRET_KEY` / `MLID_SECRET_KEY_B` when set. They are skipped175when no backend answers and refuse anything but localhost.176
Files main
Menu

Theme