touchque-device-risk 1.0.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 ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: e972e85766a804a3e99663f810ce1fc14c825db4ff4cea8a4842bb9e66ef507f
4
+ data.tar.gz: 5a08990ff45afede5dffa29b05691c2229fd07d3b3b1f88f85245e869f1ecc96
5
+ SHA512:
6
+ metadata.gz: be8ae91ea52fe380978efe901aeb79fb73672d26e7ee13b48424510f5b1395221639e35493cfbad4329fab8bbca02bc173e7aacb500dddc3c01857f8b6301bbf
7
+ data.tar.gz: 7d109e3c9769ad474b21152476f4a90e6da0034c232899828b0779282116c18c7b3f1393e4140d75dba741f9328085f6e9044f2972c762d29794e86e8ff7c51c
data/CHANGELOG.md ADDED
@@ -0,0 +1,14 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file. The
4
+ format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
5
+
6
+ ## [1.0.0] — 2026-11-24
7
+
8
+ ### Added
9
+ - **Touchque Device Risk as its own gem.** Device risk leaves the main `touchque` gem (6.0.0 no longer has `tq.device_risk`): `Touchque::DeviceRisk::Client.new(api_key:, api_secret:, base_url:, timeout:)` with its own small client (the same API key and secret, `TQ_API_KEY` / `TQ_API_SECRET` / `TQ_API_URL`, the same request signing, timeout and errors as the main gem, under `Touchque::DeviceRisk`). `require "touchque/device_risk"`.
10
+ - `check(request_id, event:, external_username:, client_ip:, device_risk:)` (`POST /device-risk/check`), `get_event(request_id)` (`GET /device-risk/events/{requestId}`), `search_events(...)` (`GET /device-risk/events`) and `Client.parse_check`, as they were on `tq.device_risk`.
11
+ - **`activity(type:, ...)`: report what a visitor did that your server saw** (`POST /device-risk/activity`): `type:` (`payment_attempt`, `login_failed`, `not_found`, `forbidden`, `otp_sent`, `code_failed`), `request_id:`, `visitor_id:`, `client_ip:`, `external_username:`, `outcome:` (`approved`, `declined`, `error`), `card:` (`{ bin: 6-8 digits, last4: 4 digits }`), `phone:`, `path:`. Answers `recorded`, `visitorId`, `signals` (`abuse_card_testing`, `abuse_card_shared`, `abuse_login_failures`, `abuse_probing`, `abuse_otp_pumping`, `abuse_code_guessing`) and `pathClass`. A card that is not exactly a BIN and the last 4 digits (a card number, a `number` or `pan` key) raises `ConfigError` before anything is sent.
12
+ - `check` answers carry `suspect` (the suspect score in shadow: `score` 0-100, `band`, `wouldDo`, `mode`, `reasons` with `code`, `points`, `by`, `text`) and `accountDevice` (`status` known, likely, new or first, `visitorId`, `since`); `Client.parse_suspect` and `Client.parse_account_device` read them from `get_event` answers and `search_events` rows. `Client::MATCHED_BY` lists `fpc` (the first-party cookie).
13
+ - `Touchque::DeviceRisk::WebhookEvents::DEVICE_RISK_SIGNAL` and `DEVICE_RISK_ALERT` (were `Webhook::EVENT_DEVICE_RISK_*` in the main gem).
14
+ - The `bot` hash of `check`, `get_event` and each `search_events` item carries `type` (`ai_agent`, `automation`, `script` or nil), `tools`, `agent` and `input` on servers since 2026-11-24; the API can return the signal codes `device_input_synthetic` and `device_ai_agent` (a number-matched step-up only, never a block).
data/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Touchque
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,125 @@
1
+ # touchque-device-risk
2
+
3
+ The official Ruby server SDK for **Touchque Device Risk**: a visitor ID for every browser on your
4
+ sign-up, password-reset, sign-in or approval page, a risk verdict for the account it is used for, and
5
+ the abuse your server sees (card testing, failed sign-ins, probing, SMS pumping, code guessing).
6
+
7
+ Device Risk is a paid add-on: it answers 409 `device_risk_off` until your workspace turns it on in the
8
+ [Touchque dashboard](https://dashboard.touchque.com).
9
+
10
+ Full docs: **[support.touchque.com](https://support.touchque.com)**
11
+
12
+ ## Install
13
+
14
+ ```ruby
15
+ # Gemfile
16
+ gem "touchque-device-risk"
17
+ ```
18
+
19
+ ## Setup
20
+
21
+ The same API key and secret as the main Touchque gem:
22
+
23
+ ```bash
24
+ TQ_API_KEY=tq_your_key
25
+ TQ_API_SECRET=your_api_secret
26
+ ```
27
+
28
+ ```ruby
29
+ require "touchque/device_risk"
30
+
31
+ dr = Touchque::DeviceRisk::Client.new # reads the environment
32
+ dr = Touchque::DeviceRisk::Client.new(api_key: key, api_secret: secret, timeout: 10) # or explicit (seconds)
33
+ ```
34
+
35
+ Every call is signed with your API secret: keep it on your server. Thread-safe: create one and reuse it.
36
+
37
+ ## Check a page's identification
38
+
39
+ The page identifies the browser with `@touchque/device-risk` (the script tag `device.js` fills a
40
+ `touchque_request_id` field in your form, or `identify({ siteKey, purpose })` gives a `requestId`). Never
41
+ trust the page's copy: check it on your server.
42
+
43
+ ```ruby
44
+ r = dr.check(params[:touchque_request_id], event: "sign_up", external_username: email, client_ip: request.remote_ip)
45
+ ask_for_email_code if r["stepUp"] # a step-up, never a refusal on it alone
46
+ ```
47
+
48
+ - Pass the field as it came: missing, empty, made up or expired is still a verdict (`"report"`:
49
+ `missing`, `unknown`, `expired`, `invalid`; the signal `device_identification_missing`), never an exception.
50
+ - `event:`: `sign_in` (default), `sign_up`, `password_reset` or `approval` (`Client::EVENTS`).
51
+ - The answer: `report`, `requestId`, `visitorId`, `confidence`, `visitor`, `counts`, `network`,
52
+ `velocity`, `bot`, `accountDevice`, `suspect`, `signals`, `stepUp`, `wouldStepUp`, `requires`, `mode`,
53
+ `engine`, `caseCode`. It fails toward asking: `stepUp` is true unless the API says exactly false.
54
+ - `suspect` is the suspect score, in shadow (it decides nothing yet): `score` 0-100, `band`
55
+ (low, medium, high, critical), `wouldDo` (allow, number_match, passkey, block) and `reasons`
56
+ (`code`, `points`, `by`: server, site, page or brand, `text`).
57
+ - `accountDevice`: did this account use the device before? `status` known, likely, new or first.
58
+
59
+ For a sign-in approved on the phone with the main Touchque gem, pass the same field as
60
+ `device_risk_request_id:` to its `login.request` or `risk.check` instead.
61
+
62
+ ## Read and search identifications
63
+
64
+ ```ruby
65
+ event = dr.get_event("dre_...") # the trusted identification, the verdict, accountDevice, suspect
66
+ suspect = Touchque::DeviceRisk::Client.parse_suspect(event["suspect"])
67
+
68
+ cursor = nil
69
+ loop do
70
+ page = dr.search_events(account: "ada@example.com", step_up: true, limit: 50, cursor: cursor)
71
+ page["events"].each { |e| puts e["requestId"] }
72
+ break unless (cursor = page["nextCursor"])
73
+ end
74
+ ```
75
+
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`.
79
+
80
+ ## Report what your server saw
81
+
82
+ ```ruby
83
+ a = dr.activity(type: "payment_attempt", request_id: params[:touchque_request_id], client_ip: request.remote_ip,
84
+ external_username: email, outcome: "declined", card: { bin: "411111", last4: "1111" })
85
+ stop_taking_cards if a["signals"].include?("abuse_card_testing")
86
+ ```
87
+
88
+ - `type:`: `payment_attempt`, `login_failed`, `not_found`, `forbidden` (with `path:`), `otp_sent` (with
89
+ `phone:`), `code_failed` (a wrong coupon or gift-card code).
90
+ - Name the visitor with `request_id:`, `visitor_id:` or `client_ip:` (a bot that never runs your page
91
+ still counts on its network).
92
+ - The answer: `recorded`, `visitorId`, `signals` (`abuse_card_testing`, `abuse_card_shared`,
93
+ `abuse_login_failures`, `abuse_probing`, `abuse_otp_pumping`, `abuse_code_guessing`) and, for a path,
94
+ `pathClass`. For 24 hours the visitor's next checks carry those signals and the suspect score weighs them.
95
+ - A card is its BIN (6 to 8 digits) and last 4 digits only. Anything else (a card number, a `number`
96
+ or `pan` key) raises `Touchque::DeviceRisk::ConfigError` before anything is sent.
97
+
98
+ ## Webhooks
99
+
100
+ Verify Touchque webhooks with the main Touchque gem, then compare `event` with
101
+ `Touchque::DeviceRisk::WebhookEvents::DEVICE_RISK_SIGNAL` (a signal that asks for more) or
102
+ `DEVICE_RISK_ALERT` (an alert rule of the workspace went off).
103
+
104
+ ## Errors
105
+
106
+ All under `Touchque::DeviceRisk`, subclasses of `Error`:
107
+
108
+ - `ConfigError`: a wrong argument or configuration (nothing was sent).
109
+ - `APIError`: the API answered an error (`status`, `code`, `retry_after`, `case_code`); a redirect is an error too.
110
+ - `FeatureError` (`FeatureNotInPlanError`, `FeatureReadOnlyError`, `FeatureOffError`): Device risk is not
111
+ in your organization's plan, being turned off, or switched off on this deployment.
112
+ - `NetworkError`: the request never reached Touchque.
113
+
114
+ ## Tests
115
+
116
+ ```bash
117
+ bundle install
118
+ bundle exec rake test
119
+ ```
120
+
121
+ The tests run against the shared fake Touchque API (`testing/fake-touchque-api.mjs`, Node.js).
122
+
123
+ ## License
124
+
125
+ MIT
@@ -0,0 +1,297 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Touchque
4
+ module DeviceRisk
5
+ DEFAULT_BASE_URL = "https://api.touchque.com"
6
+
7
+ # Touchque Device Risk (a paid add-on, off until your workspace turns it on): a visitor
8
+ # ID for every browser on your sign-up, password-reset, sign-in or approval page, and
9
+ # what your server saw it do. The page identifies with @touchque/device-risk (the
10
+ # script tag, or identify({ siteKey, purpose }), which gives { visitorId, requestId,
11
+ # confidence }) and sends you the requestId. Never trust the page's copy: read the
12
+ # identification here (get_event) or check it for an account (check). Touchque keeps
13
+ # keyed hashes only, with a key of your workspace alone, and its risk engine decides.
14
+ #
15
+ # Every signal only ever asks for more: "stepUp" means an extra check on this page (an
16
+ # emailed code, a passkey, a number-matched approval), never a refusal. For sign-ins
17
+ # approved on the phone with the main Touchque gem, pass the requestId to its
18
+ # login.request / risk.check as device_risk_request_id: instead. Collect it only on
19
+ # these pages and name it in your privacy notice.
20
+ #
21
+ # With the script tag (device.js), the form arrives with touchque_request_id:
22
+ #
23
+ # dr = Touchque::DeviceRisk::Client.new # TQ_API_KEY, TQ_API_SECRET
24
+ # r = dr.check(params[:touchque_request_id], event: "sign_in", external_username: email)
25
+ #
26
+ # Pass it as it came. Missing, empty, made up or expired, it is still a verdict
27
+ # ("report" missing, unknown, expired; the signal device_identification_missing), never
28
+ # an exception: a page without the tag, or with it blocked, only gets the visitor a
29
+ # step-up.
30
+ #
31
+ # Thread-safe: create one and reuse it.
32
+ class Client
33
+ # @api private: the ConfigError message for a missing key or secret.
34
+ MISSING_KEYS = "Set TQ_API_KEY and TQ_API_SECRET (or pass api_key: and api_secret:)."
35
+ # The pages a device report may come from.
36
+ EVENTS = %w[sign_in sign_up password_reset approval].freeze
37
+ # What the page had sent: ok, replayed, or no usable identification.
38
+ REPORTS = %w[ok replayed missing unknown expired invalid].freeze
39
+ # How a visitor was recognised (an event's "matchedBy").
40
+ MATCHED_BY = %w[key fpc sid traits new].freeze
41
+ # What your server saw the visitor do (activity's type:).
42
+ ACTIVITY_TYPES = %w[payment_attempt login_failed not_found forbidden otp_sent code_failed].freeze
43
+ # payment_attempt: what the payment provider answered.
44
+ ACTIVITY_OUTCOMES = %w[approved declined error].freeze
45
+ # The abuse codes an activity can raise. New codes may be added.
46
+ ACTIVITY_SIGNALS = %w[abuse_card_testing abuse_card_shared abuse_login_failures abuse_probing abuse_otp_pumping abuse_code_guessing].freeze
47
+ # The class of a not_found / forbidden path.
48
+ PATH_CLASSES = %w[admin wordpress secrets source db_admin debug shell other].freeze
49
+ REQUEST_ID = /\Adre_[A-Za-z0-9_-]{22}\z/
50
+ 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
52
+ CARD_NUMBER = "never send the card number: card: is { bin: 6 to 8 digits, last4: 4 digits }"
53
+
54
+ # Anything left nil falls back to the environment: TQ_API_KEY, TQ_API_SECRET and
55
+ # TQ_API_URL (default https://api.touchque.com): the same key and secret as the main
56
+ # Touchque gem. +timeout+ is seconds per request.
57
+ def initialize(api_key: nil, api_secret: nil, base_url: nil, timeout: 10)
58
+ api_key ||= ENV.fetch("TQ_API_KEY", nil)
59
+ api_secret ||= ENV.fetch("TQ_API_SECRET", nil)
60
+ base_url ||= ENV["TQ_API_URL"].to_s.empty? ? DEFAULT_BASE_URL : ENV.fetch("TQ_API_URL")
61
+ raise ConfigError, MISSING_KEYS if api_key.to_s.empty? || api_secret.to_s.empty?
62
+ raise ConfigError, "api_key must start with \"tq_\". Did you accidentally swap api_key and api_secret?" unless api_key.start_with?("tq_")
63
+
64
+ Util.assert_safe_url!(base_url, "base_url")
65
+ @http = HTTP.new(api_key: api_key, api_secret: api_secret, base_url: base_url.chomp("/"), timeout: timeout)
66
+ end
67
+
68
+ # Never shows the API key or secret.
69
+ def inspect
70
+ "#<#{self.class.name} base_url=#{@http.base_url.inspect}>"
71
+ end
72
+
73
+ # Checks the page's identification for an account: binds it (one account per
74
+ # identification, 15 minutes) and asks the risk engine. Pass the form field as it came:
75
+ # nil, empty or made up is still a verdict ("report" missing, unknown), never an
76
+ # exception. 409 device_risk_off until your workspace turns Device risk on.
77
+ # device_risk: instead of request_id, the page's report (collect()).
78
+ #
79
+ # r = dr.check(params[:touchque_request_id], event: "sign_up", external_username: email, client_ip: request.remote_ip)
80
+ # ask_for_email_code if r["stepUp"] # never refuse on it alone
81
+ def check(request_id = nil, event: "sign_in", external_username: nil, client_ip: nil, device_risk: nil)
82
+ raise ConfigError, "check(): event must be one of #{EVENTS.join(", ")}" unless EVENTS.include?(event)
83
+
84
+ body = {}
85
+ if request_id.is_a?(String) && !request_id.empty?
86
+ body["requestId"] = request_id[0, 64]
87
+ elsif !device_risk.to_s.empty?
88
+ body["deviceRisk"] = device_risk
89
+ end
90
+ body["event"] = event
91
+ body["externalUsername"] = external_username unless external_username.to_s.empty?
92
+ body["clientIp"] = client_ip unless client_ip.to_s.empty?
93
+ self.class.parse_check(@http.post("/device-risk/check", body))
94
+ end
95
+
96
+ # Your workspace's identifications, newest first, one page at a time
97
+ # (GET /device-risk/events): a date range (from:/to: YYYY-MM-DD or ISO times; 7 days by
98
+ # default, at most 90, within your retention) and any of the filters. ip: is an address
99
+ # or a CIDR range and is never returned. Pass "nextCursor" back as cursor: until it is
100
+ # nil; do not page by moving the dates. A search that would read too much is a 422
101
+ # search_too_broad: narrow the range or add a filter. Each event may carry "suspect"
102
+ # (see parse_suspect) and "matchedBy" (MATCHED_BY).
103
+ # { "events" => [...], "nextCursor" => String | nil, "from" => String, "to" => String }.
104
+ def search_events(step_up: nil, limit: nil, **filters)
105
+ unknown = filters.keys - SEARCH_FILTERS.keys
106
+ raise ConfigError, "search_events() does not know #{unknown.join(', ')}" unless unknown.empty?
107
+ raise ConfigError, "search_events() limit must be 1 to 100" unless limit.nil? || (limit.is_a?(Integer) && limit.between?(1, 100))
108
+
109
+ params = {}
110
+ filters.each { |k, v| params[SEARCH_FILTERS[k]] = v if v.is_a?(String) && !v.empty? }
111
+ params["stepUp"] = step_up ? "true" : "false" if [true, false].include?(step_up)
112
+ params["limit"] = limit.to_s if limit
113
+ raw = @http.get("/device-risk/events", params) || {}
114
+ cursor = raw["nextCursor"]
115
+ { "events" => raw["events"].is_a?(Array) ? raw["events"] : [],
116
+ "nextCursor" => cursor.is_a?(String) && !cursor.empty? ? cursor : nil,
117
+ "from" => raw["from"].to_s, "to" => raw["to"].to_s }
118
+ end
119
+
120
+ # 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.
123
+ def get_event(request_id)
124
+ raise ConfigError, "get_event() needs a request_id (dre_...)" unless request_id.is_a?(String) && REQUEST_ID.match?(request_id)
125
+
126
+ @http.get("/device-risk/events/#{request_id}")
127
+ end
128
+
129
+ # Reports what a visitor did that your server saw (POST /device-risk/activity):
130
+ # payments, failed sign-ins, probing, SMS codes, wrong codes. Touchque counts it per
131
+ # visitor and per network and answers the abuse codes it raised; for 24 hours the
132
+ # visitor's next identifications and checks carry them (shadow: they decide nothing on
133
+ # their own).
134
+ #
135
+ # a = dr.activity(type: "payment_attempt", request_id: params[:touchque_request_id],
136
+ # client_ip: request.remote_ip, outcome: "declined", card: { bin: "411111", last4: "1111" })
137
+ # stop_taking_cards if a["signals"].include?("abuse_card_testing")
138
+ #
139
+ # Name the visitor with request_id: (the form field as it came), visitor_id: (tqv_…) or
140
+ # client_ip:. outcome: is ACTIVITY_OUTCOMES (payment_attempt), phone: is for otp_sent,
141
+ # path: for not_found / forbidden. Never send a card number: a card that is not exactly
142
+ # { bin: 6-8 digits, last4: 4 digits } raises ConfigError before anything is sent.
143
+ # { "recorded" => Boolean, "visitorId" => String | nil, "signals" => [String] }, plus
144
+ # "pathClass" (PATH_CLASSES) for a path.
145
+ def activity(type:, request_id: nil, visitor_id: nil, client_ip: nil, external_username: nil, outcome: nil, card: nil,
146
+ phone: nil, path: nil)
147
+ body = self.class.activity_body(type: type, request_id: request_id, visitor_id: visitor_id, client_ip: client_ip,
148
+ external_username: external_username, outcome: outcome, card: card, phone: phone, path: path)
149
+ self.class.parse_activity(@http.post("/device-risk/activity", body))
150
+ end
151
+
152
+ # @api private: activity's request body, validated.
153
+ def self.activity_body(type:, request_id:, visitor_id:, client_ip:, external_username:, outcome:, card:, phone:, path:)
154
+ raise ConfigError, "activity(): type must be one of #{ACTIVITY_TYPES.join(", ")}" unless ACTIVITY_TYPES.include?(type)
155
+
156
+ body = { "type" => type }
157
+ # The form field as it came: anything but a string is no identification.
158
+ body["requestId"] = request_id if request_id.is_a?(String) && !request_id.empty?
159
+ { "visitorId" => visitor_id, "clientIp" => client_ip, "externalUsername" => external_username,
160
+ "phone" => phone, "path" => path }.each do |key, value|
161
+ next if value.nil? || value == ""
162
+ raise ConfigError, "activity(): #{key} must be a String" unless value.is_a?(String)
163
+
164
+ body[key] = value
165
+ end
166
+ raise ConfigError, "activity(): name the visitor: request_id, visitor_id or client_ip" unless body.key?("requestId") || body.key?("visitorId") || body.key?("clientIp")
167
+ raise ConfigError, "activity(): external_username is at most 255 characters" if body["externalUsername"].to_s.length > 255
168
+ raise ConfigError, "activity(): path is at most 2048 characters" if body["path"].to_s.length > 2048
169
+ raise ConfigError, "activity(): phone must be 6 to 15 digits, with an optional leading +" if body.key?("phone") && !body["phone"].match?(/\A\+?[0-9]{6,15}\z/)
170
+
171
+ unless outcome.nil?
172
+ raise ConfigError, "activity(): outcome must be one of #{ACTIVITY_OUTCOMES.join(", ")}" unless ACTIVITY_OUTCOMES.include?(outcome)
173
+
174
+ body["outcome"] = outcome
175
+ end
176
+ body["card"] = card_body(card) unless card.nil?
177
+ body
178
+ end
179
+
180
+ # A card as its BIN and last 4 digits only; anything that could be a card number is refused.
181
+ def self.card_body(card)
182
+ raise ConfigError, "activity(): #{CARD_NUMBER}" unless card.is_a?(Hash)
183
+
184
+ c = card.transform_keys(&:to_s)
185
+ raise ConfigError, "activity(): #{CARD_NUMBER}" unless c.keys.sort == %w[bin last4]
186
+
187
+ bin = c["bin"]
188
+ last4 = c["last4"]
189
+ unless bin.is_a?(String) && last4.is_a?(String) && bin.match?(/\A[0-9]{6,8}\z/) && last4.match?(/\A[0-9]{4}\z/)
190
+ raise ConfigError, "activity(): #{CARD_NUMBER}"
191
+ end
192
+
193
+ { "bin" => bin, "last4" => last4 }
194
+ end
195
+ private_class_method :card_body
196
+
197
+ # Reads an activity answer: "recorded" only when it says exactly true; unknown path
198
+ # classes are dropped.
199
+ def self.parse_activity(raw)
200
+ body = raw.is_a?(Hash) ? raw : {}
201
+ out = { "recorded" => body["recorded"] == true,
202
+ "visitorId" => body["visitorId"].is_a?(String) ? body["visitorId"] : nil,
203
+ "signals" => body["signals"].is_a?(Array) ? body["signals"].grep(String) : [] }
204
+ out["pathClass"] = body["pathClass"] if PATH_CLASSES.include?(body["pathClass"])
205
+ out
206
+ end
207
+
208
+ # The suspect score of an answer, event or search row (in shadow: it decides nothing
209
+ # yet), or nil: "score" 0-100, "band" (low | medium | high | critical), "wouldDo"
210
+ # (allow | number_match | passkey | block: what it would ask for), "mode" ("shadow")
211
+ # and "reasons" ("code", "points", "by": server | site | page | brand, "text").
212
+ def self.parse_suspect(raw)
213
+ return nil unless raw.is_a?(Hash) && raw["score"].is_a?(Integer)
214
+
215
+ reasons = (raw["reasons"].is_a?(Array) ? raw["reasons"] : []).filter_map do |r|
216
+ next unless r.is_a?(Hash) && r["code"].is_a?(String)
217
+
218
+ { "code" => r["code"], "points" => r["points"].is_a?(Integer) ? r["points"] : 0,
219
+ "by" => %w[server site page brand].include?(r["by"]) ? r["by"] : "server",
220
+ "text" => r["text"].is_a?(String) ? r["text"] : "" }
221
+ end
222
+ score = raw["score"].clamp(0, 100)
223
+ band = if %w[low medium high critical].include?(raw["band"]) then raw["band"]
224
+ elsif score >= 80 then "critical"
225
+ elsif score >= 60 then "high"
226
+ elsif score >= 30 then "medium"
227
+ else "low"
228
+ end
229
+ { "score" => score, "band" => band,
230
+ "wouldDo" => %w[allow number_match passkey block].include?(raw["wouldDo"]) ? raw["wouldDo"] : "allow",
231
+ "mode" => "shadow", "reasons" => reasons }
232
+ end
233
+
234
+ # Did this account use the device before (once a check names the account), or nil:
235
+ # "status" known | likely | new | first, "visitorId" (likely: the account's visitor it
236
+ # looks like) and "since" (known: the account's first identification on it).
237
+ def self.parse_account_device(raw)
238
+ return nil unless raw.is_a?(Hash) && %w[known likely new first].include?(raw["status"])
239
+
240
+ out = { "status" => raw["status"] }
241
+ out["visitorId"] = raw["visitorId"] if raw["visitorId"].is_a?(String)
242
+ out["since"] = raw["since"] if raw["since"].is_a?(String)
243
+ out
244
+ end
245
+
246
+ # Reads an answer, failing toward asking: "stepUp" is true unless it says exactly
247
+ # false; junk signals are dropped.
248
+ def self.parse_check(raw)
249
+ body = raw.is_a?(Hash) ? raw : {}
250
+ signals = (body["signals"].is_a?(Array) ? body["signals"] : []).filter_map do |s|
251
+ next unless s.is_a?(Hash) && s["code"].is_a?(String)
252
+
253
+ item = { "code" => s["code"], "text" => s["text"].is_a?(String) ? s["text"] : "",
254
+ "strength" => %w[passkey none].include?(s["strength"]) ? s["strength"] : "number_match" }
255
+ item["enforced"] = s["enforced"] if [true, false].include?(s["enforced"])
256
+ item["evidence"] = s["evidence"] if s["evidence"].is_a?(Hash)
257
+ item
258
+ end
259
+ out = {
260
+ "report" => REPORTS.include?(body["report"]) ? body["report"] : "invalid",
261
+ "requestId" => body["requestId"].is_a?(String) ? body["requestId"] : nil,
262
+ "visitorId" => body["visitorId"].is_a?(String) ? body["visitorId"] : nil,
263
+ "confidence" => body["confidence"].is_a?(Numeric) ? body["confidence"] : nil,
264
+ "visitor" => body["visitor"].is_a?(Hash) ? body["visitor"] : nil,
265
+ "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).
267
+ "network" => body["network"].is_a?(Hash) ? body["network"] : nil,
268
+ "velocity" => body["velocity"].is_a?(Hash) ? body["velocity"] : nil,
269
+ # "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).
279
+ "bot" => body["bot"].is_a?(Hash) ? body["bot"] : nil,
280
+ # Did this account use the device before (nil before an account is named); see parse_account_device.
281
+ "accountDevice" => parse_account_device(body["accountDevice"]),
282
+ # The suspect score, in shadow (nil from servers that do not send it); see parse_suspect.
283
+ "suspect" => parse_suspect(body["suspect"]),
284
+ "signals" => signals,
285
+ "stepUp" => body["stepUp"] != false,
286
+ "wouldStepUp" => body["wouldStepUp"] == true,
287
+ "requires" => %w[number_match passkey].include?(body["requires"]) ? body["requires"] : "none",
288
+ "mode" => body["mode"] == "enforce" ? "enforce" : "shadow",
289
+ # The engine's state for this check; "unavailable" when the risk engine could not be reached and the verdict is a safe default.
290
+ "engine" => body["engine"].is_a?(String) ? body["engine"] : nil
291
+ }
292
+ out["caseCode"] = body["caseCode"] if body["caseCode"].is_a?(String)
293
+ out
294
+ end
295
+ end
296
+ end
297
+ end
@@ -0,0 +1,108 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Touchque
4
+ module DeviceRisk
5
+ # Base class of every error this gem raises.
6
+ class Error < StandardError; end
7
+
8
+ # Touchque answered with an error (status 400 or more, or a redirect). +status+ is the
9
+ # HTTP status, +code+ the machine-readable code (+device_risk_off+,
10
+ # +card_number_not_allowed+...) and +data+ the decoded JSON body.
11
+ class APIError < Error
12
+ attr_reader :status, :data
13
+
14
+ def initialize(status, data = nil, message = nil)
15
+ @status = status
16
+ @data = data.is_a?(Hash) ? data : {}
17
+ super(message || @data["message"] || @data["error"] || "Touchque API error: HTTP #{status}")
18
+ end
19
+
20
+ # Machine-readable error code, e.g. "device_risk_off".
21
+ def code
22
+ @data["code"]
23
+ end
24
+
25
+ # The API's +error+ field.
26
+ def error
27
+ @data["error"]
28
+ end
29
+
30
+ # Seconds to wait before retrying (429).
31
+ def retry_after
32
+ @data["retryAfter"]
33
+ end
34
+
35
+ # "Why?" case code of a refusal (+K7P-2QX+): your team opens the decision by it in
36
+ # the dashboard.
37
+ def case_code
38
+ @data["caseCode"].is_a?(String) ? @data["caseCode"] : nil
39
+ end
40
+
41
+ # The error for an answer: a FeatureError subclass for the three feature
42
+ # codes, else APIError.
43
+ def self.for(status, data = nil, message = nil)
44
+ klass = data.is_a?(Hash) ? FeatureError::BY_ERROR[data["error"]] : nil
45
+ (klass || APIError).new(status, data, message)
46
+ end
47
+ end
48
+
49
+ # The organization behind your workspace cannot use this feature here (HTTP
50
+ # 403). +feature_reason+:
51
+ # - +:not_in_plan+: not in its plan (+feature_not_in_plan+); an owner or admin
52
+ # adds it in the Touchque dashboard;
53
+ # - +:read_only+: being turned off (+feature_read_only+); reads still work for
54
+ # 14 days, changes are refused;
55
+ # - +:off+: switched off on this Touchque deployment (+feature_off+).
56
+ # +feature+ is the catalog id (+device_risk+). An APIError, so existing +rescue+
57
+ # blocks still catch it; rescue one of the three subclasses to tell them apart.
58
+ class FeatureError < APIError
59
+ REASON = nil
60
+
61
+ # The catalog id of the feature, or nil.
62
+ def feature
63
+ @data["feature"].is_a?(String) ? @data["feature"] : nil
64
+ end
65
+
66
+ # +:not_in_plan+, +:read_only+ or +:off+.
67
+ def feature_reason
68
+ self.class::REASON
69
+ end
70
+ end
71
+
72
+ # +feature_not_in_plan+: the feature is not in the organization's plan.
73
+ class FeatureNotInPlanError < FeatureError
74
+ REASON = :not_in_plan
75
+ end
76
+
77
+ # +feature_read_only+: the feature is being turned off; reads work, changes are refused.
78
+ class FeatureReadOnlyError < FeatureError
79
+ REASON = :read_only
80
+ end
81
+
82
+ # +feature_off+: the feature is switched off on this Touchque deployment.
83
+ class FeatureOffError < FeatureError
84
+ REASON = :off
85
+ end
86
+
87
+ FeatureError::BY_ERROR = {
88
+ "feature_not_in_plan" => FeatureNotInPlanError,
89
+ "feature_read_only" => FeatureReadOnlyError,
90
+ "feature_off" => FeatureOffError,
91
+ }.freeze
92
+
93
+ # The request never reached Touchque (DNS, connection refused, timeout). Unlike
94
+ # APIError, generally safe to retry.
95
+ class NetworkError < Error
96
+ def initialize(message)
97
+ super("Touchque: network request failed: #{message}")
98
+ end
99
+ end
100
+
101
+ # Missing or invalid configuration, or a wrong argument (raised before any request).
102
+ class ConfigError < Error
103
+ def initialize(message)
104
+ super("Touchque config error: #{message}")
105
+ end
106
+ end
107
+ end
108
+ end
@@ -0,0 +1,110 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "net/http"
4
+ require "openssl"
5
+ require "uri"
6
+
7
+ module Touchque
8
+ module DeviceRisk
9
+ # @api private: every partner API call, signed with HMAC-SHA256 over
10
+ # "METHOD:pathWithQuery:timestamp:nonce:sha256(body)", sent once, never redirected.
11
+ # The same signing as the main Touchque gem.
12
+ class HTTP
13
+ MAX_RESPONSE_BYTES = 10 * 1024 * 1024
14
+ # What a request that never got a usable answer raises (every Errno, a garbled
15
+ # answer, TLS): NetworkError for the caller.
16
+ NETWORK_ERRORS = [Timeout::Error, SystemCallError, SocketError, OpenSSL::SSL::SSLError, IOError,
17
+ Net::HTTPBadResponse, Net::HTTPHeaderSyntaxError, Net::ProtocolError].freeze
18
+
19
+ attr_reader :base_url
20
+
21
+ def initialize(api_key:, api_secret:, base_url:, timeout:)
22
+ @api_key = api_key
23
+ @api_secret = api_secret
24
+ @base_url = base_url
25
+ @timeout = timeout
26
+ @uri = URI.parse(base_url)
27
+ end
28
+
29
+ # Never shows the API key or secret (logs, consoles, error reporters).
30
+ def inspect
31
+ "#<#{self.class.name} base_url=#{@base_url.inspect}>"
32
+ end
33
+
34
+ def get(path, params = nil)
35
+ send_request("GET", path + self.class.build_query(params), nil)
36
+ end
37
+
38
+ def post(path, body = {})
39
+ send_request("POST", path, body || {})
40
+ end
41
+
42
+ # Deterministic query string: keys sorted, values URL-encoded, "?"-prefixed (or "").
43
+ def self.build_query(params)
44
+ return "" if params.nil?
45
+
46
+ pairs = params.map { |k, v| [k.to_s, v] }.reject { |_, v| v.nil? }.sort_by(&:first)
47
+ return "" if pairs.empty?
48
+
49
+ "?" + pairs.map { |k, v| "#{Util.seg(k)}=#{Util.seg(v.to_s)}" }.join("&")
50
+ end
51
+
52
+ def self.sign(secret, method, path_with_query, body, timestamp, nonce)
53
+ message = "#{method.upcase}:#{path_with_query}:#{timestamp}:#{nonce}:#{Util.sha256_hex(body)}"
54
+ Util.hmac_hex(secret, message)
55
+ end
56
+
57
+ private
58
+
59
+ def send_request(method, path_with_query, body)
60
+ body_text = body.nil? ? "" : Util.json(Util.stringify(body))
61
+ timestamp = Util.now_ms.to_s
62
+ nonce = Util.random_hex(16)
63
+ klass = { "GET" => Net::HTTP::Get, "POST" => Net::HTTP::Post }.fetch(method)
64
+ req = klass.new(@uri.path.chomp("/") + path_with_query)
65
+ req["x-api-key"] = @api_key
66
+ req["x-signature"] = self.class.sign(@api_secret, method, path_with_query, body_text, timestamp, nonce)
67
+ req["x-timestamp"] = timestamp
68
+ req["x-nonce"] = nonce
69
+ req["Accept"] = "application/json"
70
+ req["User-Agent"] = "touchque-device-risk-ruby/#{VERSION}"
71
+ unless body.nil?
72
+ req["Content-Type"] = "application/json"
73
+ req.body = body_text
74
+ end
75
+ res = perform(req)
76
+ text = res.body.to_s.dup.force_encoding("UTF-8")
77
+ status = res.code.to_i
78
+ data = Util.parse_json(text)
79
+ if status >= 300
80
+ data = {} unless data.is_a?(Hash)
81
+ if data["retryAfter"].nil? && res["Retry-After"].to_s.match?(/\A\d+\z/)
82
+ data["retryAfter"] = res["Retry-After"].to_i
83
+ end
84
+ if status < 400
85
+ # An API endpoint never redirects; one that does is not Touchque's.
86
+ raise APIError.new(status, data, "Touchque: unexpected redirect (HTTP #{status}); redirects are never followed.")
87
+ end
88
+ raise APIError.for(status, data)
89
+ end
90
+ data.is_a?(Hash) ? data : {}
91
+ end
92
+
93
+ def perform(req)
94
+ http = Net::HTTP.new(@uri.host, @uri.port)
95
+ http.use_ssl = @uri.scheme == "https"
96
+ http.open_timeout = @timeout
97
+ http.read_timeout = @timeout
98
+ http.write_timeout = @timeout if http.respond_to?(:write_timeout=)
99
+ res = http.request(req)
100
+ if res["Content-Length"].to_i > MAX_RESPONSE_BYTES || res.body.to_s.bytesize > MAX_RESPONSE_BYTES
101
+ raise NetworkError, "the answer is larger than 10 MB"
102
+ end
103
+
104
+ res
105
+ rescue *NETWORK_ERRORS => e
106
+ raise NetworkError, e.message
107
+ end
108
+ end
109
+ end
110
+ end
@@ -0,0 +1,74 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "openssl"
5
+ require "securerandom"
6
+ require "uri"
7
+
8
+ module Touchque
9
+ module DeviceRisk
10
+ # @api private: small helpers (no third-party gems), as in the main Touchque gem.
11
+ module Util
12
+ module_function
13
+
14
+ def sha256_hex(data)
15
+ OpenSSL::Digest::SHA256.hexdigest(data)
16
+ end
17
+
18
+ def hmac_hex(key, data)
19
+ OpenSSL::HMAC.hexdigest("SHA256", key, data)
20
+ end
21
+
22
+ def random_hex(bytes = 16)
23
+ SecureRandom.hex(bytes)
24
+ end
25
+
26
+ def now_ms
27
+ (Time.now.to_f * 1000).to_i
28
+ end
29
+
30
+ # A path segment, percent-encoded (encodeURIComponent / rawurlencode).
31
+ def seg(value)
32
+ URI.encode_www_form_component(value.to_s).gsub("+", "%20")
33
+ end
34
+
35
+ # JSON text, compact, non-ASCII kept as is (like JSON.stringify).
36
+ def json(value)
37
+ JSON.generate(value)
38
+ end
39
+
40
+ def parse_json(text)
41
+ return nil if text.nil? || text.strip.empty?
42
+
43
+ JSON.parse(text)
44
+ rescue JSON::ParserError
45
+ nil
46
+ end
47
+
48
+ # Keys as strings, deeply (symbol keys from Ruby callers become the API's names).
49
+ def stringify(value)
50
+ case value
51
+ when Hash then value.each_with_object({}) { |(k, v), h| h[k.to_s] = stringify(v) }
52
+ when Array then value.map { |v| stringify(v) }
53
+ when Symbol then value.to_s
54
+ else value
55
+ end
56
+ end
57
+
58
+ # https, or http to localhost / loopback only (local development).
59
+ def assert_safe_url!(url, name)
60
+ uri = URI.parse(url.to_s)
61
+ return if uri.scheme == "https"
62
+
63
+ if uri.scheme == "http"
64
+ return if %w[localhost 127.0.0.1 ::1 [::1]].include?(uri.host.to_s.downcase)
65
+
66
+ raise ConfigError, "Refusing a plaintext http:// #{name} for \"#{uri.host}\". The API key and request signature would be sent in the clear: use https://."
67
+ end
68
+ raise ConfigError, "#{name} must be http(s): #{url}"
69
+ rescue URI::InvalidURIError
70
+ raise ConfigError, "#{name} is not a valid URL: #{url}"
71
+ end
72
+ end
73
+ end
74
+ end
@@ -0,0 +1,7 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Touchque
4
+ module DeviceRisk
5
+ VERSION = "1.0.0"
6
+ end
7
+ end
@@ -0,0 +1,28 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "device_risk/version"
4
+ require_relative "device_risk/errors"
5
+ require_relative "device_risk/util"
6
+ require_relative "device_risk/http"
7
+ require_relative "device_risk/client"
8
+
9
+ module Touchque
10
+ # 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.
13
+ #
14
+ # # TQ_API_KEY=tq_... TQ_API_SECRET=...
15
+ # dr = Touchque::DeviceRisk::Client.new
16
+ # r = dr.check(params[:touchque_request_id], event: "sign_in", external_username: email)
17
+ module DeviceRisk
18
+ # The +event+ values of Device risk's webhook events. Verify the webhook with the
19
+ # main Touchque gem (tq.webhook), then compare its +event+ with these. Ignore types
20
+ # you do not know.
21
+ module WebhookEvents
22
+ # An identification or a check raised a signal that asks for more. Never a trait.
23
+ DEVICE_RISK_SIGNAL = "DEVICE_RISK_SIGNAL"
24
+ # An alert rule of the workspace went off.
25
+ DEVICE_RISK_ALERT = "DEVICE_RISK_ALERT"
26
+ end
27
+ end
28
+ end
@@ -0,0 +1,4 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Lets `require "touchque-device-risk"` (the gem's name) work too.
4
+ require_relative "touchque/device_risk"
metadata ADDED
@@ -0,0 +1,57 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: touchque-device-risk
3
+ version: !ruby/object:Gem::Version
4
+ version: 1.0.0
5
+ platform: ruby
6
+ authors:
7
+ - Touchque
8
+ bindir: bin
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies: []
12
+ description: 'Server SDK for Touchque Device Risk: a visitor ID for every browser
13
+ on your sign-up, reset, sign-in or approval page, a risk verdict, and the abuse
14
+ your server sees.'
15
+ email:
16
+ - developer@touchque.com
17
+ executables: []
18
+ extensions: []
19
+ extra_rdoc_files: []
20
+ files:
21
+ - CHANGELOG.md
22
+ - LICENSE
23
+ - README.md
24
+ - lib/touchque-device-risk.rb
25
+ - lib/touchque/device_risk.rb
26
+ - lib/touchque/device_risk/client.rb
27
+ - lib/touchque/device_risk/errors.rb
28
+ - lib/touchque/device_risk/http.rb
29
+ - lib/touchque/device_risk/util.rb
30
+ - lib/touchque/device_risk/version.rb
31
+ homepage: https://touchque.com
32
+ licenses:
33
+ - MIT
34
+ metadata:
35
+ source_code_uri: https://github.com/Touchque/touchque-device-risk-ruby
36
+ changelog_uri: https://github.com/Touchque/touchque-device-risk-ruby/blob/main/CHANGELOG.md
37
+ documentation_uri: https://support.touchque.com
38
+ rubygems_mfa_required: 'true'
39
+ rdoc_options: []
40
+ require_paths:
41
+ - lib
42
+ required_ruby_version: !ruby/object:Gem::Requirement
43
+ requirements:
44
+ - - ">="
45
+ - !ruby/object:Gem::Version
46
+ version: '3.1'
47
+ required_rubygems_version: !ruby/object:Gem::Requirement
48
+ requirements:
49
+ - - ">="
50
+ - !ruby/object:Gem::Version
51
+ version: '0'
52
+ requirements: []
53
+ rubygems_version: 4.0.23
54
+ specification_version: 4
55
+ summary: 'Official Ruby server SDK for Touchque Device Risk: check a page''s device
56
+ identification, read and search identifications, report abuse activity.'
57
+ test_files: []