Metadata-Version: 2.4
Name: touchque-device-risk
Version: 1.0.0
Summary: Official Python server SDK for Touchque Device Risk: check a browser's identification, read and search identifications, report site activity
Home-page: https://touchque.com
Author: Touchque
Author-email: developer@touchque.com
Project-URL: Source, https://github.com/Touchque/touchque-device-risk-python
Classifier: Programming Language :: Python :: 3
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Requires-Python: >=3.7
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: requests>=2.25.1
Provides-Extra: dev
Requires-Dist: pytest>=7.0.0; extra == "dev"
Dynamic: author
Dynamic: author-email
Dynamic: classifier
Dynamic: description
Dynamic: description-content-type
Dynamic: home-page
Dynamic: license-file
Dynamic: project-url
Dynamic: provides-extra
Dynamic: requires-dist
Dynamic: requires-python
Dynamic: summary

# touchque-device-risk

The official Python server SDK for **Touchque Device Risk**: a visitor ID for every
browser on your sign-up, password-reset, sign-in or approval page, a risk verdict for
an account, a search of your identifications, and the activity your server saw
(payments, failed sign-ins, probing, SMS codes, wrong codes).

The browser side is [`@touchque/device-risk`](https://www.npmjs.com/package/@touchque/device-risk)
(the script tag, or `identify()`). Device risk is a paid add-on: until your workspace
turns it on, every call answers 409 `device_risk_off`.

📘 Full docs: **[support.touchque.com](https://support.touchque.com)**

## Install

```bash
pip install touchque-device-risk
```

Python 3.7 or later. The package has its own client: it does not need `touchque-authenticator`.

## Setup

Use the API key and secret of your workspace (Touchque dashboard → Developers → API keys):

```bash
TQ_API_KEY=tq_your_key
TQ_API_SECRET=your_api_secret
```

```python
from touchque_device_risk import Config, TouchqueDeviceRisk

device_risk = TouchqueDeviceRisk()                                            # from the environment
# device_risk = TouchqueDeviceRisk(Config(api_key=..., api_secret=...))       # explicit
```

`Config` takes `api_key`, `api_secret`, `base_url` (default `https://api.touchque.com`, or
`TQ_API_URL`; plaintext `http://` only for localhost) and `timeout` (ms, default 10000).
Every request is signed with HMAC-SHA256, like every Touchque SDK.

## Check a page's identification

With the script tag on your page, the form arrives with a `touchque_request_id` field.
Pass it as it came: missing, empty, made up or expired is still a verdict
(`report`: `missing`, `unknown`, `expired`; the signal `device_identification_missing`),
never an exception.

```python
r = device_risk.check(
    request.form.get('touchque_request_id'),
    event='sign_up',                    # sign_in (default), sign_up, password_reset, approval
    external_username=email,
    client_ip=request.remote_addr,
)
if r['stepUp']:
    ask_for_email_code()                # ask for more: never refuse on it alone
# r['visitorId'], r['signals'], r['bot'], r['network'], r['accountDevice'], r['suspect'], r['caseCode']
```

`device_risk=` instead of the request id relays the page's report (`collect()`) whole.

- `stepUp`: ask for more on this page (an emailed code, a passkey, a number-matched
  approval). It fails toward asking: anything but an exact `False` is `True`.
- `accountDevice`: once an account is named, did it use this device before
  (`known`, `likely`, `new`, `first`).
- `suspect`: the suspect score in shadow (0-100, `band`, `wouldDo`, every reason with its
  points and who proves it). It decides nothing yet.
- `engine == 'unavailable'`: the risk engine could not be reached and the verdict is a
  safe default (an outage, not risk).

For sign-ins approved with Touchque, pass the request id to `login.request` /
`risk.check` of the `touchque` SDK as `device_risk_request_id` instead.

## Read and search identifications

```python
event = device_risk.get_event(request_id)       # the trusted identification (dre_...)

cursor = None
while True:
    page = device_risk.search_events(signal='device_tampered', from_='2026-11-01', cursor=cursor)
    for e in page['events']:
        print(e['at'], e['visitorId'], e['caseCode'])
    cursor = page['nextCursor']
    if not cursor:
        break
```

Filters: `from_`, `to` (7 days by default, at most 90), `signal`, `step_up`, `kind`,
`origin`, `ip` (an address or CIDR range, a filter only), `account`, `visitor_id`,
`request_id`, `cursor`, `limit` (1-100).

## Report activity

What a visitor did that your server saw. Touchque counts it per visitor and per network
and answers the abuse codes it raised (`abuse_card_testing`, `abuse_card_shared`,
`abuse_login_failures`, `abuse_probing`, `abuse_otp_pumping`, `abuse_code_guessing`);
for 24 hours the visitor's next checks carry them and the suspect score weighs them.

```python
a = device_risk.activity(
    'payment_attempt',                             # login_failed, not_found, forbidden, otp_sent, code_failed
    request_id=request.form.get('touchque_request_id'),  # or visitor_id=, or client_ip= alone
    client_ip=request.remote_addr,
    outcome='declined',                            # approved, declined, error
    card={'bin': '424242', 'last4': '4242'},       # never the card number
)
if 'abuse_card_testing' in a['signals']:
    stop_taking_cards()                            # your call
```

A card is its BIN (6-8 digits) and last 4 digits only. A card number, in any field of
`card`, raises `TouchqueConfigException` before anything is sent. `phone=` (for
`otp_sent`) and `path=` (for `not_found` / `forbidden`, answered with its `pathClass`)
are optional.

## Webhooks

`DeviceRiskWebhookEvents.DEVICE_RISK_SIGNAL` and `DEVICE_RISK_ALERT` are the `event`
values of Touchque's Device risk webhooks. Verify a webhook's signature with the
`touchque` SDK before reading it.

## Errors

- `TouchqueConfigException`: a bug in your code (a wrong `event`, a card number, a bad
  request id for `get_event`), raised before any request.
- `TouchqueAPIException` (`status`, `code`, `case_code`): Touchque answered with an
  error, e.g. 409 `device_risk_off`. `TouchqueFeatureNotInPlanException`,
  `TouchqueFeatureReadOnlyException` and `TouchqueFeatureOffException` (all
  `TouchqueFeatureException`, `feature == 'device_risk'`) when your organization cannot
  use Device risk here.
- `TouchqueNetworkException`: the request never reached Touchque (generally safe to retry).

## Development

```bash
python3 -m venv .venv && .venv/bin/pip install -e '.[dev]'
.venv/bin/python -m pytest
```

The contract tests start the shared fake API (`../testing/fake-touchque-api.mjs`) and
need `node` on `PATH`; they skip themselves otherwise.

## License

MIT
