Metadata-Version: 2.4
Name: airsoft-defense-connector
Version: 0.1.0
Summary: Python SDK for the Airsoft Defence API
Author: Airsoft Defence Ltd.
License-Expression: MIT
Project-URL: Source, https://github.com/Airsoft-Defence/python3-connector
Project-URL: Documentation, https://airsoft-defence.co.uk/api
Keywords: airsoft,airsoft-defence,api,sdk,oauth2
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Dynamic: license-file

# Airsoft Defense Connector for Python

A synchronous Python SDK for the [Airsoft Defence API](https://airsoft-defence.co.uk/api). It supports Python 3.11+ and uses the standard library for HTTP and OAuth. No third-party runtime dependencies are required.

## Install and check connectivity

Use Python 3.11 or later. In your application's virtual environment, run:

```sh
python -m pip install airsoft-defense-connector
```

Import the SDK as `airsoft_defense_connector`. This example checks the demo API and prints `{'message': 'pong'}` without credentials.

```python
from airsoft_defense_connector import Client

sdk = Client(environment="demo")
print(sdk.ping())
```

## Choose production or demo

The default API is `https://airsoft-defence.co.uk/api`. Set `Client(environment="demo")` to use `https://demo.airsoft-defence.co.uk/api`. Use credentials and tokens from the selected site.

You can also set `AIRSOFT_DEFENCE_ENV` or create `airsoft_defence.toml` in your application's working directory:

```toml
# Use "demo" for testing or "production" for the live API.
environment = "demo"
```

The client checks these settings in order:

1. An explicit `base_url`.
2. The constructor's `environment` argument.
3. The `AIRSOFT_DEFENCE_ENV` environment variable.
4. The `environment` setting in the working directory's `airsoft_defence.toml`.
5. The production default.


## Choose an authentication flow

| Goal | Use | Requirements |
| --- | --- | --- |
| Call the API as a server integration | Client credentials | A registered OAuth client ID, secret, and scopes |
| Connect a specific user | Authorization code with PKCE | Client ID and secret, exact callback URL, browser consent, and a server-side session |
| Register a client during setup | Authenticated client registration | An eligible account's API login token |
| Connect a new retailer installation | Hosted store connection | A stable installation UUID, HTTPS callback, and access to an approved store |
| Sign a first-party app user in directly | Sanctum | The user's account and their two-factor code if required |
| Use a token you already have | Bearer authentication | Pass the OAuth access token or API login token to `Client(token)` |

Keep secrets and tokens on the server. A user signs in to Airsoft Defence in their browser for the consent flow.

## Run the CLI examples

The examples are in the source repository and the PyPI source archive. From a checkout, install the SDK with `python -m pip install -e .`, then set the credentials for an OAuth client that grants the scopes needed below. The commands use PowerShell.

```powershell
$env:AIRSOFT_DEFENCE_CLIENT_ID = '<your client ID>'
$env:AIRSOFT_DEFENCE_CLIENT_SECRET = '<your client secret>'
python examples/oauth.py
python examples/list_stores.py
python examples/player_defence_status.py 123
```

| Script | Purpose | Default scope |
| --- | --- | --- |
| `examples/oauth.py` | Confirms OAuth issued an access token without printing it. | `store:list` |
| `examples/list_stores.py` | Prints the API's store directory as JSON. | `store:list` |
| `examples/player_defence_status.py` | Prints the player record ID as a string and the API's boolean `valid` value. | `user:limited` |
| `examples/authorization_code.py` | Supplies helper functions for your web application's OAuth routes. | Supplied by your app |
| `examples/sanctum.py` | Shows direct user sign-in with two-factor verification. | Uses the signed-in account's permissions |

Set `AIRSOFT_DEFENCE_SCOPE` if the client uses another authorised scope, such as `user:restricted` when checking its own player record. Set `AIRSOFT_DEFENCE_API_BASE_URL` for a test environment. On a POSIX shell use `export` for these variables. The scripts return exit code 1 for an integration error and the player script returns 2 for invalid arguments.

## Sign in a user with Sanctum

Use Sanctum for first-party mobile or web sign-in when the user needs an API token for their own account. No OAuth client ID or secret is needed.

```python
result = sdk.sanctum_login(email, password)

if result["status"] == "two_factor_required":
    # Keep temp_token in memory while prompting for the user's code.
    result = sdk.sanctum_verify_two_factor(result["temp_token"], authenticator_code)
    # For a recovery code, use sanctum_recover_two_factor(temp_token, recovery_code).

session = result["client"].session_check()
```

A successful result contains `token`, `user` when available, and the authenticated `client`. Reattach a saved final token with `sdk.with_token(saved_token)`. Store that token securely and leave authenticator codes as strings so leading zeroes survive.

Run the Sanctum CLI example with `python examples/sanctum.py`. Set `AIRSOFT_DEFENCE_EMAIL` and `AIRSOFT_DEFENCE_PASSWORD` in a trusted test environment. For a 2FA account, also set either `AIRSOFT_DEFENCE_TOTP` (a current code) or `AIRSOFT_DEFENCE_RECOVERY_CODE` (an unused code).

A temporary challenge token is single-use on success and expires if the user waits too long. Never attach it as a bearer token. If verification returns 422, prompt for another code using the current challenge. For 401 during verification, restart sign-in. On 429, wait and use the API's Retry-After value when available. A 423 indicates an account hold.

The session check reports server-side activity information, including `sanctum_token_refreshed` and `inactive_expiry_at` when available. It does not return a new bearer token or an OAuth refresh token. If your saved bearer token is rejected, ask the user to sign in again.

## Call the API using client credentials

```python
import os

from airsoft_defense_connector import Client

sdk = Client()
tokens = sdk.client_credentials(
    os.environ["AIRSOFT_DEFENCE_CLIENT_ID"],
    os.environ["AIRSOFT_DEFENCE_CLIENT_SECRET"],
    "store:list",
)
api = sdk.with_token(tokens["access_token"])
stores = api.list_stores()
```

Use the returned `expires_in` when scheduling renewal. Repeat `client_credentials()` when you need a new token. `with_token()` creates a new client and keeps the current base URL and timeout.

## Register an OAuth client in your application

Use the API login token for the account that will own the client. For trusted setup, `login(email, password)` returns a token or a `requires_2fa` response with a temporary token. Pass that temporary token to `verify_two_factor()` or `recover_two_factor()` to finish API sign-in.

```python
callback_url = "https://app.example.com/airsoft/callback"
registration = sdk.with_token(owner_login_token).register_oauth_client(
    "Example integration",
    callback_url,
)
client_id = registration["data"]["client_id"]
client_secret = registration["data"]["client_secret"]
scopes = registration["data"]["scopes"]
```

Register once per installation and store the secret server-side. Use the registered callback URL verbatim in the authorization request and token exchange.

## Connect a user with browser consent

Use the `examples/authorization_code.py` in your web application.

1. In your Connect handler, call `start_connection(sdk, settings)`, store its attempt in the current user's server-side session, and redirect the browser to the returned URL.
2. In the callback, fetch and remove the attempt from the session in one operation. Pass the attempt and the callback query parameters to `finish_connection(sdk, settings, attempt, query)`. It checks state and expiry, then exchanges the code with the original PKCE verifier.
3. Store the access token, expiry, and any refresh token against this user in server-side storage. Attach the access token to API calls with `sdk.with_token()`.

Use a fresh state and PKCE verifier for each attempt. The SDK builds the S256 challenge in `authorization_url()`. A concurrent refresh can invalidate another worker's token. Serialise refreshes per connection and persist any replacement refresh token before allowing another refresh.

```python
tokens = sdk.refresh_oauth_token(client_id, client_secret, stored_refresh_token)
api = sdk.with_token(tokens["access_token"])
```

If the server rejects a revoked or expired refresh token, send the user through consent again.

## Connect a new retailer installation

Use the hosted store connection when the integration has no existing OAuth client. The retailer signs in on Airsoft Defence, completes any two-factor challenge, and selects an approved store.

In your server-side connect handler, use a stable installation UUID and a public HTTPS callback. Generate a fresh PKCE verifier for each attempt.

```python
from base64 import urlsafe_b64encode
from hashlib import sha256
from secrets import token_hex

code_verifier = token_hex(32)
digest = sha256(code_verifier.encode("ascii")).digest()
code_challenge = urlsafe_b64encode(digest).rstrip(b"=").decode("ascii")
attempt = sdk.start_store_connection(installation_id, redirect_uri, code_challenge)
```

Save the returned `attempt_id`, `expires_at`, and verifier against the installation and the administrator who started setup. Confirm that `approval_url` uses the Airsoft Defence host for the selected environment, then redirect the retailer there.

The callback receives `attempt_id` and `approval_proof` as POST fields. Match them to the pending attempt, check expiry, and require the initiating administrator's authenticated session before redeeming. A cross-site POST can arrive without the session cookie. If needed, hold the proof briefly on the server and redirect the browser to resume setup in that session. Prevent duplicate redemption.

```python
connection = sdk.redeem_store_connection(attempt_id, saved_verifier, approval_proof)
tokens = sdk.exchange_authorization_code(
    connection["client_id"],
    connection["client_secret"],
    connection["redirect_uri"],
    connection["authorization_code"],
    saved_verifier,
)
```

Keep the selected store, OAuth credentials, and token set together on the server. Replace the stored credentials and tokens on reconnect, and use the OAuth refresh flow above to renew access.


## API methods and results

Pass the printed hexadecimal member ID as a string to `api.player_status_by_member_id("00ab12cd34ef5")`. The helper resolves the member ID before checking defence status. An empty search returns `None`. This flow requires permission to search the player list.

The source repository and source archive include `API_ENDPOINTS.md`, which maps all 87 documented routes to SDK methods. Use `api.search_players({"member_id": member_id})` to look up a membership reference and `api.player_status(player_id)` to check the returned record ID. Photo methods accept a local path as a string or `Path`. Record IDs can be UUIDs or positive numeric IDs on compatible routes.

| Area | Methods |
| --- | --- |
| Connection and account | `ping`, `session_check`, `current_user`, `user_details` |
| Sites and stores | `list_sites`, `get_site`, `list_stores`, `get_store` |
| Games and attendance | `list_games`, `get_game`, `check_in_player`, `self_check_in` |
| Player status | `player_status` |
| Custom JSON requests | `request(method, path, query=..., json=...)` |

```python
stores = api.list_stores({"search": "Example"})
games = api.list_games(page=2, per_page=25)
status = api.player_status(123)
versions = api.legal_versions()
```

Use an API-relative path beginning with `/` without the `/api` prefix. Pass query parameters separately. The SDK returns decoded dictionaries or lists, or `None` for an empty response. Filters and pagination follow the API documentation.

## Handle errors and run tests

`ApiError` exposes `status_code`, any JSON `response`, and `retry_after`. Check credentials on 401 and scope, role, or record access on 403. A 409 on attendance may mean the check-in already exists. Use the response details on 422 and the Retry-After header on 429. `TransportError` covers network failures, timeouts, and invalid successful responses. `ValueError` covers invalid settings or request arguments.

The default API base URL is `https://airsoft-defence.co.uk/api`. Set `Client(base_url="http://127.0.0.1:8080/api", timeout=10)` for local fixtures. Timeout is in seconds and applies to blocking socket operations. HTTPS is required for remote endpoints. The SDK prevents redirects and sends each request once.

From a checkout, install the SDK and run `python -m unittest discover -s tests`. The tests use mocked HTTP responses. Live authenticated verification needs an authorised OAuth client.

## Licence

Copyright © 2026 Airsoft Defence Ltd. The MIT License permits commercial use, modification, and redistribution, including in proprietary mobile apps and e-commerce integrations. Include the copyright and licence notices whenever you distribute the SDK or substantial portions of it. See the `LICENSE` file in the distribution.
