> This page is for Applications Protection.

> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.humansecurity.com/llms.txt.

# Configuration

## Overview

The HUMAN enforcer can be configured within the JavaScript code via the `HumanSecurityConfiguration` object.

## HumanSecurityConfiguration

An object of configuration values that dictate the behavior of the HumanSecurityEnforcer. This object is needed when initializing a new HumanSecurityEnforcer instance.

Required values:

* px\_app\_id
* px\_auth\_token
* px\_cookie\_secret

### px\_app\_id

The application ID. Required to initialize the Enforcer.

```ts
const config: HumanSecurityConfiguration = {
    // ...
    px_app_id: '`<APP_ID>`',
    // ...
}
```

\


### px\_auth\_token

The token used for authorization with the HUMAN backend. Required to initialize the Enforcer.

```ts
const config: HumanSecurityConfiguration = {
    // ...
    px_auth_token: '`<AUTH_TOKEN>`',
    // ...
}
```

### px\_cookie\_secret

The secret used to encrypt and decrypt the risk cookie. Required to initialize the Enforcer.

```ts
const config: HumanSecurityConfiguration = {
    // ...
    px_cookie_secret: '`<COOKIE_SECRET>`',
    // ...
}
```

### px\_module\_enabled

This boolean serves as an on/off switch for the entire module, providing a way to enable and disable all Enforcer capabilities quickly and easily.

**Default**: `true`

```ts
const config: HumanSecurityConfiguration = {
    // ...
    px_module_enabled: false,
    // ...
}
```

### px\_module\_mode

This feature controls the behavior of the enforcer by changing how it executes certain parts of the workflow. Most notably, different modes allow for analysis and fine-tuning of the enforcer behavior without serving block pages that affect end users.

Possible values:

* `"monitor"` - the enforcer will perform all functions without returning block responses
* `"active_blocking"` - the enforcer will return block responses when needed

**Default**: `"monitor"`

```ts
const config: HumanSecurityConfiguration = {
    // ...
    px_module_mode: 'active_blocking',
    // ...
}
```

### px\_logger\_severity

The verbosity of the logs generated by the enforcer.

Possible values:

* `"none"` - No logs will be generated
* `"error"` - Sparse logs will be generated only when errors occur
* `"debug"` - Detailed logs will always be generated (not advisable for production environments)

**Default**: `"error"`

```ts
const config: HumanSecurityConfiguration = {
    // ...
    px_logger_severity: 'debug',
    // ...
}
```

### px\_s2s\_timeout

The maximum time in milliseconds to wait for the risk API request. If this timeout is reached, the original request will be allowed to pass (fail open).

**Default**: `1000`

```ts
const config: HumanSecurityConfiguration = {
    // ...
    px_s2s_timeout: 2000,
    // ...
}
```

### px\_ip\_headers

By default, the IP is taken from the [req.ip property](https://expressjs.com/en/api.html#req.ip). However, if this value is inaccurate, the enforcer can extract the IP from the headers configured here. The headers are traversed in the order they are listed. The first header value that exists will be used as the client IP.

**Default**: `[]`

```ts
const config: HumanSecurityConfiguration = {
    // ...
    px_ip_headers: ['true-ip', 'true-client-ip'],
    // ...
}
```

### px\_advanced\_blocking\_response\_enabled

In specific cases (e.g., XHR post requests), a full captcha page render might not be an option. In such cases the advanced blocking response returns a JSON object containing all the information needed to render a customized captcha challenge implementation - be it a popup modal, a section on the page, etc. This allows for flexibility and customizability in terms\
of how the captcha pages are displayed.

**Default**: `true`

```ts
const config: HumanSecurityConfiguration = {
    // ...
    px_advanced_blocking_response_enabled: false,
    // ...
}
```

### px\_first\_party\_enabled

To prevent suspicious or unwanted behavior on the client side, some browsers or extensions (e.g., adblockers) may deny the frontend JavaScript code from making requests to other domains. This prevents the HUMAN sensor from making requests to the HUMAN backends, which greatly limits HUMAN's detection capabilities. To avoid this problem, first party enables the enforcer to be used as a proxy for HUMAN servers, and to serve content to the browser from a first party endpoint (i.e., an endpoint on the customer’s domain).

**Default**: `true`

```ts
const config: HumanSecurityConfiguration = {
    // ...
    px_first_party_enabled: false,
    // ...
}
```

### px\_custom\_first\_party\_prefix

By default, first party endpoints always begin with the application ID without the initial "PX". For example, if the application ID is `PX12345678`, then all first party routes will take the form `/12345678/*`. This configuration sets a custom prefix for first party routes to use in addition to the default prefix. When configured, the enforcer will respond to first party requests with endpoints matching the patterns `/<px_custom_first_party_prefix>/init.js`, `/<px_custom_first_party_prefix>/xhr/*`, and `/<px_custom_first_party_prefix>/captcha/*`.

**Default**: `""` (when empty, will use the default as described above)

```ts
const config: HumanSecurityConfiguration = {
    // ...
    px_custom_first_party_prefix: "/custom-prefix",
    // ...
}
```

### px\_custom\_first\_party\_sensor\_endpoint

For an application with ID `PX12345678`, the first party sensor endpoint is `/12345678/init.js` by default. This configuration customizes the entire first party sensor script endpoint. Note that in addition to responding to requests that match this configured route, the enforcer will also proxy first party requests that match the default pattern (`/12345678/init.js`) and patterns according to the custom prefix (`/<px_custom_first_party_prefix>/init.js`) if one is configured.

**Default**: `""`

```ts
const config: HumanSecurityConfiguration = {
    // ...
    px_custom_first_party_sensor_endpoint: "/human_sensor",
    // ...
}
```

### px\_custom\_first\_party\_xhr\_endpoint

For an application with ID `PX12345678`, the first party XHR endpoint is `/12345678/xhr` by default. This configuration customizes the first party XHR endpoint. Note that in addition to responding to requests that match this configured route, the enforcer will also proxy first party requests that match the default pattern (`/12345678/xhr/*`) and patterns according to the custom prefix (`/<px_custom_first_party_prefix>/xhr/*`) if one is configured.

**Default**: `""`

```ts
const config: HumanSecurityConfiguration = {
    // ...
    px_custom_first_party_xhr_endpoint: "/human_xhr",
    // ...
}
```

### px\_custom\_first\_party\_captcha\_endpoint

For an application with ID `PX12345678`, the first party captcha endpoint is `/12345678/captcha` by default. This configuration customizes the first party captcha endpoint. Note that in addition to responding to requests that match this configured route, the enforcer will also proxy first party requests that match the default pattern (`/12345678/captcha/*`) and patterns according to the custom prefix (`/<px_custom_first_party_prefix>/captcha/*`) if one is configured.

**Default**: `""`

```ts
const config: HumanSecurityConfiguration = {
    // ...
    px_custom_first_party_captcha_endpoint: "/human_captcha",
    // ...
}
```

### px\_first\_party\_timeout\_ms

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

**Default**: `4000`

```ts
const config: HumanSecurityConfiguration = {
    // ...
    px_first_party_timeout_ms: 5000,
    // ...
}
```

### px\_bypass\_monitor\_header

When enabling the enforcer for the first time, it is recommended to do so in monitor mode to collect data before actually starting to block user requests. Prior to switching the module mode to active\_blocking entirely, it's also crucial to verify that the full blocking flow works as expected. This feature activates the full blocking flow even while in monitor mode if a particular header is present on the request.

**Default**: `""`

```ts
const config: HumanSecurityConfiguration = {
    // ...
    px_bypass_monitor_header: 'x-px-block',
    // ...
}
```

### px\_enforced\_routes

Customers may want certain, but not all, endpoints to be enforced by HUMAN, even when the Enforcer is in monitor mode. These routes will go through the full enforcer workflow, including blocking requests when necessary. That is, even when the enforcer is in monitor mode, these defined routes will behave as if in active blocking mode.

**Default**: `[]`

```ts
const config: HumanSecurityConfiguration = {
    // ...
    px_enforced_routes: ['/enforced_route', /.*\/enforced\/regex$/],
    // ...
}
```

### px\_custom\_is\_enforced\_request

> **Note**
>
> This configuration is meant for cases that require more complex custom logic. It is recommended to use the `px_enforced_routes` configuration for simpler cases.

Customers may want certain, but not all, endpoints to be enforced by HUMAN, even when the Enforcer is in monitor mode. This configurable function provides a way to define which requests should be enforced based on custom logic. The function accepts the incoming request as an argument and returns a boolean indicating whether the request should be enforced (the request will behave as if in active blocking mode) or not.

* Parameters
  * request: [Request](https://expressjs.com/en/api.html#req)
* Returns a boolean (or a Promise resolving to a boolean)

**Default**: `null`

```ts
const config: HumanSecurityConfiguration = {
    // ...
    px_custom_is_enforced_request: (request: Request): boolean | Promise<boolean> => {
        return request.method === 'POST' && request.path.includes('/enforced_route');
    },
    // ...
}
```

### px\_monitored\_routes

Enables certain endpoints to be monitored rather than enforced by HUMAN, even when the enforcer is in active blocking mode.

**Default**: `[]`

```ts
const config: HumanSecurityConfiguration = {
    // ...
    px_monitored_routes: ['/monitored_route', /.*\/monitored\/regex$/],
    // ...
}
```

### px\_custom\_is\_monitored\_request

> **Note**
>
> This configuration is meant for cases that require more complex custom logic. It is recommended to use the `px_monitored_routes` configuration for simpler cases.

Customers may want certain, but not all, endpoints to be monitored by HUMAN, even when the Enforcer is in active\_blocking mode. This configurable function provides a way to define which requests should be monitored based on custom logic. The function accepts the incoming request as an argument and returns a boolean indicating whether the request should be monitored (the request will behave as if in monitor mode) or not.

* Parameters
  * request: [Request](https://expressjs.com/en/api.html#req)
* Returns a boolean (or a Promise resolving to a boolean)

**Default**: `null`

```ts
const config: HumanSecurityConfiguration = {
    // ...
    px_custom_is_monitored_request: (request: Request): boolean | Promise<boolean> => {
        return request.method === 'GET' && request.path.includes('/monitored');
    },
    // ...
}
```

### px\_sensitive\_headers

The HUMAN detector requires information about the HTTP request as part of its bot detections. Certain headers may contain information that should not be forwarded to other servers, including the HUMAN backend. Configuring these header names as sensitive headers will remove these headers from requests sent to other backends by HUMAN.

**Default**: `["cookie", "cookies"]`

```ts
const config: HumanSecurityConfiguration = {
    // ...
    px_sensitive_headers: ['x-sensitive-token'],
    // ...
}
```

### px\_sensitive\_routes

Certain endpoints may require more stringent protection from bot attacks (e.g., endpoints that execute payments or handle personal information). In these cases, routes can be configured as sensitive routes, meaning risk API calls will be made even if the request contains a valid, unexpired cookie.

**Default**: `[]`

```ts
const config: HumanSecurityConfiguration = {
    // ...
    px_sensitive_routes: ['/login', /.*\/sensitive\/regex$/],
    // ...
}
```

### px\_custom\_is\_sensitive\_request

> **Note**
>
> This configuration is meant for cases that require more complex custom logic. It is recommended to use the `px_sensitive_routes` configuration for simpler cases.

Requests can be configured as sensitive, meaning risk API calls will be made even if the request contains a valid, unexpired cookie. This configurable function provides a way to define which requests should be considered sensitive based on custom logic. The function accepts the incoming request as an argument and returns a boolean indicating whether the request should be considered sensitive or not.

* Parameters
  * request: [Request](https://expressjs.com/en/api.html#req)
* Returns a boolean (or a Promise resolving to a boolean)

**Default**: `null`

```ts
const config: HumanSecurityConfiguration = {
    // ...
    px_custom_is_sensitive_request: (request: Request): boolean | Promise<boolean> => {
        return request.method === 'POST' || request.method === 'PUT';
    },
    // ...
}
```

### px\_filter\_by\_extension

HUMAN does not enforce static assets such as images and documents. To prevent unnecessary API calls to HUMAN servers and needless computation, the enforcer filters all requests with a valid static file extension. Filtering by extension only applies to HTTP requests with methods GET and HEAD.

**Default**: `[ '.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', '.json', '.xml' ]`

```ts
const config: HumanSecurityConfiguration = {
    // ...
    px_filter_by_extension: ['.css', '.js', '.png'],
    // ...
}
```

### px\_filter\_by\_http\_method

Filters out requests according to their HTTP method, avoiding unnecessary traffic in the enforcer verification flow and reducing operating costs.

**Default**: `[]`

```ts
const config: HumanSecurityConfiguration = {
    // ...
    px_filter_by_http_method: ['OPTIONS'],
    // ...
}
```

### px\_filter\_by\_ip

Filters out requests according to their IP address, avoiding unnecessary traffic in the enforcer verification flow and reducing operation costs.

**Default**: `[]`

```ts
const config: HumanSecurityConfiguration = {
    // ...
    px_filter_by_ip: ['1.1.1.1', '2.2.2.2/8'],
    // ...
}
```

### px\_filter\_by\_route

Route prefixes (endpoints) specified here will not be blocked, regardless of the score they receive. A request to a filtered route will not generate any risk or async activities.

**Default**: `[]`

```ts
const config: HumanSecurityConfiguration = {
    // ...
    px_filter_by_route: ['/filtered_route', /.*\/filtered\/regex$/],
    // ...
}
```

### px\_filter\_by\_user\_agent

Filters out requests according to their user agent value, avoiding unnecessary traffic in the enforcer verification flow and reducing operation costs.

**Default**: `[]`

```ts
const config: HumanSecurityConfiguration = {
    // ...
    px_filter_by_user_agent: ['filtered_UA'],
    // ...
}
```

### px\_custom\_is\_filtered\_request

This configuration is meant for cases that require more complex custom logic. It is recommended to use the `px_filter_by_route`, `px_filter_by_user_agent`, `px_filter_by_http_method`, `px_filter_by_ip`, and `px_filter_by_extension` configurations for simpler cases.

Customers may prefer to filter certain requests (i.e., not apply HUMAN enforcement at all). These requests will not be blocked, and they will not generate any risk or async activities. This configurable function provides a way to define which requests should be filtered based on custom logic. The function accepts the incoming request as an argument and returns a boolean indicating whether the request should be filtered or not.

* Parameters
  * request: [Request](https://expressjs.com/en/api.html#req)
* Returns a boolean (or a Promise resolving to a boolean)

**Default**: `null`

```ts
const config: HumanSecurityConfiguration = {
    // ...
    px_custom_is_filtered_request: (request: Request): boolean | Promise<boolean> => {
        return request.method === 'GET' && request.path.includes('/static/');
    },
    // ...
}
```

### px\_css\_ref

Provides a way to include an additional custom .css file to add to the block page.

**Default**: `""`

```ts
const config: HumanSecurityConfiguration = {
    // ...
    px_css_ref: 'https://www.example.com/custom_style.css',
    // ...
}
```

### px\_js\_ref

Provides a way to include a custom JS script to add to the block page. This script will run after the default JS scripts.

**Default**: `""`

```ts
const config: HumanSecurityConfiguration = {
    // ...
    px_js_ref: 'https://www.example.com/custom_script.js',
    // ...
}
```

### px\_custom\_logo

Adds a custom logo to the block page that will be shown to users. This aligns the block page with the customer's brand.

**Default**: `""`

```ts
const config: HumanSecurityConfiguration = {
    // ...
    px_custom_logo: 'https://www.example.com/custom_logo.png',
    // ...
}
```

### px\_custom\_cookie\_header

The Enforcer attempts to extract the HUMAN cookies from the 'Cookie' header. If the HUMAN cookies are transferred on a header other than 'Cookies', the header name should be configured here.

**Default**: `"x-px-cookies"`

```ts
const config: HumanSecurityConfiguration = {
    // ...
    px_custom_cookie_header: 'x-custom-cookies',
    // ...
}
```

### px\_user\_agent\_max\_length

The maximum length of the `User-Agent` header. If the user agent header value exceeds this length, it will be truncated to this length prior to processing.

**Default**: `8528`

```ts
const config: HumanSecurityConfiguration = {
    // ...
    px_user_agent_max_length: 2048,
    // ...
}
```

This value should not be changed without consulting with the HUMAN Customer Success team.

### px\_secured\_pxhd\_enabled

Whether the PXHD cookie set on the HTTP response should include the [Secure attribute](https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#restrict_access_to_cookies).

**Default**: `false`

```ts
const config: HumanSecurityConfiguration = {
    // ...
    px_secured_pxhd_enabled: true,
    // ...
}
```

### px\_max\_activity\_batch\_size

By default, asynchronous activities are sent to the HUMAN backend after processing every request. To reduce the number of HTTP requests made by the Express server to the HUMAN backend, it is possible to save these activities in memory and send them in a single HTTP request. This configuration specifies the maximum number of asynchronous activities to store in-memory before sending them to the HUMAN backend.

The enforcer will send asynchronous activities in batches only when the `px_max_activity_batch_size` configuration is greater than 1. Batches will be sent whenever the number of async activities reaches the configured `px_max_activity_batch_size`, or after `px_batch_activities_timeout_ms` milliseconds have passed since the previous batch was sent, whichever comes first.

**Default**: 0

```ts
const config: HumanSecurityConfiguration = {
    // ...
    px_max_activity_batch_size: 20,
    // ...
}
```

### px\_batch\_activities\_timeout\_ms

By default, asynchronous activities are sent to the HUMAN backend after processing every request. To reduce the number of HTTP requests made by the Express server to the HUMAN backend, it is possible to save these activities in memory and send them in a single HTTP request. This configuration specifies the maximum amount of time (in milliseconds) to wait between requests sending the batched activities to the HUMAN backend.

The enforcer will send asynchronous activities in batches only when the `px_max_activity_batch_size` configuration is greater than 1. Batches will be sent whenever the number of async activities reaches the configured `px_max_activity_batch_size`, or after `px_batch_activities_timeout_ms` milliseconds have passed since the previous batch was sent, whichever comes first.

**Default**: 1000

```ts
const config: HumanSecurityConfiguration = {
    // ...
    px_batch_activities_timeout_ms: 2000,
    // ...
}
```

### px\_cors\_support\_enabled

CORS (Cross-Origin Resource Sharing) is a mechanism that enables the server to indicate when a request contains cross-origin resources. It does so by adding special HTTP headers to the request, which permits the browser to load these resources. Without these headers, the browser may block requests to these resources for security reasons.

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](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#examples_of_access_control_scenarios).

In the Enforcer, CORS behavior must be configured to address both simple requests (without preflight) and more complex ones (with preflight). Enabling CORS support via this configuration will have the following effects:

* It will automatically add the following default CORS response headers to block responses resulting from CORS requests.

```none
Access-Control-Allow-Origin: `<ORIGIN_REQUEST_HEADER_VALUE>`
Access-Control-Allow-Credentials: true
```

* It will activate the `px_cors_create_custom_block_response_headers` configuration, which will allow for customizing the block response headers via a custom function.
* It will activate the `px_cors_preflight_request_filter_enabled` and `px_cors_custom_preflight_handler` configurations, which allow for filtering and custom handling of preflight requests.

**Default**: `false`

```ts
const config: HumanSecurityConfiguration = {
    // ...
    px_cors_support_enabled: true,
    // ...
}
```

### px\_cors\_create\_custom\_block\_response\_headers

If the default CORS response headers are not sufficient, this configuration can be used to completely 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
  * request: [Request](https://expressjs.com/en/api.html#req)
* Returns an object of the type Record\<string, string\[]> (or a Promise resolving to this type)

**Default:** `null`

```ts
const config: HumanSecurityConfiguration = {
    // ...
    px_cors_create_custom_block_response_headers: (
        request: Request,
    ): Record<string, string[]> => {
        return {
            'Access-Control-Allow-Origin': [request.get('origin')],
            'Access-Control-Allow-Credentials': ['false'],
            'Access-Control-Allow-Methods': ['GET', 'POST', 'PUT'],
            'X-Custom-Header': ['1']
        };
    },
    // ...
}
```

### px\_cors\_preflight\_request\_filter\_enabled

This configuration disables enforcement for CORS preflight requests. When this configuration is set to true, CORS preflight requests will be filtered from the enforcer flow. That is, they will pass through the enforcer flow without triggering detection or block responses.

**Default**: `false`

```ts
const config: HumanSecurityConfiguration = {
    // ...
    px_cors_preflight_request_filter_enabled: true,
    // ...
}
```

### px\_cors\_custom\_preflight\_handler

If a more customized approach is needed for handling CORS preflight requests, this custom function can be set to define the desired behavior. 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.

> **Custom Preflight Handler and Preflight Request Filtering**
>
> The `px_cors_custom_preflight_handler` will be invoked prior to determining whether or not 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
  * request: [Request](https://expressjs.com/en/api.html#req)
* Returns either null or an object implementing the `IMinimalResponse` interface (defined below). It is also possible to return a Promise resolving to one of these types.

```ts
interface `IMinimalResponse` {
    status: number;
    headers: Record<string, string[]>;
    body: any;
};
```

**Default**: `null`

```ts
const config: HumanSecurityConfiguration = {
    // ...
    px_cors_custom_preflight_handler: (request: Request): ``IMinimalResponse`` | ``Promise<``IMinimalResponse``>`` => {
        const headers = {
            'Access-Control-Allow-Origin': [request.get('origin')],
            'Access-Control-Allow-Methods': [request.get('access-control-request-method')],
            'Access-Control-Allow-Headers': [request.get('access-control-request-headers')],
            'Access-Control-Allow-Credentials': ['true'],
            'Access-Control-Max-Age': ['86400']
        };
        return {
            status: 204,
            headers,
            body: null,
        };
    },
    // ...
}
```

### px\_additional\_activity\_handler

The additional activity handler is a custom function passed to the enforcer. The enforcer runs this callback 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 of the additional activity handler 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: HumanSecurityConfiguration
  * context: IContext
  * request: [Request](https://expressjs.com/en/api.html#req)
* Returns void or a Promise resolving to void

**Default**: `null`

```ts
const config: HumanSecurityConfiguration = {
    // ...
    px_additional_activity_handler: (
        config: HumanSecurityConfiguration,
        context: IContext,
        request: Request
    ): void => {
        request.setHeader('x-px-score', `${context.score}`);
        request.setHeader('x-px-rtt', `${context.riskApiData.riskRtt}`);
    },
    // ...
}
```

### px\_enrich\_custom\_parameters

This custom function enriches activities sent from the enforcer to HUMAN with additional custom data. This data can include user information, session IDs, or other data that HUMAN should have access to. These custom parameters are defined by a configurable function that must return an object that contains these custom parameters. There is a limit of 10 custom parameters.

* Parameters
  * config: HumanSecurityConfiguration
  * request: [Request](https://expressjs.com/en/api.html#req)
* Returns `CustomParameters` | `Promise<`CustomParameters`>`

**Default**: null

```ts
const config: HumanSecurityConfiguration = {
    // ...
    px_enrich_custom_parameters: async (
        config: HumanSecurityConfiguration,
        request: Request,
    ): `CustomParameters` | `Promise<`CustomParameters`>` => {
        const body = request.method === 'POST' &&
            request.get('content-type')?.includes('application/json') ?
            request.body : null;
        return {
            custom_param1: 'hardcoded value',
            custom_param2: request.get('header-name'),
            custom_param3: body?.['body_property']
        };
    },
    // ...
}
```

### px\_graphql\_enabled

Whether the enforcer should attempt to parse and report information about GraphQL operations on incoming requests.

**Default**: `true`

```ts
const config: HumanSecurityConfiguration = {
    // ...
    px_graphql_enabled: false,
    // ...
}
```

### px\_graphql\_routes

A list of prefixes for all routes that should be considered GraphQL routes. If `px_graphql_enabled` is `true`, all POST requests with routes that match the prefixes configured here will have their bodies parsed for GraphQL operations.

**Default**: `["/graphql"]`

```ts
const config: HumanSecurityConfiguration = {
    // ...
    px_graphql_routes: ['/graphql', /^\/\w+\/graphql/],
    // ...
}
```

### px\_sensitive\_graphql\_operation\_types

A list of operation types (query, mutation, or subscription) that should be considered sensitive. If one or more GraphQL operations on an HTTP request is found to have a type matching the list configured here, it will trigger a Risk API call even if the request contains a valid, unexpired cookie.

**Default**: `[]`

```ts
const config: HumanSecurityConfiguration = {
    // ...
    px_sensitive_graphql_operation_types: ['mutation'],
    // ...
}
```

### px\_sensitive\_graphql\_operation\_names

A list of operation names that should be considered sensitive. If one or more GraphQL operations on an HTTP request is found to have a name matching the list configured here, it will trigger a Risk API call even if the request contains a valid, unexpired cookie.

**Default**: `[]`

```ts
const config: HumanSecurityConfiguration = {
    // ...
    px_sensitive_graphql_operation_names: ['LoginOperation', 'CheckoutOperation'],
    // ...
}
```

### px\_url\_decode\_reserved\_characters

By design, the enforcer treats [reserved characters](https://datatracker.ietf.org/doc/html/rfc3986#section-2.2) in URLs differently from their percent-encoded counterparts. For example, the URL `https://example.com/path-with-%3F-mark` will be parsed as having path `/path-with-%3F-mark`, while the URL `https://example.com/path-with-?-mark` would be parsed as having path `/path-with-` and query parameters `-mark`.

However, some servers, frameworks, or business logic may apply percent decoding to reserved characters within the URL path. Setting this configuration to `true` will apply percent decoding to reserved characters in the URL path prior to parsing.

**Default**: `false`

```ts
const config: HumanSecurityConfiguration = {
    // ...
    px_url_decode_reserved_characters: true,
    // ...
}
```

### px\_logger\_auth\_token

The token used to authenticate with HUMAN's enforcer logging services. This value is required for setting up the header-based logger feature.

**Default**: `""`

```ts
const config: HumanSecurityConfiguration = {
    // ...
    px_logger_auth_token: '`<LOGGER_AUTH_TOKEN>`',
    // ...
}
```

### px\_proxy\_url

> **Note**
>
> This configuration was added in version 8.5.0.

If your architecture requires the use of a proxy server to access outside services, you may designate a proxy URL or IP and port to use. This will use HTTP tunneling and direct all outgoing HUMAN traffic to the defined proxy address.

> **Warning**
>
> If using HTTPS, please ensure that the proxy's certificate is installed on the machine running the enforcer.

**Default**: `""`

```ts
const config: HumanSecurityConfiguration = {
    // ...
    px_proxy_url: 'https://1.2.3.4:8888',
    // ...
}
```

\


## Account Defender Configurations

### px\_jwt\_cookie\_name

The name of the cookie that contains the JWT token from which user identifiers should be extracted.

**Default**: `""`

```ts
const config: HumanSecurityConfiguration = {
    // ...
    px_jwt_cookie_name: 'auth',
    // ...
}
```

### px\_jwt\_cookie\_user\_id\_field\_name

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

**Default**: `""`

```ts
const config: HumanSecurityConfiguration = {
    // ...
    px_jwt_cookie_user_id_field_name: 'nameID',
    // ...
}
```

### px\_jwt\_cookie\_additional\_field\_names

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

**Default**: `[]`

```ts
const config: HumanSecurityConfiguration = {
    // ...
    px_jwt_cookie_additional_field_names: ['exp', 'iss'],
    // ...
}
```

### px\_jwt\_header\_name

The name of the header that contains the JWT token from which user identifiers should be extracted.

**Default**: `""`

```ts
const config: HumanSecurityConfiguration = {
    // ...
    px_jwt_header_name: 'x-jwt-authorization',
    // ...
}
```

### px\_jwt\_header\_user\_id\_field\_name

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

**Default**: `""`

```ts
const config: HumanSecurityConfiguration = {
    // ...
    px_jwt_header_user_id_field_name: 'sub',
    // ...
}
```

### px\_jwt\_header\_additional\_field\_names

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

**Default**: `[]`

```ts
const config: HumanSecurityConfiguration = {
    // ...
    px_jwt_header_additional_field_names: ['exp', 'iss'],
    // ...
}
```

## Credential Intelligence Configurations

### px\_login\_credentials\_extraction\_enabled

This enables the extraction and reporting of credentials from the Enforcer. This must be set to `true` to enable the Credential Intelligence product.

**Default**: `false`

```ts
const config: HumanSecurityConfiguration = {
    // ...
    px_login_credentials_extraction_enabled: true,
    // ...
}
```

### px\_login\_credentials\_extraction

An array of configurations for each credential endpoint. Each element in the array is an object representing a distinct endpoint to which credentials are sent, and includes information about how to identify these credential-bearing requests, how to extract the credentials from the request, and how to determine if the request operation (login, signup, etc.) was successful based on the returned HTTP response.

**Default**: `[]`

```ts
const config: HumanSecurityConfiguration = {
    // ...
    px_login_credentials_extraction: [
        {
            path: '/auth/[A-Za-z0-9]{12}/login',
            path_type: 'regex',
            method: 'POST',
            sent_through: 'body',
            user_field: 'username',
            pass_field: 'password',
            login_successful_reporting_method: 'status',
            login_successful_statuses: [200, 202]
        },
        {
            path: '/sign-up',
            method: 'POST',
            sent_through: 'custom',
            extract_credentials_callback: (request: Request): Credentials => {
                if (!request.body || request.get('x-reject-signup')) {
                    return null;
                }
                return {
                    user: request.body['new_username'],
                    pass: request.body['password']
                };
            },
            login_successful_reporting_method: 'custom',
            login_successful_callback: (response: Response): boolean => {
                return response.get('set-cookie')?.includes('session_token=');
            }
        },
        // ...
    ],
    // ...
}
```

Each credential endpoint configuration object contains the following fields:

#### path

**Required**. The path of the request that contains the credentials. It can be either an exact path or a string in the form of a regular expression.

```ts
{
    // ...
    path: '/sign-up',
    // ...
}
```

#### path\_type

**Optional**. Whether the incoming request path should be evaluated against the configured path as a regular expression or as an exact match.

Possible values:

* `"exact"` - The value set in `path` must match the request path exactly as is.
* `"regex"` - The value set in `path` represents a regular expression to be matched against the request path.

**Default**: `"exact"`

```ts
{
    // ...
    path: '/auth/[A-Za-z0-9]{12}/login',
    path_type: 'regex',
    // ...
}
```

#### method

**Required**. The HTTP method of the request that contains the credentials. This can be set to any string representing an HTTP method (e.g., `"GET"`, `"POST"`, `"PUT"`).

```ts
{
    // ...
    method: 'POST',
    // ...
}
```

#### sent\_through

**Required**. Whether the credentials should be extracted from the request headers, query parameters, body, or via a defined custom callback.

Possible values:

* `"body"` - The credentials will be extracted according to the configured `user_field` and `pass_field` values from the request body.
* `"header"` - The credentials will be extracted from the request headers according to the configured `user_field` and `pass_field`.
* `"query-param"` - The credentials will be extracted from the query parameters according to the configured `user_field` and `pass_field`.
* `"custom"` - The credentials will be extracted by invoking the `extract_credentials_callback`.

Sent Through Body: Content Types

If `"body"` is configured as the `sent_through` value, the Enforcer must read and parse the incoming request body. The Enforcer parses the request body based on the `Content-Type` request header.

Supported content types are listed below and assume use of the built-in [express.json()](https://expressjs.com/en/4x/api.html#express.json) and [express.urlencoded()](https://expressjs.com/en/4x/api.html#express.urlencoded) body parser middlwares.

* `application/json`
* `application/x-www-form-urlencoded`

To support other content types, set the `sent_through` to `"custom"` and define a `extract_credentials_callback` to extract the credentials from the request as desired.

#### user\_field

**Required** only if `sent_through` is set to `"body"`, `"header"`, or `"query-param"`.

The name of the field, header name, or query parameter where the username can be found.

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

#### pass\_field

**Required** only 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.

```ts
{
    // ...
    sent_through: 'body',
    pass_field: 'password',
    // ...
}
```

> **Nested Objects in a JSON Body**
>
> The `user_field` and `pass_field` configurations support 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 from the following JSON body:

```json
{
    "user_info": {
        "username": "user123"
    },
    "authentication": {
        "password": "P@s$w0rD!"
    }
}
```

#### extract\_credentials\_callback

**Required** only if `sent_through` is set to `"custom"`.

A custom credential extraction callback that returns the raw credentials from the request. It receives the HTTP request as a parameter and should return a Credentials object of the following type.

```ts
type Credentials = {
    user?: string;  // the raw username
    pass?: string;  // the raw password
};
```

* Parameters
  * request: [Request](https://expressjs.com/en/api.html#req)
* Returns Credentials or a Promise resolving to a Credentials object.

If neither the username nor the password can be extracted from the request, the function should return `null`.

```ts
{
    // ...
    sent_through: 'custom',
    extract_credentials_callback: async (request: Request): Promise<Credentials> => {
        if (!request.body) return null;
        // ...
        // custom extraction resulting in username and password
        // ...
        if (!username || !password) {
            // unsuccessful extraction
            return null;
        }
        // successfully extracted credentials
        return { user: username, pass: password };
    },
    // ...
}
```

#### protocol

**Optional**. Whether to process credentials as part of single or multiple HTTP requests. By default, the module tries to process requests depending on which credential fields were extracted.

Possible values:

* `"v2"` - Both username and password are present on the same HTTP request and must be extracted successfully to trigger Credential Intelligence.
* `"multistep_sso"` - The username and password are delivered on different HTTP requests. Either the username or password, but not both, must be extracted successfully to trigger Credential Intelligence.
* `"both"` - The username and password may be present on the same HTTP request or on different HTTP requests. If either username or password is successfully extracted, the Enforcer will send the credentials according to the `multistep_sso` protocol. If both username and password are successfully extracted, the Enforcer will send the credentials according to the `v2` protocol.

**Default**: `"both"`

```ts
{
    // ...
    protocol: 'v2',
    // ...
}
```

#### login\_successful\_reporting\_method

**Required**. The method by which the Enforcer will determine whether the login request was successful.

Possible values:

* `"status"` - The Enforcer will determine if the login request was successful by evaluating the response status code against the `login_successful_statuses` configuration.
* `"body"` - The Enforcer will determine if the login request was successful by evaluating the response body content against the `login_successful_body_regex` configuration.
* `"header"` - The Enforcer will determine if the login request was successful by evaluating the response headers against the `login_successful_header_name` and `login_successful_header_value` configurations.
* `"custom"` - The Enforcer will determine if the login request was successful by invoking the `login_successful_callback`.

**Default**: `"status"`

#### login\_successful\_statuses

**Optional**. An array of HTTP statuses signifying a successful login. All other status codes will be treated as unsuccessful login attempts. Takes effect only when the `login_successful_reporting_method` is set to `"status"`.

**Default**: `[200]`

```ts
{
    // ...
    login_successful_reporting_method: 'status',
    login_successful_statuses: [200, 202],
    // ...
}
```

#### login\_successful\_body\_regex

**Required** only if `login_successful_reporting_method` is set to `"body"`. A regular expression (or string representing a regular expression) to against which the response body will be evaluated. A match indicates a successful login.

**Default**: `""`

```ts
{
    // ...
    login_successful_reporting_method: 'body',
    login_successful_body_regex: 'Welcome, [A-Za-z0-9_]+!'
    // ...
}
```

#### login\_successful\_header\_name

**Required** only if `login_successful_reporting_method` is set to `"header"`. A response header name signifying a successful login response. If the `login_successful_header_value` field is empty or not configured, any response containing this header name will be considered a successful login. If the `login_successful_header_value` is configured, the response header value must be an exact match.

**Default**: `""`

```ts
{
    // ...
    login_successful_reporting_method: 'header',
    login_successful_header_name: 'x-login-successful'
    // ...
}
```

#### login\_successful\_header\_value

**Optional**. If this value is configured, a login attempt will be considered successful only if the response contains a header name matching the `login_successful_header_name`, and whose value is exactly equal to this configuration value. Takes effect only when the `login_successful_reporting_method` is set to `"header"`.

**Default**: `""`

```ts
{
    // ...
    login_successful_reporting_method: 'header',
    login_successful_header_name: 'x-user-status',
    login_successful_header_value: 'logged-in'
    // ...
}
```

#### login\_successful\_callback

**Required** only if `login_successful_reporting_method` is set to `"custom"`. A custom callback that accepts the HTTP response and returns a boolean or Promise resolving to a boolean that indicates whether the login attempt was successful.

* Parameters
  * response: [Response](https://expressjs.com/en/api.html#res)
* Returns a boolean or Promise resolving to a boolean.

**Default**: `null`

```ts
{
    // ...
    login_successful_reporting_method: 'custom',
    login_successful_callback: (response: Response): boolean => {
        return response.statusCode === 200 && response.get('set-cookie')?.includes('session_token=');
    },
    // ...
}
```

### px\_compromised\_credentials\_header

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.

**Default**: `"px-compromised-credentials"`

```ts
const config: HumanSecurityConfiguration = {
    // ...
    px_compromised_credentials_header: 'x-ci-compromised',
    // ...
}
```

### px\_send\_raw\_username\_on\_additional\_s2s\_activity

Whether to report the raw username on the `additional_s2s` activity. When set to `false`, the raw username will never be reported. When set to `true`, the raw username will only be reported if (1) the credentials are compromised, and (2) the login request was successful.

**Default**: `false`

```ts
const config: HumanSecurityConfiguration = {
    // ...
    px_send_raw_username_on_additional_s2s_activity: true,
    // ...
}
```

### px\_automatic\_additional\_s2s\_activity\_enabled

Whether to send the `additional_s2s` activity, which reports on whether the login was successful, automatically in the `postEnforce` function. This should only be set to `false` if it is not possible to determine whether the login was successful based on the HTTP response. This means the `additional_s2s` activity must be sent in some other way.

**Default**: `true`

```ts
const config: HumanSecurityConfiguration = {
    // ...
    px_automatic_additional_s2s_activity_enabled: false,
    // ...
}
```

### px\_additional\_s2s\_activity\_header\_enabled

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. This should only be enabled if the `px_automatic_additional_s2s_activity_enabled` is set to `false`.

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.

**Default**: `false`

```ts
const config: HumanSecurityConfiguration = {
    // ...
    px_additional_s2s_activity_header_enabled: true,
    // ...
}
```

Below is an example of JavaScript code at the origin server to handle parsing, enrichment, and sending of the `additional_s2s` activities that arrive on request headers.

```js
app.post('/login', (req, res) => {
    // handle login flow, resulting in variables
    // isLoginSuccessful (boolean) and responseStatusCode (number)

    if (
        req.get('px-additional-activity') &&
        req.get('px-additional-activity-url')
    ) {
        handlePxAdditionalActivity(req, responseStatusCode, isLoginSuccessful);
    }
});

function handlePxAdditionalActivity(req, statusCode, isLoginSuccessful) {
    try {
        // extract url and activity from the request headers
        const url = req.get('px-additional-activity-url');
        const activity = JSON.parse(req.get('px-additional-activity'));

        // enrich the activity details with added information
        activity.details['http_status_code'] = statusCode;
        activity.details['login_successful'] = isLoginSuccessful;

        if (activity.details['credentials_compromised'] && isLoginSuccessful) {
            // add raw username if credentials are compromised and login is successful (only if desired)
            activity.details['raw_username'] = req.body.username;
        } else {
            // remove raw username if login is not successful or credentials are not compromised
            delete activity.details['raw_username'];
        }

        // send the POST request
        axios.post(url, activity, {
            headers: {
                'Authorization': `Bearer ${env.PX_AUTH_TOKEN}`,
                'Content-Type': 'application/json'
            }
        });
    } catch (err) {
        console.error(`Error: ${err}`);
    }
}
```

\


## Hype Sale Challenge

The enforcer will serve a Hype Sale Challenge for any request that is marked as a hype sale. To mark a request as hype sale, add a custom parameter with the key `is_hype_sale` and a boolean value of `true` in the [configurable custom parameters function](#px_enrich_custom_parameters).

The following configuration will initiate a Hype Sale Challenge for any request that contains the query param `id` with the value `123` (e.g., `https://www.example.com/product?id=123`).

```ts
const config: HumanSecurityConfiguration = {
    // ...
    px_enrich_custom_parameters: async (
        config: HumanSecurityConfiguration,
        request: Request,
    ): `CustomParameters` | `Promise<`CustomParameters`>` => {
        return {
            is_hype_sale: req.query.id === '123'
        };
    },
    // ...
}
```