Metadata-Version: 2.4
Name: preflight-sdk
Version: 1.0.0
Summary: Thin fail-closed client for the Preflight pre-dial API. Standard library only.
License-Expression: MIT
Project-URL: Homepage, https://www.preflightapi.com/docs/
Project-URL: Documentation, https://www.preflightapi.com/docs/
Project-URL: Support, https://www.preflightapi.com/support.html
Project-URL: Source, https://github.com/palfi-andras/preflight
Keywords: preflight,tcpa,dnc,opt-out,consent,voice,sms
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Topic :: Communications :: Telephony
Classifier: Typing :: Typed
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Dynamic: license-file

# Preflight Python SDK

A thin client for the Preflight pre-dial API. Standard library only (Python 3.9+), no dependencies. Typed (`py.typed`).

```sh
pip install preflight-sdk
```

Preflight applies encoded rules and keeps evidence. This SDK does not make anyone compliant and does not replace
counsel.

```python
from preflight_sdk import Preflight

pf = Preflight("https://api.preflightapi.com", os.environ["PREFLIGHT_KEY"])

d = pf.check({"to": "(702) 555-0142", "channel": "voice", "purpose": "marketing", "method": "ai_voice"})
if d["decision"] == "allow":
    place_call()                                  # d["obligations"] belong in your opening script
elif d["decision"] == "defer":
    reschedule(d["next_allowed_at"])
else:
    drop_lead(d["reasons"])                       # includes "preflight_unavailable"

pf.record_opt_out({"phone": "+12065550142", "channel": "voice", "source": "in_call", "raw": "stop calling me"})
pf.record_consent({"phone": "+17025550142", "kind": "express_written", "source": "https://acme.example/quote", "wording": "..."})
job = pf.batch(items)                              # polls until done; job["results"] is in item order
pf.report_outcome(check_id, "placed", "CA123")           # after the call or text ends: placed | not_placed | failed
ev = pf.get_evidence("+17025550142")
```

Account and data calls, each one request to the endpoint of the same name in the [API reference](https://www.preflightapi.com/docs/api.html):

```python
pf.revoke_consent(consent_id, "asked to stop")
pf.get_consent_capture(capture_id)                     # consent widget certificate
pf.claim_consent_capture(capture_id, "+17025550142")   # 409 unless it is the capture's phone
lst = pf.create_list({"kind": "litigator", "name": "Vendor feed"})
pf.import_list_entries(lst["id"], file_text, options={"mode": "replace", "edition_date": "2026-10-01"}, timeout=120)
pf.list_lists()
pf.get_check_evidence(check_id)
r = pf.get_check_evidence_pdf(check_id)                # {"pdf": bytes, "bundle_sha256": ...}
pf.get_rule_changes("2026-10-14.3")                    # or a date, or None for all
pf.get_rule_impact(limit=1000)                         # follow next_cursor with cursor=
hook = pf.create_webhook("https://acme.example/preflight", ["opt_out.created"])  # secret shown once
pf.list_webhooks()
pf.delete_webhook(hook["id"])
```

## Verifying webhooks

```python
from preflight_sdk import verify_webhook

# raw body exactly as received: request.get_data() (Flask), await request.body() (Starlette), never a parsed dict
if not verify_webhook(request.get_data(), request.headers.get("preflight-signature"), os.environ["PREFLIGHT_WEBHOOK_SECRET"]):
    abort(400)
```

Returns `True` only when a `v1` value in `preflight-signature` is the HMAC-SHA256 of `<t>.<raw body>` under the
endpoint secret (the whole `whsec_...` string from `create_webhook`) and `t` is within `tolerance` seconds (default
300) of now in either direction. Anything else (missing or malformed header, non-numeric, stale or future `t`, wrong
signature) returns `False`; it never raises for bad input from the network. It raises `TypeError` for programming
errors: a body that is not bytes or str (for example a parsed dict), an empty secret, a negative tolerance. The
compare is constant time (`hmac.compare_digest`), and any matching `v1` is accepted (for secret rotation).
`verify_webhook(raw_body, header, secret, tolerance=300, now=None)`; `now` is Unix seconds, for tests.
Receiver guide: [Webhooks guide](https://www.preflightapi.com/docs/).

## Fail-closed behaviour

- `check()` defaults to a **300 ms** timeout per attempt. On a timeout, a network error, a 429, a 5xx (after one
  quick retry) or any 4xx it **returns** `{"decision": "block", "reasons": [{"code": "preflight_unavailable", ...}]}` instead of
  raising. Treat it like any other `block`: do not dial or text. A 4xx also carries its HTTP `status` in the reason.
- A timeout can leave a check the server already recorded as an allowed attempt that you never dialed; it keeps
  counting toward the frequency and volume caps. The block's reason carries the `idempotency_key` the check was sent
  under. Call `pf.release_unplaced(req, d)` (same request, the block decision) within 5 minutes: it replays the key and,
  if the stored check was an allow, reports `not_placed`. Over-counting is the safe direction, so skipping this only
  costs reachable leads. Never use it for a call you placed.
- There is no fail-open option. The only alternative is `throw_on_error=True` (on the client or per call), which
  raises `PreflightError` (with `status`, `code`, `body`, `retry_after`) so you can handle the failure yourself. Even then, no
  answer means do not dial.
- Retries: a network error, timeout, 429 or 5xx is retried; any other status is not. `check()` gets one quick retry
  (`check_max_retries`, default 1) and never sleeps longer than its timeout, so a `Retry-After` longer than that ends
  it at once with the block decision: worst case about two timeouts. Every other call gets `max_retries` (default 2)
  with jittered exponential backoff (`retry_base_delay`, default 0.2 s) or the server's `Retry-After` when it sends
  one, up to `max_retry_delay` (default 10 s); a longer `Retry-After` raises `RateLimitError` (or `ServerError` for
  a 503) with `retry_after` so you can schedule the retry.
- A retry never records a write twice: every attempt of a POST sends the **same** `Idempotency-Key`, and the server
  replays a key it has already answered instead of running the request again. The key is a UUID generated
  per call; when you retry a failed `record_opt_out` (or any write) yourself, pass `idempotency_key=` (your inbound
  message id, or `new_idempotency_key()` kept for the job) so your retries are replays too. The server keeps keys
  for 24 hours: a retry later than that runs again (for an opt-out, a second opt-out event: it still blocks, but the
  audit trail shows it twice).
- Every method other than `check()` always raises `PreflightError` on failure (default timeout 10 s): swallowing a
  failed opt-out or revocation would be unsafe, so retry it until it succeeds.
- `import_list_entries` and `create_list` retry like any write; a replayed import returns the first import's counts
  and does not apply the file again.
- `create_webhook` retries like any write; a replay returns the same signing secret, so a retry never makes a second
  endpoint.
- `batch()` is screening only (items must not set `commit`). It raises if the job fails or polling exceeds
  `max_wait`; an item the server could not evaluate comes back as `{"error": {...}}`: treat it as do-not-dial.

The per-attempt timeout is a total deadline (not per socket read), covering an error response's body too, so a server that drips bytes cannot outlast it. The SDK never follows redirects (a 30x fails closed without a retry and the API key is never sent elsewhere), and `check()` rejects a response whose `reasons` is not a list.

## Errors

Every failure is a `PreflightError`; the subclass says why: `InvalidRequestError` (400, 422), `AuthenticationError`
(401), `PermissionDeniedError` (403), `NotFoundError` (404), `ConflictError` (409), `RateLimitError` (429),
`ServerError` (5xx), `NetworkError` (no response) and `RequestTimeoutError`. Other statuses (a refused redirect, 413,
421) are a plain `PreflightError`.

```python
from preflight_sdk import AuthenticationError, PreflightError

try:
    pf.record_opt_out(opt_out, idempotency_key=inbound_message_id)
except AuthenticationError:
    alert_ops("Preflight key rejected")
except PreflightError as e:
    requeue(opt_out, delay=e.retry_after)  # keep the same key on the next try
```

Requests send `User-Agent: preflight-sdk-python/<SDK_VERSION>`. `SDK_VERSION` and `API_VERSION` (the `/v1` API this
SDK speaks) are exported.

Request and response types (`TypedDict`) are in `preflight_sdk.types`.

