Documentation
¶
Overview ¶
Package devicerisk is the Go server SDK for Touchque Device Risk (a paid add-on, off until your workspace turns it on): a visitor ID for every browser on your sign-up, password-reset, sign-in or approval page, and what your server saw it do.
The page identifies with @touchque/device-risk (the script tag, or identify({ siteKey, purpose }), which gives { visitorId, requestId, confidence }) and sends you the requestId. Never trust the page's copy: read the identification here (GetEvent) or check it for an account (Check). Touchque keeps keyed hashes only, with a key of your workspace alone, and its risk engine decides.
Every signal only ever asks for more: StepUp means an extra check on this page (an emailed code, a passkey, a number-matched approval), never a refusal. For sign-ins approved on the phone with the main Touchque SDK, pass the requestId as DeviceRiskRequestID in its LoginRequestOptions and RiskCheckOptions instead. Collect it only on these pages and name it in your privacy notice.
With the script tag (device.js), the form arrives with touchque_request_id:
dr, err := devicerisk.New() // TQ_API_KEY, TQ_API_SECRET
r, err := dr.Check(ctx, devicerisk.CheckOptions{RequestID: req.FormValue("touchque_request_id"), ExternalUsername: email})
Pass it as it came. Missing, empty, made up or expired, it is still a verdict (Report missing, unknown, expired; the signal device_identification_missing), never an error: a page without the tag, or with it blocked, only gets the visitor a step-up.
Index ¶
- Constants
- Variables
- func ActivityBody(opts ActivityOptions) (map[string]interface{}, error)
- type APIError
- type AccountDevice
- type ActivityOptions
- type ActivityResult
- type Card
- type CheckOptions
- type CheckResult
- type Client
- func (c *Client) Activity(ctx context.Context, opts ActivityOptions) (*ActivityResult, error)
- func (c *Client) Check(ctx context.Context, opts CheckOptions) (*CheckResult, error)
- func (c *Client) GetEvent(ctx context.Context, requestID string) (map[string]interface{}, error)
- func (c *Client) SearchEvents(ctx context.Context, opts SearchOptions) (*SearchResult, error)
- type Config
- type ConfigError
- type NetworkError
- type SearchOptions
- type SearchResult
- type Signal
- type Suspect
- type SuspectReason
Constants ¶
const ( // EventDeviceRiskSignal: an identification or a Check raised a signal // that asks for more (enforced or in shadow). Never a trait. EventDeviceRiskSignal = "DEVICE_RISK_SIGNAL" // EventDeviceRiskAlert: an alert rule of the workspace went off. EventDeviceRiskAlert = "DEVICE_RISK_ALERT" )
The event values of Device risk's webhook events. Verify the webhook with the main Touchque SDK (Webhook), then compare its event with these. Ignore types you do not know.
const DefaultBaseURL = "https://api.touchque.com"
DefaultBaseURL is used when Config.BaseURL and TQ_API_URL are both unset.
const Version = "1.0.0"
Version is this package's version, sent in the User-Agent.
Variables ¶
var ( ErrFeature = errors.New("touchque: feature not available") ErrFeatureNotInPlan = errors.New("touchque: feature not in the organization's plan") ErrFeatureReadOnly = errors.New("touchque: feature is being turned off (read-only)") ErrFeatureOff = errors.New("touchque: feature switched off on this deployment") )
The organization behind your workspace cannot use Device risk here (HTTP 403). An *APIError matches one of these with errors.Is, and ErrFeature for any of the three; its Feature field names the feature:
- ErrFeatureNotInPlan: not in its plan (feature_not_in_plan); an owner or admin adds it in the Touchque dashboard;
- ErrFeatureReadOnly: being turned off (feature_read_only); reads still work for 14 days, changes are refused;
- ErrFeatureOff: switched off on this Touchque deployment (feature_off).
var ActivityOutcomes = []string{"approved", "declined", "error"}
ActivityOutcomes are what the payment provider answered (payment_attempt).
var ActivitySignals = []string{"abuse_card_testing", "abuse_card_shared", "abuse_login_failures", "abuse_probing", "abuse_otp_pumping", "abuse_code_guessing"}
ActivitySignals are the abuse codes an activity can raise. New codes may be added.
var ActivityTypes = []string{"payment_attempt", "login_failed", "not_found", "forbidden", "otp_sent", "code_failed"}
ActivityTypes are what your server saw the visitor do (ActivityOptions.Type).
var CheckEvents = []string{"sign_in", "sign_up", "password_reset", "approval"}
CheckEvents are the pages a device report may come from.
var MatchedBy = []string{"key", "fpc", "sid", "traits", "new"}
MatchedBy are how a visitor was recognised (an event's matchedBy): its device-bound key, the first-party cookie (fpc), its stored id, its traits, or new.
var PathClasses = []string{"admin", "wordpress", "secrets", "source", "db_admin", "debug", "shell", "other"}
PathClasses are the classes of a not_found / forbidden path.
var Reports = []string{"ok", "replayed", "missing", "unknown", "expired", "invalid"}
Reports are what the page had sent: ok, replayed, or no usable identification.
Functions ¶
func ActivityBody ¶
func ActivityBody(opts ActivityOptions) (map[string]interface{}, error)
ActivityBody validates opts and returns the request body of Activity: a *ConfigError for a wrong field (nothing is sent).
Types ¶
type APIError ¶
type APIError struct {
StatusCode int
Message string
// Code is the machine-readable error code (e.g. "device_risk_off",
// "card_number_not_allowed"), when the API sent one.
Code string
// RetryAfter: seconds to wait before retrying (429).
RetryAfter int
// CaseCode is the "Why?" case code of a refusal (K7P-2QX): your team opens
// the decision by it in the dashboard. Empty for other errors.
CaseCode string
// Feature is the catalog id (device_risk) of a feature refusal; see
// ErrFeatureNotInPlan. Empty for other errors.
Feature string
Data map[string]interface{}
}
APIError represents an error returned by the Touchque API (status >= 400).
type AccountDevice ¶
type AccountDevice struct {
// Status: known (this visitor served it), likely (another of its
// visitors has the same trait profile on the same network), new (the
// account has other devices here, not this one) or first (none yet).
Status string
// VisitorID (likely): the account's visitor it looks like.
VisitorID string
// Since (known): the account's first identification on it, ISO 8601.
Since string
}
AccountDevice says whether this account used the device before (once a check names the account).
func ParseAccountDevice ¶
func ParseAccountDevice(raw interface{}) *AccountDevice
ParseAccountDevice reads the "accountDevice" member of an answer or a GetEvent answer: nil when it is not one.
type ActivityOptions ¶
type ActivityOptions struct {
// Type is one of ActivityTypes: payment_attempt, login_failed, not_found,
// forbidden (with Path), otp_sent (with Phone), code_failed (a wrong
// coupon or gift-card code). Required.
Type string
// RequestID is the page's identification (the touchque_request_id field as it came).
RequestID string
// VisitorID is the visitor (tqv_…), instead of RequestID.
VisitorID string
// ClientIP is the visitor's address (its network is counted); required
// when neither id is known: a bot that never runs your page still counts.
ClientIP string
// ExternalUsername is the account it was for (at most 255 characters).
ExternalUsername string
// Outcome (payment_attempt) is what the payment provider answered: approved, declined or error.
Outcome string
// Card (payment_attempt) is the card's BIN and last 4 digits. Anything
// else is refused before anything is sent.
Card *Card
// Phone (otp_sent) is the number the code went to: 6 to 15 digits, an optional leading +.
Phone string
// Path (not_found / forbidden) is the path asked for (only its class is counted; at most 2048 characters).
Path string
}
ActivityOptions is what a visitor did that your server saw.
type ActivityResult ¶
type ActivityResult struct {
// Recorded is false when Touchque's counters are not reachable (nothing failed).
Recorded bool
// VisitorID is the visitor it was counted for, empty when only ClientIP named it.
VisitorID string
// PathClass (a not_found / forbidden path) is one of PathClasses, else empty.
PathClass string
// Signals are the abuse codes it raised (ActivitySignals): for 24 hours the
// visitor's next identifications and checks carry them.
Signals []string
}
ActivityResult is the answer of Activity.
func ParseActivity ¶
func ParseActivity(res map[string]interface{}) *ActivityResult
ParseActivity reads an Activity answer: Recorded only when it says exactly true; unknown path classes are dropped.
type Card ¶
type Card struct {
// BIN is the first 6 to 8 digits.
BIN string
// Last4 is the last 4 digits.
Last4 string
}
Card is a payment card as its BIN and last 4 digits only: never the card number.
type CheckOptions ¶
type CheckOptions struct {
// RequestID is the touchque_request_id form field (the script tag) or
// identify()'s requestId, as it came: empty is answered Report "missing".
RequestID string
// DeviceRisk is instead the page's report (collect()), relayed untouched.
DeviceRisk string
// Event is the page: sign_in (default), sign_up, password_reset or approval.
Event string
// ExternalUsername is the account the page is for, when there is one. One account per identification.
ExternalUsername string
// ClientIP is the end user's address; default: where the browser identified from.
ClientIP string
}
CheckOptions is one page's identification, for an account.
type CheckResult ¶
type CheckResult struct {
// Report is what the page had sent: ok; replayed (another account, or sent
// twice); or no usable identification, which raises
// device_identification_missing: missing (none or empty), unknown (made up,
// or another workspace's), expired (over 15 minutes old), invalid (a relayed
// report that cannot be read).
Report string
RequestID string
// VisitorID (tqv_…) is this browser in your workspace only.
VisitorID string
Confidence float64
// Visitor holds firstSeenAt, lastSeenAt, seenCount, matchedBy, sealed, status (your admin's mark), labels.
Visitor map[string]interface{}
Counts map[string]interface{}
// Network is the address as the risk engine saw it (never coordinates):
// countryCode, region, city, accuracyKm, timeZone, asn, asnOrg, type
// (isp, hosting, tor, unknown), tor, hosting, hostingProvider, timezoneMismatch.
Network map[string]interface{}
// Velocity holds the visitor's counts: accounts24h, accounts30d,
// signUps24h, countries24h, idResets7d, identifications1h, identifications24h.
Velocity map[string]interface{}
// Bot is one answer to "a bot?": result (detected, suspected,
// not_detected) and reasons (detected ones first, then suspected:
// webdriver, headless, pointer_synthetic, zero_window, soft_gpu,
// tool_<name>, agent_verified, input_synthetic, agent_pace, cdp,
// agent_unverified, agent_claimed). Servers since 2026-11-24 also send
// (absent on older ones): type (ai_agent: an AI agent or bot by its own
// identity, or a pause before every step; automation: a driven browser;
// script: moved or typed like software in a browser that shows no
// driver; or nil), tools (automation tools whose marks were on the page:
// selenium, playwright, puppeteer, phantomjs, nightmare, headless_chrome),
// agent (nil, or provider, name, category ai_agent | ai_crawler |
// search_crawler, identity verified | unverified | claimed: a Web Bot
// Auth signature checked against the provider's published keys, or the
// user agent only) and input (insert_no_keys, uniform_keys,
// instant_keys, center_press, agent_pace).
Bot map[string]interface{}
// AccountDevice: did this account use the device before? nil before an account is named.
AccountDevice *AccountDevice
// Suspect is the suspect score in shadow; nil from servers that do not send it.
Suspect *Suspect
Signals []Signal
// StepUp: ask for more on this page. Never a reason to refuse.
StepUp bool
// WouldStepUp: a signal that asks was raised, enforced or not.
WouldStepUp bool
// Requires is none, number_match or passkey.
Requires string
// Mode is enforce when at least one raised signal is enforced, else shadow.
Mode string
// Engine is the engine's state for this check; "unavailable" when the risk engine could not be reached and the verdict is a safe default (empty when the answer carries none).
Engine string
// CaseCode opens the decision record ("Why?") in the dashboard.
CaseCode string
}
CheckResult is the answer.
func ParseCheck ¶
func ParseCheck(res map[string]interface{}) *CheckResult
ParseCheck reads an answer, failing toward asking: StepUp is true unless it says exactly false; junk signals are dropped.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client is the Touchque Device Risk client. Safe for concurrent use: create one and reuse it.
func New ¶
New builds a Client from TQ_API_KEY / TQ_API_SECRET / TQ_API_URL, or from config if given (config[0], at most one).
func NewClient ¶
NewClient builds a Client from config. Panics on invalid configuration (as the main Touchque SDK's NewClient) — use New() for a version that returns an error instead.
func (*Client) Activity ¶
func (c *Client) Activity(ctx context.Context, opts ActivityOptions) (*ActivityResult, error)
Activity reports what a visitor did that your server saw (POST /device-risk/activity): payments, failed sign-ins, probing, SMS codes, wrong codes. Touchque counts it per visitor and per network and answers the abuse codes it raised; for 24 hours the visitor's next identifications and checks carry them (shadow: they decide nothing on their own).
a, err := dr.Activity(ctx, devicerisk.ActivityOptions{Type: "payment_attempt", RequestID: req.FormValue("touchque_request_id"),
ClientIP: ip, Outcome: "declined", Card: &devicerisk.Card{BIN: "411111", Last4: "1111"}})
if err == nil && slices.Contains(a.Signals, "abuse_card_testing") { stopTakingCards() }
Never send a card number: a Card that is not exactly a BIN and the last 4 digits is a *ConfigError, before anything is sent.
func (*Client) Check ¶
func (c *Client) Check(ctx context.Context, opts CheckOptions) (*CheckResult, error)
Check checks the page's identification for an account: it binds it (one account per identification, 15 minutes) and asks the risk engine. Pass the form field as it came: empty or made up is still a verdict (Report missing, unknown), never an error. 409 device_risk_off until your workspace turns Device risk on.
r, err := dr.Check(ctx, devicerisk.CheckOptions{RequestID: req.FormValue("touchque_request_id"), Event: "sign_up", ExternalUsername: email, ClientIP: ip})
if err == nil && r.StepUp { askForEmailCode() } // never refuse on it alone
func (*Client) GetEvent ¶
GetEvent reads the trusted identification behind a requestId: the visitor (visitorId, confidence, matchedBy), what the page showed (facts), the risk engine's verdict, accountDevice and suspect (read them with ParseAccountDevice and ParseSuspect). Read-only.
func (*Client) SearchEvents ¶
func (c *Client) SearchEvents(ctx context.Context, opts SearchOptions) (*SearchResult, error)
SearchEvents searches your workspace's identifications, newest first, one page at a time (GET /device-risk/events). Do not page by moving From/To. A search that would read too much is a 422 search_too_broad: narrow the range or add a filter.
type Config ¶
Config holds the client's configuration: the same API key and secret as the main Touchque SDK.
func ConfigFromEnv ¶
ConfigFromEnv builds a Config from TQ_API_KEY / TQ_API_SECRET / TQ_API_URL.
func DefaultConfig ¶
DefaultConfig creates a new Config with standard defaults.
type ConfigError ¶
type ConfigError struct {
Message string
}
ConfigError means invalid or missing configuration, or a wrong argument (returned before any request).
func (*ConfigError) Error ¶
func (e *ConfigError) Error() string
type NetworkError ¶
type NetworkError struct {
Message string
}
NetworkError means the request never reached the API (DNS, connection, timeout).
func (*NetworkError) Error ¶
func (e *NetworkError) Error() string
type SearchOptions ¶
type SearchOptions struct {
From, To, Signal, Kind, Origin, IP, Account, VisitorID, RequestID, Cursor string
StepUp *bool
Limit int
}
SearchOptions are SearchEvents' filters. From/To are YYYY-MM-DD (UTC) or ISO times (7 days before To by default, at most 90 days, within your retention). IP is an address or a CIDR range and is never returned. StepUp filters only when set. Cursor is the previous page's NextCursor, as it came. Limit is 1 to 100 (0: the default 25).
type SearchResult ¶
SearchResult is one page of SearchEvents: pass NextCursor back as Cursor until it is empty. Each event has no address and no raw trait; read its "suspect" with ParseSuspect and its "matchedBy" against MatchedBy.
type Signal ¶
type Signal struct {
// Code: device_tampered, device_virtual, device_geo_mismatch,
// device_many_accounts, device_signup_burst, device_id_resets,
// device_many_countries, device_wrong_site, device_report_replayed,
// device_private_window (context only), device_step_up_by_admin,
// device_identification_missing (no identification, or one that does not verify),
// device_pointer_synthetic (the pointer or a finger moved like software),
// device_new_storage_burst and device_network_signup_burst (many new browsers,
// or sign-ups, in a day from phones like this one on this network),
// device_input_synthetic (typed or clicked like software) and
// device_ai_agent (an AI agent or bot by its own signature or user agent);
// these two ask for a number-matched step-up only, never a block. The
// abuse codes of Activity (ActivitySignals) are carried for 24 hours too.
// New codes are added in minor versions.
Code string
Text string
// Strength is what a step-up for it should be: number_match, passkey, or none (context only).
Strength string
// Enforced: scored now; false means reported only (shadow) until Touchque enforces it.
Enforced bool
Evidence map[string]interface{}
}
Signal is one signal. Each one only ever asks for more.
type Suspect ¶
type Suspect struct {
// Score is 0 to 100.
Score int
// Band is low, medium, high or critical.
Band string
// WouldDo is what it would ask for: allow (0-29), number_match (30-59),
// passkey (60+), or block (a sign-up or password reset at 80+ with a
// reason the server proved; an existing account's sign-in is never blocked).
WouldDo string
// Mode is shadow.
Mode string
Reasons []SuspectReason
}
Suspect is the suspect score, in shadow: it decides nothing yet.
func ParseSuspect ¶
func ParseSuspect(raw interface{}) *Suspect
ParseSuspect reads the suspect score of an answer, a GetEvent answer or a SearchEvents row (its "suspect" member): nil when it is not one.
type SuspectReason ¶
type SuspectReason struct {
Code string
// Points: negative for a known browser or a trusted mark.
Points int
// By is who proves it: server (Touchque saw it), site (your server
// reported it: Activity), page (the browser reported it) or brand (your
// admin's mark).
By string
Text string
}
SuspectReason is one reason of the suspect score.