Integrate using Cloudflare Workers

This guide describes how to use Cloudflare Workers to integrate Detection and Response services into your web app. For more information about Cloudflare Workers, see Cloudflare's documentation.

Note

This guide describes integrating using the new Platform SDK. If you've already integrated using the older Detection and Response SDK, you can find that guide here.

Prerequisites

Your web application must be integrated with Cloudflare Workers.

Step 1: Get client credentials

Client credentials are used to identify your app and generate access tokens for authorizing Transmit requests. To obtain them, you'll need to create an application in the Admin Portal (if you don’t have one yet).

  1. From Applications , click Add application .
  2. Add the friendly application name to display in the Admin Portal.
  3. Add a client display name, and your website URL as a redirect URI (e.g., https://your-domain.com ).
    Note

    These fields are required for all Transmit apps, but won’t be used for Detection and Response.

  4. Click Add to create your application. This will automatically generate your client credentials.

Step 2: Load SDK via Cloudflare Worker

Load and initialize the Platform SDK using CloudFlare Workers:

  1. Log in to your Cloudflare dashboard and go to Workers .
  2. Create or update an existing Worker, and make sure the Worker's routes are defined for all the relevant application pages (see Routes for information about adding routes to Cloudflare Workers).
  3. To load and initialize the SDK, on the Worker page click Quick edit and add the code below to the Javascript code pane on the left. The [CLIENT_ID] is your client ID from step 1.
Copy
Copied
class TransmitHeadElementHandler {
  element(element) {
    const tsPlatformSDK = `
      // Loads the latest SDK within the major version 1
      // See changelog for details and update version if necessary
      <script src="https://platform-websdk.transmitsecurity.io/platform-websdk/1.x/ts-platform-websdk.js" defer="true" id="ts-platform-script"></script>
      <script>
      console.log("Setting up event listener for script loading");
      document.getElementById("ts-platform-script").addEventListener("load", function(e) {
            console.log("tsPlatform ready");
            window.tsPlatform.initialize({ clientId: "[CLIENT_ID]" })
      });
      </script>
    `;
    element.append(tsPlatformSDK, { html: true });
  }
}

async function handleRequest(request) {
  const response = await fetch(request);
  const contentType = response.headers.get("Content-Type");

  const rewriter = new HTMLRewriter().on('head', new TransmitHeadElementHandler());

  if (contentType && contentType.startsWith("text/html")) {
    // transform with HTMLRewriter only if content-type is html
    return rewriter.transform(response);
  } else {
    return response;
  }
}

addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request));
});

Step 3: Set user

A user identifier must be reported to Transmit Security after you've fully authenticated the user (including, for example, any required 2FA that was done). This will set the user for all subsequent events in the browser session.

To do this, add the JS code below after your application has authenticated a user to your Worker (or after SDK initialization if you already have the user context of the authenticated user when loading the page). The [USER_ID] is an opaque identifier for the user in your system.

Copy
Copied
window.tsPlatform.drs.setAuthenticatedUser('[USER_ID]');
Note:

This must not include personal user identifiers, such as email.

Step 4: Report actions via Cloudflare

To obtain risk recommendations for sensitive actions, your application should report these actions using the Platform SDK. To do this, you need to add an event listener to the relevant form or button on your webpage, and add the code below to your Worker. Replace [ACTION_TYPE] with the appropriate action type from our list of actions.

Copy
Copied
const tsAccountProtectionLoginHandler = `
<script>
 function onSubmitLogin(event) {
   event.preventDefault();
   window.tsPlatform.drs.triggerActionEvent("[ACTION_TYPE]").then((value) => {
     form.submit();
   }).catch((value) => {
     form.submit();
   });
 }
 let form = document.getElementById("login");
 if (form) {
   form.addEventListener('submit', onSubmitLogin);
 }
</script>
`;
Note:

Make sure to pass the received actionToken to your backend along with the actual action invocation to ensure you can leverage the recommendation in the next step.

Step 5: Fetch recommendation

You can fetch recommendations for the reported action using the Recommendation API.

These APIs are authorized using an OAuth access token so you'll need to fetch a token using your client credentials (from step 1). The token should target the following resource: https://risk.identity.security. To do this, send the following request:

Copy
Copied
  const { access_token } = await fetch(
    `https://api.transmitsecurity.io/oidc/token`,
    {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
      body: new URLSearchParams({
        grant_type: client_credentials,
        client_id: [CLIENT_ID],
        client_secret: [CLIENT_SECRET],
        resource: 'https://risk.identity.security'
      })
    }
  );

From your backend, invoke the Recommendation API by sending a request like the one below. The [ACCESS_TOKEN] is the authorization token you obtained using your client credentials and [ACTION_TOKEN] is the actionToken received from the SDK in step 4.

Copy
Copied
const query = new URLSearchParams({
  action_token: '[ACTION_TOKEN]',
}).toString();

const resp = await fetch(
  `https://api.transmitsecurity.io/risk/v1/recommendation?${query}`,
  {
    method: 'GET',
    headers: {
      Authorization: 'Bearer [ACCESS_TOKEN]',
    },
  }
);

Step 6: Clear user

After the user logs out or the user session expires, you should clear the set user so they are not associated with future actions. To clear the user with Cloudflare Workers, you need to add an event listener to the relevant logout button on your webpage, and add the code below to your Worker:

Copy
Copied
const tsClearUserHandler = `
<script>
 function onUserLogout(event) {
   window.tsPlatform.drs.clearUser()
 }
 let button = document.getElementById("logout");
 if (button) {
   button.addEventListener('click', onUserLogout);
 }
</script>
`;