devicerisk

package module
v1.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 26, 2026 License: MIT Imports: 20 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

touchque-device-risk-go

The official Go server SDK for Touchque Device Risk: a visitor ID for every browser on your sign-up, password-reset, sign-in or approval page, a risk verdict for the account it is used for, and the abuse your server sees (card testing, failed sign-ins, probing, SMS pumping, code guessing), and which bot sent a request your page's tag never saw.

Device Risk is a paid add-on: it answers 409 device_risk_off until your workspace turns it on in the Touchque dashboard.

Full docs: support.touchque.com

Install

go get github.com/Touchque/touchque-device-risk-go

Only the standard library; Go 1.26 or newer.

Setup

The same API key and secret as the main Touchque SDK:

TQ_API_KEY=tq_your_key
TQ_API_SECRET=your_api_secret
import devicerisk "github.com/Touchque/touchque-device-risk-go"

dr, err := devicerisk.New() // reads the environment
dr = devicerisk.NewClient(&devicerisk.Config{APIKey: key, APISecret: secret, TimeoutMs: 10000}) // panics on a bad config

Every call is signed with your API secret: keep it on your server. A *Client is safe for concurrent use.

Check a page's identification

The page identifies the browser with @touchque/device-risk (the script tag device.js fills a touchque_request_id field in your form, or identify({ siteKey, purpose }) gives a requestId). Never trust the page's copy: check it on your server.

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() // a step-up, never a refusal on it alone
}
  • Pass the field as it came: missing, empty, made up or expired is still a verdict (Report: missing, unknown, expired, invalid; the signal device_identification_missing), never an error.
  • Event: sign_in (default), sign_up, password_reset or approval (CheckEvents).
  • *CheckResult fails toward asking: StepUp is true unless the API says exactly false.
  • Suspect is the suspect score, in shadow (it decides nothing yet): Score 0-100, Band (low, medium, high, critical), WouldDo (allow, number_match, passkey, block) and Reasons (Code, Points, By: server, site, page or brand, Text).
  • AccountDevice: did this account use the device before? Status known, likely, new or first.
  • Network is the address as the risk engine saw it, with the kind of network (see The network).
  • Bot is one answer to "a bot?" (result, reasons, type, tools, agent, input), a map as the API sent it. tools names the automation tools (selenium, playwright, puppeteer, phantomjs, nightmare, headless_chrome) and the AI agents whose marks were on the page: claude_agent (the Claude app's browser or Claude in Chrome), comet_agent (Perplexity Comet), genspark_agent, browser_use, stagehand and skyvern; each is tool_<name> in reasons. Other reasons include cdp (the DevTools protocol attached), cdp_input (a press with no pressure), input_no_focus (a click or key into a page that was not in front), insert_text_bulk (text with no key pressed), scripted_click (a form sent with no click or key), headless_window and emulator. New tools and reasons may be added in minor versions; older servers send fewer.

For a sign-in approved on the phone with the main Touchque SDK, pass the same field as DeviceRiskRequestID in its LoginRequestOptions or RiskCheckOptions instead.

Read and search identifications

ev, err := dr.GetEvent(ctx, "dre_...") // the trusted identification, the verdict, accountDevice, suspect
suspect := devicerisk.ParseSuspect(ev["suspect"])

stepUp := true
cursor := ""
for {
	page, err := dr.SearchEvents(ctx, devicerisk.SearchOptions{Account: "ada@example.com", StepUp: &stepUp, Limit: 50, Cursor: cursor})
	if err != nil {
		break
	}
	for _, e := range page.Events { /* requestId, at, visitorId, kind, network, matchedBy, signals, suspect… */ }
	if cursor = page.NextCursor; cursor == "" {
		break
	}
}

Filters: From, To (7 days by default, at most 90), Signal, StepUp, Kind (the page), Origin, IP (an address or a CIDR range, never returned), Account, VisitorID, RequestID, NetworkKind and Shared (see The network), Limit (1 to 100) and the opaque Cursor. A search that would read too much is a 422 search_too_broad.

The network

Network (in Check, GetEvent and each SearchEvents row) is the address as the risk engine saw it, never coordinates, as a map: countryCode, city, asn, asnOrg, type (isp, hosting, tor, relay for Apple's iCloud Private Relay, unknown), proxy and more. Newer servers also say what kind of network it is (absent on older ones, nil for an identification from before it). kind is one of devicerisk.NetworkKinds (residential, mobile_carrier, education, business, public_wifi, hosting, proxy, vpn, tor, relay, unknown): an open list, new values may be added in minor versions, so keep a default branch. kindSource says where it came from. vpn is a VPN company's own address (the suspect score's network_vpn, 10 points). shared means many browsers used the identification's own address on your pages in 24 hours (a school, an office, a café or a mobile operator; context only), with sharedVisitors24h and sharedAccounts24h as "at least" counts (1, 2, 5, 10, 100 or 1000). lookAlikeMatching is false when this computer was recognised only by its own key, cookie or stored id, never because it looks like another one, and nil when not decided (phones, tablets and Safari are never matched by look-alike). The shared fields and lookAlikeMatching are nil when not counted, or when ClientIP was another address than the one the browser identified from. proxy means the address was reported as a proxy in the last 30 days: context that counts little (absent on older servers). In SearchEvents, NetworkKind matches only identifications classified since network kind exists (older ones have no kind), and Shared set to false matches only the ones counted and not shared (one that was not counted matches neither). Older servers ignore both filters.

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

kind, _ := r.Network["kind"].(string)                  // "" from an older server or identification
atLeast, _ := r.Network["sharedVisitors24h"].(float64) // JSON numbers are float64

shared := true
page, err := dr.SearchEvents(ctx, devicerisk.SearchOptions{NetworkKind: "education", Shared: &shared})

Report what your server saw

a, err := dr.Activity(ctx, devicerisk.ActivityOptions{
	Type:             "payment_attempt",
	RequestID:        req.FormValue("touchque_request_id"),
	ClientIP:         ip,
	ExternalUsername: email,
	Outcome:          "declined",                                   // what the payment provider answered
	Card:             &devicerisk.Card{BIN: "411111", Last4: "1111"}, // never the card number
})
if err == nil && slices.Contains(a.Signals, "abuse_card_testing") {
	stopTakingCards()
}
  • Type: payment_attempt, login_failed, not_found, forbidden (with Path), otp_sent (with Phone), code_failed (a wrong coupon or gift-card code).
  • Name the visitor with RequestID, VisitorID or ClientIP (a bot that never runs your page still counts on its network).
  • *ActivityResult: Recorded, VisitorID, Signals (abuse_card_testing, abuse_card_shared, abuse_login_failures, abuse_probing, abuse_otp_pumping, abuse_code_guessing) and, for a path, PathClass. For 24 hours the visitor's next checks carry those signals and the suspect score weighs them.
  • A card is its BIN (6 to 8 digits) and last 4 digits only; anything else is a *ConfigError before anything is sent.

Bot check

Many bots never run your page, so the tag never sees them: ChatGPT-User, GPTBot, Meta's crawlers, curl, scripts. BotCheck sends one request's IP and headers from your server and answers which bot it is, whether that name is proven, and what Touchque would do. Touchque decides on its own servers, with no third-party service at request time, and keeps nothing but short-lived counters.

http.HandleFunc("/pricing", func(w http.ResponseWriter, req *http.Request) {
	ctx, cancel := context.WithTimeout(req.Context(), 500*time.Millisecond) // never hold the page for it
	defer cancel()
	b, err := dr.BotCheck(ctx, devicerisk.BotCheckRequestFrom(req, clientIP(req)))
	if err == nil && b.Bot.Result != "not_detected" {
		log.Printf("bot %s %s/%s identity=%s suggestion=%s rule=%s",
			b.Bot.Category, b.Bot.Provider, b.Bot.Name, b.Bot.Identity, b.Suggestion, b.Bot.Rule)
	}
	// ... serve the page
})
  • clientIP is yours: the visitor's address as your proxy or load balancer reports it (empty: req.RemoteAddr).
  • Bot: Result (detected, suspected, not_detected), Category (ai_agent, ai_assistant, ai_crawler, ai_search, search_crawler, link_preview, seo, monitoring, archiver, feed_reader, security_scanner, http_client, headless_browser, automation), Provider and Name (OpenAI, ChatGPT-User), VerifiedBy, Confidence, Rule and Reasons (Code, Text: a sentence for your fraud team).
  • Bot.Identity: verified (its operator's signature, published addresses or reverse DNS proved it), unverified (a spoofed name: its operator publishes a way to check, and the check failed) or claimed (no way to check it, or not right now).
  • Network: ASN, ASNOrg, CountryCode, Hosting; nil when Touchque cannot tell.
  • Suggestion is advice in shadow: Touchque never enforces it. allow (a verified bot, a declared crawler, assistant or other bot that cannot be checked, or no bot), block (a spoofed name), challenge (an AI agent that only names itself, since it acts for a person; undeclared automation; or a suspected bot).
  • Authorization, Cookie, Proxy-Authorization, X-Api-Key and Set-Cookie go with empty values, the URL without its query string, and a request with no headers as [].
  • What the visitor sent never makes it fail: the first 100 headers go, a name is cut to 128 characters and a value to 4096, the body is kept under 32 KB, and the request tells Touchque it was cut (truncated). A header HTTP does not allow, a method other than 1 to 16 letters or a URL Touchque could not read is left out. Only no IP (or one that is not an address) is a *ConfigError, before anything is sent.
  • Go's net/http does not keep the order headers arrived in, so BotCheckRequestFrom sends them as a set (HeaderOrderUnknown). When your edge gives you the order, build Headers yourself in that order.
  • HTTPVersion and TLS go only when you set them from what your edge saw. BotCheckRequestFrom never sets them: r.Proto is the connection to your server, which behind a proxy is the proxy's.
  • New categories and fields may be added: they come through as strings, and Raw keeps the whole answer.

Webhooks

Verify Touchque webhooks with the main Touchque SDK, then compare event with devicerisk.EventDeviceRiskSignal (a signal that asks for more) or devicerisk.EventDeviceRiskAlert (an alert rule of the workspace went off).

Errors

  • *ConfigError: a wrong argument or configuration (nothing was sent).
  • *APIError: the API answered an error (StatusCode, Code, RetryAfter, CaseCode, Feature). errors.Is(err, devicerisk.ErrFeature) (or ErrFeatureNotInPlan, ErrFeatureReadOnly, ErrFeatureOff): Device risk is not in your organization's plan, being turned off, or switched off on this deployment.
  • *NetworkError: the request never reached Touchque.

Tests

go test ./...

The tests run against the shared fake Touchque API (testing/fake-touchque-api.mjs, Node.js); the bot check tests and the network-kind answer tests use a local httptest server.

License

MIT

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.

For the visitors that never run your page (ChatGPT-User, GPTBot, crawlers, curl, scripts), BotCheck tells from one request's IP and headers which bot sent it and whether that name is proven, with a suggestion in shadow:

b, err := dr.BotCheck(ctx, devicerisk.BotCheckRequestFrom(req, ip))

Index

Constants

View Source
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.

View Source
const DefaultBaseURL = "https://api.touchque.com"

DefaultBaseURL is used when Config.BaseURL and TQ_API_URL are both unset.

View Source
const Version = "1.1.0"

Version is this package's version, sent in the User-Agent.

Variables

View Source
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).
View Source
var ActivityOutcomes = []string{"approved", "declined", "error"}

ActivityOutcomes are what the payment provider answered (payment_attempt).

View Source
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.

View Source
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).

View Source
var BotCategories = []string{"ai_agent", "ai_assistant", "ai_crawler", "ai_search", "search_crawler", "link_preview", "seo",
	"monitoring", "archiver", "feed_reader", "security_scanner", "http_client", "headless_browser", "automation"}

BotCategories are the kinds of bot a bot check names. New ones may be added: BotCheckBot.Category carries them as they came.

View Source
var BotCheckBlankedHeaders = []string{"authorization", "cookie", "proxy-authorization", "x-api-key", "set-cookie"}

BotCheckBlankedHeaders go by name only, matched without case: credentials and session cookies never leave your server, while their place among the headers still counts.

View Source
var BotCheckHTTPVersions = []string{"1.0", "1.1", "2", "3"}

BotCheckHTTPVersions are the values BotCheckRequest.HTTPVersion is sent as.

View Source
var BotConfidences = []string{"high", "medium", "low"}

BotConfidences are how sure a bot check is.

View Source
var BotIdentities = []string{"verified", "unverified", "claimed"}

BotIdentities are whether a bot's name is proven: verified, unverified (a spoofed name) or claimed (no way to check it).

View Source
var BotResults = []string{"detected", "suspected", "not_detected"}

BotResults are a bot check's answers to "a bot?".

View Source
var BotSuggestions = []string{"allow", "block", "challenge"}

BotSuggestions are a bot check's advice, in shadow: Touchque never enforces it.

View Source
var BotVerifiedBy = []string{"signature", "ip_list", "reverse_dns", "asn"}

BotVerifiedBy are what proved a verified bot's name.

View Source
var CheckEvents = []string{"sign_in", "sign_up", "password_reset", "approval"}

CheckEvents are the pages a device report may come from.

View Source
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.

View Source
var NetworkKinds = []string{"residential", "mobile_carrier", "education", "business", "public_wifi", "hosting", "proxy", "vpn", "tor", "relay", "unknown"}

NetworkKinds are the kinds of network an address is on: the network's "kind" in Check, GetEvent and SearchEvents answers, and SearchOptions.NetworkKind. A VPN, hosting, a proxy company, Tor and a relay always win over a place. An open list: new values may be added in minor versions and come through as they came, so keep a default branch. Absent from older servers' answers.

View Source
var PathClasses = []string{"admin", "wordpress", "secrets", "source", "db_admin", "debug", "shell", "other"}

PathClasses are the classes of a not_found / forbidden path.

View Source
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).

func BotCheckBody added in v1.1.0

func BotCheckBody(req BotCheckRequest) (map[string]interface{}, error)

BotCheckBody returns the request body of BotCheck: its headers are [][2]string pairs in order, or a map[string]string when the order is unknown, with the sensitive values blank, whoever built req. What the visitor sent never makes it fail; a *ConfigError is only for what your code passed wrong (no IP, a header without a name), and 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).

func (*APIError) Error

func (e *APIError) Error() string

func (*APIError) Is

func (e *APIError) Is(target error) bool

Is lets errors.Is match the feature sentinels.

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 BotCheckBot added in v1.1.0

type BotCheckBot struct {
	// Result is detected, suspected or not_detected (BotResults).
	// not_detected means no sign of a bot in this one request (also what an
	// answer that cannot be read says: "cannot tell" is never a bot); a page
	// that runs the tag tells more (Check).
	Result string
	// Category is the kind of bot (BotCategories): ai_agent, ai_assistant,
	// ai_crawler, ai_search, search_crawler, link_preview, seo, monitoring,
	// archiver, feed_reader, security_scanner, http_client,
	// headless_browser or automation. New ones may be added.
	Category string
	// Provider is who runs it, e.g. OpenAI.
	Provider string
	// Name is what it is called, e.g. ChatGPT-User.
	Name string
	// Identity is whether that name is proven (BotIdentities):
	//   - verified: its operator's signature, published addresses or reverse
	//     DNS proved it;
	//   - unverified: a spoofed name. Its operator publishes a way to check
	//     it, and that check failed;
	//   - claimed: its operator gives no way to check it, or Touchque cannot
	//     check it right now (never a guess).
	Identity string
	// VerifiedBy is what proved a verified name: signature, ip_list,
	// reverse_dns or asn (BotVerifiedBy).
	VerifiedBy string
	// Confidence is high, medium or low (BotConfidences).
	Confidence string
	// Rule is the stable id of the rule that decided, e.g.
	// directory.chatgpt_user, http_client.curl or
	// browser.chromium_without_client_hints.
	Rule string
	// Reasons are every sign seen, each with a sentence for your fraud team.
	Reasons []BotCheckReason
}

BotCheckBot is the answer to "which bot sent this, and is that proven?". Each field is what the API sent, values this version does not know included; empty means none.

type BotCheckHeader added in v1.1.0

type BotCheckHeader struct {
	Name  string
	Value string
}

BotCheckHeader is one header of the visitor's request.

type BotCheckNetwork added in v1.1.0

type BotCheckNetwork struct {
	// ASN is the network's autonomous system number (0 when unknown).
	ASN int
	// ASNOrg is the organization that runs it.
	ASNOrg string
	// CountryCode is the address's two-letter country code.
	CountryCode string
	// Hosting means a cloud or hosting network, not a home or mobile one
	// (false also when unknown: Raw["network"] tells the two apart).
	Hosting bool
}

BotCheckNetwork is the visitor's network, from Touchque's own data.

type BotCheckReason added in v1.1.0

type BotCheckReason struct {
	// Code is the sign's stable code.
	Code string
	// Text says it in an English sentence your fraud team reads.
	Text string
}

BotCheckReason is one sign a bot check saw.

type BotCheckRequest added in v1.1.0

type BotCheckRequest struct {
	// IP is the visitor's IPv4 or IPv6 address, as your server saw it.
	// Required. A port ("203.0.113.7:51234", "[2001:db8::1]:443") and a zone
	// are dropped, and ::ffff:a.b.c.d goes as a.b.c.d.
	IP string
	// Headers are the request's headers, in the order they arrived when you
	// know it (the order is a sign too); empty for a request that had none.
	// Authorization, Cookie, Proxy-Authorization, X-Api-Key and Set-Cookie go
	// with empty values, their names kept for the order. What the visitor
	// sent never makes BotCheck fail: the first 100 headers go, a name is cut
	// to 128 characters and a value to 4096, the body is kept under 32 KB,
	// and the request tells Touchque it was cut ("truncated"). HTTP/2
	// pseudo-headers and headers HTTP does not allow are left out.
	Headers []BotCheckHeader
	// HeaderOrderUnknown says Headers are not in the order they arrived (Go's
	// net/http does not keep it): they go as a set, repeats of a name joined
	// with ", ", and Touchque reads no order into them. BotCheckRequestFrom
	// sets it.
	HeaderOrderUnknown bool
	// Method is the request's method (GET, POST…). Optional; one that is not
	// 1 to 16 letters is left out.
	Method string
	// URL is the URL or path asked for. Optional. Only its host and path are
	// sent: the query string, the fragment and any user:password are dropped
	// first, and Touchque stores none of it. A host Touchque could not read
	// goes as the path alone; one over 4096 characters is left out.
	URL string
	// HTTPVersion is the HTTP version the visitor spoke to your edge, only
	// when your edge tells you: 1.0, 1.1, 2 or 3 (HTTP/2.0 and h2 read as 2).
	// Anything else is left out. Never your server's own r.Proto: behind a
	// proxy that is the proxy's connection, not the visitor's.
	HTTPVersion string
	// TLS is what your edge saw of the visitor's handshake. Optional.
	TLS *BotCheckTLS
}

BotCheckRequest is one request a visitor sent your server. Build it with BotCheckRequestFrom, or by hand when your edge gives you the headers in the order they arrived.

func BotCheckRequestFrom added in v1.1.0

func BotCheckRequestFrom(r *http.Request, clientIP string) BotCheckRequest

BotCheckRequestFrom builds the BotCheckRequest of a request your handler received. clientIP is the visitor's address as your proxy or load balancer reports it; empty, it is the connection's own address (r.RemoteAddr). Take it from X-Forwarded-For only when your own proxy sets that header.

Go's net/http keeps neither the order the headers arrived in nor, over HTTP/1, the case of their names, so they go as a set (HeaderOrderUnknown) and Touchque reads no order into them. HTTP/2 and 3 names go in lower case, as on the wire. Host (HTTP/1) and Transfer-Encoding, which net/http moves out of r.Header, are put back. Sensitive values are blank already, and the body is never read. HTTPVersion and TLS stay empty: r.Proto is the connection to your server (behind a proxy, the proxy's); set them only from what your edge saw.

type BotCheckResult added in v1.1.0

type BotCheckResult struct {
	Bot BotCheckBot
	// Network is nil when Touchque cannot tell.
	Network *BotCheckNetwork
	// Suggestion is advice in shadow: Touchque never enforces it, your server
	// decides (BotSuggestions). An answer that cannot be read says allow.
	//   - allow: a verified bot, a declared crawler, assistant or other bot that
	//     cannot be checked, or no bot;
	//   - block: a spoofed name (Identity unverified, or a failed signature);
	//   - challenge: an AI agent that only names itself (it acts for a person:
	//     ask that person), undeclared automation (an HTTP client, a headless
	//     browser, a browser whose claims contradict each other) or a suspected bot.
	Suggestion string
	// RulesVersion is the version of the rules that answered, e.g. 2026.11.25-1.
	RulesVersion string
	// Raw is the whole answer as it came, with any fields this version does not know.
	Raw map[string]interface{}
}

BotCheckResult is the answer of BotCheck.

func ParseBotCheck added in v1.1.0

func ParseBotCheck(res map[string]interface{}) *BotCheckResult

ParseBotCheck reads a BotCheck answer without failing on what it does not know: unknown values come through as they came, unknown fields stay in Raw, and reasons without a code are dropped. What it cannot read is "cannot tell": Result not_detected and Suggestion allow, never a block.

type BotCheckTLS added in v1.1.0

type BotCheckTLS struct {
	// Ciphers are the cipher suites the visitor offered, as your edge writes
	// them (for example nginx's $ssl_ciphers). A longer list is cut to 4096
	// characters.
	Ciphers string
	// JA4 is the visitor's JA4 TLS fingerprint, when your edge computes one
	// (one over 128 characters is not a JA4 and is left out).
	JA4 string
}

BotCheckTLS is what your edge (load balancer, CDN or TLS terminator) saw of the visitor's TLS handshake. Both are optional.

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 and mark: the mark actually applied
	// to this identification, "step_up" always, "trusted" only when the
	// browser matched by its stored key or id (never by traits), else nil (any
	// other value reads as nil). Older servers send no mark.
	Visitor map[string]interface{}
	Counts  map[string]interface{}
	// Network is the address as the risk engine saw it (never coordinates),
	// as the API sent it: countryCode, region, city, accuracyKm, timeZone,
	// asn, asnOrg, type (isp, hosting, tor, relay: Apple's iCloud Private
	// Relay, never a VPN or hosting; or unknown), tor, hosting,
	// hostingProvider, proxy (reported as a proxy in the last 30 days:
	// context; absent on older servers; the proxy list includes IP2Proxy
	// LITE data available from https://lite.ip2location.com),
	// timezoneMismatch. Newer servers also send the kind of network
	// (absent on older ones): kind (NetworkKinds, an open list: new values may
	// be added in minor versions), kindSource (address, network, mixed,
	// network_open or name), vpn (a VPN company's own address), shared (10 or
	// more browsers, or 5 or more accounts from 3 or more browsers, used the
	// identification's own address on your pages in 24 hours: context only),
	// sharedVisitors24h and sharedAccounts24h ("at least" counts: 1, 2, 5,
	// 10, 100 or 1000, as float64 like every JSON number) and
	// lookAlikeMatching (false: this computer was recognised only by its own
	// key, cookie or stored id, never because it looks like another one;
	// true: look-alike matching was allowed). Each is nil when not known:
	// kind, kindSource and vpn for an identification from before them; the
	// shared fields and lookAlikeMatching when not counted, or when ClientIP
	// was another address than the one the browser identified from
	// (sharedAccounts24h also with no account; lookAlikeMatching also when
	// not decided: phones, tablets and Safari).
	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, the detected ones first (webdriver,
	// headless, tool_<name> for each of tools, agent_verified), then the
	// suspected ones (pointer_synthetic, input_synthetic, agent_pace,
	// zero_window, headless_window, emulator, cdp: the DevTools protocol
	// attached, cdp_input: a press with no pressure, input_no_focus: a click
	// or key into a page that was not in front, insert_text_bulk: text with
	// no key pressed, scripted_click: a form sent with no click or key,
	// agent_unverified, agent_claimed), and soft_gpu next to another reason.
	// New reasons may be added in minor versions. Servers since 2026-11-24
	// also send (absent on older ones): type (ai_agent: an AI agent or bot by
	// its own identity or its marks on the page, 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 (whose
	// marks were on the page: the automation tools selenium, playwright,
	// puppeteer, phantomjs, nightmare and headless_chrome, and the AI agents
	// claude_agent (the Claude app's browser or Claude in Chrome),
	// comet_agent (Perplexity Comet), genspark_agent, browser_use, stagehand
	// and skyvern), 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). The AI agents' tools and the
	// reasons cdp_input, input_no_focus, insert_text_bulk and scripted_click
	// come from servers since 2026-11-25.
	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

func New(config ...*Config) (*Client, error)

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

func NewClient(config *Config) *Client

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) BotCheck added in v1.1.0

func (c *Client) BotCheck(ctx context.Context, req BotCheckRequest) (*BotCheckResult, error)

BotCheck asks which bot sent one request your server received (POST /device-risk/bot-check), for the visitors that never run your page's tag: ChatGPT-User, GPTBot, Meta's crawlers, curl and scripts. It sends the visitor's IP and headers. Touchque answers on its own servers, with no third-party service at request time (the bot operators' own published address lists and signing keys, fetched ahead of time, reverse DNS and its own network data), and keeps nothing but short-lived keyed-hash counters.

b, err := dr.BotCheck(ctx, devicerisk.BotCheckRequestFrom(req, ip))
if err == nil && b.Suggestion == "block" { logSpoofedBot(b.Bot.Name) } // a spoofed name; advice in shadow

Authorization, Cookie, Proxy-Authorization, X-Api-Key and Set-Cookie go with empty values, and the URL without its query string. What the visitor sent never makes it fail: past 100 headers, long names or values, or over 32 KB, the request is kept to the API's limits and says it was cut. No IP is a *ConfigError before anything is sent. 409 device_risk_off until your workspace turns Device risk on; 429 (RetryAfter) past your workspace's bot-check budget.

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

func (c *Client) GetEvent(ctx context.Context, requestID string) (map[string]interface{}, error)

GetEvent reads the trusted identification behind a requestId: the visitor (visitorId, confidence, matchedBy, mark: the mark actually applied, see CheckResult.Visitor), 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

type Config struct {
	APIKey    string
	APISecret string
	BaseURL   string
	TimeoutMs int
}

Config holds the client's configuration: the same API key and secret as the main Touchque SDK.

func ConfigFromEnv

func ConfigFromEnv() (*Config, error)

ConfigFromEnv builds a Config from TQ_API_KEY / TQ_API_SECRET / TQ_API_URL.

func DefaultConfig

func DefaultConfig(apiKey, apiSecret string) *Config

DefaultConfig creates a new Config with standard defaults.

func (*Config) Validate

func (c *Config) Validate() error

Validate checks the config and fills in defaults (BaseURL, TimeoutMs), without panicking.

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
	// NetworkKind is the kind of network (one of NetworkKinds; Kind is the
	// page), sent as networkKind. It matches only identifications classified
	// since network kind exists: older ones have no kind. Sent as it is, so a
	// kind newer than this version works; one the server does not know is a
	// 400 invalid_network_kind.
	NetworkKind string
	// Shared filters only when set, sent as shared=true or shared=false:
	// true, identifications whose own address was shared (many browsers on
	// your pages in 24 hours); false, the ones counted and not shared. An
	// identification that was not counted matches neither.
	Shared *bool
}

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). Servers from before network kind ignore NetworkKind and Shared: the search is then not narrowed by them.

type SearchResult

type SearchResult struct {
	Events     []map[string]interface{}
	NextCursor string
	From, To   string
}

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, its "matchedBy" against MatchedBy and its "network" as CheckResult.Network describes it.

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 on this network from devices like this one: phones,
	// or identical computers where look-alikes are not joined),
	// device_input_synthetic (typed or clicked like software) and
	// device_ai_agent (an AI agent or bot by its own signature or user agent,
	// or, on servers since 2026-11-25, an AI agent's marks on the page it
	// drives: the Claude app's browser or Claude in Chrome, Perplexity Comet,
	// Genspark, Browser Use, Stagehand, Skyvern);
	// 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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL