Metadata-Version: 2.4
Name: touchque-device-risk
Version: 1.1.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, the activity your server saw
(payments, failed sign-ins, probing, SMS codes, wrong codes), and a bot check of any
request to your server.

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.
- `bot`: one answer to "a bot?": `result` (`detected`, `suspected`, `not_detected`),
  `reasons`, `type` (`ai_agent`, `automation`, `script`), `tools`, `agent` and `input`.
  `tools` names the automation tools (`selenium`, `playwright`, `puppeteer`, `phantomjs`,
  `nightmare`, `headless_chrome`) and the AI agents (`claude_agent`: the Claude app's
  browser or Claude in Chrome; `comet_agent`: Perplexity Comet; `genspark_agent`,
  `browser_use`, `stagehand`, `skyvern`) whose marks were on the page; each is also a
  `tool_<name>` reason. Input that only software sends gives a suspected reason:
  `cdp_input` (a mouse press with no pressure), `input_no_focus` (a click or key into a
  page not in front), `insert_text_bulk` (text with no key pressed), `scripted_click` (a
  form sent with no click or key); so do `headless_window` (a window with no browser
  frame, like headless Chrome's) and `emulator` (an Android emulator's graphics). New
  values may be added in minor versions.
- `engine == 'unavailable'`: the risk engine could not be reached and the verdict is a
  safe default (an outage, not risk).

`network` is the address as the risk engine saw it (the place, never coordinates):
`countryCode`, `region`, `city`, `asn`, `asnOrg`, `type` (`isp`, `hosting`, `tor`,
`relay`: Apple's iCloud Private Relay, `unknown`), `tor`, `hosting`, `proxy` and more.
Newer servers add these (absent on older ones; `None` when not classified or not counted):

- `kind`: `residential`, `mobile_carrier`, `education`, `business`, `public_wifi`,
  `hosting`, `proxy`, `vpn`, `tor`, `relay` or `unknown` (`DEVICE_RISK_NETWORK_KINDS`, an
  open list: new values may be added in minor versions), with `kindSource` (where it came
  from: `address`, `network`, `mixed`, `network_open`, `name`) and `vpn` (a VPN company's
  own address).
- `shared`: many browsers used this address on your pages in the last 24 hours (a school,
  an office, a cafe, a mobile operator). `sharedVisitors24h` and `sharedAccounts24h` are
  "at least" counts: 1, 2, 5, 10, 100 or 1000.
- `lookAlikeMatching`: `False` when Touchque recognised this computer only by its own key,
  cookie or stored id, never because it looks like another one; `None` for a phone, a
  tablet or Safari, which are never matched by look-alike.

The shared fields and `lookAlikeMatching` describe the browser's own address: they are
`None` when `client_ip` is another address than the one the browser identified from.

`proxy` means the address was on a public proxy list in the last 30 days: often a resold
home or school line, so it counts little (absent on older servers). `kind` adds no points
of its own except `vpn` (`network_vpn`, 10) and `proxy` (`network_proxy`, 6); `shared` and
`lookAlikeMatching` are context only.

Touchque uses the IP2Proxy LITE database for [proxy and VPN detection](https://www.ip2location.com).
This site or product includes IP2Proxy LITE data available from https://lite.ip2location.com.

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`
(the page), `origin`, `ip` (an address or CIDR range, a filter only), `account`,
`visitor_id`, `request_id`, `network_kind`, `shared`, `cursor`, `limit` (1-100).

```python
vpn_sign_ups = device_risk.search_events(network_kind='vpn', kind='sign_up')
on_shared_addresses = device_risk.search_events(shared=True)
```

`network_kind` (sent as `networkKind`) matches only identifications classified since the
kind of network exists: older ones never match. `shared=True` finds identifications whose
own address was shared, `shared=False` the ones counted and not shared; an identification
that was not counted matches neither. Older servers ignore both.

## 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.

## Bot check

Many bots never run JavaScript, so the page tag never sees them: ChatGPT-User, GPTBot,
Meta's crawlers, curl, scripts. Send one request's address and headers from your
server; Touchque answers which bot it is, whether that identity is proven, and what it
would do. It decides on its own servers, from the bot operators' own published address
lists and signing keys; what it cannot check, it says it cannot check.

```python
from flask import request
from touchque_device_risk import TouchqueException

@app.before_request
def check_for_bots():
    try:
        r = device_risk.bot_check_wsgi(request.environ)
    except TouchqueException:
        return None                                   # unreachable or over budget: carry on
    if r['suggestion'] != 'allow':                    # advice only: Touchque enforces nothing
        log.info('bot check: %s %s %s', r['bot']['name'], r['bot']['identity'], r['bot']['rule'])
```

- `bot`: `result` (`detected`, `suspected`, `not_detected`), `category` (`ai_agent`,
  `ai_assistant`, `ai_crawler`, `ai_search`, `search_crawler`, `link_preview`, `seo`,
  `monitoring`, `archiver`, `feed_reader`, `security_scanner`, `http_client`,
  `headless_browser`, `automation`; a new one comes through as it is), `provider` and
  `name` (`OpenAI`, `ChatGPT-User`), `identity`, `verifiedBy` (`signature`, `ip_list`,
  `reverse_dns`, `asn`), `confidence`, `rule` (a stable id, `directory.chatgpt_user`)
  and `reasons` (`code`, and `text`: a sentence for your fraud team).
- `identity`: `verified` (its operator's signature, published addresses or reverse DNS
  proved it), `unverified` (a **spoofed** name: its operator publishes a way to check
  and the check failed) or `claimed` (no way to check it, or not right now).
- `suggestion` is advice in shadow, never enforced: `allow` (a verified bot, a declared
  crawler, assistant or other bot it cannot check, or no bot), `block` (a spoofed name),
  `challenge` (an AI agent that only names itself, since it acts for a person; undeclared
  automation: an HTTP client, a headless browser, a browser that contradicts itself; or a
  suspected bot).
- `network`: `asn`, `asnOrg`, `countryCode`, `hosting`, or `None` when it cannot tell.

Django: `bot_check_wsgi(request.META)`. Starlette, FastAPI: `bot_check_asgi(request.scope)`;
it blocks, so from an `async def` endpoint run it with `run_in_threadpool`. Anything
else: `bot_check(ip, headers, method=, url=, http_version=, tls=)`, with `headers` as
`[name, value]` pairs in the order received (`[]` for a request that had none; a dict
goes as order unknown). Behind a proxy, pass `ip=` the visitor's address. Pass
`http_version=` and `tls=` only when your edge tells you what the visitor's connection
was: the helpers never send your server's own protocol, which behind a proxy is the
proxy's.

Authorization, Cookie, Proxy-Authorization, X-Api-Key and Set-Cookie go with empty
values (their names stay, for the order), only the URL's host and path go, and Touchque
never logs or stores header values. What the visitor sent never raises, so a bot
cannot switch the check off: past 100 headers the rest is left out, a name is cut to
128 characters, a value to 4096, a body over 32 KB has its longest values cut, and
`"truncated": true` tells Touchque so. A header HTTP does not allow, a method other than
1 to 16 letters or a URL Touchque could not read is left out rather than refused. The
bot check has its own budget per workspace (past it, a 429 with `retry_after`).

## 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`, a bot check without the visitor's address), 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
