Repository Public
1# MacLustr Identity — Python SDK23Package `maclustr_identity`, source in [`sdk/python`](../sdk/python). Python 3.10+, one dependency (`httpx`),4fully typed (`py.typed`), synchronous and asynchronous clients with the same surface.56**Status: not published to PyPI.** Install from the repository path (see below). Version 0.1.0.78## Security rule: server-side only910A secret key (`mlid_sk_test_…`, `mlid_sk_live_…`) can read, revoke and erase every verification of your11application. This SDK is meant for server code: never embed a key in a web page, a mobile or desktop app, a12shared notebook or a repository. The person being verified only ever receives the session `url`. The webhook13signing secret (`whsec_…`) is server-side only as well.1415The clients refuse a value that is not a secret key and never print the key (`repr()` shows the base URL and16the mode). Created objects hide `client_secret`, `url` and webhook `secret` from their `repr()`.1718## Install1920```bash21pip install /path/to/maclustr-identity/sdk/python22# or23uv pip install /path/to/maclustr-identity/sdk/python24```2526`integrations/demo-wallet/setup.sh` installs it in editable mode (`-e ../../sdk/python`).2728## Quickstart2930```python31import os32from maclustr_identity import MacLustrIdentity, MacLustrIdentityError3334identity = MacLustrIdentity(api_key=os.environ["MLID_SECRET_KEY"])3536def may_raise_limit(user_id: str) -> bool:37 try:38 return identity.is_user_verified(user_id) is not None39 except MacLustrIdentityError:40 return False # unreachable or failing service: stay refused (fail closed)4142session = identity.verification_sessions.create(43 purpose="Raise the transfer limit",44 external_user_id=user.id, # opaque id, never an e-mail or a name45 return_url="https://wallet.example/verify/return",46)47# redirect the browser to session.url48```4950Async:5152```python53from maclustr_identity import AsyncMacLustrIdentity5455async with AsyncMacLustrIdentity(api_key=os.environ["MLID_SECRET_KEY"]) as identity:56 verification = await identity.is_user_verified("user_42")57```5859A complete application is in [`integrations/demo-wallet`](../integrations/demo-wallet); the generic guide is in60[`integrations/README.md`](../integrations/README.md).6162## Clients6364`MacLustrIdentity(api_key, *, base_url="https://identity.spboucher.ai", timeout=30.0, max_retries=2, http_client=None)`65`AsyncMacLustrIdentity(...)` — same arguments, `http_client` being an `httpx.AsyncClient`.6667| Argument | |68|---|---|69| `api_key` | required; must start with `mlid_sk_test_` or `mlid_sk_live_` |70| `base_url` | origin of the service, no path |71| `timeout` | seconds, per attempt |72| `max_retries` | retries after the first attempt |73| `http_client` | your own `httpx.Client` / `httpx.AsyncClient` (it is then yours to close) |7475Both are context managers (`with` / `async with`); otherwise call `close()` / `await aclose()`.76Attributes: `base_url`, `livemode`, `verification_sessions`, `verifications`, `webhooks`.7778Every method below exists on both clients; on the async client it is awaitable, and `list_auto_paging`79is an async iterator (`async for`).8081### `verification_sessions`8283| Method | Returns |84|---|---|85| `create(*, purpose, external_user_id=None, verification_policy=None, return_url=None, locale=None, metadata=None, expires_in_minutes=None, idempotency_key=None)` | `CreatedVerificationSession` |86| `retrieve(session_id)` | `VerificationSession` |87| `list(*, limit=None, starting_after=None, status=None, external_user_id=None)` | `Page[VerificationSession]` |88| `list_auto_paging(*, limit=None, status=None, external_user_id=None)` | iterator of `VerificationSession` |89| `cancel(session_id, *, idempotency_key=None)` | `VerificationSession` |9091`purpose` is required (≤ 120 characters, shown to the person). `verification_policy` defaults to92`identity_document_face_v1`; `identity_document_v1` is the document-only policy. `return_url` must be allowed93for the application. `metadata` is at most 2000 bytes and must not hold personal data. `expires_in_minutes`94is clamped to 10..1440 (default 60). `CreatedVerificationSession` adds `client_secret` and `url`, returned by95`create` only.9697Session statuses: `created`, `awaiting_consent`, `awaiting_document`, `awaiting_selfie`, `processing`,98`manual_review`, `verified`, `inconclusive`, `rejected`, `expired`, `cancelled`, `revoked`. A cancellation emits99`verification.cancelled`. An unknown `starting_after` raises `InvalidRequestError` (`invalid_cursor`).100101### `verifications`102103| Method | Returns |104|---|---|105| `retrieve(verification_id)` | `Verification` |106| `status(verification_id)` | `VerificationStatusSummary` (`status`, `valid`, `assurance_level`, `expires_at`) |107| `list(*, limit=None, starting_after=None, status=None, external_user_id=None)` | `Page[Verification]` |108| `list_auto_paging(*, limit=None, status=None, external_user_id=None)` | iterator of `Verification` |109| `revoke(verification_id, *, reason=None, idempotency_key=None)` | `Verification` |110| `delete_personal_data(verification_id)` | `PersonalDataDeletion` (`deleted`, counters in `.raw`) |111112`Verification` attributes: `verification_id`, `session_id`, `status`, `assurance_level`, `method`,113`verification_policy`, `policy_version`, `livemode`, `simulated`, `external_user_id`, `reasons`114(list of `Reason(code, message)`), `dimensions`, `decision_engine`, `created_at`, `verified_at`, `expires_at`,115`revoked_at`, `personal_data_deleted_at`, and the property `is_valid` (status `verified` and not expired).116It never contains a name, a document number, an image or any extracted field.117118Verification statuses: `verified`, `manual_review`, `inconclusive`, `rejected`, `revoked`. A status added by a119later service version is kept as received (`is_valid` is then `False`). `dimensions` maps each dimension to120`{"status": …}` with optional `notes`; scores are not kept once a decision is made. `reason_codes` lists the121codes of `reasons`: among them `review_not_completed` (the review by a person was not completed before its122deadline: the result is `inconclusive` and the person may start again) and `decision_overturned` (a contested123decision was set aside). `KNOWN_REASON_CODES` and `RETRYABLE_SESSION_STATUSES` are exported.124Assurance levels: `document_check`, `document_face_liveness_check`, `document_manual_review`,125`document_face_manual_review`, and `sandbox_simulated` for sandbox results (`simulated=True`).126127### `is_user_verified(external_user_id)`128129Lists the user's `verified` verifications (newest first) and returns the first valid one, or `None`. It raises130like any other call when the service is unreachable: treat that as "not verified".131132### `webhooks`133134| Method | Returns |135|---|---|136| `create(*, url, events=None, description=None, idempotency_key=None, max_retries=None)` | `CreatedWebhookEndpoint` (with `secret`, once) |137| `list()` | `Page[WebhookEndpoint]` |138| `delete(endpoint_id)` | `DeletedWebhookEndpoint` |139| `rotate_secret(endpoint_id, *, idempotency_key=None, max_retries=None)` | `RotatedWebhookSecret` |140| `construct_event(payload, sig_header, secret, tolerance=300)` | `Event` (same as `Webhook.construct_event`) |141| `verify_signature(payload, sig_header, secret, tolerance=300)` | `None` |142143### Objects144145All objects are frozen dataclasses built with `from_dict`. The complete JSON is kept in `.raw`; a field the146API did not send is `None`, an unknown field is ignored (but stays in `.raw`), so API evolutions do not raise.147Timestamps are ISO 8601 strings; `parse_datetime(value)` returns an aware `datetime`. `Page` has `data`,148`has_more`, and supports `len()` and iteration.149150## Webhooks151152```python153from maclustr_identity import Webhook, SignatureVerificationError154155try:156 event = Webhook.construct_event(payload, sig_header, secret, tolerance=300)157except SignatureVerificationError:158 return 400159```160161- `payload` is the **raw request body** (`bytes` or `str`): `await request.body()` in FastAPI / Starlette,162 `request.get_data()` in Flask, `request.body` in Django. A parsed dict is refused (`payload_not_raw`).163- `sig_header` is the `MLID-Signature` header: `t=<unix seconds>,v1=<hex>[,v1=<hex>]`. Each `v1` is164 HMAC-SHA256(secret, `"<t>." + raw body`). After `rotate_secret`, two `v1` values are sent for 24 hours and165 either secret verifies.166- Comparison uses `hmac.compare_digest`. The timestamp must be within `tolerance` seconds of now.167- Error codes: `signature_header_invalid`, `signature_mismatch`, `signature_expired`, `payload_not_raw`,168 `payload_invalid`, `secret_missing`.169- Other headers: `MLID-Event-Id` (stable across retries), `MLID-Delivery-Id`, `MLID-Event-Type`.170171`Event` attributes: `id`, `type`, `api_version`, `created` (unix seconds), `livemode`, `object`, `raw`, and two172convenience properties:173174| Event types | Set property |175|---|---|176| `verification.created`, `verification.processing`, `verification.expired`, `verification.cancelled` | `event.session` (`VerificationSession`) |177| `verification.completed`, `verification.verified`, `verification.inconclusive`, `verification.manual_review`, `verification.rejected`, `verification.revoked` | `event.verification` (`Verification`) |178179`event.session_ended_without_decision` is true for `verification.cancelled` and `verification.expired`: nothing180was decided and the person may start a new session. `verification.cancelled` is sent when your server cancels a181session and when the person withdraws consent, including during a manual review; in that last case no decision182event follows and the session carries the `verification_id` of the review that will never conclude. An event183type or object kind this SDK version does not know never raises: `event.type` is the string received,184`event.object` is the plain dict and both properties are `None`.185186Deliveries are at-least-once and unordered: deduplicate on `event.id`, and do not let an older event overwrite187a newer state. `Webhook.sign(payload, secret, timestamp=None)` builds a header for your own tests.188189Complete endpoints, both covered by the test suite:190[`examples/fastapi_webhook.py`](../sdk/python/examples/fastapi_webhook.py),191[`examples/flask_webhook.py`](../sdk/python/examples/flask_webhook.py).192193## Idempotency and retries194195Every `POST` sends an `Idempotency-Key` (`sdk-<uuid>`), identical across the automatic retries of that call;196pass `idempotency_key=` to cover your own retries. The service honours it on session creation, session197cancellation, verification revocation, webhook creation and secret rotation: a repeated key with the same body198returns the original response (HTTP header `Idempotent-Replayed: true`; the SDK returns the object, it does not199expose the header), `409 idempotency_key_reused` when the body differs, and `409 idempotency_in_progress`200while the first request is still running.201202Only network errors (including timeouts), HTTP 429 and HTTP 5xx are retried, up to `max_retries` times. Delay203before retry *n* (0-based): a random value in [50 %, 100 %] of `min(8 s, 0.5 s × 2ⁿ)`. When the response204carries `Retry-After` (429 `rate_limited`, 503 `service_unavailable`), that delay is used instead, capped at20560 s. Quotas (`429 daily_session_limit`) are not retried. No other 4xx is ever retried. `backoff_delay(attempt)`206and `should_retry(status, code)` are exported. `webhooks.create` and `webhooks.rotate_secret` are retried like207every other POST, with the same key: a retry returns the endpoint (and its secret) or the rotated secret of the208first attempt, it never creates or rotates twice (`max_retries=0` disables retries for one call). Two separate209calls use two keys: calling `rotate_secret` again rotates again. Rate limits are shared by every process of the210service: several of your workers using the same key share one budget.211212## Exceptions213214`MacLustrIdentityError` attributes: `message`, `status` (`None` without a response), `type`, `code`, `param`,215`request_id`, `headers`.216217| Class | HTTP | Typical `code` |218|---|---|---|219| `InvalidRequestError` | 400, 411, 413, 422 | `purpose_required`, `unknown_policy`, `return_url_not_allowed`, `invalid_webhook_url`, `invalid_cursor` (unknown `starting_after`), `payload_too_large` (413, body over 256 KB), `length_required` (411) |220| `AuthenticationError` | 401 | `missing_api_key`, `invalid_api_key` |221| `PermissionDeniedError` | 403 | `insufficient_scope`, `application_suspended`, `compliance_gate_closed`, `forbidden_network` |222| `NotFoundError` | 404 | `resource_missing` (also for objects of another application or mode, including a webhook endpoint deleted or rotated with a key of the other mode) |223| `ConflictError` | 409 | `session_not_cancellable`, `not_revocable`, `idempotency_key_reused`, `idempotency_in_progress` |224| `RateLimitError` | 429 | `rate_limited`, `daily_session_limit`; has `retry_after` |225| `APIServerError` | 5xx | `internal_error`, `service_unavailable` (503); has `retry_after` |226| `APIConnectionError` | none | `connection_failed`, `request_timeout` |227| `SignatureVerificationError` | none | see Webhooks |228229## Testing helper230231```python232from maclustr_identity.testing import complete_sandbox_session, acomplete_sandbox_session233234complete_sandbox_session(session.url, scenario="verified")235```236237Arguments: `url` (or `session_id` + `client_secret` + `base_url`), `scenario`238(`verified | manual_review | inconclusive | rejected`), `method` (default: the first method of the policy),239`http_client`. It calls `GET /v1/sessions/{id}`, `POST …/consent` and `POST …/sandbox` with the session client240secret and returns the flow state. It raises on a live session.241242## Tests243244```bash245cd sdk/python246uv venv .venv --python 3.12 && uv pip install --python .venv/bin/python -e ".[dev]"247.venv/bin/pytest -m "not integration" # 56 unit tests: signature, retries, idempotency, errors, tolerant models, pagination, async, examples248.venv/bin/pytest # + 12 integration tests against the local backend (MLID_BASE_URL, default http://localhost:8870) with its dispatcher249```250251## Known limitations252253- `webhooks.list()` is not paginated by the service (at most 16 endpoints per application and mode).254- `webhooks.delete` and `verifications.delete_personal_data` are `DELETE` calls: the service does not255 deduplicate them. A retried `webhooks.delete` whose first answer was lost raises `NotFoundError`: the endpoint256 is gone, which is what was asked.257- The `Idempotent-Replayed` response header is not exposed by the SDK.258- A 413 `payload_too_large` is answered before the body is read and the connection is closed: depending on259 timing, `httpx` may report it as an `APIConnectionError` instead of the 413 when the body is still being sent.260- No built-in Django example; `Webhook.construct_event(request.body, request.headers.get("MLID-Signature"), secret)` is all it takes.261