Metadata-Version: 2.5
Name: 9in
Version: 0.1.0
Summary: Official Python SDK for 9in: sign-in (OIDC + PKCE), access token verification, Management API, adapters and webhooks.
Project-URL: Homepage, https://9in.io
Project-URL: Documentation, https://9in.io/docs/
Project-URL: Source, https://github.com/9in-io/python-sdk
Project-URL: Issues, https://github.com/9in-io/python-sdk/issues
Project-URL: Changelog, https://github.com/9in-io/python-sdk/blob/main/CHANGELOG.md
Author-email: Cubelet Ltd <info@cubelet.co.uk>
License-Expression: MIT
License-File: LICENSE
Keywords: 9in,authentication,jwt,oauth2,oidc,openid-connect,pkce,single-sign-on,sso,webhooks
Classifier: Development Status :: 4 - Beta
Classifier: Framework :: FastAPI
Classifier: Framework :: Flask
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Internet :: WWW/HTTP :: Session
Classifier: Topic :: Security
Classifier: Typing :: Typed
Requires-Python: >=3.10
Requires-Dist: cryptography>=42
Provides-Extra: fastapi
Requires-Dist: fastapi>=0.100; extra == 'fastapi'
Provides-Extra: flask
Requires-Dist: flask>=2.3.3; extra == 'flask'
Description-Content-Type: text/markdown

9in Python SDK
==============

<img src="https://raw.githubusercontent.com/9in-io/python-sdk/main/docs/img/logo.png" width="160" alt="9in"/>

Official Python SDK for [9in](https://9in.io): hosted login, OpenID Connect provider and SSO.

- **Sign users in** with `WebAppAuth`: authorization code flow with PKCE, endpoints from OIDC
  discovery, ID tokens verified against your tenant's keys, refresh token rotation and logout.
- **Protect your API**: verify access tokens locally with every algorithm of your tenant's key
  library, and, in hybrid mode, catch revocations at once with cached introspection.
- **Manage users** through the Management API: users, sessions, single-use sign-in links and
  bulk import.
- **Keep users in your own database** with the adapter protocol v2 (`/authenticate`, `/user`,
  `/event`) and signed requests and responses.
- **Receive webhooks**, verify their signature and process each event once.
- **Flask and FastAPI helpers**: a sign-in blueprint, `@require_auth`, and FastAPI dependencies.

Requires Python 3.10+. One dependency, [`cryptography`](https://cryptography.io); HTTP goes
through the standard library. Fully typed, and safe to share between threads.

```bash
pip install 9in
```

The package is `9in` on PyPI and `nine` in Python (`import nine`). Guides are at
[9in.io/docs](https://9in.io/docs/).

| Building with | Use |
|---|---|
| Django | [`9in-django`](https://github.com/9in-io/django) (sign-in, local users, DRF, webhooks, adapter) |
| JavaScript, Next.js, React | [`@9in-io/sdk`](https://github.com/9in-io/sdk), [`@9in-io/nextjs`](https://github.com/9in-io/nextjs), [`@9in-io/react`](https://github.com/9in-io/react) |
| PHP or Laravel | [`9in/php-sdk`](https://github.com/9in-io/php-sdk), [`9in/laravel`](https://github.com/9in-io/laravel) |

## Configuration

Every class takes its settings as arguments, and `from_env()` reads them from the environment:

| Variable | Used for |
|---|---|
| `NINE_ISSUER` | Your tenant, e.g. `https://acme.9in.io`, or your custom login domain |
| `NINE_CLIENT_ID` | The application's client ID |
| `NINE_CLIENT_SECRET` | Confidential applications, the Management API and introspection |
| `NINE_REDIRECT_URI` | The callback URL registered on the application |
| `NINE_AUDIENCE` | Your API's identifier: to request access tokens for it, and to verify them |
| `NINE_ADAPTER_SECRET` | The adapter's signing secret (Connections → User database) |
| `NINE_WEBHOOK_SECRET` | The webhook endpoint's signing secret (comma-separated while you rotate) |

`nine.env.get("ISSUER")` returns `NINE_ISSUER` (or None).

## Sign users in

Create a **Regular Web App** in the console with your callback URL (for example
`https://app.acme.com/nine/callback`) and logout URL, and copy its client ID and secret.

### Flask

```python
import os

from flask import Flask

from nine.flask import create_blueprint, current_user, get_access_token, login_required

app = Flask(__name__)
app.secret_key = os.environ["SECRET_KEY"]
app.register_blueprint(create_blueprint())   # /nine/login, /nine/signup, /nine/callback, /nine/logout


@app.get("/")
@login_required                              # signed-out visitors sign in and come back
def home():
    user = current_user()                    # sub, email, name, … from the verified ID token
    token = get_access_token()               # for your API (set NINE_AUDIENCE); refreshed and rotated
    return f"Hello {user['email']}"
```

`create_blueprint()` reads `NINE_ISSUER`, `NINE_CLIENT_ID`, `NINE_CLIENT_SECRET` and
`NINE_REDIRECT_URI` (or pass a `WebAppAuth`). Link to `/nine/login?return_to=/somewhere` and
`/nine/logout`. Flask's default session is a signed cookie, which the user can read: use a
server-side session (Flask-Session) to keep tokens off the browser.

### Any framework

`WebAppAuth` does the protocol; you keep the pending login and the tokens in your server-side
session:

```python
import nine

auth = nine.WebAppAuth.from_env()

# GET /nine/login
login = auth.create_login(return_to="/dashboard")       # screen="signup" opens the sign-up form
session["nine_login"] = login.pending                    # JSON-serialisable; a secret
redirect_to(login.url)

# GET /nine/callback: checks state, iss and PKCE, exchanges the code, verifies the ID token
tokens = auth.handle_callback(request_url, session.pop("nine_login", None))
session["nine_tokens"] = tokens.to_dict()
tokens.claims                                            # sub, email, name, …
redirect_to(tokens.return_to or "/")                     # only ever a same-site path

# later: refreshed (9in rotates refresh tokens, so save the new set)
tokens = auth.ensure_fresh(nine.TokenSet.from_dict(session["nine_tokens"]))
session["nine_tokens"] = tokens.to_dict()
profile = auth.userinfo(tokens.access_token)

# GET /nine/logout
auth.revoke(tokens.refresh_token)
redirect_to(auth.logout_url(id_token_hint=tokens.id_token, post_logout_redirect_uri="https://app.acme.com/"))
```

- **The `state` is single-use**, compared in constant time, and expires after 15 minutes. Pass a
  shared `cache=` when several processes handle callbacks.
- **The callback is checked** for 9in's `iss` parameter (RFC 9207); the ID token's signature,
  issuer, audience, expiry and nonce are verified before you see any claims.
- **Public applications** (no client secret) work the same way with PKCE; confidential ones
  authenticate with HTTP Basic.
- `create_login(prompt="login" | "consent" | "none" | "select_account", login_hint=…, locale="de")`.
- `auth.client_credentials(audience=…, scope=…)` gets a token for the application itself.

## Protect your API

```python
from nine import InsufficientScopeError, InvalidTokenError, TokenVerifier

verifier = TokenVerifier("https://acme.9in.io", audience="https://api.acme.com")

try:
    claims = verifier.verify(request.headers.get("Authorization"), scope="orders:read")
except (InvalidTokenError, InsufficientScopeError) as error:
    abort(error.status)            # 401 / 403

claims["sub"]        # the user (or the client ID for machine tokens)
claims["client_id"]  # the calling application
```

`nine.verify_access_token(token, issuer=…, audience=…, scope=…)` does the same in one call.

Every algorithm of the console's key library is accepted: RS256/384/512, PS256/384/512, ES256,
ES384 and EdDSA (Ed25519) from your tenant's JWKS. When a key names its `alg`, the token must use
exactly it, and the key type must fit. For an API whose tokens are signed with an HMAC key
(HS256/384/512), pass that key's secret: `TokenVerifier(issuer, secret=os.environ["NINE_API_SECRET"])`.
Only access tokens (`typ: at+jwt`) pass, never ID tokens. Keys are cached for ten minutes; a token
with an unknown key id fetches them again once (key rotation), and unknown key ids are then
ignored for a minute.

With Flask or FastAPI:

```python
from nine.flask import current_claims, require_auth

@app.get("/api/orders")
@require_auth(scope="orders:read")           # 401 / 403 with a WWW-Authenticate header
def orders():
    return {"user": current_claims()["sub"]}
```

```python
from fastapi import Depends, FastAPI

from nine.fastapi import require_auth

app = FastAPI()

@app.get("/api/orders")
def orders(claims: dict = Depends(require_auth(scope="orders:read"))):
    return {"user": claims["sub"]}
```

Both verify with `nine.create_token_verifier()` from `NINE_ISSUER`, `NINE_AUDIENCE` and, for
hybrid mode, `NINE_CLIENT_ID` / `NINE_CLIENT_SECRET`, unless you pass `verifier=`.

### Revocation-aware verification (hybrid)

A JWT stays valid until it expires, even after the user signs out or an admin revokes it.
`HybridTokenVerifier` checks the token locally, asks 9in once (introspection) and caches the
answer until a revocation webhook arrives:

```python
from nine import HybridTokenVerifier

verifier = HybridTokenVerifier(
    "https://acme.9in.io",
    audience="https://api.acme.com",
    client_id=client_id,             # a confidential application, for introspection
    client_secret=client_secret,
    # mode="hybrid"                  # default with credentials; "local" or "introspect"
    # cache=shared_cache             # share answers between processes (see Caching)
    # cache_ttl=300                  # longest an answer is trusted without hearing from 9in
)

claims = verifier.verify(request.headers.get("Authorization"), scope="orders:read")

# In your webhook endpoint (subscribe it to token.revoked, session.revoked, user.*):
verifier.handle_event(event)
```

- **Opaque access tokens** (`9in_at_…`) are always introspected, and cached in hybrid mode.
- **Cache lifetime:** an answer never outlives the token. A refusal is remembered until the
  token expires (a minute for an opaque token).
- **Eviction:** `token.revoked` evicts by `jti`, `session.revoked` by `sid`, and
  `user.sessions_revoked` / `user.deleted` / `user.updated` / `user.password_changed` by user.
- `nine.create_token_verifier()` builds one from the environment (`NINE_TOKEN_MODE` sets the mode).

## Manage users

Give a confidential application the `management:*` scopes in the console, then:

```python
from nine import ManagementClient

management = ManagementClient.from_env()           # NINE_ISSUER, NINE_CLIENT_ID, NINE_CLIENT_SECRET

user = management.create_user({"email": "jane@acme.com", "password": "correct horse battery", "email_verified": True})
management.update_user(user["id"], {"name": "Jane Doe", "metadata": {"plan": "pro"}})
management.find_user_by_email("JANE@acme.com")     # the user, or None
management.find_user("phone_number", "+447700900000")
page = management.list_users(query="acme.com", limit=50)  # {"users": [...], "next_cursor": ...}
management.get_user(user["id"])                    # {"user", "identities", "sessions", "has_password", "mfa"}

link = management.create_login_link(user["id"], return_to="https://app.acme.com/nine/callback")
link["url"]                                        # single use; expires at link["expires_at"]

management.list_user_sessions(user["id"])
management.revoke_user_sessions(user["id"])        # signs the user out everywhere
management.block_user(user["id"])
management.unblock_user(user["id"])
management.delete_user(user["id"])

management.import_users([{"id": "legacy-42", "email": "old@acme.com", "password_hash": "$2b$12$…"}], on_conflict="update")
```

Users, sessions and inputs use the API's own snake_case names (`email_verified`,
`phone_number`, `password_hash`), the same going in and coming out; times are ISO 8601 UTC
strings. Each call asks for the one scope it needs, so an application granted only some
management scopes works; tokens are cached until shortly before they expire.

## Keep users in your own database

9in can check passwords against your database and look users up there (Connections → User
database → Your server). Implement an `Adapter` and serve it with `AdapterHandler`:

```python
from nine import Adapter, AdapterHandler, AdapterUser, env


class MyUsers(Adapter):
    def authenticate(self, identifier, password):        # {"type": "email" | "username" | "phone", "value": …}
        user = db.find_by_login(identifier["type"], identifier["value"])
        if user is None or not user.check_password(password):
            return self.INVALID
        return self.BLOCKED if user.disabled else to_adapter_user(user)

    def find_user(self, query):                           # {"id": …} or {"identifier": {…}}
        user = db.get(query["id"]) if "id" in query else db.find_by_login(**query["identifier"])
        return to_adapter_user(user) if user else None

    def on_event(self, event):                            # otp.requested, user.updated, …
        if event["event_type"] == "otp.requested":
            send_code(event["data"]["to"], event["data"]["code"])


def to_adapter_user(user):
    return AdapterUser(id=str(user.id), email=user.email, email_verified=user.confirmed, name=user.full_name)


handler = AdapterHandler(env.get("ADAPTER_SECRET"), MyUsers())

# Flask: one route for /nine/authenticate, /nine/user and /nine/event
@app.post("/nine/<any(authenticate, user, event):route>")
def adapter(route):
    answer = handler.handle(request.method, request.path, request.headers, request.get_data())
    return answer.body, answer.status, answer.headers
```

`AdapterHandler` checks each request's `9in-signature` (HMAC over the timestamp, method, path
and raw body, 5 minutes of tolerance), routes the three endpoints with 9in's status codes, and
signs every response over `<path>#<9in-request-id>` so it can't be replayed for another request.
Pass `[new_secret, old_secret]` while you rotate the secret.

## Webhooks

```python
from nine import EventDeduplicator, MemoryCache, NineError, env, verify_webhook

dedupe = EventDeduplicator(MemoryCache())    # a shared cache with an atomic add() for several processes

@app.post("/nine/webhook")
def webhook():
    try:
        event = verify_webhook(env.get_list("WEBHOOK_SECRET"), request.get_data(), request.headers.get("9in-signature"), "/nine/webhook")
    except NineError as error:
        return {"error": error.error}, error.status

    def handle():
        if event["event_type"] == "user.created":
            crm.add_contact(event["data"]["user"])
        verifier.handle_event(event)         # if you use HybridTokenVerifier

    outcome = dedupe.process(event["id"], handle)
    return "", 409 if outcome == EventDeduplicator.IN_PROGRESS else 204
```

`verify_webhook` checks the signature over the **raw** body and the path 9in posted to (pass it
explicitly when a proxy rewrites paths), with 5 minutes of tolerance, and returns the event:
`{id, event_type, created_at, tenant, environment, data}`. `EventDeduplicator.process` runs the
handler once per event id: `processed` or `duplicate` → answer 2xx; `in_progress` (another
delivery is running) → 409 so 9in retries later; if the handler raises, the id is released and
the error re-raised, so 9in's retry processes the event. In FastAPI,
`event: dict = Depends(nine.fastapi.webhook_event())` does the verification.

## Caching and threads

The SDK caches discovery documents and keys per process, and keeps hybrid answers, used
sign-in states and processed event ids in a `Cache`. The default `MemoryCache` is thread-safe
and lives in one process. With several processes, pass one shared cache (`cache=`): any object
with `get(key)`, `set(key, value, ttl)`, `delete(key)` and an atomic `add(key, value, ttl)`.
Values are JSON-compatible.

```python
import json

import redis


class RedisCache:
    def __init__(self, client):
        self.r = client

    def get(self, key):
        raw = self.r.get(key)
        return None if raw is None else json.loads(raw)

    def set(self, key, value, ttl=None):
        self.r.set(key, json.dumps(value), ex=ttl)

    def delete(self, key):
        self.r.delete(key)

    def add(self, key, value, ttl=None):
        return bool(self.r.set(key, json.dumps(value), ex=ttl, nx=True))


cache = RedisCache(redis.Redis())
```

HTTP goes through `nine.UrllibHttpClient` (10 s timeout, TLS verified, redirects never
followed). Pass `http=` with your own `HttpClient` to change the timeout or use a proxy.

## Issuers must use https

Every class refuses an issuer that is not `https://` (`insecure_issuer`), so a typo can't send
codes, tokens or client secrets in clear text. Plain http is accepted for `localhost`,
`*.localhost` and loopback addresses. For other development hosts (e.g. `http://auth:8897` in
Docker) pass `allow_insecure_issuer=True` or set `NINE_ALLOW_INSECURE_ISSUER=true`. Issuers with
a query string, fragment or credentials are refused (`invalid_issuer`).

## Errors

Every failure is a `nine.NineError` with an `error` code (`invalid_token`, `insufficient_scope`,
`invalid_state`, `invalid_grant`, `access_denied`, `invalid_signature`, `insecure_issuer`,
`network_error`, …), a `description` and, for HTTP errors, a `status`:

| Class | When | `status` |
|---|---|---|
| `InvalidTokenError` | A token is missing, malformed, expired, revoked or for another API | 401 |
| `InsufficientScopeError` | A valid token lacks a scope (`.missing` lists them) | 403 |
| `InvalidStateError` | A callback's state doesn't match, was used, or expired | 400 |
| `SignatureError` | A `9in-signature` is missing, malformed, expired or wrong (`.reason`) | 401 |
| `NineError` | Anything else, e.g. errors from 9in (`invalid_grant`, `not_found`) or `jwks_unavailable` when 9in can't be reached (answer 503) | varies |

Errors from the Management API keep 9in's JSON body in `.body` (`details`, `field`, …).

## Development

```bash
uv sync                  # or: pip install -e . pytest flask fastapi httpx mypy ruff
uv run pytest            # unit tests (a fake 9in tenant; no network)
uv run mypy && uv run ruff check
```

The live end-to-end tests sign in through 9in's real hosted pages on test tenants, verify real
tokens, webhooks and adapter calls, and delete the users they create:

```bash
NINE_E2E=1 NINE_E2E_ENV=/path/to/.env.e2e uv run pytest tests/test_live.py
```

`examples/` has a Flask app (sign-in, an API route, webhooks, the adapter) and a FastAPI API.
Report bugs in [issues](https://github.com/9in-io/python-sdk/issues).

## License

The MIT License (MIT). See [LICENSE](https://github.com/9in-io/python-sdk/blob/main/LICENSE). 9in is by [Cubelet Ltd](https://cubelet.co.uk).
