Skip to navigation

Go v5 configuration options

Browse available configuration options for the Go v5 Enforcer.

Each Enforcer has a set of configuration options that control the Enforcer’s functionality and features. While some are required, many of these are optional configurations that you can use to customize the Enforcer’s behavior. You can reference available configurations with this article. Define these options in application code with perimeterx.BuildconfigParams or perimeterx.NewconfigParamsBuilder, or in a JSON file loaded with perimeterx.GetconfigParamsFromJson.

While all Enforcers come with the same set of required configurations, the optional configurations available for each may differ. We recommend updating to the latest Enforcer version to ensure you have access to the latest features and configurations.

The Go Enforcer reads these options from a ConfigParams value. Build it in one of three ways:

  • Builder: Call perimeterx.NewconfigParamsBuilder with px_app_id, px_auth_token, and px_cookie_secret. Set every other option with the builder’s Set* methods, then call Build(). Note that some method names differ from the corresponding px_* key.
  • JSON: Store the px_* keys in a JSON file and load it with perimeterx.GetconfigParamsFromJson.
  • Directly: Pass a map[string]interface{} of px_* keys to perimeterx.BuildconfigParams.
Initialize ConfigParams with one of these three methods. A struct literal skips the defaults the builder applies.
Example
configParams, err := perimeterx.BuildconfigParams(map[string]interface{}{
"px_app_id": "<APP_ID>",
"px_auth_token": "<AUTH_TOKEN>",
"px_cookie_secret": "<COOKIE_SECRET>",
"px_module_mode": "active_blocking",
})

Quick reference

Feature nameKeyTypeDefaultDescription
Application IDpx_app_idStringnoneHUMAN Application ID
Authentication tokenpx_auth_tokenStringnoneHUMAN authentication token
Cookie secretpx_cookie_secretStringnoneHUMAN cookie secret
Backend domainpx_backend_urlStringhttps://sapi-<APP_ID>.perimeterx.netDomain to which HUMAN risk requests are sent
Collector domainpx_backend_collector_urlStringhttps://collector-<APP_ID>.perimeterx.netDomain to which HUMAN collector requests are sent
S2S timeoutpx_s2s_timeoutInteger1000Total time, in milliseconds, that the Enforcer will wait for the Risk API request to return before timing out and passing the request
Activities timeoutpx_activities_timeoutInteger1000Total time, in milliseconds, that the Enforcer will wait for an activity request to return
Blocking scorepx_blocking_scoreInteger1000-100. The minimum risk score that the Enforcer blocks from.

Required configurations

These configurations are necessary for the Enforcer’s basic functionality and features.

Basic functionality configurations

px_app_id
stringRequired

Your HUMAN Application ID in the form of PX12AB34CD. You can copy this value from the HUMAN Console in Platform Settings > Applications Overview. If you have multiple applications, make sure to copy the ID of the application you want the Enforcer on.

perimeterx.NewconfigParamsBuilder(map[string]interface{}{
"px_app_id": "<APP_ID>",
})
px_auth_token
stringRequired

The application’s server token needed to authorize with HUMAN’s backend. You can copy this value from the HUMAN Console in Platform Settings > Applications Overview > Click the appropriate application > Server token tab.

perimeterx.NewconfigParamsBuilder(map[string]interface{}{
"px_auth_token": "<AUTH_TOKEN>",
})
stringRequired

The secret used to encrypt and decrypt the risk cookie sent from the HUMAN Sensor. You can copy this value from the HUMAN Console in Sightline Cyberfraud Defense > Traffic Policy Overview > Click the appropriate application > Click the key > Copy value.

perimeterx.NewconfigParamsBuilder(map[string]interface{}{
"px_cookie_secret": "<COOKIE_SECRET>",
})
px_backend_url
stringDefaults to https://sapi-<APP_ID>.perimeterx.net

Do not set this value unless directed by your HUMAN Solutions Engineer.

The base URL for the HUMAN SAPI (Risk API and related calls). If empty, the Enforcer uses the default host for your Application ID.

SetRiskHost("https://sapi-<APP_ID>.perimeterx.net")
px_backend_collector_url
stringDefaults to https://collector-<APP_ID>.perimeterx.net

Do not set this value unless directed by your HUMAN Solutions Engineer.

The base URL for first-party XHR proxying and for the collector URL included on the block page. Async activities are sent to px_backend_url. If unset, the Enforcer uses https://collector-<APP_ID>.perimeterx.net.

SetCollectorHost("https://collector-<APP_ID>.perimeterx.net")
px_s2s_timeout
integerDefaults to 1000

The total time in milliseconds that the Enforcer will wait for the Risk API request to return before timing out and passing the request.

SetS2STimeout(2000)
px_activities_timeout
integerDefaults to 1000

The total time in milliseconds that the Enforcer will wait for an activity request to return.

SetActivitiesTimeout(2000)
px_blocking_score
integerDefaults to 100

The minimum risk score that the Enforcer will block. Ranges from 0 (lowest risk) to 100 (highest risk).

SetBlockingScore(20)

Basic feature configurations

px_logger_severity
"none" | "error" | "debug"Defaults to "error"

The severity at which the logger will output logs.

  • none: The logger will not generate any logs.
  • error: The logger will only generate logs on fatal errors.
  • debug: The logger will generate detailed logs for debugging purposes. Not recommended for production environments.

See px_logger_auth_token for a header-based alternative.

SetLoggerSeverityLevel("debug")
px_ip_headers
string[]Defaults to []

An array of header names that are trusted to contain the true client IP. Headers are traversed in the order they’re listed, and the first header value will always be used as the client IP.

The first non-empty value is used when it is a valid IP address. Otherwise, the Enforcer uses the connection’s remote address.

SetIPHeaders([]string{"x-true-ip", "x-real-ip"})
px_module_enabled
booleanDefaults to true

Whether the Enforcer module is enabled.

  • true: Enable the module
  • false: Disable the module
SetModuleEnabled(false)
px_module_mode
"monitor" | "active_blocking"Defaults to "monitor"

The Enforcer’s operation mode.

  • monitor: The Enforcer performs all functions without returning block responses. Useful for analyzing and adjusting Enforcer behavior without serving block pages to end users. If you have routes that must have enforcement at all times, see Enforced routes.
  • active_blocking: The Enforcer will return block responses as needed.
SetModuleMode("active_blocking")
px_send_page_activities
booleanDefaults to true

Whether the Enforcer sends a page_requested activity for requests that aren’t blocked. Disabling this feature prevents HUMAN from receiving the request data that populates the portal, including how many requests were processed.

SetSendPageActivities(false)
px_send_block_activities
booleanDefaults to true

Whether the Enforcer sends a block activity when a request is blocked. Disabling this feature prevents HUMAN from receiving block metrics.

SetSendBlockActivities(false)

Optional configurations

These configurations aren’t required, but you can use them to further customize the Enforcer’s behavior.

Additional activity handler

px_additional_activity_handler
functionDefaults to nil

A custom function passed to the Enforcer that runs after sending page_requested or block activity to the Collector and before forwarding the request to the next step in the pipeline. A common use case is to set the score as a variable or header. Then the application can read the score and do what is defined within the application’s logic.

Parameters:

  • config: perimeterx.ConfigParams
  • context: *perimeterx.PxContext
  • request: *http.Request

This function is not called when px_custom_verification_handler is set.

additionalActivityHandler := func(config perimeterx.ConfigParams, context *perimeterx.PxContext, request *http.Request) {
request.Header.Set("x-px-score", fmt.Sprint(context.Score))
}
SetAdditionalActivityHandler(additionalActivityHandler)

Advanced blocking response (ABR)

px_advanced_blocking_response_enabled
booleanDefaults to true

In specific cases such as XHR post requests, a full CAPTCHA page render might not be an option. In such cases, the Advanced Blocking Response (ABR) returns a JSON object containing all the information needed to render a customized CAPTCHA challenge implementation such as a popup modal, a section on the page, etc. This provides more flexibility and customizability in displaying the CAPTCHA challenge.

  • true: Enable ABR
  • false: Disable ABR
SetAdvancedBlockingResponseEnabled(false)
booleanDefaults to false

When set to true, the Enforcer does not call the Risk API when cookie decryption or validation fails. Instead, it blocks the request immediately.

SetBlockInvalidCookie(true)

Bypass monitor header

px_bypass_monitor_header
stringDefaults to x-px-block

Activates the full blocking flow to verify the flow works as expected if the specified header is present on the request with a value of 1. Often used to test the Enforcer block workflow during monitor mode, where the Enforcer usually collects data without blocking user requests, before switching to active_blocking. Requests with this header will go through the entire blocking workflow despite being in monitor mode.

To disable blocking behavior on the specified header, set the value to 0.

SetBypassMonitorHeader("x-human-block")

Credentials Intelligence

These configurations let you extract and detect compromised credentials. They’re closely related to Credentials Intelligence-related features in Sightline Cyberfraud Defense.

At minimum, ensure the following are configured to enable Credential Intelligence:

px_login_credentials_extraction_enabled
booleanDefaults to false

Whether to enable the extraction and reporting of credentials from the Enforcer for Credential Intelligence.

  • true: Enable Credential Intelligence
  • false: Disable Credential Intelligence
SetLoginCredentialsExtractionEnabled(true)
px_login_credentials_extraction
object[]Defaults to []

An array of configuration objects for each credential endpoint. Each element in the array is an object representing a distinct endpoint to which credentials are sent and includes:

  • How to identify these credential-bearing requests
  • How to extract the credentials from the request

Login success is configured once for the Enforcer with px_login_successful_reporting_method. To extract credentials with your own function for every request, use px_custom_credentials_extractor instead of this array.

path
stringDefaults to "/login"

The path of the request that contains the credentials. See path_type for how this value is compared with the request path.

Example
{
"path": "/sign-up"
}
path_type
"exact" | "regex"Defaults to "exact"

Whether the incoming request path is compared with path as an exact string or as a regular expression.

  • exact: The request path must equal path.
  • regex: The request path is used as the regular expression and is tested against path. The comparison is case-sensitive.
Example
{
"path": "/login",
"path_type": "exact"
}
method
"post" | "put" | "get"Defaults to "post"

The HTTP method of the request that contains the credentials. Accepted values are post, put, and get.

Example
{
"method": "post"
}
sent_through
"body" | "header" | "query-param"Defaults to "body"

Where the credentials are read from.

  • "body": The credentials are extracted according to user_field and pass_field from the request body. The Enforcer parses the body based on the Content-Type request header:
    • application/json
    • application/x-www-form-urlencoded
    • multipart/form-data
  • "header": The credentials are extracted according to user_field and pass_field from the request headers.
  • "query-param": The credentials are extracted according to user_field and pass_field from the request query parameters.

Use px_custom_credentials_extractor when credentials are not in one of these locations.

Example
{
"sent_through": "body"
}
user_field
stringDefaults to "username"

Required if sent_through is set to "body", "header", or "query-param". The name of the field containing the username in the request body, headers, or query parameters.

Supports subfields in cases of Content-Type: application/json bodies with nested objects. The subfields can be separated with periods. For example, the credential endpoint configuration object can include a user_field with the value "user_info.username" and a pass_field with the value "authentication.password" to support extracting the credentials.

{
// ...
sent_through: 'body',
user_field: 'username',
// ...
}

This field is optional. When it is omitted, the Enforcer uses username.

pass_field
stringDefaults to "password"

Required if sent_through is set to "body", "header", or "query-param". The name of the field, header name, or query parameter where the password can be found.

Supports subfields in cases of Content-Type: application/json bodies with nested objects. The subfields can be separated with periods. For example, the credential endpoint configuration object can include a user_field with the value "user_info.username" and a pass_field with the value "authentication.password" to support extracting the credentials.

{
// ...
sent_through: 'body',
user_field: 'username',
// ...
}

This field is optional. When it is omitted, the Enforcer uses password.

SetLoginCredentialsExtractionDetails([]interface{}{
map[string]interface{}{
"path": "/auth/[A-Za-z0-9]{12}/login",
"path_type": "regex",
"method": "post",
"sent_through": "body",
"user_field": "username",
"pass_field": "password",
},
map[string]interface{}{
"path": "/sign-up",
"method": "post",
"sent_through": "body",
"user_field": "user_info.username",
"pass_field": "authentication.password",
},
})
px_credentials_intelligence_version
"v2" | "multistep_sso"Defaults to "v2"

The credential hashing protocol for every configured credential endpoint. Credential Intelligence runs when the username, the password, or both are extracted.

  • "v2": The username and password from the same request are hashed together.
  • "multistep_sso": A non-empty password is reported as the password step. Otherwise a non-empty username is reported as the username step.
SetCIProtocol("multistep_sso")
px_compromised_credentials_header
stringDefaults to px-compromised-credentials

The header name to be set on the incoming request if the credentials are compromised. If this header is added, its value will always be 1. If credentials have not been identified as compromised, the header will not be added to the request.

SetPXCompromisedCredentialsHeader("x-ci-compromised")
px_additional_s2s_activity_header_enabled
booleanDefaults to false

Whether to attach the additional_s2s payload and URL as headers to the original request. This is done so that the additional_s2s activity can be enriched with the proper login_successful value and sent to the provided URL at a later stage. Enabling this configuration disables automatic sending of additional_s2s activity.

When set to true, the following headers are added to the origin request:

  • px-additional-activity: A JSON object containing the payload of the additional_s2s activity. The login_successful and http_status_code fields should be set prior to sending the activity.
  • px-additional-activity-url: The URL to which the additional_s2s payload should be sent as an HTTP POST request.
SetAdditionalS2SActivityHeaderEnabled(true)
px_send_raw_username_on_additional_s2s_activity
booleanDefaults to false

Whether to report the raw username on the additional_s2s activity.

  • false: The raw username is not reported.
  • true: The raw username is reported.
SetAddRawUsernameOnAdditionalS2SActivity(true)
px_login_successful_reporting_method
"status" | "body" | "header" | "custom"

How the Enforcer decides that a login succeeded. This method applies to every credential endpoint. Set it when Credential Intelligence is enabled. If it is unset, login success is not reported on the additional_s2s activity.

CreateDefaultHumanSecurityMiddleware wraps the handler’s http.ResponseWriter and calls PostEnforce after the handler returns. That call reads the response and reports login success. A custom middleware must pass a perimeterx.ResponseWriterWrapper into the handler, then call PostEnforce with that wrapper, the enforcement context, and the Runtime.

SetLoginResponseValidationMethod("status")
px_login_successful_status
integer[]Defaults to [200]

The default HTTP status codes that indicate a successful login. This takes effect when the px_login_successful_reporting_method is set to status.

Each value is an exact status code. To treat a range of codes as success, use px_custom_login_response_validation with px_login_successful_reporting_method set to custom.

SetLoginResponseValidationStatusCode([]interface{}{200, 202})
px_login_successful_body_regex
string

The default body regular expression that indicates a successful login. This takes effect when the px_login_successful_reporting_method is set to body.

SetRegexPatternToValidateLoginResponseBody("Welcome, [A-Za-z0-9_]+!")
px_login_successful_header_name
stringDefaults to x-px-login-successful

The default response header name that indicates a successful login. This takes effect when the px_login_successful_reporting_method is set to header.

SetHeaderNameToValidateLoginResponse("x-login-successful")
px_login_successful_header_value
stringDefaults to 1

The default response header value that indicates a successful login. This takes effect when the px_login_successful_reporting_method is set to header.

SetHeaderValueToValidateLoginResponse("1")
px_custom_credentials_extractor
functionDefaults to nil

A custom function that extracts credentials from the request. When this function is set, the Enforcer uses it instead of px_login_credentials_extraction.

The function signature is func(*perimeterx.RequestWrapper) *perimeterx.LoginCredentials. Return the extracted username and password, or nil when extraction is unsuccessful.

customCredentialsExtractor := func(requestWrapper *perimeterx.RequestWrapper) *perimeterx.LoginCredentials {
// Return nil when the username or password cannot be extracted.
return nil
}
SetCustomCredentialsExtractor(customCredentialsExtractor)
px_custom_login_response_validation
perimeterx.LoginResponseValidator

A custom implementation of perimeterx.LoginResponseValidator. The Enforcer calls IsSuccessfulLogin when px_login_successful_reporting_method is custom.

IsSuccessfulLogin receives the perimeterx.ResponseWriterWrapper passed to PostEnforce and returns whether the login succeeded. Response headers are available from Header().

type loginValidator struct{}
func (loginValidator) IsSuccessfulLogin(response perimeterx.ResponseWriterWrapper) bool {
return response.Header().Get("set-cookie") != ""
}
SetCustomLoginResponseValidator(loginValidator{})

CORS support

You can configure the Enforcer to support Cross-Origin Resource Sharing (CORS) requests. CORS is a mechanism that lets the server indicate if a request contains cross-origin resources by adding special HTTP headers to the request. These headers let the browser load these resources. Without them, the browser may block requests to these resources for security reasons instead.

In most cases, CORS employs a two-stage procedure with a preliminary “preflight” request followed by the actual request. The preflight request checks if the actual request will be responded to. To learn more about different request types, see these examples.

You must configure the Enforcer to address both simple requests (without preflight) and more complex ones (with preflight) to support CORS requests.

px_cors_support_enabled
booleanDefaults to false

Whether to enable CORS support.

  • true: Enable CORS support
  • false: Disable CORS support

After setting this configuration to true, the Enforcer:

SetCorsSupportEnabled(true)
px_cors_create_custom_block_response_headers
functionDefaults to nil

If the default CORS response headers are not sufficient, you can use this configuration to customize the headers that should be added to all block responses resulting from CORS requests. If this function is defined, the default headers will not be added. Only those headers specified in the returned object will be added to the block response.

Parameters:

The Go function also receives *perimeterx.PxContext.

customBlockHeaders := func(request *http.Request, context *perimeterx.PxContext) http.Header {
return http.Header{
"Access-Control-Allow-Origin": []string{request.Header.Get("Origin")},
"Access-Control-Allow-Credentials": []string{"true"},
"X-Custom-Header": []string{"1"},
}
}
SetCorsCreateCustomCorsHeaders(customBlockHeaders)
px_cors_preflight_request_filter_enabled
booleanDefaults to false

Disables enforcement for CORS preflight requests. When set to true, CORS preflight requests will be pass through the Enforcer flow without triggering detection or block responses.

  • true: Filter out preflight requests
  • false: Don’t filter out preflight requests
SetCorsFilterPreflightRequestsEnabled(true)
px_cors_custom_preflight_handler
functionDefaults to nil

A custom function to define desired behavior for handling CORS preflight requests, if needed. The custom function should receive the original HTTP request and return an object representing the HTTP response to be returned. If null or any other falsy value is returned from the function, the Enforcer will continue processing the preflight request.

The px_cors_custom_preflight_handler will be invoked prior to determining whether to filter the request based on the px_cors_preflight_request_filter_enabled configuration. This allows for returning customized responses for preflight requests that meet certain conditions and filtering those that don’t meet these conditions.

Parameters:

customPreflightHandler := func(request *http.Request) *http.Response {
if request.Header.Get("Access-Control-Request-Headers") == "" {
return nil
}
response := &http.Response{
StatusCode: http.StatusNoContent,
Header: http.Header{},
}
response.Header.Set("Access-Control-Allow-Origin", request.Header.Get("Origin"))
return response
}
SetCorsCustomPreflightHandler(customPreflightHandler)
stringDefaults to X-PX-Cookies

By default, the Enforcer extracts HUMAN cookies from the Cookie header. However, if these cookies are transferred on a different header, then that header’s name must be provided with this configuration.

SetCustomCookieHeader("x-custom-cookies")

Custom first party endpoints

These configurations let you use the Enforcer as a proxy for HUMAN servers and serve content to the browser from a first party endpoint. These are particularly useful when browser or extension restrictions that block JavaScript requests to other domains, such as adblockers, prevent the HUMAN Sensor from making requests to HUMAN’s backend. When this happens, it significantly limits HUMAN’s detection capabilities, so we recommend enabling these configurations to maintain full detection capabilities.

px_first_party_enabled
booleanDefaults to true

Whether to enable first party mode for Bot Defender or Sightline Cyberfraud Defense.

SetFirstPartyEnabled(false)
px_first_party_xhr_enabled
booleanDefaults to true

Whether first party XHR requests are proxied to the Collector. When this is false, or when px_first_party_enabled is false, requests to the first party XHR path receive an empty JSON body or, if the path ends in gif, an empty GIF, and are not forwarded.

SetFirstPartyXHREnabled(false)
px_first_party_timeout_ms
integerDefaults to 4000

The maximum time in milliseconds to wait for first party requests.

The checkpoint script uses px_activities_timeout instead.

SetFirstPartyTimeout(2000)

Custom parameters

These configurations are related to custom parameters.

px_enrich_custom_parameters
functionDefaults to nil

Enriches activities sent from the Enforcer to HUMAN with additional custom parameters. This data can include user information, session IDs, or other data that HUMAN should have access to. The function receives an empty parameters map and the incoming request, and must return the parameters map. The Enforcer sends custom_param1 through custom_param10.

Parameters:

Returns: map[string]interface{}

enrichCustomParams := func(customParams map[string]interface{}, request *http.Request) map[string]interface{} {
customParams["custom_param1"] = "string"
customParams["custom_param2"] = request.Method
return customParams
}
SetEnrichCustomParams(enrichCustomParams)

Custom verification handler

px_custom_verification_handler
functionDefaults to nil

A custom function that replaces the default block response. When this function is set, the Enforcer returns its result and does not render the default block page. Return an *http.Response to block the request, or nil to allow it. The additional activity handler is not called.

Parameters:

  • config: perimeterx.ConfigParams
  • context: *perimeterx.PxContext
  • request: *http.Request

Returns: *http.Response

customVerificationHandler := func(config perimeterx.ConfigParams, context *perimeterx.PxContext, request *http.Request) *http.Response {
if context.Score >= config.BlockingScore {
return perimeterx.Block(context, &config, request)
}
return nil
}
SetCustomVerificationHandler(customVerificationHandler)

Enforced routes

These configurations let you define specific routes that should be enforced by HUMAN when the Enforcer is in monitor mode. These routes will always be subject to the full Enforcer workflow, including blocking requests if necessary.

Primitive string values are treated as path prefixes. For example, /login also matches /login/callback.

px_enforced_routes
string[]Defaults to []

Routes or prefixes that should be enforced by HUMAN even when the Enforcer is in monitor mode.

SetEnforcedRoutes([]string{"/checkout", "/account/payment"})
px_enforced_routes_regex
string[]Defaults to []

Regular expressions for routes that are enforced even when px_module_mode is monitor. Each value is matched against the URL path.

SetEnforcedRoutesRegex([]string{"^/checkout", "^/account/.*/payment$"})

Filters

These configurations let you filter out certain requests or assets from the Enforcer. These values will be ignored by the Enforcer and will never be blocked.

px_filter_by_extension
string[]Defaults to [".css", ".bmp", ".tif", ".ttf", ".docx", ".woff2", ".js", ".pict", ".tiff", ".eot", ".xlsx", ".jpg", ".csv", ".eps", ".woff", ".xls", ".jpeg", ".doc", ".ejs", ".otf", ".pptx", ".gif", ".pdf", ".swf", ".svg", ".ps", ".ico", ".pls", ".midi", ".svgz", ".class", ".png", ".ppt", ".mid", ".webp", ".jar", ".map"]

Filters out requests whose path ends with one of the specified file extensions. By default, HUMAN doesn’t enforce static assets such as images and documents to minimize unnecessary API calls and computation, but you can configure this list at any time.

The comparison uses the path as received. See px_matrix_params_enabled to strip semicolon matrix parameters before the comparison.

SetExtensionsToBeFiltered([]string{".css", ".js", ".png", ".jpg"})
px_matrix_params_enabled
booleanDefaults to false

Whether the Enforcer removes semicolon matrix parameters from each path segment before comparing the path with px_filter_by_extension.

When this is false, a path is filtered when it ends with a configured extension. /assets/app.js;v=2 is not filtered, because it does not end in .js, and /admin/delete-user;.js is filtered, because it ends in .js.

When this is true, matrix parameters are removed first. /assets/app.js;v=2 is filtered as /assets/app.js, and /admin/delete-user;.js is not filtered, because the path is /admin/delete-user.

SetMatrixParamsEnabled(true)
px_filter_by_http_method
string[]Defaults to []

Filters out requests with the specified HTTP method to avoid unnecessary traffic in the Enforcer verification flow.

SetFilterByHttpMethods([]string{"OPTIONS", "TRACE"})
px_filter_by_ip
string[]Defaults to []

Filters out requests with the specified IP address to avoid unnecessary traffic in the Enforcer verification flow.

Each entry can be a single IP address or a CIDR range, such as 21.0.0.0/8.

SetFilterByIps([]string{"10.21.21.21", "21.0.0.0/8"})
px_filter_by_route
string[]Defaults to []

Filters out requests with the specified route to avoid unnecessary traffic in the Enforcer verification flow. Requests to these specified routes will never be blocked regardless of their risk score and will never generate risk or async activities. Primitive string values are treated as path prefixes. For example, /login also matches /login/callback.

SetWhitelistRoutes([]string{"/health", "/static"})
px_filter_by_route_regex
string[]Defaults to []

Regular expressions for routes that should be filtered to avoid unnecessary traffic in the Enforcer verification flow. Requests to these specified routes will never be blocked regardless of their risk score and will never generate risk or async activities.

SetWhitelistRoutesRegex([]string{"^/health$", "^/static/.*"})
px_filter_by_user_agent
string[]Defaults to []

Filters out requests with the specified user agent to avoid unnecessary traffic in the Enforcer verification flow. Each value must match the full user agent. The comparison is case-insensitive.

SetFilterByUserAgents([]string{"test-agent", "FilteredAgent"})

GraphQL support

These configurations let the Enforcer extract GraphQL data from requests so that it can enforce these requests in the same way as other types of traffic.

px_graphql_enabled
booleanDefaults to true

Whether to parse and report information about GraphQL operations on incoming requests. When true, requests whose path matches px_graphql_routes have their JSON bodies parsed for GraphQL operations.

SetGraphqlEnabled(true)
px_graphql_routes
string[]Defaults to [".*graphql.*"]

A list of regex routes that should be considered GraphQL routes. If a request’s route matches any of the regexes in this list, HUMAN checks for sensitive GraphQL operations as specified in px_sensitive_graphql_operation_names and px_sensitive_graphql_operation_types.

Each value is compiled as a regular expression.

SetGraphqlRoutes([]string{".*graphql.*", "^/gql$"})
px_sensitive_graphql_operation_names
string[]Defaults to []

A list of operation names that should be considered sensitive. Some routes may be more prone to bot attacks than others, such as routes that execute payments or handle personal information. You can configure these routes as sensitive to ensure a more stringent protection.

If one or more GraphQL operations has a name or keyword matching this list, the Enforcer will trigger a Risk API call even if the request contains a valid, unexpired cookie. Matches against extracted GraphQL words from:

Names are matched exactly. Use px_sensitive_graphql_operation_names_regex for regular expressions.

SetSensitiveGraphqlOperationNames([]string{"LoginOperation", "AccountInfoQuery"})
px_sensitive_graphql_operation_names_regex
string[]Defaults to []

A list of regular expressions for GraphQL operation names that should be considered sensitive. The Enforcer uses these expressions when px_sensitive_graphql_operation_names is unset, and it also tests extracted GraphQL keywords against them. A match triggers a Risk API call even if the request contains a valid, unexpired cookie.

SetSensitiveGraphqlOperationNamesRegex([]string{"(?i)login", "^Account.*"})
px_sensitive_graphql_operation_types
"query" | "mutation" | "subscription"Defaults to []

A list of operation types that should be considered sensitive. Some routes may be more prone to bot attacks than others, such as routes that execute payments or handle personal information. You can configure these routes as sensitive to ensure a more stringent protection.

If one or more GraphQL operations on an HTTP request has a type matching this list, the Enforcer will trigger a Risk API call even if the request contains a valid, unexpired cookie.

SetSensitiveGraphqlOperationTypes([]string{"query", "mutation"})
px_graphql_keywords
string[]Defaults to []

A list of regular expressions of keywords to identify important terms from GraphQL operation queries. These keywords are used to determine the purpose of the operation (such as login, checkout, or search) and can also be used to specify which operations should be considered sensitive. Any matching patterns will be extracted and reported to HUMAN. See px_sensitive_graphql_operation_names for more information. See px_extract_graphql_keywords for an alternative using a custom function.

Each value is compiled as a regular expression and matched against the GraphQL query.

SetGraphqlKeywords([]string{"performLogin", "addToCart", "keyword\\d+"})
px_extract_graphql_keywords
functionDefaults to nil

A custom function that identifies key terms from GraphQL operation queries. When this function is set, the Enforcer uses its return value and does not evaluate px_graphql_keywords.

This function accepts the GraphQL query string and must return the keywords found in the query. These keywords are used to determine the purpose of the operation (such as login, checkout, or search) and can also be used to specify which GraphQL operations should be considered sensitive. See px_sensitive_graphql_operation_names for more information.

Parameters:

  • query: string

Returns: []string

extractGraphqlKeywords := func(query string) []string {
if strings.Contains(query, "performLogin") {
return []string{"login"}
}
return []string{}
}
SetCustomGraphqlKeywordsExtractor(extractGraphqlKeywords)

HUMAN Challenge and hard block customization

These configurations let you customize the HUMAN Challenge block page as well as the hard block page, which appears when a request is blocked without a Challenge. Hard block pages inherit the same styling as the HUMAN Challenge according to the following configurations and cannot be customized separately.

px_css_ref
string

A way to include a custom CSS file to the block page.

Maps to {{cssRef}} in the hard block page template.

SetCSSRef("https://www.example.com/custom_style.css")
px_js_ref
string

A way to include custom JavaScript to the block page. This script will run after the default JavaScript scripts.

Maps to {{jsRef}} in the hard block page template.

SetJsRef("https://www.example.com/custom_script.js")
string

Adds a custom logo to the HUMAN Challenge block page via URL.

Maps to {{customLogo}} in the hard block page template.

SetCustomLogo("https://www.example.com/custom_logo.png")

Monitored routes

These configurations let you specify routes that should be monitored by the Enforcer, which means their requests will never be blocked, even when the Enforcer is in active_blocking mode. This means that these routes will go through the full Enforcer workflow and generate risk and async activities, but all block activities will only be simulated blocks on these routes.

Primitive string values are treated as path prefixes. For example, /login also matches /login/callback.

px_monitored_routes
string[]Defaults to []

A list of endpoints to be monitored rather than blocked by the Enforcer, even when the Enforcer is in active_blocking mode.

Values are path prefixes. /preview also matches /preview/draft.

SetMonitoredRoutes([]string{"/preview", "/internal/draft"})
px_monitored_routes_regex
string[]Defaults to []

Regular expressions for routes that should be treated as monitored even when the Enforcer is in active_blocking mode.

SetMonitoredRoutesRegex([]string{"^/preview", "^/internal/.*/draft$"})
px_custom_is_monitored_request
functionDefaults to nil

This configuration is meant for cases that require more complex logic. We recommended you use px_monitored_routes for most cases.

A custom function that lets you define which endpoints should be monitored based on custom logic such as a header, HTTP method, or user agent. It accepts the incoming request as an argument and returns true when the request should be monitored.

Parameters:

This function is only called when the module mode is in active_blocking, the bypass monitor header isn’t present, and there are no matching monitored routes. If the function panics, the request is treated as not monitored.

isMonitoredRequest := func(req *http.Request) bool {
return req.Header.Get("set-monitor-mode") == "true"
}
SetCustomIsMonitoredRequest(isMonitoredRequest)

Remote Configuration

Remote Configuration lets you update your Enforcer’s configuration from the HUMAN portal rather than interacting with the Enforcer package directly.

px_logger_auth_token
string

An alternative to the basic logger configuration. This sends Enforcer logs to HUMAN’s logging service if a specific header is present on the request. This is particularly useful for expedited debugging, diagnosis, and resolution of any integration or Enforcer-related issues.

Contact HUMAN to receive your token.

SetLoggerAuthToken("<LOGGER_AUTH_TOKEN>")
px_remote_config_enabled
booleanDefaults to false

Whether enforcement uses the configuration returned by Remote Configuration. When this is false, the Enforcer keeps using the configuration you set at startup. Set this to true together with px_remote_config_id and px_remote_config_auth_token.

SetRemoteConfigEnabled(true)
px_remote_config_auth_token
string

The token used to authenticate the Enforcer with the HUMAN Remote Configuration service.

Contact HUMAN to receive your token.

SetRemoteConfigAuthToken("<REMOTE_CONFIG_AUTH_TOKEN>")
px_remote_config_id
string

The ID associated with the Remote Configuration.

Contact HUMAN to receive your ID.

SetRemoteConfigId("00000000-0000-0000-0000-000000000000")
px_remote_config_timeout
integerDefaults to 5000

The amount of time, in milliseconds, to wait for a Remote Configuration request.

SetRemoteConfigTimeout(3000)
px_remote_config_max_age_seconds
integerDefaults to 600

The maximum length of time, in seconds, between requests to update the Remote Configuration.

SetRemoteConfigMaxAgeSeconds(300)

Sensitive headers removal

px_sensitive_headers
string[]Defaults to ["cookie", "cookies"]

Specifies certain headers that should not be forwarded to any other destination, including the HUMAN Detector. While HUMAN’s detection system will continue to use these headers to determine whether to block or not, the specified headers won’t be forwarded from the Enforcer, won’t appear in Enforcer activities, and won’t be sent to any other IP if the Enforcer acts as a proxy.

The application still receives these headers. The Enforcer omits them from requests it sends to HUMAN and from first-party proxy requests.

SetSensitiveHeaders([]string{"cookie", "cookies", "x-sensitive-token"})

Sensitive routes

These configurations let you specify certain routes that need particularly stringent protection from attacks, such as endpoints that execute payments or handle personal information. Sensitive routes will always trigger a Risk API call even if the request contains a valid, unexpired, low-score cookie.

Primitive string values are treated as path prefixes. For example, /login also matches /login/callback.

Requests with high-score cookies won’t send a Risk API call.

px_sensitive_routes
string[]Defaults to []

A list of prefixes for all routes that should be considered sensitive.

SetSensitiveRoutes([]string{"/login", "/checkout"})
px_sensitive_routes_regex
string[]Defaults to []

A list of regular expressions for all routes that should be considered sensitive.

SetSensitiveRoutesRegex([]string{"^/login$", "^/api/.*/checkout$"})
px_custom_is_sensitive_request
functionDefaults to nil

This configuration is meant for cases that require more complex logic. We recommended you use px_sensitive_routes for most cases.

A custom function that lets you define which requests should be considered sensitive based on custom logic. It accepts the incoming request as an argument and returns a boolean indicating whether the request should be considered sensitive.

Parameters:

A panic inside this function is recovered and treated as false.

isSensitiveRequest := func(req *http.Request) bool {
return req.Method == http.MethodPost || req.Method == http.MethodPut
}
SetCustomIsSensitiveRequest(isSensitiveRequest)

Users identifiers

These configurations let you extract user identifiers from a JWT carried on the request either in a cookie or a header. They’re closely related to the Accounts and Account Takeover or Fake Account features in Sightline Cyberfraud Defense.

The Enforcer reads the JWT from the configured cookie first, then from the configured header if cookie extraction does not succeed. Field names support dot notation for nested JWT claim (for example, product.id).

string

The name of the cookie that contains the JWT token that HUMAN should extract user identifiers from.

SetJwtCookieName("auth")
string

The field name in the JWT object, extracted from the JWT cookie, that contains the user ID to be extracted and reported.

SetJwtCookieUserIdFieldName("nameID")
string[]Defaults to []

The field names in the JWT object, extracted from the JWT cookie, that should be extracted and reported in addition to the user ID.

SetJwtCookieAdditionalFieldNames([]string{"exp", "iss"})
px_jwt_header_name
string

The name of the header that contains the JWT token that HUMAN should extract user identifiers from.

SetJwtHeaderName("x-jwt-authorization")
px_jwt_header_user_id_field_name
string

The field name in the JWT object, extracted from the JWT header, that contains the user ID to be extracted and reported.

SetJwtHeaderUserIdFieldName("sub")
px_jwt_header_additional_field_names
string[]Defaults to []

The field names in the JWT object, extracted from the JWT header, that should be extracted and reported in addition to the user ID.

SetJwtHeaderAdditionalFieldNames([]string{"exp", "iss"})