Install the Cloudflare Enforcer

If your organization uses Cloudflare, you can use HUMAN's Cloudflare Enforcer to protect against malicious behavior. The Cloudflare Enforcer is installed using a Cloudflare Worker, or a snippet of code, and is deployed to your content delivery network (CDN). The Enforcer dictates how traffic should be handled per your organization's standards.

You can learn how to install the Cloudflare Enforcer with this article.

Prerequisites

  • A Cloudflare account. You can sign up for an account from Cloudflare's website.
  • A command-line interface (CLI).
  • A text editor.
  • Node Version Manager (nvm) installed on your device. See nvm’s GitHub repository to learn how to install it.
  • The latest version of Node.js. After installing nvm, enter nvm install stable in your CLI to install it.
  • Wrangler installed on your device. You can enter npm install -g wrangler in your CLI to install it.
  • Your unique HUMAN information:
    • Your Application ID. You can find this under Platform Settings > Applications > Overview in the HUMAN console. If you have multiple environments, you will also have multiple Application IDs, so be sure to choose the correct ID for the environment you want to install on.
    • Your Server Token. You can find this under Platform Settings > Applications > Status & Settings > Server Token.
    • Your Risk Cookie Key. You can find this under Bot Defender > Policies > Policy Settings > Policy Information.

Installation

There are two parts to the Cloudflare Enforcer installation:

  1. Create the Cloudflare worker
  2. Install the HUMAN Enforcer
  3. Set up remote configuration

The majority of the installation process is done through a CLI.

Create the Cloudflare Worker

  1. In your CLI, enter npm create cloudflare@latest. If you’re prompted to install additional packages to complete the installation, hit y to do so.
Need to install the following packages:
[email protected]
Ok to proceed? y/n
  1. When prompted, enter a folder name to create your Worker in. This will also be the Worker’s name in your Cloudflare dashboard. In the example below, we've named our folder human-cloudflare-enforcer.
npm create cloudflare@latest

using create-cloudflare version 2.XX.Y
╭ Create an application with Cloudflare Step 1 of 3
│
╰ In which directory do you want to create your application? also used as application name
  ./human-cloudflare-enforcer
  1. When prompted, select the "Hello World" Worker option and hit return to proceed.
│ dir ./human-cloudflare-enforcer
│
╰ What type of application do you want to create?
  ● "Hello World" Worker
  ○ "Hello World" Worker (Python)
  ○ "Hello World" Durable Object
  ○ Website or web app
  ○ Example router & proxy Worker
  ○ Scheduled Worker (Cron Trigger)
  ○ Queue consumer & producer Worker
  ○ API starter (OpenAPI compliant)
  ○ Worker built from a template hosted in a git repository
  1. Select whether to install the Worker using TypeScript. By default, the Worker will install in JavaScript.

🚧

Note

Whether you use TypeScript or JavaScript is up to you, but be sure to remember what you choose. Later in the installation, you will need to choose the code snippet that corresponds to the language you installed in.

├ What type of application do you want to create?
│ type "Hello World" Worker
│
╰ Do you want to use TypeScript?
  Yes / No
  1. When prompted, select No to deploying your application.
╭ Deploy with Cloudflare Step 3 of 3
│
╰ Do you want to deploy your application?
  Yes / No

Afterwards, you should receive a success message that reads APPLICATION CREATED. This means you created a basic Cloudflare Worker, and you're ready to move on to installing the HUMAN Enforcer.

Install the HUMAN Enforcer

  1. In your CLI, enter cd folder_name to open the folder you created in Create the Cloudflare Worker, Step 2. Based on our earlier example, we would enter cd human-cloudflare-enforcer.
  2. Enter npm i --save @humansecurity/cloudflare-enforcer. This will install the latest Cloudflare Enforcer from HUMAN.
  3. Enter cd src.
  4. In your preferred text editor, open either index.ts or index.js depending on your choice in Create the Cloudflare Worker, Step 4. The .ts file is for TypeScript installations, while .js is for JavaScript.

📘

Note

You can check the file type you have by entering ls while inside the src folder. This will show you your index file's type.

  1. Delete all the code currently in the index file. The following snippet shows all the default code you should delete.
/**
 * Welcome to Cloudflare Workers! This is your first worker.
 *
 * - Run `npm run dev` in your terminal to start a development server
 * - Open a browser tab at http://localhost:8787/ to see your worker in action
 * - Run `npm run deploy` to publish your worker
 *
 * Learn more at https://developers.cloudflare.com/workers/
 */
export default {
        async fetch(request, env, ctx) {
                return new Response('Hello World!');
        },
};
  1. Copy the appropriate code snippet, either TypeScript or JavaScript, from below and paste it into your index file.

📘

Note

In addition to choosing between TypeScript and JavaScript, you must also make sure to pick the right type of Worker. This can either be an ES Module or Service Module, and it depends on your Cloudflare configuration. You can see some examples from both Workers in Cloudflare's documentation.

import {
    HumanSecurityEnforcer
} from "@humansecurity/cloudflare-enforcer";

const config = {
    px_app_id: '<APP_ID>',
    px_auth_token: '<AUTH_TOKEN>',
    px_cookie_secret: '<COOKIE_SECRET>',
    // ...
};

export default {
    async fetch(request, env, ctx) {
        // create a new enforcer
        const enforcer = await HumanSecurityEnforcer.initialize(config, env);

        // call enforce
        const retVal = await enforcer.enforce(ctx, request);

        // if enforce returned a response, return that response
        if (retVal instanceof Response) {
            return retVal;
        }

        // retrieve the resource from the cache or origin server
        // make sure to use the value returned from enforce
        const response = await fetch(retVal);

        // call postEnforce and return the resulting response
        return await enforcer.postEnforce(ctx, response);
    },
};
import {
    HumanSecurityEnforcer,
    HumanSecurityConfiguration
} from '@humansecurity/cloudflare-enforcer';

const config: HumanSecurityConfiguration = {
    px_app_id: '<APP_ID>',
    px_auth_token: '<AUTH_TOKEN>',
    px_cookie_secret: '<COOKIE_SECRET>',
    // ...
};

interface Env {
    // If using Human Security features that require the PXKV Namespace
    PXKV: KVNamespace;
}

export default {
    async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise < Response > {
        // create a new enforcer
        const enforcer = await HumanSecurityEnforcer.initialize(config, env);

        // call enforce
        const retVal = await enforcer.enforce(ctx, request);

        // if enforce returned a response, return that response
        if (retVal instanceof Response) {
            return retVal;
        }

        // retrieve the resource from the cache or origin server
        // make sure to use the value returned from enforce
        const response = await fetch(retVal);

        // call postEnforce and return the resulting response
        return await enforcer.postEnforce(ctx, response);
    },
};
import {
    HumanSecurityEnforcer
} from '@humansecurity/cloudflare-enforcer';

// define an enforcer configuration however you see fit
const config = {
    px_app_id: '<APP_ID>',
    px_auth_token: '<AUTH_TOKEN>',
    px_cookie_secret: '<COOKIE_SECRET>',
    // ...
};

async function handleEvent(event) {
    // provide the enforcer configuration as an argument and await the returned Promise
    // to receive an instance of the HumanSecurityEnforcer
    const enforcer = await HumanSecurityEnforcer.initialize(config);

    // call enforce
    const retVal = await enforcer.enforce(event);

    // if enforce returned a response, return that response
    if (retVal instanceof Response) {
        return retVal;
    }

    // retrieve the resource from the cache or origin server
    // make sure to use the value returned from enforce
    const response = await fetch(retVal);

    // call postEnforce and return the resulting response
    return await enforcer.postEnforce(event, response);
}

addEventListener('fetch', (event) => {
    event.respondWith(handleEvent(event));
});
import {
    HumanSecurityEnforcer,
    HumanSecurityConfiguration
} from "@humansecurity/cloudflare-enforcer";

const config: HumanSecurityConfiguration = {
    px_app_id: '<APP_ID>',
    px_auth_token: '<AUTH_TOKEN>',
    px_cookie_secret: '<COOKIE_SECRET>',
    // ...
};

async function handleEvent(event: FetchEvent): Promise < Response > {
    // create a new enforcer
    const enforcer = await HumanSecurityEnforcer.initialize(config);

    // call enforce
    const retVal = await enforcer.enforce(event);

    // if enforce returned a response, return that response
    if (retVal instanceof Response) {
        return retVal;
    }

    // retrieve the resource from the cache or origin server
    // make sure to use the value returned from enforce
    const response = await fetch(retVal);

    // call postEnforce and return the resulting response
    return await enforcer.postEnforce(event, response);
}

addEventListener('fetch', (event) => {
    event.respondWith(handleEvent(event));
});
  1. Update the px_app_id, px_auth_token, and px_cookie_secret fields with your Application ID, Server Token, and Risk Cookie Key respectively.

📘

Note

These are the minimum required fields that must be completed in order for the Enforcer to work. You can always return to this file to customize your Enforcer later with our optional configurations.

// define an enforcer configuration however you see fit
const config = {
    px_app_id: '<APP_ID>',
    px_auth_token: '<AUTH_TOKEN>',
    px_cookie_secret: '<COOKIE_SECRET>',
    // ...
};
  1. Save and close the file.

  2. Enter npx wrangler deploy to deploy your Worker. You may be prompted to log in to your Wrangler or Cloudflare account.

  3. Navigate to your Cloudflare dashboard and open Workers & Pages. Your new Worker with the HUMAN Enforcer should appear with the same name you gave it in Create the Cloudflare Worker, Step 2. In our case, the Worker is named human-cloudflare-enforcer.

  4. Select the Worker, then select Settings > Triggers > Add route under Routes. This is where you can you add URL routes and zones to monitor with the Cloudflare Enforcer. We recommend protecting your full domain, including all pages on your domain, with the pattern subdomain.apex.com/*. For example, to protect the full domain of a site with the url www.example.com, you would provide the following fields:

    • Route: www.example.com/*
    • Zone: example.com

Next, now that your Cloudflare Worker has been integrated with the Enforcer, you must set up remote configuration fields in your Worker.

Set up remote configuration

Remote configuration is a feature that lets you access and modify your Enforcer’s configuration remotely without redeploying your Cloudflare Worker. This also allows the HUMAN team to troubleshoot or customize your Enforcer directly. Remote configuration is required as part of your Enforcer setup.

📘

Note

HUMAN will never change your Enforcer configuration without your permission. You can learn more about remote configurations with our help article.

To complete the remote configuration setup, you will need to contact our team. You can reach out to your account manager or reach out to us at [email protected].

  1. In your Cloudflare dashboard’s Workers & Pages, select the Worker you created in Create the Cloudflare Worker, Step 2. In our case, the Worker is named human-cloudflare-enforcer.

  2. Navigate to the Worker’s Settings > Variables > KV Namespace Bindings and select Create a KV namespace.

  3. Select Create a namespace and enter a name for it, then select Add.

  4. Return to your Worker’s Settings > Variables > KV Namespace Bindings and select Add binding.

  5. Create a KV variable with the following fields:

    • Variable name: Enter PXKV. The name must be set to PXKV for the remote configuration to work.
    • KV Namespace: Select the Namespace you created in Step 3.
  6. Select Deploy.

  7. Navigate back the Cloudflare dashboard > Websites and select the domain to trigger the Enforcer’s Worker.

  8. Navigate to Workers Routes and select Edit next to the Route to bind your Worker to.

  9. In the Edit route window that appears, select the Worker you created from the dropdown menu and select Save.

  10. From the route you bound the Worker to, share the full website address with HUMAN’s Support team. Once we receive your URL, we will complete the setup for you.

Your Cloudflare Enforcer has been successfully installed with the minimum requirements to monitor activity on your Cloudflare CDN. You can further customize the Enforcer’s behavior by referencing our configuration options.

Once you finish installing, be sure to contact HUMAN to complete your tuning process.