Metadata-Version: 2.4
Name: signedapproval
Version: 0.1.1
Summary: Official Python SDK for SignedApproval, Clevername's human-approval service — request approvals and verify Ed25519-signed receipts
Project-URL: Homepage, https://signedapproval.net
Project-URL: Repository, https://github.com/AlexFloyd13/signedapproval
Author: Floyd Media LLC
License: MIT
Keywords: approval,ed25519,human-in-the-loop,passkey,signedapproval
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Requires-Python: >=3.9
Provides-Extra: verify
Requires-Dist: cryptography>=41.0; extra == 'verify'
Description-Content-Type: text/markdown

# signedapproval

Official Python SDK for [SignedApproval](https://signedapproval.net), the human-approval service behind [Clevername](https://clevername.net) -- request approvals from any app or agent and verify the Ed25519-signed receipts.

## Install

```bash
python3 -m pip install 'signedapproval[verify]==0.1.1'
```

Requires Python 3.9+. The base API client uses only the standard library; local receipt verification uses the existing `cryptography` extra.

The offline verification examples require 0.1.1. Check that this version is
published before using the registry command; 0.1.0 has only server verification.

## Quick start

```python
from signedapproval import SignedApproval
import hashlib
import json
import os

sa = SignedApproval("sa_live_...")
def sha256(text):
    return hashlib.sha256(text.encode("utf-8")).hexdigest()

# Configure independently of the receipt/key-discovery response.
pinned_keys = json.loads(os.environ["SA_PINNED_PUBLIC_KEYS"])
expected_approver = sha256(os.environ["SA_APPROVER_USER_ID"])
commit = "abc123"  # Retain the exact inputs your application intends to execute.
action = f"Deploy commit {commit} to production"

# 1. Request approval -- returns immediately
req = sa.request_approval(action=action, require_passkey=True)

# 2. Wait for the human to decide (polls every 5s, times out after 1h)
result = sa.wait_for_decision(req["request_id"])

if not result.get("decision"):
    raise RuntimeError("No signed decision")
# 3. Verify locally and compare against the inputs retained above.
proof = sa.verify_receipt(
    result["decision"], pinned_public_keys=pinned_keys,
    expected_request_id=req["request_id"], expected_action_hash=sha256(action),
    expected_approver=expected_approver, expected_method="passkey",
)
if not proof["valid"] or proof["decision"] != "approved" or proof["sandbox"] is not False:
    raise RuntimeError(f"Approval refused: {proof['failure_reason'] or proof['decision']}")
# Execute only the exact commit/action checked above.
```

Receipt v1 hashes the exact UTF-8 **action text**, not `context` or other structured arguments. Include every execution-critical input in that text and retain it locally. `expected_approver` is the full SHA-256 hex digest of the intended approver's user ID, not a truncated display hint. Provision signing public keys through a trusted channel; fetching them from the same service as the receipt does not provide an independent trust anchor.

## API reference

### `SignedApproval(api_key, base_url="https://signedapproval.net")`

| Parameter | Type | Description |
|-----------|------|-------------|
| `api_key` | `str` | `sa_live_` or sandbox `sa_test_`. A test key does not enable sandbox receipt acceptance. |
| `base_url` | `str` | Override the base URL. |

Raises `ValueError` if the API key format is invalid.

### `request_approval(**kwargs) -> dict`

Create an approval request. The approver receives a push notification.

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `action` | `str` | *required* | Human-readable description (max 280 chars) |
| `context` | `dict` | `None` | Structured metadata shown to the approver |
| `callback_url` | `str` | `None` | Webhook URL called with the signed decision |
| `require_passkey` | `bool` | `False` | Require FIDO2 hardware passkey |
| `require_totp` | `bool` | `False` | Require TOTP authenticator |
| `ttl_seconds` | `int` | `3600` | Time-to-live (60--86400 seconds) |
| `requires_individual_decision` | `bool` | `False` | Marks the request as high impact — the approver sees a badge (still included in "approve all"). Use for irreversible / high-blast-radius actions. |

Returns:

```python
{
    "request_id": "550e8400-...",   # UUID
    "status": "pending",
    "expires_at": "2026-01-01T13:00:00Z"
}
```

### `get_status(request_id) -> dict`

Poll the status of an approval request.

When the status is `"approved"` or `"rejected"`, pass the `"decision"` dict (signature, public key ID and exact canonical payload) to `verify_receipt`.

### `wait_for_decision(request_id, timeout=3600, poll_interval=5.0) -> dict`

Blocks until the request is no longer `"pending"`.

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `request_id` | `str` | *required* | The request UUID |
| `timeout` | `float` | `3600` | Timeout in seconds |
| `poll_interval` | `float` | `5.0` | Poll interval in seconds |

Raises `SignedApprovalError` with `status_code=408` on timeout, `status_code=410` if the request expires.

### `verify_receipt(receipt, pinned_public_keys=None, check_expiry=True, *, ...) -> OfflineVerifyResult`

Verifies Ed25519 over the exact signed bytes locally, then validates the v1 schema, sandbox policy, expiry and supplied bindings. Normal v1 receipts without `sandbox` remain accepted and return `sandbox: False`; delegated methods and optional `dlg` remain supported. A signed rejection can be `valid: True`; execution also requires `decision == "approved"`. The original positional pin/expiry arguments remain supported; new options are keyword-only.

| Option | Default | Description |
|--------|---------|-------------|
| `pinned_public_keys` | Key discovery | `{key_id: base64url-SPKI-DER}` trust anchors; unknown IDs fail without networking, including with an empty dict. |
| `check_expiry` | `True` | Reject `exp <= now`; use `False` only for historical inspection. Schema validation always applies. |
| `allow_sandbox` | `False` | Test-only explicit `True` permits signed `sandbox: true` or `method: "sandbox"`. Never enable for production execution. |
| `expected_request_id` | `None` | Exact expected signed request ID. |
| `expected_action_hash` | `None` | Full lowercase SHA-256 hex of the exact action text. |
| `expected_approver` | `None` | Full lowercase SHA-256 hex of the intended approver's user ID. |
| `expected_method` | `None` | Exact verification method, e.g. `passkey`; composite/delegated methods must match exactly. |

Expected values must come from trusted application state, not from the receipt being verified. Omitted expected options skip those comparisons; use all four for authorization. Neither `sa_test_` nor a valid signature implicitly allows sandbox execution. Even with sandbox opt-in, expiry and expected bindings are enforced.

Returns:

```python
{
    "valid": True, "signature_verified": True,
    "public_key_id": "fixture-key", "decision": "approved",
    "request_id": "...", "action_hash": "<full SHA-256 hex>",
    "approver": "<full SHA-256 hex>", "method": "passkey",
    "sandbox": False,  # None until signature and schema verification succeed
    "expires_at": 1793221200,  # Unix seconds
    "failure_reason": None
}
```

`SignedReceipt` and `OfflineVerifyResult` are exported `TypedDict` types. Malformed signed envelopes fail with `payload_invalid` (or `payload_unparseable` for invalid JSON). Required v1 fields include version `1`, nonempty request/decision IDs and method, full action/approver hashes, a 32-character hex nonce, and safe integer timestamps with `exp > ts`. Optional `dlg` is a 16-character hex digest and `sandbox` must be a boolean; unknown fields fail. Missing or malformed expiry never bypasses checks. Other failures include `sandbox_not_allowed`, `expired`, `unpinned_key`, `signature_invalid`, and `request_id_mismatch` / `action_hash_mismatch` / `approver_mismatch` / `method_mismatch`. A verified signature alone does not imply `valid: True`.

### `verify(decision_id) -> dict`

Asks the public server endpoint for its verification result. This convenience method trusts the server response and does not apply `verify_receipt`'s local policy or expected bindings. Use `verify_receipt` for execution decisions.

## Error handling

All API errors raise `SignedApprovalError`:

```python
from signedapproval import SignedApproval, SignedApprovalError

sa = SignedApproval("sa_live_...")

try:
    result = sa.wait_for_decision(request_id)
except SignedApprovalError as e:
    print(e)              # "Request xyz has expired"
    print(e.status_code)  # 410
```

| Status code | Meaning |
|-------------|---------|
| 400 | Bad request (invalid params) |
| 401 | Invalid or missing API key |
| 404 | Request not found |
| 408 | `wait_for_decision` timed out |
| 410 | Request expired |
| 429 | Rate limited |

## Webhook verification

If you use `callback_url`, verify the HMAC signature on incoming webhooks:

```python
import hashlib
import hmac

def verify_webhook(raw_body: bytes, signature: str, secret: str) -> bool:
    expected = hmac.new(secret.encode(), raw_body, hashlib.sha256).hexdigest()
    return hmac.compare_digest(signature, expected)

# In your handler:
sig = request.headers["X-SignedApproval-Signature"]
if not verify_webhook(request.data, sig, os.environ["WEBHOOK_SECRET"]):
    abort(401)
```

After authenticating the webhook, apply `verify_receipt` to its `signed_receipt` with the expected inputs retained by your application. Webhook authentication alone does not establish approval for a particular action.

## Local regression tests

From the repository root with the existing `cryptography` verification extra installed:

```bash
PYTHONPATH=sdk/python python3 -m unittest discover -s sdk/python/tests -v
```

The tests verify generated Ed25519 receipts through the actual client with networking disabled, covering sandbox rejection/opt-in, signed-payload schema, tampering, expiry, pinned keys and every expected binding.

The native TLS regression uses the same existing Python verification dependency to generate ephemeral certificates and requires macOS with Swift:

```bash
node --test tests/ios-trust.test.mjs
```

It compiles the actual network service in release and DEBUG modes. Apple's Security framework checks wrong hostname, expired and untrusted certificates, valid trust with the wrong pin, and valid trust with a matching pin. Debug and unpinned hosts defer to platform trust. No certificates are installed in the keychain and certificate fetching is disabled. Other operating systems explicitly skip the native test; CI should run it on macOS. Set `PYTHON` to select the fixture generator's interpreter if needed.

## License

MIT -- Floyd Media LLC
