Metadata-Version: 2.4
Name: inkpass-sdk
Version: 0.16.0
Summary: Official Python SDK for inkPass Authentication & Authorization Service
Author-email: fluxos contributors <dev@fluxtopus.com>
License: MIT
Project-URL: Homepage, https://fluxtopus.com
Project-URL: Documentation, https://fluxtopus.com
Project-URL: Repository, https://fluxtopus.com
Project-URL: Bug Tracker, https://fluxtopus.com
Keywords: authentication,authorization,auth,inkpass,security,jwt,abac
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
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: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: Security
Classifier: Topic :: System :: Systems Administration :: Authentication/Directory
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: httpx>=0.25.0
Requires-Dist: tenacity>=8.2.0
Requires-Dist: structlog>=23.0.0
Requires-Dist: pydantic>=2.0.0
Requires-Dist: fastapi>=0.104.0
Provides-Extra: dev
Requires-Dist: pytest>=7.4.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.21.0; extra == "dev"
Requires-Dist: pytest-cov>=4.1.0; extra == "dev"
Requires-Dist: black>=23.0.0; extra == "dev"
Requires-Dist: ruff>=0.1.0; extra == "dev"
Requires-Dist: mypy>=1.0.0; extra == "dev"
Dynamic: license-file

# inkPass SDK for Python

Official Python SDK for inkPass - Authentication & Authorization Service

[![Python Version](https://img.shields.io/badge/python-3.10%2B-blue)](https://www.python.org/downloads/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

## Features

- ✅ **Type-safe** - Full type hints and Pydantic models
- ✅ **Async/await** - Built on httpx for modern async Python
- ✅ **Retries where safe** - Reads are retried with exponential backoff when InkPass sends no
  answer; calls that change state are sent once
- ✅ **Error handling** - Comprehensive exception hierarchy
- ✅ **Fail-safe** - Permission checks default to deny on errors
- ✅ **Well-tested** - Extensive test coverage
- ✅ **Easy integration** - Simple FastAPI middleware patterns

## Installation

### From PyPI (Recommended)

```bash
uv add inkpass-sdk
# or: pip install inkpass-sdk
```

### From Source (Development)

```bash
# From the monorepo root:
cd packages/inkpass-sdk-python
pip install -e ".[dev]"
```

## Quick Start

### Basic Usage

```python
import asyncio
from inkpass_sdk import InkPassClient, InkPassConfig

async def main():
    # Initialize client
    config = InkPassConfig(base_url="http://inkpass:8000")
    client = InkPassClient(config)

    # Register user
    registration = await client.register(
        email="user@example.com",
        password="SecurePassword123!",
        organization_name="My Organization"
    )

    # Login
    tokens = await client.login(
        email="user@example.com",
        password="SecurePassword123!"
    )

    # Validate token
    user = await client.validate_token(tokens.access_token)
    print(f"Logged in as: {user.email}")

    # Check permission
    can_create = await client.check_permission(
        token=tokens.access_token,
        resource="workflows",
        action="create"
    )
    print(f"Can create workflows: {can_create}")

    # Clean up
    await client.close()

asyncio.run(main())
```

### Context Manager (Recommended)

```python
from inkpass_sdk import InkPassClient, InkPassConfig

async def main():
    config = InkPassConfig(base_url="http://inkpass:8000")

    # Automatically closes on exit
    async with InkPassClient(config) as client:
        user = await client.validate_token(token)
        # ... do work
```

## FastAPI Integration

```python
from typing import Annotated
from fastapi import Depends, FastAPI, HTTPException
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from inkpass_sdk import InkPassClient, InkPassConfig

app = FastAPI()
security = HTTPBearer()

# Initialize inkPass client
inkpass_client = InkPassClient(InkPassConfig(base_url="http://inkpass:8000"))

# Dependency: Get current user
async def get_current_user(
    credentials: Annotated[HTTPAuthorizationCredentials, Depends(security)]
):
    user = await inkpass_client.validate_token(credentials.credentials)
    if not user:
        raise HTTPException(status_code=401, detail="Invalid token")
    return user

# Dependency: Require permission
def require_permission(resource: str, action: str):
    async def checker(
        user=Depends(get_current_user),
        credentials=Depends(security)
    ):
        has_perm = await inkpass_client.check_permission(
            credentials.credentials, resource, action
        )
        if not has_perm:
            raise HTTPException(status_code=403, detail="Permission denied")
        return user
    return checker

# Protected route with permission
@app.post("/workflows")
async def create_workflow(
    user=Depends(require_permission("workflows", "create"))
):
    return {"workflow": "created"}
```

## API Reference

### Client Configuration

```python
from inkpass_sdk import InkPassConfig

config = InkPassConfig(
    base_url="http://inkpass:8000",  # inkPass service URL
    api_key="optional-service-key",   # For service-to-service auth
    timeout=5.0,                       # Timeout of each attempt (seconds)
    max_retries=3,                     # Attempts in all, the first included, of a read
    retry_min_wait=1,                  # First wait between attempts (seconds), then doubling
    retry_max_wait=10,                 # Longest wait between attempts (seconds)
    verify_ssl=True,                   # Verify SSL certificates
)
```

### Client Methods

#### `register(email, password, organization_name=None)`
Register a new user.

**Returns**: `RegistrationResponse`

```python
result = await client.register(
    email="user@example.com",
    password="SecurePass123!",
    organization_name="My Org"  # Optional
)
# result.user_id, result.email, result.organization_id
```

#### `login(email, password)`
Authenticate user and get tokens.

**Returns**: `TokenResponse`

```python
tokens = await client.login("user@example.com", "password")
# tokens.access_token, tokens.refresh_token, tokens.expires_in
```

#### `validate_token(token)`
Validate JWT token and get user info.

**Returns**: `UserResponse | None`

```python
user = await client.validate_token(token)
if user:
    print(f"User: {user.email}, Org: {user.organization_id}")
```

#### `check_permission(token, resource, action, context=None)`
Check if user has permission.

**Returns**: `bool` (Fail-safe: returns `False` on errors)

```python
can_create = await client.check_permission(
    token=access_token,
    resource="workflows",
    action="create",
    context={"project_id": "123"}  # Optional ABAC context
)
```

#### `create_api_key(token, name, scopes=None, *, expires_in_days=None, never_expires=False, user_id=None, step_up_token=None)`
Create a new API key. Without `expires_in_days` (1 to 365) it lasts 90 days. Only an owner may
ask for a key that never expires (`never_expires=True`); anyone else gets `OwnerRequiredError`.
An owner may bind the key to any member of the organization with `user_id`: that key
impersonates the member (it acts as them, capped at what they hold now) but stays the owner's:
only its issuer rescopes it or reads its usage, and every other owner of the organization sees
and may revoke it (`list_impersonation_keys`); admins and the member it acts as, an owner
included, never see it. It pauses
while its issuer or its member is suspended, and ends for good (revoked, with the reason) when
its issuer stops being an owner, leaves or is deleted, or its member leaves. Its
`impersonated_by` is the owner's user ID, and `validate_api_key` returns it too; record it with
every action the key takes. A key bound to no member records its issuer too (`issued_by`) and is
not cut when that person leaves: owners rotate it by hand.

**Returns**: `APIKeyResponse` (with `expires_at`, `user_id`, `impersonated_by`, `issued_by`,
`status` and `status_reason`)

```python
api_key = await client.create_api_key(
    token=access_token,
    name="Service API Key",
    scopes=["read", "write"],
    expires_in_days=30,
)
# api_key.key (shown only once!)
```

#### `list_api_keys(token, *, include_revoked=False, scope="mine")` and `list_impersonation_keys(token, *, include_revoked=False)`
`list_api_keys` lists the keys the caller issued. With `scope="organization"`, an owner or an
admin lists every key of the organization they could revoke with `revoke_api_key`, by the same
rule; anyone else gets `OwnerOrAdminRequiredError`. `list_impersonation_keys`, for owners only
(`OwnerRequiredError` for anyone else), lists every impersonation key in the organization. Each
`APIKeySummary` has `status` (`active`, `paused`, `revoked` or `expired`) and `status_reason`
(for example `issuer_suspended`, `issuer_demoted`, `member_removed` or `owner_oversight`). Never
the key or its hash.

```python
# Every key an admin could revoke: their own and those of the members they manage.
keys = await client.list_api_keys(access_token, scope="organization")
```

#### `revoke_api_key(key_id, token)`
Revoke a key: the caller's own, a key of a member the caller may act on (an owner's only by an
owner), and, for an owner, any impersonation key or key bound to no member. InkPass keeps the
key's record and writes who revoked it to its append-only audit trail. A key the caller may not
revoke answers `PermissionDeniedError`, the same as a missing one. Not retried.

#### `set_member_status(organization_id, user_id, status, *, token=None, step_up_token=None)`
Suspend (`"suspended"`) or restore (`"active"`) someone's membership in the caller's
organization. A suspension cuts access to that organization only and revokes nothing: their API
keys and grants there pause, their standing reads `active: false, suspended: true`, and when it
is their home organization their sessions end and they cannot sign in. Needs `users:manage`;
acting on an owner or an admin is an owner's decision, a restore is held to the grant ceiling and
may need `step_up_token`, and the last owner is never suspended. It never clears the platform
operator's account lock. A member's API key with `users:manage` may call it as its member (see
[API keys that act as a member](#api-keys-that-act-as-a-member)): for a Product, whose members
all have its organization as their home and so cannot be removed with `remove_member`
(`HomeOrganizationError`), suspending is how a key takes one out, and restoring brings them
back. Inviting a suspended member again is refused; restore them instead.

**Returns**: the member as the member list shows them, with `membership_status`
**Raises**: `OrganizationMismatchError`, `OwnerRequiredError`, `NotPermittedError`,
`MemberNotFoundError`, `LastOwnerError`, `MembershipMissingError`, `AccountLockedError`,
`MemberKeyRequiredError`;
`ValueError`, before any request, for an id that is not a UUID

```python
member = await client.set_member_status("org-id", "user-id", "suspended", token=access_token)
# member["membership_status"] == "suspended"
```

### Sessions

#### `logout(token)`
Sign out: the session the access token belongs to ends, and its access and refresh tokens stop
working at once. Other sessions of the same person are untouched. `AuthenticationError` if the
session already ended. Not retried.

#### `refresh(refresh_token)`
Access tokens last 30 minutes, refresh tokens 7 days. `refresh` exchanges the refresh token for
a new pair and returns a `TokenResponse`. The refresh token is **rotated**: the old one stops
working, and presenting an already-used one is taken as theft and ends the whole session. So
`refresh` is never retried, and a transport error raises `OutcomeUnknownError`: sign in again
rather than refreshing with the old token. InkPass allows 10 refreshes (and 10 sign-outs) a
minute per client address; a backend refreshing for many people from one address should refresh
shortly before `expires_in`, not on every request.

```python
tokens = await client.login(email, password)
...
tokens = await client.refresh(tokens.refresh_token)  # store both new tokens
...
await client.logout(tokens.access_token)
```

#### `register_client_user(client_slug, email, password, ...)` and `login_client_user(client_slug, email, password, two_fa_code=None)`
Sign-up and sign-in for a user of a multi-client tenant. `register_client_user` returns the
account as a `UserResponse` and opens no session: InkPass sends no token on registration, and
outside development the account stays `pending` until `verify_email`. `login_client_user`
returns `(user, access_token)`, where `user` is a `ClientUserSession`: the `UserResponse` plus
the session InkPass opened, `access_token`, `refresh_token`, `token_type` and `expires_in`.
`refresh_token` and `expires_in` are `None` from an InkPass that does not send them.

```python
user, access_token = await client.login_client_user("wendell", email, password)
...
tokens = await client.refresh(user.refresh_token)  # a TokenResponse; store both new tokens
```

#### `verify_email(email, code, *, client_slug=None)` and `resend_verification(email, *, client_slug=None)`
Prove the mailbox of a `pending` account with the code InkPass mailed, or mail a new code.
Pass the `client_slug` the person registered under: without it InkPass looks the address up
in its default client, so a person of another client is not found (`verify_email` raises
`ValidationError`, `resend_verification` mails nothing and answers as for any address).

```python
await client.register_client_user("wendell", email, password)
await client.verify_email(email, code_from_the_email, client_slug="wendell")
```

#### Forwarding the person's address (`client_ip=`)
InkPass limits sign-up (3 a minute), login, verification and invitation acceptance per address.
A backend that calls for many people from one address passes each person's own address as
`client_ip=` to `register_client_user`, `login_client_user`, `verify_email`,
`resend_verification` and `accept_invitation`. The SDK then sends it in `X-Client-IP` with
`InkPassConfig.service_api_key` in `X-Service-API-Key`.

The key must be your Product's service identity holding the permission `client_ip:forward`
(ask the control plane for it), and the call must name your own client: `client_slug` is
required. InkPass ignores the address anywhere else and counts your backend's address. One
identity may spend at most 20 times a route's limit in each window across every address it forwards.
A `client_ip` that is not one IPv4 or IPv6 address, or one given without `client_slug` or
`service_api_key`, raises `ValueError` before any request.

```python
client = InkPassClient(InkPassConfig(base_url=url, service_api_key=identity_key))
await client.register_client_user("wendell", email, password, client_ip=request.client.host)
await client.verify_email(email, code, client_slug="wendell", client_ip=request.client.host)
```

Pass the address your own edge saw, never a header the browser can set. `login_client_user`
then checks the new token with `validate_client_token` when `service_identity_key` is set (see
below), and otherwise with `validate_token`, which counts your backend's address (30 a minute).

#### `validate_client_token(client_slug, token, *, service_identity_key=None)`
Checks a person's access token from your Product's backend. `validate_token` calls
`GET /auth/me`, which allows 30 calls a minute per address, so a backend checking every request
with it runs out at 30 a minute for all its users together. `validate_client_token` is limited
per service identity instead (6,000 a minute by default).

The key is your Product's service identity holding `tokens:introspect`, in
`InkPassConfig.service_identity_key` or passed for one call. `client_slug` must be its client.
InkPass checks the token as `/auth/me` does, so logout, revocation and suspension take effect at
once. The call returns a `ClientTokenUser` (the user plus `client_id`, `client_slug`,
`issued_at` and `expires_at`) for an active token, and None for any other token, another
client's included. A refused identity raises (`AuthenticationError`, `PermissionDeniedError`,
`RateLimitError`) instead of reading as a signed-out person. A missing key raises `ValueError`
before any request.

```python
client = InkPassClient(InkPassConfig(base_url=url, service_identity_key=identity_key))
user = await client.validate_client_token("wendell", access_token)
if user is None:
    raise NotSignedIn()
```

With `service_identity_key` set, `login_client_user` uses it for the new token too.

#### `validate_client_api_key(client_slug, api_key, *, service_identity_key=None)`
Checks an API key of your Product's client from your backend, for example each agent request
of an agent-first Product. `validate_api_key` calls `GET /auth/me` with `X-API-Key`, which
allows 30 calls a minute per address; `validate_client_api_key` is limited per service identity
instead (6,000 a minute by default).

The key is your Product's service identity holding `api_keys:introspect` (apart from
`tokens:introspect`), in `InkPassConfig.service_identity_key` or passed for one call.
`client_slug` must be its client. InkPass verifies the key as `X-API-Key` does, so revocation,
expiry and a pause take effect at once, and the check counts as a use of the key. The call
returns a `ClientAPIKeyInfo` (what `validate_api_key` returns, plus `client_id` and
`client_slug`) for an active key, and None for any other key, another client's included. A
refused identity raises (`AuthenticationError`, `PermissionDeniedError`, `RateLimitError`)
instead of reading as a revoked key. A missing identity key raises `ValueError` before any
request.

```python
client = InkPassClient(InkPassConfig(base_url=url, service_identity_key=identity_key))
key = await client.validate_client_api_key("wendell", agent_api_key)
if key is None:
    raise NotAuthenticated()
allowed = "files:read" in key.scopes
```

### Step-up

Some calls need proof that the person re-authenticated this session within the last five
minutes. Without it, InkPass answers 403 and the SDK raises `StepUpRequiredError` (a
`PermissionDeniedError`, `code == "step_up_required"`) with `required_factors`: some of
`"password"`, `"email_code"` (an account with no password) and `"two_fa_code"` (2FA on; a
recovery code stands in for it). Get a token with `step_up` and repeat the call with
`step_up_token=`; the token is bound to the session that took it.

* `transfer_ownership` (and InkPass's 2FA and email-change routes) always need it.
* The grant routes, `invite_member`, `resend_invitation`, `assign_role`, `create_api_key` and a
  restore through `set_member_status`, need it only while InkPass runs with
  `STEP_UP_ENFORCE_GRANTS=true`; with it off (the default) they only count the request. Pass a
  token anyway, or handle `StepUpRequiredError`, so nothing breaks when it is turned on.

```python
from inkpass_sdk import StepUpRequiredError

try:
    invitation = await client.invite_member("new@example.com", "developer", token=access_token)
except StepUpRequiredError as e:
    if "email_code" in e.required_factors:
        await client.start_step_up_email(access_token)  # then ask the person for the code
    proof = await client.step_up(access_token, password=password)  # or email_code=, two_fa_code=
    invitation = await client.invite_member(
        "new@example.com", "developer", token=access_token, step_up_token=proof.step_up_token
    )
```

`step_up_requirements(token)` returns the factors without trying a call.

### Members, invitations and roles

These act in the caller's own organization, with a user access token or, for `list_members`,
`remove_member`, `invite_member`, `list_invitations`, `get_member_role` and `assign_role`, an API
key bound to a member (see [API keys that act as a member](#api-keys-that-act-as-a-member)).
Leave out `token` to send the configured API key.

#### `list_members(organization_id, *, token)`
**Returns**: `list[Member]`: `id`, `email`, `role` (`owner`, `admin`, `member` or another role
name), account `status`, `membership_status` (`active` or `suspended`), `home_organization`,
`first_name`, `last_name`. Needs `users:view`; another organization is `PermissionDeniedError`.

#### `invite_member(email, role="member", *, token, step_up_token=None)`
Invite someone with a role: one of `list_roles`, or `"member"` for a membership bound to no
role. Only an owner or an admin invites (`OwnerOrAdminRequiredError`), and only an owner invites
an owner or an admin (`OwnerRequiredError`). A duplicate or an existing member is
`ValidationError`. Not retried; a transport error raises `OutcomeUnknownError`.

**How the invitee gets the code.** InkPass emails the invitation itself, in the background, with
a link to `<accept_url>?token=<code>`. `accept_url` is your product's own accept page: the
`invitations.accept_url` in your InkPass client's settings, which only the platform control plane
sets (`PATCH /api/v1/internal/clients/{client_slug}`), on an origin InkPass lists in
`CORS_ORIGINS` or in your client's own `product_origins`, https in production, with no query or
fragment. A client without one gets the
InkPass-wide `{FRONTEND_URL}/invite/accept`. The code is never returned to the caller
(`Invitation` has no code field), so the invitee learns it only from that email. Your accept page
reads `token` from its URL and passes it to `validate_invitation` and `accept_invitation` with
your `client_slug`. Invitations expire after 7 days. `resend_invitation` sends a new code, and
the old one stops working.

**Returns**: `Invitation`: `id`, `email`, `role`, `status`, `invited_by_email`, `expires_at`,
`created_at`

Also: `list_invitations(*, token, status=None)`, `revoke_invitation(invitation_id, *, token)`,
`resend_invitation(invitation_id, *, token, step_up_token=None)`.

#### `validate_invitation(code, *, client_slug=None)` and `accept_invitation(code, password, *, two_fa_code=None, client_slug=None)`
Public calls, made with no token. `validate_invitation` returns an `InvitationCheck` (`valid`,
`email`, `role`, `organization_name`, `error`) so the accept page can show what the code is for.
`accept_invitation` creates the account with this password for a new email. For an existing
account, the password must be that account's own, plus its 2FA code when 2FA is on. It signs the
invitee in.

Pass `client_slug`, your InkPass client: both calls then use
`/api/v1/auth/clients/{client_slug}/invitations/check|accept`, and an invitation into another
product's organization answers exactly as an unknown code (`valid=False`,
`ResourceNotFoundError`). Without `client_slug` they use the unscoped routes, which see only the
invitations of a client with no accept page of its own; once your client has one, pass
`client_slug`. The account and the session belong to the invitation's client. An account with
the same email in another product is not used: the invitee gets a separate account in yours.

**Returns**: `InvitationAcceptance`: a `TokenResponse` (`access_token`, `refresh_token`,
`expires_in`) plus `user_id`, `email`, `organization_id`, `role`, `is_new_user`
**Raises**: `ResourceNotFoundError` (unknown code), `ValidationError` (expired, used, revoked,
weak or wrong password), `InkPassError` with status 409, `ServiceUnavailableError` with status 503
(busy, retry). Not retried; a transport error raises `OutcomeUnknownError`.

```python
check = await client.validate_invitation(code, client_slug="worthsend")
if check.valid:
    session = await client.accept_invitation(code, password, client_slug="worthsend")
    # session.access_token, session.refresh_token, session.organization_id, session.role
```

#### `list_roles(token)`, `get_member_role(user_id, *, token)`, `assign_role(user_id, role, *, token, step_up_token=None)`
`get_member_role` returns a `MemberRole` whose `role` (a `Role`: `role_name`, `display_name`,
`priority`, ...) is `None` for a plain member bound to no role. `assign_role` needs
`users:manage`. The caller must be able to grant what the role carries, and may only change the
role of someone who holds no more than they do (`PermissionDeniedError`). Granting owner or
admin, or changing an owner's or an admin's role, is an owner's decision (`OwnerRequiredError`).
The last owner is never demoted (`LastOwnerError`). An unknown role is `ValidationError`.
`"member"` makes them a plain member bound to no role: the returned `MemberRole.role` is then
`None`. The SDK sends it as is; an InkPass older than the release that accepts it answers
`ValidationError`.

#### `get_my_role(token)`
The caller's own role in their organization, as a `MemberRole`; it needs no permission, so a
plain member can read it (their `role` is `None`). Retried like the other reads. It takes a user
token: InkPass answers an API key with 401 (`AuthenticationError`). An API-key caller reads
`owner_role` from `validate_api_key` instead, the role of the member the key acts as.

### API keys that act as a member

`create_api_key(token, name, user_id=member_id)` issues a key that acts as that member (an owner
may name anyone; anyone else only themselves). `validate_api_key(key)` returns the member the key
acts as: `user_id`, `organization_id`, `owner_email`, `owner_status` and `owner_email_verified`.
These are `None` once the member has left. It also returns `owner_role` (that member's role in
the key's organization: `owner`, `admin`, `member` or a template role; `None` once they left),
`key_status` (`active`, `paused`, ...) and `last_used_at` (when the key was last used before
this request; a retried read may see the time of its own earlier attempt). All three are `None`
from an InkPass that does not send them yet. `get_api_key_usage(key_id, token)` returns an
`APIKeyUsage` with the key's `status` (`active`, `paused`, `expired`), `status_reason` and
`last_used_at`. `revoke_api_key` stops the key at once, because InkPass checks the key's status
on every request.

Such a key manages members as its member on seven routes: `list_members`, `list_invitations`
and `get_member_role` need `users:view`, `invite_member` `users:create`, `remove_member`
`users:delete`, and `assign_role` and `set_member_status` `users:manage` (InkPass 0.13.0 and
later for `set_member_status`). Suspending takes no grant ceiling; a restore is capped to the
key's scopes, and suspending or restoring an admin or an owner is an owner decision. The permission must be named among the key's
scopes: `*` does not stand in, and a scope the member no longer holds stops working at once.
Through a key the caller grants no more than the key's scopes and makes no owner decision
(`OwnerRequiredError`), even when the member is an owner; no step-up is asked. A key bound to no
member gets `MemberKeyRequiredError` (`member_key_required`, 403). Keys still cannot manage API
keys.

```python
client = InkPassClient(InkPassConfig(api_key=member_key))
members = await client.list_members(org_id)
await client.invite_member("new@example.com", "developer")
```

### Members creating their own API keys

An owner may let every member create their own API keys, not only those holding
`api_keys:create` (ADR-028). `set_api_key_policy(org_id, True, token=owner_token)` turns it on;
it is an owner decision (`OwnerRequiredError` for anyone else). `get_api_key_policy(org_id,
token=member_token)` reads it as an `APIKeyPolicy` for any member. While it is on, a member's
`create_api_key` issues a key bound to them and capped at what they hold; `never_expires` stays
an owner's. Whatever the policy, a member lists, reads the usage of and revokes the keys they
issued. Turning it off stops new keys only.

A Product that wants every organization it creates to start with the policy on sets its client's
default once, with the control-plane key: `update_client_settings(slug, {"api_keys":
{"members_create_own_keys": True}})`. Every organization of that client whose owners have not
chosen then follows it, including those created before; an owner's `set_api_key_policy` wins over
it either way. `members_create_own_keys` must be a bool or `None`, and `api_keys` takes no other
key (`ValidationError` otherwise).

```python
await control_plane.update_client_settings(
    "rulemark", {"api_keys": {"members_create_own_keys": True}}
)
await client.set_api_key_policy(org_id, True, token=owner_token)
key = await client.create_api_key(member_token, "ci", scopes=["files:read"])
```

## Response Models

All responses are Pydantic models with full type safety:

```python
from inkpass_sdk import (
    TokenResponse,
    UserResponse,
    RegistrationResponse,
    PermissionCheckResponse,
    APIKeyResponse,
)

# TokenResponse
tokens: TokenResponse
tokens.access_token: str
tokens.refresh_token: str
tokens.token_type: str
tokens.expires_in: int

# UserResponse
user: UserResponse
user.id: str
user.email: str
user.organization_id: str
user.status: str
user.two_fa_enabled: bool
```

## Exception Handling

```python
from inkpass_sdk import (
    InkPassError,              # Base exception
    AuthenticationError,        # 401 errors
    PermissionDeniedError,      # 403 errors
    ResourceNotFoundError,      # 404 errors
    ValidationError,            # 400 and 422 errors; status_code says which
    ServiceUnavailableError,    # 503 errors
    OutcomeUnknownError,        # no answer to a change that may have gone through
    StepUpRequiredError,        # 403: re-authenticate with step_up (see Step-up)
    OwnerOrAdminRequiredError,  # 403: only an owner or an admin invites
    OwnerRequiredError,         # 403: an owner's decision
)

try:
    user = await client.validate_token(token)
except AuthenticationError as e:
    print(f"Auth failed: {e.message}")
except ServiceUnavailableError as e:
    print(f"Service down: {e.message}")
except InkPassError as e:
    print(f"Error: {e.message} (status: {e.status_code})")
```

## Advanced Usage

### Custom Retry Configuration

Only calls that are safe to repeat are retried: the reads (`validate_token`,
`validate_api_key`, `check_permission`, the `list_*` and `get_*` calls but
`get_billing_portal_url`, `step_up_requirements`,
`validate_invitation`, `is_billing_configured`, and `FileClient`'s `download`,
`get_download_url`, `list_files` and `get_file`) and `set_organization_fallback_tier`, which
changes nothing when the tier is already set. They are retried only when InkPass cannot be
reached or sends no answer (`httpx.RequestError`); an answer, an error status such as 503
included, is never retried. After the last attempt they raise `ServiceUnavailableError`
(`check_permission` returns `False`, `is_billing_configured` returns `False`).

Everything that creates or changes state is sent once: `register`, `login`, `refresh`,
`logout`, `create_api_key`, `revoke_api_key`, invitations, roles, members, billing writes,
`step_up`, `get_billing_portal_url` (it opens a Stripe session), and `FileClient`'s `upload`,
`delete`, `duplicate` and `move`. A transport error raises `ServiceUnavailableError`, or
`OutcomeUnknownError` where the change may have been made.

```python
config = InkPassConfig(
    base_url="http://inkpass:8000",
    timeout=5.0,            # Each attempt
    max_retries=5,          # Up to 5 attempts in all; 0 or 1 sends a read once
    retry_min_wait=2,       # Waits 2, 4, 8, 16 seconds ...
    retry_max_wait=30,      # ... never longer than 30
)
```

### Service-to-Service Authentication

```python
# Use API key instead of user tokens
config = InkPassConfig(
    base_url="http://inkpass:8000",
    api_key="your-service-api-key"
)

client = InkPassClient(config)
# Client will automatically use API key for requests
```

### Internal Service Authentication

Internal InkPass routes use `X-Service-API-Key`. Configure those separately from ordinary
InkPass API keys:

```python
from datetime import datetime, timezone
from inkpass_sdk import (
    InkPassClient,
    InkPassConfig,
    OutcomeUnknownError,
    ServiceUnavailableError,
)

config = InkPassConfig(
    base_url="http://inkpass:8004",
    service_api_key="wendell-service-key",
)

# Organization and user ids are UUIDs, as a string or a uuid.UUID; anything else raises
# ValueError before any request.
org_id = "6f1c2d3e-4b5a-4c6d-8e7f-90a1b2c3d4e5"

async with InkPassClient(config) as client:
    subscription = await client.get_organization_subscription(org_id)

    updated = await client.set_organization_subscription_tier(
        organization_id=org_id,
        tier="open_beta_unlimited",
        status="active",
        ends_at=datetime(2026, 7, 3, tzinfo=timezone.utc),
        source="wendell_open_beta",
        metadata={"offer_code": "ob_abc123"},
    )

    # The tier a canceled, past-due or expired subscription lands on: one of the
    # organization's active product plans, free by design (price 0, or the template's free
    # plan). Free until it is changed. An organization holding the previous fallback as its
    # fallback moves to the new one; a grant of that tier stays.
    updated = await client.set_organization_fallback_tier(org_id, tier="starter")
    print(updated.fallback_tier)

    # Only the platform service removes a tier, even one another service alone granted; a
    # tier in use (the fallback, the one it holds, a Stripe-priced one) is refused.
    try:
        await client.remove_organization_tier(org_id, tier="pilot")
    except OutcomeUnknownError:
        ...  # No answer: it may be removed. A retry gets ResourceNotFoundError if it is.
    except ServiceUnavailableError:
        ...  # 503: the organization was busy, nothing was removed. Safe to retry.
```

An organization's tiers are the slugs of its own active product plans. Every organization
starts with `free`, `open_beta_unlimited`, `unlimited` and `enterprise`, and may add plans and
remove the ones no service set; a tier that is not one of them is refused with
`ValidationError`.

`ends_at` ends the tier when it passes (the effective tier becomes the fallback, `expired`),
unless the subscription's current state came from a verified Stripe event: Stripe's `ends_at`
is the end of the paid period of a subscription that renews.

#### `list_client_members(organization_id, *, membership_status="active", limit=50, cursor=None, service_identity_key=None)`
A product's backend reads the members of one of its client's organizations with a service
identity and no user session. The identity is a key (`inkpass_service_...`) that InkPass issues to
the product's client holding `organization_members:read`; the platform's control plane issues,
rotates and revokes it (below). Set it as `InkPassConfig(service_identity_key=...)`, or pass
`service_identity_key=` for one call.

InkPass reads the client from the identity, so it answers for that client's organizations only:
another client's organization and an unknown one get the same `ResourceNotFoundError`. A missing,
unknown, revoked or expired identity, or an inactive client, is `AuthenticationError`; an
identity without `organization_members:read` is `PermissionDeniedError`. A service API key does
not work here. More than 600 requests a minute with one identity is `RateLimitError`.

It returns a `ClientMemberPage` (`schema_version` `inkpass.members.v1`, `client_slug`,
`organization_id`, `members`, `next_cursor`) of `ClientMember` (`user_id`, `email`,
`first_name`, `last_name`, `role`, `membership_status`, `home_organization`, `account_status`),
in order of user ID. `membership_status` is `active`, `suspended` or `all`; `limit` 1 to 100.
Pass `next_cursor` as `cursor` for the next page; it is `None` on the last. A cursor this list did
not return is `ValidationError`.

```python
client = InkPassClient(InkPassConfig(base_url=INKPASS_URL, service_identity_key=identity_key))
cursor = None
while True:
    page = await client.list_client_members(org_id, cursor=cursor)
    for member in page.members:
        ...
    if page.next_cursor is None:
        break
    cursor = page.next_cursor
```

#### Den files: `client.den`
A product's backend keeps its users' files in Den with a service identity of its client holding
`den_object:read`, `den_object:write` and `den_object:delete` (ADR-030). Bytes go straight
between the browser (or a worker) and storage through presigned URLs; they never pass through
InkPass or this SDK. Every call takes an organization of the identity's client and
`service_identity_key=` for one call, or uses the config's.

| Call | Permission | Returns |
| --- | --- | --- |
| `den.create_object(org_id, *, content_type, size_bytes)` | write | `DenObjectCreated`: the pending object and, up to 64 MiB, `upload_request`, one presigned PUT |
| `den.sign_parts(org_id, object_id, part_numbers, *, expires_in=None)` | write | `DenSignedParts`: a PUT per part, for an object whose `upload.mode` is `multipart` |
| `den.complete_object(org_id, object_id, parts=None)` | write | `DenObject`, now `active`. `parts` maps each part number to the ETag its PUT returned; `None` for a single upload |
| `den.abort_object(org_id, object_id)` | write | `DenObject`, `aborted`, its reservation given back |
| `den.get_object(org_id, object_id)` | read | `DenObject` |
| `den.sign_download(org_id, object_id, *, filename=None, disposition="attachment", expires_in=None)` | read | `DenDownload`: a presigned GET and the `disposition` storage will send |
| `den.delete_object(org_id, object_id)` | delete | `None`; links already signed stop working |
| `den.get_usage(org_id)` | read | `DenUsage`: the organization's quota and what the client holds |

The objects belong to the client (`owner_service` `client:<client_id>`), so all its identities
share them. Each counts against the organization's quota: a full quota is `InkPassError` with
`status_code` 507 and `code` `quota_exceeded`. Links live at most 900 seconds. `inline` is
honored for images, PDF, `text/plain`, audio and video; anything else downloads as an
attachment. Each version of a document is its own object: keep names and versions in your
database.

Another client's organization is `ResourceNotFoundError` (`code` `organization_not_found`), and
an object that is not the client's in that organization is `ResourceNotFoundError` (`object_not_found`).
A missing or revoked identity is `AuthenticationError`, a missing permission
`PermissionDeniedError`, and more than the identity's Den calls a minute (6,000 by default)
`RateLimitError`. Ids that are not UUIDs and out-of-range values raise `ValueError` before any
request. Reads and signing are retried; `create_object`, `complete_object`, `abort_object` and
`delete_object` are sent once and raise `OutcomeUnknownError` when InkPass sends no answer.

```python
client = InkPassClient(InkPassConfig(base_url=INKPASS_URL, service_identity_key=identity_key))
created = await client.den.create_object(org_id, content_type="application/pdf", size_bytes=size)
# Hand created.upload_request (method, url, headers) to the browser, which PUTs the bytes.
document = await client.den.complete_object(org_id, created.object.object_id)
link = await client.den.sign_download(
    org_id, document.object_id, filename="deck.pdf", disposition="inline", expires_in=300
)
```

##### Page renders
Den renders a PDF object into page images (WebP, one per width) and page text, so a Product
shows a document page by page without sending the PDF (ADR-031). Pages are objects of the
client and count against the quota; deleting the PDF deletes its renders.

| Call | Permission | Returns |
| --- | --- | --- |
| `den.create_render(org_id, object_id, widths)` | write | `DenRender`, `queued`; the existing render for the same object and widths. One or two widths, 200 to 2000 px |
| `den.get_render(org_id, render_id)` | read | `DenRender`: `status`, and once `ready`, `page_count` and `pages` (size in points, `images`, `text`) |
| `den.sign_render_pages(org_id, render_id, pages, *, width=None, text=False, expires_in=None)` | read | `DenRenderLinks`: an inline GET per page, its image at `width` or its text |
| `den.delete_render(org_id, render_id)` | delete | `None`; the PDF stays |

Poll `get_render` until `ready` or `failed`; a failed render names its `failure_code`
(`unreadable`, `too_many_pages`, `quota_exceeded`, ...). Signing pages before the render is
ready is `InkPassError` with `status_code` 409 (`render_not_ready`); a PDF that is not
`application/pdf` is 422 (`source_not_renderable`). `create_render` is retried like a read,
since asking again answers the same render.

```python
render = await client.den.create_render(org_id, document.object_id, [800, 1600])
while render.status in ("queued", "rendering"):
    await asyncio.sleep(2)
    render = await client.den.get_render(org_id, render.render_id)
links = await client.den.sign_render_pages(org_id, render.render_id, [1, 2, 3], width=800)
```

#### Clients: `create_client`, `update_client_settings`, `list_clients`
Each product has its own InkPass client: its users, organizations and service identities
belong to it. The control plane creates and configures it with the same control-plane service
key as the service identity calls below.

- `create_client(name, slug, *, settings=None)` returns the new `AuthClient`. A slug already in
  use is `ValidationError`. Sent once; a transport error raises `OutcomeUnknownError`, after
  which `list_clients` tells whether it was created.
- `update_client_settings(client_slug, settings)` merges `settings` into the client's and
  returns it: a top-level key replaces the stored value, two dicts merge one level deep, and
  keys not named stay. An unknown slug is `ResourceNotFoundError`. Retried.
- `list_clients()` returns every client, oldest first. Retried.

A slug is letters, digits, `.`, `_` and `-`, starting with a letter or digit; anything else, or
settings that are not a dict, raises `ValueError` before any request. Settings InkPass refuses,
for example an `invitations.accept_url` it would not use, a `product_origins` entry that is not
an origin, or an `api_keys` value other than
`{"members_create_own_keys": bool | None}`, are `ValidationError`. `api_keys.members_create_own_keys`
is the default for the client's organizations whose owners have not chosen whether members create
their own API keys (see "Members creating their own API keys").

`product_origins` lists the sites the product is published on (bare `scheme://host[:port]`
origins, https in production, at most 20; a write replaces the list). An `invitations.accept_url`
may be on one of them or on an origin in InkPass's `CORS_ORIGINS`, and one call may set both. A
client's origins count for that client only, and do not change browser CORS:

```python
await control_plane.update_client_settings(
    "rulemark",
    {
        "product_origins": ["https://rulemark.example.com"],
        "invitations": {"accept_url": "https://rulemark.example.com/join"},
    },
)
```

```python
control_plane = InkPassClient(InkPassConfig(base_url=INKPASS_URL, service_api_key=factory_key))
if "rulemark" not in {client.slug for client in await control_plane.list_clients()}:
    await control_plane.create_client("Rulemark", "rulemark")
await control_plane.update_client_settings("rulemark", {"branding": {"name": "Rulemark"}})
```

#### Service identities: `issue_service_identity`, `rotate_service_identity`, `list_service_identities`, `revoke_service_identity`
The platform's control plane (for example a factory that publishes products) manages the
service identities of each product's client. These calls need a control-plane service key as
`InkPassConfig(service_api_key=...)`: a service InkPass names in `INTERNAL_CONTROL_PLANE_SERVICES`.
Another service key is `PermissionDeniedError`, an unknown one `AuthenticationError`. No user
token, API key or service identity reaches them; without a service key they raise `ValueError`
before any request.

- `issue_service_identity(client_slug, name, permissions, *, organization_slug=None)` creates
  one and returns an `IssuedServiceIdentity` whose `key` is shown this once: InkPass keeps only
  its hash. It is bound to `organization_slug`, an organization of the client, or by default to
  the client's `<client_slug>-services` organization. An existing identity of that name is
  `InkPassError` with status 409.
- `rotate_service_identity(client_slug, name, permissions, *, organization_slug=None)` gives an
  existing one a new key, returned once. The old key stops at once; `permissions` replaces the
  identity's set; a revoked identity is active again. A missing one is `ResourceNotFoundError`.
- `list_service_identities(*, client_slug=None, organization_slug=None)` returns
  `ServiceIdentity` objects, revoked ones included, with `key_prefix` and never the key.
- `revoke_service_identity(identity_id)` stops the key at once and returns the identity
  (`is_active` False, `revoked_at` set). Revoking it again changes nothing.

`name` is lowercase letters, digits and hyphens, starting with a letter, at most 63 characters.
A permission outside InkPass's allow-list (`organization_members:read`, `notifications:send`,
...) or a malformed name is `ValidationError`; an unknown client or organization is
`ResourceNotFoundError`. Issue and rotate are sent once; a transport error raises
`OutcomeUnknownError`, after which `rotate_service_identity` gets a key you hold. The list and
revoke are retried.

```python
control_plane = InkPassClient(InkPassConfig(base_url=INKPASS_URL, service_api_key=factory_key))
try:
    issued = await control_plane.issue_service_identity(
        "rulemark", "members-reader", ["organization_members:read"]
    )
except InkPassError as error:
    if error.status_code != 409:
        raise
    issued = await control_plane.rotate_service_identity(
        "rulemark", "members-reader", ["organization_members:read"]
    )
store_secret(issued.key)  # hand it to the product; it is never shown again
...
await control_plane.revoke_service_identity(issued.id)
```

Do not put service API keys or service identity keys in browser, CLI, or mobile clients.

### Your Own HTTP Client (Tests Without a Server)

`InkPassClient` and `FileClient` take a keyword-only `http_client`, an `httpx.AsyncClient` to
send every request with. In tests, give it an `httpx.MockTransport`:

```python
import httpx
from inkpass_sdk import InkPassClient

def handler(request: httpx.Request) -> httpx.Response:
    return httpx.Response(200, json={"user_id": "u", "organization_id": "o", "role": None})

http_client = httpx.AsyncClient(
    base_url="http://inkpass.test", transport=httpx.MockTransport(handler)
)
async with InkPassClient(http_client=http_client) as client:
    my_role = await client.get_my_role("jwt")
await http_client.aclose()  # yours to close
```

The client is used as is: give it the InkPass `base_url`, since the SDK sends relative paths,
and its own timeout and TLS settings apply instead of the config's. You own it: `close()` and
`async with` leave it open. Without `http_client`, the SDK creates its own from the config and
closes it, as before.

### Disable SSL Verification (Development Only)

```python
config = InkPassConfig(
    base_url="https://inkpass:8443",
    verify_ssl=False  # NOT recommended for production!
)
```

## File Management (Den)

The SDK includes a `FileClient` for managing files in InkPass Den storage. This is primarily used for service-to-service communication (e.g., Tentacle agents uploading/downloading files).

### FileClient Usage

Every file call names the InkPass client that owns the organization. Den rejects a call with
`403` (`PermissionDeniedError`) when the organization does not belong to that client, and gives
the same response whether or not the organization exists. `client_id` is a required keyword on
every `FileClient` method; passing `None` omits it, which only an InkPass that predates the check
accepts.

```python
from inkpass_sdk.files import FileClient
from uuid import UUID

# Initialize client with service API key
file_client = FileClient(
    base_url="http://inkpass:8002",
    service_api_key="sk_tentacle_xxx"
)

# Upload a file
with open("output.png", "rb") as f:
    result = await file_client.upload(
        client_id="client-uuid",
        org_id=UUID("org-uuid"),
        workflow_id="wf-123",
        agent_id="image-gen",
        file_data=f,
        filename="generated-image.png",
        content_type="image/png",
        folder_path="/agent-outputs",
        tags=["generated", "marketing"],
        is_public=True,  # CDN-accessible
    )
    print(f"Uploaded: {result['id']}")

# Download a file
data = await file_client.download(
    client_id="client-uuid",
    org_id=UUID("org-uuid"),
    file_id=UUID("file-uuid"),
)
content = data.read()

# Get a temporary download URL (signed)
url = await file_client.get_download_url(
    client_id="client-uuid",
    org_id=UUID("org-uuid"),
    file_id=UUID("file-uuid"),
    expires_in=3600,  # 1 hour
)

# List files
files = await file_client.list_files(
    client_id="client-uuid",
    org_id=UUID("org-uuid"),
    workflow_id="wf-123",
    folder_path="/agent-outputs",
    tags=["marketing"],
)

# Delete a file (must be created by this agent or be temporary)
await file_client.delete(
    client_id="client-uuid",
    org_id=UUID("org-uuid"),
    file_id=UUID("file-uuid"),
    agent_id="image-gen",
)
```

### Temporary Files

Agents can create temporary files that auto-expire:

```python
result = await file_client.upload(
    client_id=client_id,
    org_id=org_id,
    workflow_id="wf-123",
    agent_id="data-processor",
    file_data=temp_data,
    filename="temp-result.json",
    content_type="application/json",
    is_temporary=True,
    expires_in_hours=24,  # Auto-delete after 24 hours
)
```

### Public Files (CDN)

For marketing assets that need CDN delivery:

```python
result = await file_client.upload(
    client_id=client_id,
    org_id=org_id,
    workflow_id="wf-marketing",
    agent_id="content-gen",
    file_data=image_data,
    filename="hero-image.png",
    content_type="image/png",
    is_public=True,  # Enables CDN URL
    folder_path="/public/marketing",
)
# result['cdn_url'] will contain the CDN URL
```

## Testing

### Run Tests

```bash
# Install development dependencies
pip install -e ".[dev]"

# Run tests
pytest

# Run with coverage
pytest --cov=inkpass_sdk --cov-report=html

# Run specific test
pytest tests/test_client.py::test_login_success
```

### Mock Client for Testing

```python
from unittest.mock import AsyncMock, MagicMock, patch
from inkpass_sdk import InkPassClient, UserResponse

async def test_my_function():
    client = InkPassClient()

    # Mock response
    mock_user = UserResponse(
        id="user-123",
        email="test@example.com",
        organization_id="org-123",
        status="active",
        two_fa_enabled=False,
    )

    with patch.object(client, 'validate_token', return_value=mock_user):
        user = await client.validate_token("test-token")
        assert user.email == "test@example.com"
```

## Examples

See the [`examples/`](./examples/) directory for complete examples:

- [`basic_usage.py`](./examples/basic_usage.py) - Basic SDK operations
- [`fastapi_integration.py`](./examples/fastapi_integration.py) - Complete FastAPI integration

Run examples:

```bash
# Basic usage
python examples/basic_usage.py

# FastAPI integration
uvicorn examples.fastapi_integration:app --reload
```

## Best Practices

### 1. Use Context Manager

```python
# ✅ Good - Automatically closes
async with InkPassClient(config) as client:
    user = await client.validate_token(token)

# ❌ Bad - Manual cleanup required
client = InkPassClient(config)
user = await client.validate_token(token)
await client.close()  # Easy to forget!
```

### 2. Reuse Client Instances

```python
# ✅ Good - Reuse connection pool
inkpass_client = InkPassClient(config)

@app.get("/endpoint1")
async def endpoint1():
    return await inkpass_client.validate_token(token)

@app.get("/endpoint2")
async def endpoint2():
    return await inkpass_client.check_permission(token, "resource", "action")

# ❌ Bad - Creates new connection each time
@app.get("/endpoint")
async def endpoint():
    client = InkPassClient(config)  # Don't do this!
    return await client.validate_token(token)
```

### 3. Handle Errors Gracefully

```python
# ✅ Good - Handle specific errors
try:
    user = await client.validate_token(token)
except AuthenticationError:
    return {"error": "Please login again"}
except ServiceUnavailableError:
    return {"error": "Service temporarily unavailable"}
except InkPassError as e:
    logger.error(f"inkPass error: {e}")
    return {"error": "Authentication service error"}

# ❌ Bad - Catch-all
try:
    user = await client.validate_token(token)
except Exception:
    pass  # What went wrong?
```

### 4. Trust Fail-Safe Permission Checks

```python
# Permission checks default to False on errors
# This is intentional for security!

can_delete = await client.check_permission(token, "data", "delete")
if can_delete:
    # Safe to proceed - we know they have permission
    delete_data()
else:
    # Deny access - could be no permission OR service error
    # Either way, safer to deny
    raise PermissionDenied()
```

## Troubleshooting

### Connection Errors

```python
# Check service is running
curl http://inkpass:8000/health

# Verify base_url is correct
config = InkPassConfig(base_url="http://inkpass:8000")  # No trailing slash!
```

### Token Validation Fails

```python
# Check token hasn't expired
tokens = await client.login(email, password)
print(f"Token expires in: {tokens.expires_in} seconds")

# Access tokens last 30 minutes: refresh before expires_in (refresh tokens rotate)
tokens = await client.refresh(tokens.refresh_token)
```

### Permission Checks Always Return False

```python
# Verify permission exists in inkPass
# Verify user has permission assigned
# Check resource and action names match exactly
```

## Development

### Setup Development Environment

```bash
# Create virtual environment
python -m venv venv
source venv/bin/activate  # or `venv\Scripts\activate` on Windows

# Install in development mode
pip install -e ".[dev]"

# Run tests
pytest

# Run linters
black inkpass_sdk/
ruff check inkpass_sdk/
mypy inkpass_sdk/
```

### Contributing

1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Add tests
5. Run tests and linters
6. Submit a pull request

## License

MIT License - see repository root `LICENSE`.

## Support

See https://fluxtopus.com.
