Metadata-Version: 2.5
Name: ohauthcat
Version: 0.0.2
Summary: Official OhAuthCat SDK for Python
Project-URL: Documentation, https://docs.ohauthcat.com
License-File: LICENSE
License-File: THIRD_PARTY_LICENSES
Classifier: License :: Other/Proprietary License
Classifier: Programming Language :: Python :: 3
Classifier: Typing :: Typed
Requires-Python: >=3.10
Requires-Dist: cryptography<51,>=50.0.2
Requires-Dist: httpx<1,>=0.27
Requires-Dist: pydantic<3,>=2.7
Requires-Dist: typing-extensions<5,>=4.12
Provides-Extra: dev
Requires-Dist: black==26.10.1; extra == 'dev'
Requires-Dist: build; extra == 'dev'
Requires-Dist: datamodel-code-generator==0.83.0; extra == 'dev'
Requires-Dist: hatch; extra == 'dev'
Requires-Dist: isort==6.1.0; extra == 'dev'
Requires-Dist: mypy; extra == 'dev'
Requires-Dist: pytest; extra == 'dev'
Requires-Dist: ruff==0.16.10; extra == 'dev'
Requires-Dist: setuptools>=84.1.0; extra == 'dev'
Requires-Dist: types-pyyaml==6.0.12.20260906; extra == 'dev'
Description-Content-Type: text/markdown

# ohauthcat (Python)

Typed sync and async clients for the pinned OhAuthCat versioned operations.

```sh
pip install ohauthcat
```

### Before the first release

`ohauthcat` is not published to PyPI yet, so the install command above fails until the first release. Until then, install it from the source repository. The repository is private: you need read access to `bitbucket.org/the-genie-team/ohauthcat-sdk-python` over SSH. Run these commands from your project directory; the `v0.0.2` tag matches the version above (until that tag exists, replace `--branch v0.0.2` with `--branch dev` in `git clone`, and `@v0.0.2` with `@dev` in the `pip install` URL).

```sh
git clone --depth 1 --branch v0.0.2 git@bitbucket.org:the-genie-team/ohauthcat-sdk-python.git
pip install ./ohauthcat-sdk-python
```

Without a clone:

```sh
pip install "git+ssh://git@bitbucket.org/the-genie-team/ohauthcat-sdk-python.git@v0.0.2"
```

```python
from ohauthcat import OhAuthCat, models

with OhAuthCat(api_key="sk_example") as client:
    organization = client.organizations.create_organization(
        body=models.OrganizationCreate(name="Example")
    )
```

## Errors

API failures raise `OhAuthCatError` (or a subclass) with `code`, `status`, `param`, `doc_url` and `request_id`. Arguments the SDK refuses before sending anything raise `OhAuthCatValidationError`: its `code` is `request_invalid`, `param` names the argument when known and `doc_url` links the catalogue page. It is also a `ValueError`, so existing `except ValueError` handlers keep working.

## Webhooks

Verify the exact raw request body before parsing it. Pass every secret you hold during a rotation. Verification raises `WebhookVerificationError` whose `code` is, for example, `signature_invalid` or `timestamp_outside` (older than 300 seconds).

```python
import os

from ohauthcat import webhooks
from ohauthcat.webhooks import WebhookVerificationError


def handle_webhook(raw_body: bytes, header: str) -> int:
    """raw_body: the exact request bytes; header: the OhAuthCat-Signature header."""
    try:
        event = webhooks.verify(raw_body, header, [os.environ.get("OHAUTHCAT_WEBHOOK_SECRET", "")])
    except WebhookVerificationError as err:
        print("rejected:", err.code)
        return 400
    print(event.type, event.id)
    return 204
```

`AsyncOhAuthCat` provides the same resource methods with `await` and async context management. `client.events.list()` returns a forward iterator, or async iterator. `client.portal.create_link(...)` aliases the generated portal operation. Original `models` validate requests; `response_models` tolerate additive enum strings while retaining singleton discriminators and field constraints.

## Sign-in

Configure `client_id="pk_..."` (and `environment_id="env_..."` to verify access tokens). Every sign-in needs a random `state` that you keep in the user's session and compare on the callback, or an attacker can sign your user into the attacker's account (login CSRF). `get_authorization_url` generates one when you pass none and returns it as `.state`, together with the PKCE `.code_verifier`. Refuse a missing or different state before exchanging the code. The exchange uses the secret API key, is never retried automatically (reusing a code revokes the first grant), and raises `RestartSignIn` when the user must start again.

```python
import hmac

from ohauthcat import OhAuthCat, RestartSignIn

REDIRECT_URI = "https://app.example.com/callback"


def start_sign_in(client: OhAuthCat, session: dict[str, str]) -> str:
    """Returns the URL to redirect the browser to. `session` is your server-side session."""
    auth = client.sso.get_authorization_url(redirect_uri=REDIRECT_URI, domain="customer.com")
    session["sso_state"] = auth.state
    session["sso_verifier"] = auth.code_verifier
    return auth.url


def finish_sign_in(client: OhAuthCat, session: dict[str, str], code: str, state: str) -> str:
    expected = session.pop("sso_state", "")
    verifier = session.pop("sso_verifier", "")
    if not expected or not verifier or not hmac.compare_digest(expected.encode(), state.encode()):
        raise PermissionError("sign-in expired, start again")  # never exchange the code
    try:
        token = client.sso.get_profile_and_token(
            code=code, code_verifier=verifier, redirect_uri=REDIRECT_URI
        )
    except RestartSignIn:
        raise PermissionError("sign-in expired, start again") from None
    return token.profile.email  # create your session for this user
```

Guests: a sign-in admitted under the organization's guest policy (an email domain outside its verified domains) is identified by `token.profile.access_policy == "guest"` (`AccessPolicy.guest.value` in `ohauthcat.response_models`; response enums decode to plain strings so a value newer than this SDK never fails); for every other sign-in the field is absent. `email_domain_verified` stays true for guests, so check this field when guests must get less access.

`client.sso.verify_access_token(token)` verifies ES256 with the configured issuer/client/environment and a bounded JWKS cache fetched from the active trusted broker origin. The configured issuer remains exact when retrieval fails over. `get_sso_profile(access_token=token)` additionally checks the authenticated broker profile. Await both on the async client. Issuer defaults to `https://auth.ohauthcat.com`; explicitly configured HTTP loopback origins support local fixtures. No token-supplied issuer or key URL is trusted.

Clients own their default HTTPX clients. Injected `http_client` instances remain caller-owned. Closing the SDK disables requests and token verification. Async requests have an overall deadline and cancellation cleanup. Sync HTTPX uses per-phase timeouts and checks the total budget between chunks/retries, including JWKS lock waits; a blocked network read or custom transport may exceed that total budget before control returns.

Upload a logo from bytes or a file path:

```python
with OhAuthCat(api_key="sk_example") as client:
    logo = client.logos.upload_file("logo.svg", idempotency_key="logo-2026-10")
    # or: client.logos.upload(Path("logo.png").read_bytes())
    client.branding.update_branding(body=models.BrandingUpdate(logo_url=str(logo.logo_url)))
```

`client.logos.upload(data)` and `upload_file(path)` (awaitable on the async client) refuse, before any request, a file that is empty, larger than 256 KiB, or neither a PNG (by its signature) nor an SVG (by its root element), raising `OhAuthCatError` with code `logo_invalid`, status `0` and param `data`. `check_logo(data)` runs the same check alone. Accepted bytes are base64-encoded and sent to `upload_branding_logo`; the API still validates dimensions and SVG content, and its `logo_invalid` refusal raises the same error type with the HTTP status and message.

Install tooling in a repository-local virtual environment:

```sh
python3 -m venv .venv
.venv/bin/pip install -e '.[dev]'
```

Run named test files, for example `.venv/bin/python -m pytest tests/test_transport.py`. The independent contract tests additionally need Node 24 and the development spec mock: `(cd spec-mock && pnpm install --frozen-lockfile)`.

Migration helpers are explicitly import-bound: `helper = client.migration(import_id=..., legacy_provider="workos", resolve_legacy_profile=resolver)`. Read `helper.routing.for_organization(org)` and call `helper.migrate_session(legacy_access_token=...)`; await both with the async client. Your resolver authenticates UserInfo and returns the legacy profile ID, while OhAuthCat receives only the import and that ID. Routing cache defaults to 30 seconds (maximum 60); call `helper.routing.invalidate()` after a switch or rollback. Session migration reads a fresh import. Sync resolvers must cooperate with `LegacySessionContext.remaining_seconds()` and `is_cancelled()`; async resolvers must honor cancellation, whose cleanup is awaited. See the OhAuthCat docs for the full contract and direct generated API distinction.

Automatic trusted edge failover, configurable fallback origins and request-driven dual health probes use the shared policy in handbook docs/12 §8.5. `standby=False` disables it; custom primary origins require both explicit trusted fallback origins to opt in.

## Portal links

A setup link lasts `expires_in` seconds, 300 (5 minutes) to 2,592,000 (30 days); leave it out for the default of 604,800 (7 days). A link created with a secret key opens once; revoke it to end it early, and `expires_at` on the result says when it ends. `ttl` (60 to 300 seconds) is only for sealed single-use embed links; never send both.

```python
link = client.portal.create_link(
    body=models.PortalLinkCreate(
        organization="org_...", intents=[models.Intent.sso], expires_in=24 * 60 * 60
    )
)
print(link.url, link.expires_at)
```

## Development

Python 3.11 (CI also runs 3.14). From the repository root:

```sh
python3 -m venv .venv && .venv/bin/pip install -e '.[dev]'
(cd spec-mock && pnpm install --frozen-lockfile)   # Node 24; contract tests only
.venv/bin/ruff format --check . && .venv/bin/ruff check . && .venv/bin/mypy --strict src
timeout 300 .venv/bin/python -m pytest tests/test_transport.py   # targeted
.venv/bin/python scripts/check_licenses.py
sh scripts/check-pin.sh && sh scripts/check-drift.sh
sh scripts/repin.sh <core-ref>                     # local only, needs ../ohauthcat-core
.venv/bin/python -m build
```

Framework examples (FastAPI, Django, Flask) live in `examples/python`. Releases: [RELEASING.md](RELEASING.md).
