touchque-device-risk 1.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: e972e85766a804a3e99663f810ce1fc14c825db4ff4cea8a4842bb9e66ef507f
4
- data.tar.gz: 5a08990ff45afede5dffa29b05691c2229fd07d3b3b1f88f85245e869f1ecc96
3
+ metadata.gz: eaad76b43388f13c8471abcbd04d80290c7c04944f3ce238ef7e5911cec768aa
4
+ data.tar.gz: 03d6ec965acc1f06d5efe76fa3a607c67791e30d9b2f7a289500c7ce77c1911e
5
5
  SHA512:
6
- metadata.gz: be8ae91ea52fe380978efe901aeb79fb73672d26e7ee13b48424510f5b1395221639e35493cfbad4329fab8bbca02bc173e7aacb500dddc3c01857f8b6301bbf
7
- data.tar.gz: 7d109e3c9769ad474b21152476f4a90e6da0034c232899828b0779282116c18c7b3f1393e4140d75dba741f9328085f6e9044f2972c762d29794e86e8ff7c51c
6
+ metadata.gz: 2a70041493ae2783294e369bfebe6d1699314f05b775a77bdea614e61a8ed054b0a77d947d5cfe3b25cae9815de42750a2afbab548e168685bcd3e4fde3ddd92
7
+ data.tar.gz: e5ac9c7179604ff4cff8895cf618fc9c01ee0f059c1da774b63aa5fdd01c97cb1334fbe067126b817b5ce447fb8ba44c38a7aa645153025bae138e311607688a
data/CHANGELOG.md CHANGED
@@ -3,6 +3,14 @@
3
3
  All notable changes to this project will be documented in this file. The
4
4
  format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
5
5
 
6
+ ## [1.1.0] — 2026-11-26
7
+
8
+ ### Added
9
+ - `visitor["mark"]`: the mark actually applied to the identification (`step_up` always, `trusted` only when the browser matched by its stored key or id, never by traits, else nil), in `check` and `get_event`; `check` reads any other value as nil (`Client.visitor_of`). `visitor["status"]` stays your admin's mark. Absent from older servers.
10
+ - **Bot check: `bot_check(ip:, headers:, method:, url:, http_version:, tls:)` and `bot_check_rack(env)`** (`POST /device-risk/bot-check`): which bot sent one request your server received, for the bots that never run the page tag (ChatGPT-User, GPTBot, Meta's crawlers, Grok's fetches, curl, scripts). Sends the visitor's IP and headers in the order received (`[[name, value], ...]`, `[]` for a request that had none; a Hash goes as an object, the order unknown), with `Authorization`, `Cookie`, `Proxy-Authorization`, `X-Api-Key` and `Set-Cookie` as empty values, and the URL without its query string; `http_version:` and `tls:` only when you pass what your edge saw. Answers a `BotCheck::Result`, a Hash with a reader per field: `bot` (`result` detected | suspected | not_detected, `category`, `provider`, `name`, `identity` verified | unverified (a spoofed name) | claimed, `verified_by`, `confidence`, `rule`, `reasons` with `code` and `text`), `network` (`asn`, `asn_org`, `country_code`, `hosting`) or nil, `suggestion` (allow | block | challenge: advice in shadow, Touchque never enforces it) and `rules_version`. Fields and values added later come through as they are; `Client.parse_bot_check` reads a stored answer. What the visitor sent never raises: the first 100 headers go, a name is cut to 128 and a value to 4096 characters, the request is kept under 32 KB, and `"truncated" => true` tells Touchque; a header HTTP does not allow, an odd method or a URL Touchque could not read is left out. No ip (or one that is not an address) or a wrong shape raises `ConfigError` before anything is sent. `bot_check_rack` reads Rails' `remote_ip` (else Rack's `ip`, else `REMOTE_ADDR`), the env's headers, method, host and path, never the env's own HTTP version. Constants `BotCheck::RESULTS`, `CATEGORIES`, `IDENTITIES`, `VERIFIED_BY`, `CONFIDENCES`, `SUGGESTIONS`, `HTTP_VERSIONS` and `BLANKED_HEADERS`.
11
+ - **Network kind.** The `network` hash of `check`, `get_event` and each `search_events` item can carry `kind` (`residential`, `mobile_carrier`, `education`, `business`, `public_wifi`, `hosting`, `proxy`, `vpn`, `tor`, `relay` or `unknown`: an open list, new values may be added in minor versions; `Client::NETWORK_KINDS`), `kindSource` (`address`, `network`, `mixed`, `network_open`, `name`), `vpn`, `shared` (many browsers on this address on your pages in 24 hours: context only), `sharedVisitors24h` and `sharedAccounts24h` ("at least" 1, 2, 5, 10, 100 or 1000) and `lookAlikeMatching`. Passed through as the API answers them: absent on older servers, nil when not classified or counted. `proxy` and the `relay` type are documented too. `search_events` takes `network_kind:` (sent as `networkKind`; only identifications classified since network kind match) and `shared:` (true or false; `false` leaves out identifications that were not counted). Older servers ignore both.
12
+ - **AI agents in `bot`** (`check`, `get_event` and each `search_events` item), on servers since 2026-11-25 (absent on older ones): `tools` can name `claude_agent` (the Claude app's browser or Claude in Chrome), `comet_agent` (Perplexity Comet), `genspark_agent`, `browser_use`, `stagehand` and `skyvern` next to the automation tools, each also a `tool_<name>` reason, and `reasons` can carry `cdp_input`, `input_no_focus`, `insert_text_bulk` and `scripted_click`. `headless_window` and `emulator`, which the docs lacked, are listed too. Plain strings, passed through as before: only the documentation is new.
13
+
6
14
  ## [1.0.0] — 2026-11-24
7
15
 
8
16
  ### Added
data/README.md CHANGED
@@ -55,10 +55,44 @@ ask_for_email_code if r["stepUp"] # a step-up, never a refusal on it alone
55
55
  (low, medium, high, critical), `wouldDo` (allow, number_match, passkey, block) and `reasons`
56
56
  (`code`, `points`, `by`: server, site, page or brand, `text`).
57
57
  - `accountDevice`: did this account use the device before? `status` known, likely, new or first.
58
+ - `bot`: one answer to "a bot, and what kind?": `result` (detected, suspected, not_detected), `reasons`, `type`
59
+ (ai_agent, automation, script), `tools`, `agent` and `input`. `tools` names the automation tools (`selenium`,
60
+ `playwright`, `puppeteer`, `phantomjs`, `nightmare`, `headless_chrome`) and the AI agents (`claude_agent`: the
61
+ Claude app's browser or Claude in Chrome; `comet_agent`: Perplexity Comet; `genspark_agent`, `browser_use`,
62
+ `stagehand`, `skyvern`) whose marks were on the page, each also a reason `tool_<name>`. Other reasons include
63
+ `cdp_input` (a press with no pressure: only the DevTools protocol sends it), `input_no_focus` (a click or key
64
+ into a page that was not in front), `insert_text_bulk` (text that arrived whole, no key pressed),
65
+ `scripted_click` (a form sent with no click or key), `headless_window` and `emulator`. Plain strings: new tools
66
+ and reasons may be added. Servers before 2026-11-25 send neither the AI agents nor `cdp_input`,
67
+ `input_no_focus`, `insert_text_bulk` or `scripted_click`.
58
68
 
59
69
  For a sign-in approved on the phone with the main Touchque gem, pass the same field as
60
70
  `device_risk_request_id:` to its `login.request` or `risk.check` instead.
61
71
 
72
+ ### The network
73
+
74
+ `network` (in `check`, `get_event` and each `search_events` item) is the address as the risk engine saw it,
75
+ never coordinates: `countryCode`, `city`, `asn`, `asnOrg`, `type` (isp, hosting, tor, relay: Apple's iCloud
76
+ Private Relay, or unknown), `proxy` (on a public proxy list in the last 30 days: context, often a home or school
77
+ line resold to a proxy network; absent on older servers) and more. Newer servers add these (absent on older
78
+ ones; nil when not classified or counted, as for an identification made before them):
79
+
80
+ - `kind`: `residential`, `mobile_carrier`, `education`, `business`, `public_wifi`, `hosting`, `proxy`, `vpn`,
81
+ `tor`, `relay` or `unknown` (`Client::NETWORK_KINDS`). An open list: new values may be added in minor
82
+ versions. `kindSource` says where it came from (`address`, `network`, `mixed`, `network_open`, `name`).
83
+ - `vpn`: a VPN company's own address (the suspect score's `network_vpn`, 10 points).
84
+ - `shared`: many browsers used this address on your pages in the last 24 hours (10 or more, or 5 or more accounts
85
+ from 3 or more browsers), usually a school, an office, a café or a mobile operator: context only
86
+ (`network_shared`, 0 points). `sharedVisitors24h` and `sharedAccounts24h` are "at least" counts (1, 2, 5, 10,
87
+ 100 or 1000). They describe the identification's own address: nil when the answer is about another one.
88
+ - `lookAlikeMatching`: `false` when Touchque recognised this computer only by its own key, cookie or stored id
89
+ (identical computers in use on its address, or a school, company or public Wi-Fi network on Touchque's list;
90
+ `network_look_alike_off`, 0 points), `true` when look-alike matching was allowed, nil when not decided (a
91
+ phone, a tablet or Safari).
92
+
93
+ Touchque uses the IP2Proxy LITE database for [proxy and VPN detection](https://www.ip2location.com).
94
+ This site or product includes IP2Proxy LITE data available from https://lite.ip2location.com.
95
+
62
96
  ## Read and search identifications
63
97
 
64
98
  ```ruby
@@ -73,9 +107,20 @@ loop do
73
107
  end
74
108
  ```
75
109
 
76
- Filters: `from:`, `to:` (7 days by default, at most 90), `signal:`, `step_up:`, `kind:`, `origin:`, `ip:`
77
- (an address or a CIDR range, never returned), `account:`, `visitor_id:`, `request_id:`, `limit:` (1 to 100)
78
- and the opaque `cursor:`. A search that would read too much is a 422 `search_too_broad`.
110
+ Filters: `from:`, `to:` (7 days by default, at most 90), `signal:`, `step_up:`, `kind:` (the page), `origin:`,
111
+ `ip:` (an address or a CIDR range, never returned), `account:`, `visitor_id:`, `request_id:`, `network_kind:`,
112
+ `shared:`, `limit:` (1 to 100) and the opaque `cursor:`. A search that would read too much is a 422
113
+ `search_too_broad`.
114
+
115
+ ```ruby
116
+ page = dr.search_events(network_kind: "education", shared: true) # school networks, shared addresses only
117
+ ```
118
+
119
+ - `network_kind:` is a `network["kind"]` (sent as `networkKind`). It matches only identifications classified
120
+ since network kind exists: older ones never match. An unknown value is a 400 `invalid_network_kind`.
121
+ - `shared: true` keeps the identifications whose own address was shared; `shared: false` keeps the ones counted
122
+ and not shared, so an identification that was not counted matches neither.
123
+ - Older servers ignore both and answer as without them.
79
124
 
80
125
  ## Report what your server saw
81
126
 
@@ -95,6 +140,42 @@ stop_taking_cards if a["signals"].include?("abuse_card_testing")
95
140
  - A card is its BIN (6 to 8 digits) and last 4 digits only. Anything else (a card number, a `number`
96
141
  or `pan` key) raises `Touchque::DeviceRisk::ConfigError` before anything is sent.
97
142
 
143
+ ## Bot check
144
+
145
+ Many bots never run your page's JavaScript, so the page tag never sees them: ChatGPT-User, GPTBot,
146
+ Meta's crawlers, Grok's fetches, curl and scripts. Send one request's address and headers from your
147
+ server, and Touchque answers which bot it is, whether that identity is proven and what it would do. It
148
+ decides on its own servers with its own data, and never logs or stores header values.
149
+
150
+ ```ruby
151
+ # Rails: in a controller, for the request it is answering
152
+ r = dr.bot_check_rack(request.env)
153
+ r.bot.result # "detected", "suspected" or "not_detected"
154
+ r.bot.name # "ChatGPT-User" (r.bot.provider: "OpenAI"), or nil
155
+ r.bot.identity # "verified", "unverified" (a spoofed name) or "claimed"
156
+ head :forbidden if r.suggestion == "block" # advice in shadow: Touchque never enforces it
157
+ ```
158
+
159
+ - `bot_check_rack` reads the address (`request.remote_ip`: set your trusted proxies), the headers in the
160
+ order the server kept them, the method, the host and the path (never the query string). It never sends
161
+ the env's own HTTP version: behind a proxy that is the proxy's connection, not the visitor's.
162
+ - Outside Rack: `dr.bot_check(ip:, headers: [[name, value], ...], method:, url:)`, the headers in the order
163
+ received (`[]` for a request that had none). Pass `http_version:` and `tls: { ciphers:, ja4: }` (to
164
+ either method) only when your edge tells you what the visitor's were. `Authorization`, `Cookie`,
165
+ `Proxy-Authorization`, `X-Api-Key` and `Set-Cookie` go with empty values.
166
+ - What the visitor sent never raises: the first 100 headers go, a name is cut to 128 characters and a value
167
+ to 4096, the request is kept under 32 KB, and `"truncated" => true` tells Touchque so. A header HTTP does
168
+ not allow, a method other than 1 to 16 letters or a URL Touchque could not read is left out. Only no
169
+ `ip` (or one that is not an address) or a wrong shape raises `ConfigError`, before anything is sent.
170
+ - The answer is a `BotCheck::Result` (a Hash with a reader per field): `bot` (`result`, `category`,
171
+ `provider`, `name`, `identity`, `verified_by`, `confidence`, `rule`, `reasons` with `code` and `text`),
172
+ `network` (`asn`, `asn_org`, `country_code`, `hosting`) or nil, `suggestion` and `rules_version`. New
173
+ fields and values come through as they are.
174
+ - `suggestion`: `allow` (a verified bot, a declared crawler, assistant or other bot Touchque cannot check, or
175
+ no bot), `block` (a spoofed name) or `challenge` (an AI agent that only names itself, since it acts for a
176
+ person; an HTTP client, a headless browser or a browser whose claims contradict each other; or a suspected
177
+ bot).
178
+
98
179
  ## Webhooks
99
180
 
100
181
  Verify Touchque webhooks with the main Touchque gem, then compare `event` with
@@ -118,7 +199,8 @@ bundle install
118
199
  bundle exec rake test
119
200
  ```
120
201
 
121
- The tests run against the shared fake Touchque API (`testing/fake-touchque-api.mjs`, Node.js).
202
+ The tests run against the shared fake Touchque API (`testing/fake-touchque-api.mjs`, Node.js); the bot
203
+ check tests against a small local fake that checks request signatures the same way (`test/bot_check_test.rb`).
122
204
 
123
205
  ## License
124
206
 
@@ -0,0 +1,495 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "ipaddr"
4
+
5
+ module Touchque
6
+ module DeviceRisk
7
+ # The bot check (Client#bot_check, Client#bot_check_rack): which bot sent one request your
8
+ # server received. Many bots never run your page's JavaScript, so the page tag never sees them
9
+ # (ChatGPT-User, GPTBot, Meta's crawlers, Grok's fetches, curl, scripts); this check reads the
10
+ # request itself. Touchque decides on its own servers with its own data: the operators'
11
+ # published address lists, Web Bot Auth signatures, reverse DNS checked both ways and its own
12
+ # network data. When a source is unavailable the answer is "cannot tell", never a guess and
13
+ # never a block. Touchque never logs or stores header values and keeps nothing from a check
14
+ # but short-lived keyed-hash counters.
15
+ module BotCheck
16
+ # What Touchque found: a bot it is sure of, signs of one, or none.
17
+ RESULTS = %w[detected suspected not_detected].freeze
18
+ # The kinds of bot. New ones may be added: an answer can carry one that is not listed here.
19
+ CATEGORIES = %w[ai_agent ai_assistant ai_crawler ai_search search_crawler link_preview seo monitoring archiver
20
+ feed_reader security_scanner http_client headless_browser automation].freeze
21
+ # Is the bot who it says it is? "unverified" is a spoofed name (see Bot#identity).
22
+ IDENTITIES = %w[verified unverified claimed].freeze
23
+ # What proved the identity.
24
+ VERIFIED_BY = %w[signature ip_list reverse_dns asn].freeze
25
+ # How sure Touchque is.
26
+ CONFIDENCES = %w[high medium low].freeze
27
+ # What Touchque would do: advice in shadow, Touchque never enforces it.
28
+ SUGGESTIONS = %w[allow block challenge].freeze
29
+ # The http_version: values ("HTTP/2", "2.0", "h2" or 2 work too).
30
+ HTTP_VERSIONS = %w[1.0 1.1 2 3].freeze
31
+ # Sent with empty values, their names kept for the order (compared without case).
32
+ BLANKED_HEADERS = %w[authorization cookie proxy-authorization x-api-key set-cookie].freeze
33
+ # The API's limits: headers per request, characters per name and per value, bytes per request
34
+ # (32 KB read as 32,000, so a body fits either reading of "KB").
35
+ MAX_HEADERS = 100
36
+ MAX_NAME_LENGTH = 128
37
+ MAX_VALUE_LENGTH = 4096
38
+ MAX_BODY_BYTES = 32_000
39
+ # @api private: a longer URL is left out, never cut (a signature may cover its path).
40
+ MAX_URL_LENGTH = 4096
41
+ # @api private: a longer JA4 is not one.
42
+ MAX_JA4_LENGTH = 128
43
+ # @api private: the methods the API reads.
44
+ METHOD = /\A[A-Za-z]{1,16}\z/
45
+ # @api private: a header name as HTTP allows it (RFC 9110 token).
46
+ TOKEN = /\A[!#$%&'*+\-.^_`|~0-9A-Za-z]+\z/
47
+ # @api private
48
+ PLAIN_AUTHORITY = /\A([A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)*\.?)(?::([0-9]{0,5}))?\z/
49
+ # @api private
50
+ DOTTED_QUAD = /\A(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\z/
51
+
52
+ # A bot check's answer: a Hash with the API's keys ("bot", "network", "suggestion",
53
+ # "rulesVersion") and a reader for each. Fields Touchque adds later stay in the Hash, and a
54
+ # value this gem does not know yet (a new category) comes through as it is.
55
+ #
56
+ # r = dr.bot_check_rack(request.env)
57
+ # r.bot.result # "detected"
58
+ # r.bot.name # "ChatGPT-User" (r.bot.provider: "OpenAI")
59
+ # r.bot.identity # "verified"
60
+ # r.suggestion # "allow"
61
+ class Result < Hash
62
+ # @api private: Client.parse_bot_check. Never raises: a missing or broken field reads as
63
+ # nothing seen (result "not_detected", suggestion "allow").
64
+ def self.parse(raw)
65
+ raw = {} unless raw.is_a?(Hash)
66
+ new.update(raw).update("bot" => Bot.parse(raw["bot"]), "network" => Network.parse(raw["network"]),
67
+ "suggestion" => BotCheck.text(raw["suggestion"]) || "allow",
68
+ "rulesVersion" => BotCheck.text(raw["rulesVersion"]))
69
+ end
70
+
71
+ # What Touchque found (a Bot). Never nil.
72
+ def bot
73
+ self["bot"]
74
+ end
75
+
76
+ # The network the request came from (a Network), or nil when Touchque could not tell.
77
+ def network
78
+ self["network"]
79
+ end
80
+
81
+ # What Touchque would do, as advice in shadow: Touchque never enforces it, your code decides.
82
+ # - "allow": a verified bot, a declared crawler, assistant or other bot Touchque cannot check,
83
+ # or no bot;
84
+ # - "block": a spoofed name (identity "unverified", or a signature that failed);
85
+ # - "challenge": an AI agent that only names itself (it acts for a person: ask that person),
86
+ # automation that does not say what it is (an HTTP client, a headless browser, a browser
87
+ # whose claims contradict each other), or a suspected bot.
88
+ # New values may be added (SUGGESTIONS).
89
+ def suggestion
90
+ self["suggestion"]
91
+ end
92
+
93
+ # The version of Touchque's rules that answered ("2026.11.25-1"), or nil.
94
+ def rules_version
95
+ self["rulesVersion"]
96
+ end
97
+ end
98
+
99
+ # What Touchque found: a Hash with the API's keys ("result", "category", "provider", "name",
100
+ # "identity", "verifiedBy", "confidence", "rule", "reasons") and a reader for each.
101
+ class Bot < Hash
102
+ # @api private: the fields that are a String or nil.
103
+ TEXT_FIELDS = %w[category provider name identity verifiedBy confidence rule].freeze
104
+
105
+ # @api private
106
+ def self.parse(raw)
107
+ raw = {} unless raw.is_a?(Hash)
108
+ out = new.update(raw)
109
+ out["result"] = BotCheck.text(raw["result"]) || "not_detected"
110
+ TEXT_FIELDS.each { |key| out[key] = BotCheck.text(raw[key]) }
111
+ out["reasons"] = (raw["reasons"].is_a?(Array) ? raw["reasons"] : []).filter_map { |r| Reason.parse(r) }
112
+ out
113
+ end
114
+
115
+ # "detected" (a bot, for sure), "suspected" (signs of one) or "not_detected" (none seen,
116
+ # or Touchque cannot tell).
117
+ def result
118
+ self["result"]
119
+ end
120
+
121
+ # The kind of bot, or nil: "ai_agent", "ai_assistant" (fetches a page a person asked an AI
122
+ # about), "ai_crawler", "ai_search", "search_crawler", "link_preview", "seo", "monitoring",
123
+ # "archiver", "feed_reader", "security_scanner", "http_client" (curl, scripts),
124
+ # "headless_browser" or "automation". New kinds may come (CATEGORIES).
125
+ def category
126
+ self["category"]
127
+ end
128
+
129
+ # Who runs the bot ("OpenAI"), or nil.
130
+ def provider
131
+ self["provider"]
132
+ end
133
+
134
+ # The bot's name ("ChatGPT-User"), or nil.
135
+ def name
136
+ self["name"]
137
+ end
138
+
139
+ # Is the bot who it says it is? nil when it names no one.
140
+ # - "verified": its operator's signature, published addresses or reverse DNS proved it;
141
+ # - "unverified": a spoofed name. It uses a name whose operator publishes a way to check,
142
+ # and that check failed;
143
+ # - "claimed": a name its operator gives no way to check, or one Touchque cannot check right now.
144
+ def identity
145
+ self["identity"]
146
+ end
147
+
148
+ # What proved the identity, or nil: "signature" (a Web Bot Auth signature), "ip_list" (the
149
+ # operator's published addresses), "reverse_dns" (its host name, checked both ways) or "asn"
150
+ # (the operator's own network).
151
+ def verified_by
152
+ self["verifiedBy"]
153
+ end
154
+
155
+ # How sure Touchque is: "high", "medium" or "low", or nil.
156
+ def confidence
157
+ self["confidence"]
158
+ end
159
+
160
+ # The rule that decided, a stable id ("directory.chatgpt_user", "http_client.curl",
161
+ # "browser.chromium_without_client_hints"), or nil.
162
+ def rule
163
+ self["rule"]
164
+ end
165
+
166
+ # Every sign Touchque saw (Reason), each with an English sentence for your fraud team. May be empty.
167
+ def reasons
168
+ self["reasons"]
169
+ end
170
+ end
171
+
172
+ # One sign Touchque saw: "code" (stable, for your code) and "text" (an English sentence a
173
+ # fraud team reads).
174
+ class Reason < Hash
175
+ # @api private: nil unless it carries a code.
176
+ def self.parse(raw)
177
+ return nil unless raw.is_a?(Hash) && BotCheck.text(raw["code"])
178
+
179
+ new.update(raw).update("text" => raw["text"].is_a?(String) ? raw["text"] : "")
180
+ end
181
+
182
+ # The sign's stable code.
183
+ def code
184
+ self["code"]
185
+ end
186
+
187
+ # What it means, in English ("" when the answer had none).
188
+ def text
189
+ self["text"]
190
+ end
191
+ end
192
+
193
+ # The network a request came from, from Touchque's own data: a Hash with the API's keys
194
+ # ("asn", "asnOrg", "countryCode", "hosting") and a reader for each, each nil when unknown.
195
+ class Network < Hash
196
+ # @api private
197
+ def self.parse(raw)
198
+ return nil unless raw.is_a?(Hash)
199
+
200
+ new.update(raw).update("asn" => raw["asn"].is_a?(Integer) ? raw["asn"] : nil,
201
+ "asnOrg" => BotCheck.text(raw["asnOrg"]), "countryCode" => BotCheck.text(raw["countryCode"]),
202
+ "hosting" => [true, false].include?(raw["hosting"]) ? raw["hosting"] : nil)
203
+ end
204
+
205
+ # The network's number (8075), or nil.
206
+ def asn
207
+ self["asn"]
208
+ end
209
+
210
+ # Who runs the network ("Microsoft Corporation"), or nil.
211
+ def asn_org
212
+ self["asnOrg"]
213
+ end
214
+
215
+ # The network's country, two letters ("US"), or nil.
216
+ def country_code
217
+ self["countryCode"]
218
+ end
219
+
220
+ # true: a cloud or hosting network (where scripts and many proxies run); false: not one;
221
+ # nil: unknown.
222
+ def hosting
223
+ self["hosting"]
224
+ end
225
+ end
226
+
227
+ module_function
228
+
229
+ # @api private: +value+ when it is a non-empty String, else nil.
230
+ def text(value)
231
+ value.is_a?(String) && !value.empty? ? value : nil
232
+ end
233
+
234
+ # @api private: the request body. Raises ConfigError, before anything is sent, only for what
235
+ # your code passed wrong (no ip or not one address, a wrong shape). What the visitor sent never
236
+ # raises: the first 100 headers stay, names and values are cut to the API's limits, the body is
237
+ # fitted to 32 KB, and "truncated" => true tells Touchque so.
238
+ def request_body(ip:, headers:, method:, url:, http_version:, tls:, where: "bot_check()")
239
+ body = { "ip" => ip_of(ip, where) }
240
+ pairs, ordered, truncated = header_list(headers, where)
241
+ unless method.nil? || method == ""
242
+ raise ConfigError, "#{where}: method must be a String" unless method.is_a?(String)
243
+
244
+ m = utf8(method).strip
245
+ body["method"] = m if METHOD.match?(m) # anything but 1 to 16 letters is left out
246
+ end
247
+ unless url.nil? || url == ""
248
+ raise ConfigError, "#{where}: url must be a String" unless url.is_a?(String)
249
+
250
+ short = url_of(url)
251
+ body["url"] = short if short
252
+ end
253
+ version = normalize_version(http_version)
254
+ body["httpVersion"] = version if version
255
+ tls = tls_of(tls, where)
256
+ body["tls"] = tls if tls
257
+ fit(body, pairs, ordered, truncated)
258
+ end
259
+
260
+ # @api private: the body within 32 KB. The longest values are cut to one length, the longest
261
+ # that fits. Names always fit (100 of 128 characters); only a url or cipher list made long by
262
+ # escaping can crowd them out, so tls goes first, then the url, and the last headers only after.
263
+ def fit(body, pairs, ordered, truncated)
264
+ build = lambda do |count, cap, drop|
265
+ kept = pairs.first(count).map { |name, value| [name, cut(value, cap)] }
266
+ out = { "ip" => body["ip"], "headers" => ordered ? kept : kept.to_h }
267
+ { "method" => 3, "url" => 2, "httpVersion" => 3, "tls" => 1 }.each do |key, kept_below|
268
+ out[key] = body[key] if body.key?(key) && drop < kept_below
269
+ end
270
+ cut_any = kept.each_with_index.any? { |(_, value), i| value.length < pairs[i][1].length }
271
+ out["truncated"] = true if truncated || count < pairs.size || cut_any
272
+ out
273
+ end
274
+ fits = ->(b) { Util.json(b).bytesize <= MAX_BODY_BYTES }
275
+ whole = build.call(pairs.size, MAX_VALUE_LENGTH, 0)
276
+ return whole if fits.call(whole)
277
+
278
+ drop = 0
279
+ drop += 1 while drop < 2 && !fits.call(build.call(pairs.size, 0, drop))
280
+ low = 0
281
+ high = MAX_VALUE_LENGTH - 1
282
+ while low < high
283
+ mid = (low + high + 1) / 2
284
+ if fits.call(build.call(pairs.size, mid, drop)) then low = mid else high = mid - 1 end
285
+ end
286
+ count = pairs.size
287
+ out = build.call(count, low, drop)
288
+ out = build.call(count -= 1, 0, drop) while count.positive? && !fits.call(out)
289
+ out
290
+ end
291
+
292
+ # @api private: one IPv4 or IPv6 address; a zone is dropped and ::ffff:a.b.c.d goes as a.b.c.d.
293
+ def ip_of(ip, where)
294
+ address = ip.is_a?(String) ? utf8(ip).strip.sub(/%.*\z/m, "") : ""
295
+ parsed = begin
296
+ IPAddr.new(address) if address.match?(/\A[0-9A-Fa-f:.]+\z/)
297
+ rescue IPAddr::Error
298
+ nil
299
+ end
300
+ raise ConfigError, "#{where}: ip is required: the visitor's IPv4 or IPv6 address, as your server saw it" unless parsed
301
+
302
+ parsed.ipv4_mapped? ? parsed.native.to_s : address
303
+ end
304
+
305
+ # @api private: the headers as they go, whether in the order received, and whether any was
306
+ # left out or cut: HTTP/2 pseudo-headers (method and url carry them, and :path has the query)
307
+ # and a nil value are left out; so is a header HTTP does not allow (a name that is not a
308
+ # token, a line break or NUL in the value), on which the API would refuse the whole check.
309
+ # The first 100 stay; names are cut to 128 characters and values to 4096; secrets go blank.
310
+ def header_list(headers, where)
311
+ list = case headers
312
+ when Array then headers
313
+ when Hash then headers.to_a
314
+ else raise ConfigError, "#{where}: headers must be [[name, value], ...] in the order received ([] for none), or { name => value }"
315
+ end
316
+ truncated = false
317
+ pairs = []
318
+ list.each do |pair|
319
+ raise ConfigError, "#{where}: each header is a [name, value] pair" unless pair.is_a?(Array) && pair.size == 2
320
+
321
+ name, value = pair
322
+ name = name.to_s if name.is_a?(Symbol)
323
+ raise ConfigError, "#{where}: a header name is a non-empty String" unless name.is_a?(String) && !name.empty?
324
+ next if value.nil? || name.start_with?(":")
325
+
326
+ name = utf8(name)
327
+ value = utf8(value_text(value, where))
328
+ if !TOKEN.match?(name) || value.match?(/[\r\n\0]/)
329
+ truncated = true
330
+ next
331
+ end
332
+ pairs << [name, value]
333
+ end
334
+ truncated ||= pairs.size > MAX_HEADERS # more is not a browser: the rest is left out, never an error
335
+ pairs = pairs.first(MAX_HEADERS).map do |name, value|
336
+ blank = BLANKED_HEADERS.include?(name.downcase)
337
+ sent = blank ? "" : cut(value, MAX_VALUE_LENGTH)
338
+ truncated ||= name.length > MAX_NAME_LENGTH || (!blank && sent.length < value.length)
339
+ [cut(name, MAX_NAME_LENGTH), sent]
340
+ end
341
+ [pairs, !headers.is_a?(Hash), truncated]
342
+ end
343
+
344
+ # @api private: several values of one header are joined as HTTP joins them.
345
+ def value_text(value, where)
346
+ case value
347
+ when String then value
348
+ when Symbol, Numeric then value.to_s
349
+ when Array then value.map { |v| value_text(v, where) }.join(", ")
350
+ else raise ConfigError, "#{where}: a header value must be a String"
351
+ end
352
+ end
353
+
354
+ # @api private: the host and path only, never the query string or fragment, nor a user:password@.
355
+ # A path, or an http(s) URL (ws and wss read as http and https); a host Touchque could not read
356
+ # goes as the path alone; anything else, or one over 4096 characters, is nil.
357
+ def url_of(url)
358
+ head = utf8(url).strip.sub(/[?#].*\z/m, "")
359
+ out = if head.start_with?("/")
360
+ head
361
+ elsif (m = %r{\A(https?|wss?)://([^/]*)(/.*)?\z}im.match(head))
362
+ scheme = { "ws" => "http", "wss" => "https" }.fetch(m[1].downcase, m[1].downcase)
363
+ authority = m[2].split("@", -1).last.to_s
364
+ path = m[3].to_s
365
+ plain_host?(authority) ? "#{scheme}://#{authority}#{path}" : (path.empty? ? "/" : path)
366
+ end
367
+ out if out && cut(out, MAX_URL_LENGTH) == out
368
+ end
369
+
370
+ # @api private: a host Touchque reads as it is: letters, digits, dots, hyphens and underscores,
371
+ # an IPv4 address, a port up to 65535. Anything else (the Host header is the visitor's) goes as
372
+ # the path alone, so an odd Host never makes the API refuse the check.
373
+ def plain_host?(authority)
374
+ m = PLAIN_AUTHORITY.match(authority)
375
+ return false if m.nil? || (!m[2].to_s.empty? && m[2].to_i > 65_535)
376
+
377
+ host = m[1].chomp(".")
378
+ labels = host.split(".")
379
+ return false if labels.any? { |label| label.downcase.start_with?("xn--") }
380
+
381
+ # A name that ends in a number is read as an IPv4 address: it must be one.
382
+ labels.last.match?(/\A(?:[0-9]+|0x[0-9a-f]*)\z/i) ? DOTTED_QUAD.match?(host) : true
383
+ end
384
+
385
+ # @api private: "1.0", "1.1", "2" or "3" from "HTTP/2", "2.0", "h2", 2, 1.1...; nil (left out) for anything else.
386
+ def normalize_version(version)
387
+ version = version.to_s if version.is_a?(Numeric)
388
+ return nil unless version.is_a?(String)
389
+
390
+ v = utf8(version).strip.downcase.sub(%r{\Ahttp/}, "")
391
+ { "1.0" => "1.0", "1.1" => "1.1", "2" => "2", "2.0" => "2", "h2" => "2", "h2c" => "2",
392
+ "3" => "3", "3.0" => "3", "h3" => "3" }[v]
393
+ end
394
+
395
+ # @api private: what the brand's edge saw of TLS: ciphers (cut to 4096 characters: the list the
396
+ # visitor offered can be long) and ja4 (one over 128 characters is not a JA4: left out).
397
+ def tls_of(tls, where)
398
+ return nil if tls.nil?
399
+ raise ConfigError, "#{where}: tls must be { ciphers:, ja4: }" unless tls.is_a?(Hash)
400
+
401
+ out = {}
402
+ tls.each do |key, value|
403
+ key = key.to_s
404
+ raise ConfigError, "#{where}: tls takes ciphers: and ja4: only, not #{key}" unless %w[ciphers ja4].include?(key)
405
+ next if value.nil? || value == ""
406
+ raise ConfigError, "#{where}: tls #{key} must be a String" unless value.is_a?(String)
407
+
408
+ value = utf8(value).strip
409
+ next if value.empty?
410
+
411
+ if key == "ciphers"
412
+ out[key] = cut(value, MAX_VALUE_LENGTH)
413
+ elsif value.length <= MAX_JA4_LENGTH
414
+ out[key] = value
415
+ end
416
+ end
417
+ out.empty? ? nil : out
418
+ end
419
+
420
+ # @api private: what bot_check_rack reads from a Rack env. The headers come in the env's order
421
+ # (servers add them as they arrive), in lower case (Rack keeps no case). No HTTP version: the
422
+ # env's SERVER_PROTOCOL is the connection to this server, behind a proxy the proxy's.
423
+ def rack_request(env)
424
+ headers = []
425
+ env.each do |key, value|
426
+ next unless key.is_a?(String) && value.is_a?(String)
427
+
428
+ name = if key.start_with?("HTTP_") then key.delete_prefix("HTTP_")
429
+ elsif key == "CONTENT_TYPE" || key == "CONTENT_LENGTH" then key
430
+ end
431
+ # Some servers keep the protocol in HTTP_VERSION: not a header the visitor sent.
432
+ next if name.nil? || (key == "HTTP_VERSION" && protocol?(value))
433
+
434
+ headers << [name.downcase.tr("_", "-"), value]
435
+ end
436
+ method = env["rack.methodoverride.original_method"] || env["REQUEST_METHOD"]
437
+ { ip: rack_ip(env), headers: headers, method: method.is_a?(String) ? method : nil, url: rack_url(env) }
438
+ end
439
+
440
+ # @api private: "HTTP/1.1" and the like, as a server sets it (a visitor's Version header is not one).
441
+ def protocol?(value)
442
+ value.is_a?(String) && utf8(value).start_with?("HTTP/")
443
+ end
444
+
445
+ # @api private: Rails' request.remote_ip, else Rack's request.ip (both read X-Forwarded-For
446
+ # behind trusted proxies), else the TCP peer.
447
+ def rack_ip(env)
448
+ ip = quietly { env["action_dispatch.remote_ip"]&.to_s }
449
+ ip = quietly { ::Rack::Request.new(env).ip } if !text(ip) && defined?(::Rack::Request)
450
+ ip = env["REMOTE_ADDR"] unless text(ip)
451
+ text(ip)
452
+ end
453
+
454
+ # @api private: Rails raises on a spoofed Client-Ip header; the next source answers instead.
455
+ def quietly
456
+ yield
457
+ rescue StandardError
458
+ nil
459
+ end
460
+
461
+ # @api private
462
+ def rack_url(env)
463
+ host = [env["HTTP_HOST"], env["SERVER_NAME"]].find { |h| text(h) }
464
+ path = utf8(env["SCRIPT_NAME"].to_s) + utf8(env["PATH_INFO"].to_s)
465
+ return text(path) unless host
466
+
467
+ scheme = text(env["rack.url_scheme"]) || "http"
468
+ "#{utf8(scheme)}://#{utf8(host)}#{path}"
469
+ end
470
+
471
+ # @api private: valid UTF-8 (a header holds bytes; a Rack env's are binary), a bad byte
472
+ # replaced by U+FFFD, so the JSON never fails.
473
+ def utf8(text)
474
+ s = if [Encoding::UTF_8, Encoding::BINARY, Encoding::US_ASCII].include?(text.encoding)
475
+ text.dup.force_encoding(Encoding::UTF_8)
476
+ else
477
+ text.encode(Encoding::UTF_8, invalid: :replace, undef: :replace)
478
+ end
479
+ s.valid_encoding? ? s : s.scrub
480
+ end
481
+
482
+ # @api private: at most +max+ UTF-16 code units (what the API counts), never inside a character.
483
+ def cut(text, max)
484
+ return text if text.length * 2 <= max
485
+
486
+ units = 0
487
+ text.each_char.with_index do |char, i|
488
+ units += char.ord > 0xFFFF ? 2 : 1
489
+ return text[0, i] if units > max
490
+ end
491
+ text
492
+ end
493
+ end
494
+ end
495
+ end
@@ -36,8 +36,13 @@ module Touchque
36
36
  EVENTS = %w[sign_in sign_up password_reset approval].freeze
37
37
  # What the page had sent: ok, replayed, or no usable identification.
38
38
  REPORTS = %w[ok replayed missing unknown expired invalid].freeze
39
+ # The marks a visitor's "mark" can hold (nil: none applied).
40
+ MARKS = %w[trusted step_up].freeze
39
41
  # How a visitor was recognised (an event's "matchedBy").
40
42
  MATCHED_BY = %w[key fpc sid traits new].freeze
43
+ # The kind of network an answer's network["kind"] names (search_events' network_kind:). An open
44
+ # list: new values may be added in minor versions, so an answer can carry one not listed here.
45
+ NETWORK_KINDS = %w[residential mobile_carrier education business public_wifi hosting proxy vpn tor relay unknown].freeze
41
46
  # What your server saw the visitor do (activity's type:).
42
47
  ACTIVITY_TYPES = %w[payment_attempt login_failed not_found forbidden otp_sent code_failed].freeze
43
48
  # payment_attempt: what the payment provider answered.
@@ -48,7 +53,7 @@ module Touchque
48
53
  PATH_CLASSES = %w[admin wordpress secrets source db_admin debug shell other].freeze
49
54
  REQUEST_ID = /\Adre_[A-Za-z0-9_-]{22}\z/
50
55
  SEARCH_FILTERS = { from: "from", to: "to", signal: "signal", kind: "kind", origin: "origin", ip: "ip", account: "account",
51
- visitor_id: "visitorId", request_id: "requestId", cursor: "cursor" }.freeze
56
+ visitor_id: "visitorId", request_id: "requestId", network_kind: "networkKind", cursor: "cursor" }.freeze
52
57
  CARD_NUMBER = "never send the card number: card: is { bin: 6 to 8 digits, last4: 4 digits }"
53
58
 
54
59
  # Anything left nil falls back to the environment: TQ_API_KEY, TQ_API_SECRET and
@@ -99,9 +104,13 @@ module Touchque
99
104
  # or a CIDR range and is never returned. Pass "nextCursor" back as cursor: until it is
100
105
  # nil; do not page by moving the dates. A search that would read too much is a 422
101
106
  # search_too_broad: narrow the range or add a filter. Each event may carry "suspect"
102
- # (see parse_suspect) and "matchedBy" (MATCHED_BY).
107
+ # (see parse_suspect), "matchedBy" (MATCHED_BY) and "network" (as in parse_check).
108
+ # network_kind: is a network["kind"] (NETWORK_KINDS, sent as networkKind): it matches only
109
+ # identifications classified since network kind exists, never older ones. shared: true keeps
110
+ # the identifications whose own address was shared, false the ones counted and not shared: one
111
+ # that was not counted matches neither. Older servers ignore both and answer as without them.
103
112
  # { "events" => [...], "nextCursor" => String | nil, "from" => String, "to" => String }.
104
- def search_events(step_up: nil, limit: nil, **filters)
113
+ def search_events(step_up: nil, shared: nil, limit: nil, **filters)
105
114
  unknown = filters.keys - SEARCH_FILTERS.keys
106
115
  raise ConfigError, "search_events() does not know #{unknown.join(', ')}" unless unknown.empty?
107
116
  raise ConfigError, "search_events() limit must be 1 to 100" unless limit.nil? || (limit.is_a?(Integer) && limit.between?(1, 100))
@@ -109,6 +118,7 @@ module Touchque
109
118
  params = {}
110
119
  filters.each { |k, v| params[SEARCH_FILTERS[k]] = v if v.is_a?(String) && !v.empty? }
111
120
  params["stepUp"] = step_up ? "true" : "false" if [true, false].include?(step_up)
121
+ params["shared"] = shared ? "true" : "false" if [true, false].include?(shared)
112
122
  params["limit"] = limit.to_s if limit
113
123
  raw = @http.get("/device-risk/events", params) || {}
114
124
  cursor = raw["nextCursor"]
@@ -118,8 +128,9 @@ module Touchque
118
128
  end
119
129
 
120
130
  # The trusted identification behind a request_id: the visitor, how sure, what the page
121
- # showed, the risk engine's verdict, "accountDevice" and "suspect" (read them with
122
- # parse_account_device / parse_suspect). Read-only.
131
+ # showed, the risk engine's verdict, "network" and "bot" (as in parse_check), "accountDevice"
132
+ # and "suspect" (read them with parse_account_device / parse_suspect). Read-only.
133
+ # visitor["mark"] is the mark actually applied (see parse_check).
123
134
  def get_event(request_id)
124
135
  raise ConfigError, "get_event() needs a request_id (dre_...)" unless request_id.is_a?(String) && REQUEST_ID.match?(request_id)
125
136
 
@@ -205,6 +216,68 @@ module Touchque
205
216
  out
206
217
  end
207
218
 
219
+ # Asks which bot sent one request your server received (POST /device-risk/bot-check). Many
220
+ # bots never run your page's JavaScript, so the page tag never sees them: ChatGPT-User,
221
+ # GPTBot, Meta's crawlers, Grok's fetches, curl and scripts. Your server sends the visitor's
222
+ # address and headers; Touchque answers which bot it is, whether that identity is proven and
223
+ # what it would do. Touchque never logs or stores header values and keeps nothing from a
224
+ # check but short-lived keyed-hash counters. In a Rack app (Rails, Sinatra) use
225
+ # bot_check_rack(request.env).
226
+ #
227
+ # r = dr.bot_check(ip: visitor_ip, headers: [["Host", "shop.example"], ["User-Agent", ua], ["Accept", "*/*"]],
228
+ # method: "GET", url: "https://shop.example/login", http_version: "1.1")
229
+ # r.bot.result # "detected", "suspected" or "not_detected"
230
+ # r.bot.identity # "verified", "unverified" (a spoofed name) or "claimed"
231
+ # r.suggestion # "allow", "block" or "challenge": advice in shadow, Touchque never enforces it
232
+ #
233
+ # ip: is the visitor's IPv4 or IPv6 address as your server saw it. headers: is
234
+ # [[name, value], ...] in the order received (the order is a sign too; [] for a request that had
235
+ # none), or { name => value } when the order is unknown. Authorization, Cookie,
236
+ # Proxy-Authorization, X-Api-Key and Set-Cookie go with empty values, their names kept for the
237
+ # order. What the visitor sent never raises: the first 100 headers go, a name is cut to 128
238
+ # characters and a value to 4096, the request is kept under 32 KB, and "truncated" => true tells
239
+ # Touchque so; a header HTTP does not allow, a method other than 1 to 16 letters or a URL
240
+ # Touchque could not read is left out. No ip (or not one address) or a wrong shape raises
241
+ # ConfigError before anything is sent. url: goes without its query string (only the host and
242
+ # path are read). http_version: ("1.0", "1.1", "2" or "3") and tls: ({ ciphers:, ja4: }) only
243
+ # when your edge tells you what the visitor's were, never your server's own protocol. Answers a
244
+ # BotCheck::Result. 400 (APIError code invalid_ip, headers_required, too_large, invalid_body),
245
+ # 409 device_risk_off until your workspace turns Device risk on, 429 (retry_after) past your
246
+ # workspace's bot checks per minute.
247
+ def bot_check(ip:, headers:, method: nil, url: nil, http_version: nil, tls: nil)
248
+ body = BotCheck.request_body(ip: ip, headers: headers, method: method, url: url, http_version: http_version, tls: tls)
249
+ self.class.parse_bot_check(@http.post("/device-risk/bot-check", body))
250
+ end
251
+
252
+ # bot_check for the request a Rack app (Rails, Sinatra, Roda, Hanami) is answering: pass its
253
+ # env (request.env; a request object that answers #env works too). It sends the visitor's
254
+ # address (Rails' request.remote_ip, else Rack's request.ip, else REMOTE_ADDR: set your trusted
255
+ # proxies), the headers in the order the server kept them (in lower case: Rack keeps no case),
256
+ # the method and the host and path. It never sends the env's own HTTP version: that is the
257
+ # connection to this server, behind a proxy the proxy's. ip: replaces the env's address;
258
+ # http_version: and tls: are what your edge saw, as for bot_check.
259
+ #
260
+ # Like bot_check, it never raises for what the visitor sent.
261
+ #
262
+ # r = dr.bot_check_rack(request.env) # in a Rails controller
263
+ # head :forbidden if r.suggestion == "block" # a spoofed bot name; your choice to act on it
264
+ def bot_check_rack(env, ip: nil, http_version: nil, tls: nil)
265
+ env = env.env if !env.is_a?(Hash) && env.respond_to?(:env)
266
+ raise ConfigError, "bot_check_rack(): pass the Rack env (request.env)" unless env.is_a?(Hash)
267
+
268
+ req = BotCheck.rack_request(env)
269
+ body = BotCheck.request_body(ip: ip || req[:ip], headers: req[:headers], method: req[:method], url: req[:url],
270
+ http_version: http_version, tls: tls, where: "bot_check_rack()")
271
+ self.class.parse_bot_check(@http.post("/device-risk/bot-check", body))
272
+ end
273
+
274
+ # Reads a bot check answer (the decoded JSON) into a BotCheck::Result. Never raises: fields
275
+ # and values added later come through as they are, a missing or broken one reads as nothing
276
+ # seen (result "not_detected", suggestion "allow").
277
+ def self.parse_bot_check(raw)
278
+ BotCheck::Result.parse(raw)
279
+ end
280
+
208
281
  # The suspect score of an answer, event or search row (in shadow: it decides nothing
209
282
  # yet), or nil: "score" 0-100, "band" (low | medium | high | critical), "wouldDo"
210
283
  # (allow | number_match | passkey | block: what it would ask for), "mode" ("shadow")
@@ -243,8 +316,19 @@ module Touchque
243
316
  out
244
317
  end
245
318
 
319
+ # The visitor as it came; a "mark" other than trusted or step_up reads as nil (no mark applied).
320
+ def self.visitor_of(raw)
321
+ return nil unless raw.is_a?(Hash)
322
+ return raw unless raw.key?("mark")
323
+
324
+ raw.merge("mark" => MARKS.include?(raw["mark"]) ? raw["mark"] : nil)
325
+ end
326
+
246
327
  # Reads an answer, failing toward asking: "stepUp" is true unless it says exactly
247
- # false; junk signals are dropped.
328
+ # false; junk signals are dropped. visitor["mark"] is the mark actually applied to the
329
+ # identification: "step_up" always, "trusted" only when the browser matched by its stored
330
+ # key or id (never by traits), else nil; visitor["status"] stays your admin's mark. Absent
331
+ # from older servers.
248
332
  def self.parse_check(raw)
249
333
  body = raw.is_a?(Hash) ? raw : {}
250
334
  signals = (body["signals"].is_a?(Array) ? body["signals"] : []).filter_map do |s|
@@ -261,21 +345,37 @@ module Touchque
261
345
  "requestId" => body["requestId"].is_a?(String) ? body["requestId"] : nil,
262
346
  "visitorId" => body["visitorId"].is_a?(String) ? body["visitorId"] : nil,
263
347
  "confidence" => body["confidence"].is_a?(Numeric) ? body["confidence"] : nil,
264
- "visitor" => body["visitor"].is_a?(Hash) ? body["visitor"] : nil,
348
+ "visitor" => visitor_of(body["visitor"]),
265
349
  "counts" => body["counts"].is_a?(Hash) ? body["counts"] : nil,
266
- # The address (never coordinates), the visitor's counts, one answer to "a bot?" (detected | suspected | not_detected).
350
+ # "network" is the address as the risk engine saw it (never coordinates), passed through as the API answers
351
+ # it: countryCode, region, city, accuracyKm, timeZone, asn, asnOrg, type (isp | hosting | tor | relay: Apple's
352
+ # iCloud Private Relay | unknown), tor, hosting, hostingProvider, proxy (on a public proxy list in the last 30
353
+ # days: context; absent on older servers; the proxy list includes IP2Proxy LITE data available from
354
+ # https://lite.ip2location.com), timezoneMismatch and, absent on older servers (nil when not classified, as
355
+ # for an identification made before them): kind (NETWORK_KINDS, an open list: new values may be added in minor
356
+ # versions), kindSource (address | network | mixed | network_open | name, the operator's name only: shown,
357
+ # never used for a decision), vpn (a VPN company's own address), shared (many browsers used this address on
358
+ # your pages in the last 24 hours: context only), sharedVisitors24h and sharedAccounts24h (at least 1, 2, 5,
359
+ # 10, 100 or 1000; nil when not counted) and lookAlikeMatching (false: this computer was recognised only by
360
+ # its own key, cookie or stored id; true: look-alike matching was allowed; nil: not decided). The shared
361
+ # fields describe the identification's own address: nil when the answer is about another one.
267
362
  "network" => body["network"].is_a?(Hash) ? body["network"] : nil,
268
363
  "velocity" => body["velocity"].is_a?(Hash) ? body["velocity"] : nil,
269
364
  # "bot" is passed through as the API answers it: result (detected | suspected | not_detected), reasons
270
- # (detected ones first, then suspected: webdriver, headless, pointer_synthetic, zero_window, soft_gpu,
271
- # tool_<name>, agent_verified, input_synthetic, agent_pace, cdp, agent_unverified, agent_claimed) and,
272
- # on servers since 2026-11-24 (absent on older ones): type (ai_agent: an AI agent or bot by its own
273
- # identity, or a pause before every step; automation: a driven browser; script: moved or typed like
274
- # software in a browser that shows no driver; or null), tools (automation tools whose marks were on
275
- # the page: selenium, playwright, puppeteer, phantomjs, nightmare, headless_chrome), agent (null, or
276
- # provider, name, category ai_agent | ai_crawler | search_crawler, identity verified | unverified |
277
- # claimed: a Web Bot Auth signature checked against the provider's published keys, or the user agent
278
- # only) and input (insert_no_keys, uniform_keys, instant_keys, center_press, agent_pace).
365
+ # (detected ones first: webdriver, headless, tool_<name>, agent_verified; then suspected: pointer_synthetic,
366
+ # input_synthetic, agent_pace, zero_window, headless_window, emulator, cdp, cdp_input (a press with no
367
+ # pressure: only the DevTools protocol sends it), input_no_focus (a click or key into a page that was not in
368
+ # front), insert_text_bulk (text that arrived whole, no key pressed), scripted_click (a form sent with no
369
+ # click or key), agent_unverified, agent_claimed; soft_gpu (software graphics) only next to another) and, on
370
+ # servers since 2026-11-24 (absent on older ones): type (ai_agent: an AI agent or bot by its own identity or
371
+ # its marks on the page, or a pause before every step; automation: a driven browser; script: moved or typed
372
+ # like software in a browser that shows no driver; or null), tools (the automation tools and AI agents whose
373
+ # marks were on the page: selenium, playwright, puppeteer, phantomjs, nightmare, headless_chrome and, on
374
+ # servers since 2026-11-25, claude_agent (the Claude app's browser or Claude in Chrome), comet_agent
375
+ # (Perplexity Comet), genspark_agent, browser_use, stagehand, skyvern), agent (null, or provider, name,
376
+ # category ai_agent | ai_crawler | search_crawler, identity verified | unverified | claimed: a Web Bot Auth
377
+ # signature checked against the provider's published keys, or the user agent only) and input
378
+ # (insert_no_keys, uniform_keys, instant_keys, center_press, agent_pace). New tools and reasons may be added.
279
379
  "bot" => body["bot"].is_a?(Hash) ? body["bot"] : nil,
280
380
  # Did this account use the device before (nil before an account is named); see parse_account_device.
281
381
  "accountDevice" => parse_account_device(body["accountDevice"]),
@@ -2,6 +2,6 @@
2
2
 
3
3
  module Touchque
4
4
  module DeviceRisk
5
- VERSION = "1.0.0"
5
+ VERSION = "1.1.0"
6
6
  end
7
7
  end
@@ -4,12 +4,13 @@ require_relative "device_risk/version"
4
4
  require_relative "device_risk/errors"
5
5
  require_relative "device_risk/util"
6
6
  require_relative "device_risk/http"
7
+ require_relative "device_risk/bot_check"
7
8
  require_relative "device_risk/client"
8
9
 
9
10
  module Touchque
10
11
  # Touchque Device Risk: a visitor ID for every browser on your sign-up, password-reset,
11
- # sign-in or approval page, a risk verdict for the account it is used for, and the
12
- # abuse your server sees.
12
+ # sign-in or approval page, a risk verdict for the account it is used for, the abuse your
13
+ # server sees, and which bot sent a request your server received (bot_check).
13
14
  #
14
15
  # # TQ_API_KEY=tq_... TQ_API_SECRET=...
15
16
  # dr = Touchque::DeviceRisk::Client.new
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: touchque-device-risk
3
3
  version: !ruby/object:Gem::Version
4
- version: 1.0.0
4
+ version: 1.1.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Touchque
@@ -23,6 +23,7 @@ files:
23
23
  - README.md
24
24
  - lib/touchque-device-risk.rb
25
25
  - lib/touchque/device_risk.rb
26
+ - lib/touchque/device_risk/bot_check.rb
26
27
  - lib/touchque/device_risk/client.rb
27
28
  - lib/touchque/device_risk/errors.rb
28
29
  - lib/touchque/device_risk/http.rb