# Bot Detection in a Cloudflare Worker: What the Edge Can and Cannot See

On this page

1. [What can a standard Worker read?](https://maskbreak.com/blog/cloudflare-workers-bot-detection#free-signals)
2. [Which checks need the browser?](https://maskbreak.com/blog/cloudflare-workers-bot-detection#cannot-see)
3. [Edge triage on facts you already have](https://maskbreak.com/blog/cloudflare-workers-bot-detection#triage)
4. [Step 1: Add the script to the page with your form](https://maskbreak.com/blog/cloudflare-workers-bot-detection#step-1-add-the-script)
5. [Step 2: Send the check from your server (the Worker)](https://maskbreak.com/blog/cloudflare-workers-bot-detection#step-2-send-the-check)
6. [Step 3: Submit your form once](https://maskbreak.com/blog/cloudflare-workers-bot-detection#step-3-submit-your-form-once)
7. [Failing open at the edge is not optional](https://maskbreak.com/blog/cloudflare-workers-bot-detection#fail-open)
8. [Use waitUntil for anything you do not need an answer from](https://maskbreak.com/blog/cloudflare-workers-bot-detection#side-effects)
9. [The short version](https://maskbreak.com/blog/cloudflare-workers-bot-detection#summary)

On a standard Cloudflare Worker, you can read the visitor’s IP address, ASN and country. For HTTPS requests, you can also read the negotiated TLS version and cipher. Cloudflare exposes JA3 and JA4 fingerprints to Enterprise customers who have purchased Bot Management. To inspect what happens inside the visitor’s browser, collect evidence on the page and send it with the form.

[Deploy the Maskbreak Worker to Cloudflare](https://deploy.workers.cloudflare.com/?url=https://github.com/sentinelsup/maskbreak-cloudflare-worker) to check a signup form on your existing site. Paste your live Maskbreak key, then attach a route such as `www.example.com/signup*`. The template adds the browser script to matching HTML forms. If the form submits to a different path, set `SUBMIT_PATH` and attach that route too.

The example below starts in watch mode. The Worker sends a visitor check before the form reaches your origin, logs the result and lets the submission continue.

## What can a standard Worker read?

On an incoming visitor request, `CF-Connecting-IP` gives the client IP. `request.cf` adds network and connection details. This helper reads a subset you can use on any plan.

javascript

```
function connectionInfo(request) {
  const cf = request.cf || {};
  return {
    ip: request.headers.get('CF-Connecting-IP'),
    asn: cf.asn,
    country: cf.country,
    tlsVersion: cf.tlsVersion,
    tlsCipher: cf.tlsCipher,
  };
}
```

The country value can be `T1` for Tor or `XX` when the country is unknown. A TLS version such as `TLSv1.3` describes the connection. Many browsers and automated clients negotiate the same version and cipher. Cloudflare lists these fields in its [Workers Request reference](https://developers.cloudflare.com/workers/runtime-apis/request/#incomingrequestcfproperties) and documents the [special country codes](https://developers.cloudflare.com/fundamentals/reference/http-headers/#cf-ipcountry).

### When does a Worker get JA3 or JA4?

With Enterprise Bot Management, `request.cf.botManagement` can also supply a bot score and TLS client fingerprints. Read `request.cf?.botManagement?.ja3Hash` for JA3 or `request.cf?.botManagement?.ja4` for JA4. Both describe how a TLS client starts a connection. Even on an entitled zone, a request can lack a fingerprint, for example on plain HTTP or when Bot Management skips the request. Treat a missing value as unknown. See [Cloudflare’s JA3 and JA4 availability notes](https://developers.cloudflare.com/bots/additional-configurations/ja3-ja4-fingerprint/).

Get a free API key

The Free plan includes 10,000 visitor checks a month with no card, and setup starts in watch mode, which logs every decision and blocks no one until you turn blocking on.

[Get your API key](https://maskbreak.com/signup?next=%2Fdashboard%3Fsetup%3Dcloudflare%23integration)

## Which checks need the browser?

To inspect a canvas, check browser APIs for tampering or link visits through a browser identifier, JavaScript must run on the page and send its evidence back. A TLS fingerprint can group clients that share a handshake. On its own it identifies neither a particular device nor the person submitting the form.

A residential proxy can share an ASN and country with ordinary customers of the same ISP. The standard Worker fields alone cannot establish whether a connection is being relayed.

So the useful division is:

- **At the edge, before origin:** known-bad networks, datacenter ASNs, Tor exits, obvious automation by user agent, and rate limiting. Cheap, no round trip, no cost to your origin.
- **At the action, with the browser's evidence:** device signals (automation, emulator, antidetect browser, browser tampering), multi-account linking, and the VPN and proxy reading of the visitor's own connection. These need the browser to have spoken.

## Edge triage on facts you already have

The first pattern needs no API: act at the edge, before the request reaches your application, on the connection facts.

javascript

```
const DATACENTER_ASNS = new Set([16509, 14618, 15169, 8075, 14061, 16276]);

export default {
  async fetch(request, env, ctx) {
    const url = new URL(request.url);
    // Only guard what is worth guarding. Everything else passes through.
    if (!url.pathname.startsWith('/signup')) return fetch(request);

    const cf = request.cf || {};
    if (DATACENTER_ASNS.has(cf.asn)) {
      // Friction, not a verdict: mark it for stricter handling downstream.
      const marked = new Request(request);
      marked.headers.set('X-Edge-Datacenter', '1');
      return fetch(marked);
    }
    return fetch(request);
  }
};
```

Be careful how hard you lean on that list. A datacenter ASN is a fact about infrastructure, not a verdict about a person: corporate VPNs, mobile carrier gateways and privacy relays all live in ranges that look like hosting. Refusing signup outright on ASN alone costs real users. It is a reasonable trigger for a challenge or stricter downstream handling, and a poor trigger for a 403. If your origin reads a header like that one, make sure only the Worker can set it.

## Step 1: Add the script to the page with your form

The full check needs evidence from the visitor's browser. On the page that holds the form, load the script and put `class="monocle-enriched"` on the `<form>` element itself (never on an input):

html

```
<script async src="https://maskbreak.com/assets/sentinel.js"></script>

<form class="monocle-enriched" method="post" action="/signup">
  <input type="email" name="email" required>
  <button type="submit">Create account</button>
</form>
```

The script adds three hidden fields to that form: `monocle` (the network token), `sentinel_fp` (the browser check id) and `sentinel_tz` (the time zone). A JavaScript frontend calls `await window.Sentinel.collect()` instead (check that `window.Sentinel` exists, and submit anyway when it does not) and sends its `token`, `fingerprintEventId` and `tz` in a JSON body; the Worker below reads both. If the page sends a `Content-Security-Policy`, add `https://maskbreak.com`, `https://mcl.maskbreak.com`, `https://*.mcl.maskbreak.com`, `https://mesu.maskbreak.com` and `'wasm-unsafe-eval'` to `script-src`, the `mcl` hosts (https and wss) and `mesu` to `connect-src`, and `https://mesu.maskbreak.com blob:` to `worker-src`.

## Step 2: Send the check from your server (the Worker)

The Worker reads the posted body once, sends the check, and forwards the original request to your origin. It sends whatever evidence arrived, including none: a check without a token or a browser check id is how the console tells you which half is missing. In watch mode, the default, it only logs.

javascript

```
// worker.js: in front of POST /signup on your zone
export default {
  async fetch(request, env, ctx) {
    const url = new URL(request.url);
    if (request.method !== 'POST' || url.pathname !== '/signup') {
      return fetch(request);
    }

    // Read the body once, then rebuild the request for the origin.
    const raw = await request.arrayBuffer();
    const fields = readFields(request.headers.get('Content-Type') || '', raw);
    const verdict = await checkVisitor(fields, env);

    if (env.MASKBREAK_MODE === 'enforce' && verdict?.decision === 'block') {
      return new Response(JSON.stringify({ error: 'Request declined' }), {
        status: 403,
        headers: { 'Content-Type': 'application/json' },
      });
    }
    // Watch mode, or anything short of a block in enforce mode: the origin
    // runs as before. A review is the origin's call (step up, not refuse).
    return fetch(new Request(request, { body: raw }));
  },
};

// Form posts carry monocle / sentinel_fp / sentinel_tz; JSON from
// Sentinel.collect() carries token / fingerprintEventId / tz.
function readFields(type, raw) {
  try {
    const text = new TextDecoder().decode(raw);
    if (type.includes('application/json')) {
      const body = JSON.parse(text);
      return body && typeof body === 'object' ? body : {};
    }
    if (type.includes('application/x-www-form-urlencoded')) {
      return Object.fromEntries(new URLSearchParams(text));
    }
  } catch (_) { /* unreadable body: send the check without evidence */ }
  return {};
}

async function checkVisitor(b, env) {
  let result = null;
  try {
    const res = await fetch('https://maskbreak.com/v1/evaluate', {
      method: 'POST',
      headers: {
        Authorization: `Bearer ${env.MASKBREAK_API_KEY}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        token: b.monocle || b.token || '',
        fingerprintEventId: b.sentinel_fp || b.fingerprintEventId || undefined,
        tz: b.sentinel_tz || b.tz || undefined,
        email: typeof b.email === 'string' ? b.email : undefined,
      }),
      // A deadline on every outbound call: no verdict beats a late one.
      signal: AbortSignal.timeout(3000),
    });
    if (res.ok) result = await res.json();
    else console.warn('[maskbreak] HTTP', res.status);   // 401: the key, 400: the body
  } catch (err) {
    console.warn('[maskbreak] unavailable:', err.name);   // fail open
  }
  // One line per check, in Workers Logs or wrangler tail. Never the key or token.
  console.log('[maskbreak]', JSON.stringify({
    mode: env.MASKBREAK_MODE || 'watch',
    decision: result ? result.decision : null,
    reasons: result ? result.reasons : null,
    device_evidence: result ? result.device_evidence : null,
    degraded: result ? !!result.degraded : null,
  }));
  return result;
}
```

Route it on the exact path, so the Worker never runs for your static files, and put the key in a secret. Worker code is not a browser bundle, but it is not a private server either: anyone with dashboard access can read the script, and it ends up in whatever repository you deploy from.

bash

```
wrangler secret put MASKBREAK_API_KEY
```

`MASKBREAK_MODE` is an ordinary variable (`vars` in your Wrangler file), unset for now. Never `const MASKBREAK_API_KEY = 'sk_live_...'` at the top of the file, and never let the key reach the browser: a live key in client-side JavaScript is a key someone else is now using on your allowance.

## Step 3: Submit your form once

Run the app on your computer or deploy it, open the page in an ordinary browser, wait a moment, and submit the form. The first check then appears in the Maskbreak console (if half of it did not arrive, the console says which half), and `wrangler tail` shows one `[maskbreak]` line. `degraded: true` means no network token arrived (the script was blocked, the class is missing, or the body was neither a form nor JSON); `device_evidence: "not_sent"` means no browser check id arrived; `"ok"` with `degraded: false` is a complete check.

After a few days of comparing those lines with the console's Events, set `MASKBREAK_MODE` to `enforce` and redeploy: the Worker then refuses a `block` and forwards everything else. For a stricter gate in front of a sensitive action, the [Worker example on the integrations page](https://maskbreak.com/integrations#cloudflare) forwards only a complete live allow in enforce mode.

## Failing open at the edge is not optional

An origin that fails closed takes down one endpoint. An edge Worker that fails closed can take down everything on its route. Three rules worth holding to:

- **Deadline everything.** An abort signal on every outbound call. No verdict beats a late verdict.
- **Catch broadly.** Network error, abort, non-2xx, unparseable JSON: every one of them means "continue", not "throw".
- **Have a removal plan.** Delete the Workers route in the dashboard and the origin serves the path directly. A rollback you can do from a phone at 2am is worth more than a clever retry.

Also watch the Workers request allowance on your plan. Every request on the route counts, including the ones you pass straight through, and an account over its daily free allowance gets errors on the route unless the route is set to fail open. A busy route belongs on a paid plan.

## Use waitUntil for anything you do not need an answer from

Logging a verdict to your own analytics endpoint should not add latency to the response. `ctx.waitUntil` keeps the Worker alive for the side effect after the response has already gone back:

javascript

```
ctx.waitUntil(
  fetch('https://your-collector.example/events', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ path: url.pathname, decision: verdict?.decision ?? null, asn: request.cf?.asn }),
  }).catch(() => {})       // never let telemetry break the request path
);
```

## The short version

- Use a standard Worker to read the visitor’s IP, ASN, country and negotiated TLS details before the origin.
- Cloudflare’s JA3 and JA4 fields require Enterprise Bot Management. For evidence of browser tampering, collect browser signals on the page and send them with the form.
- Read `monocle`, `sentinel_fp` and `sentinel_tz` (or the `collect()` names) and send all three as `token`, `fingerprintEventId` and `tz`, every time.
- A datacenter ASN is a reason to add friction, not a reason to refuse outright.
- Deadline every outbound call and treat every failure as allow.
- Key in `wrangler secret`, read from `env`, never inline and never in the browser.

## Questions people ask

**Can a Cloudflare Worker detect bots on its own?**

A standard Worker can use the visitor IP, ASN, country, TLS version and cipher to screen a request before it reaches the origin. An ASN or TLS version alone cannot establish whether a visitor is automated. Browser-side checks can supply additional evidence such as signs of browser tampering.

**Does a standard Cloudflare Worker expose JA3 or JA4 fingerprints?**

Cloudflare requires Enterprise Bot Management for its JA3 and JA4 fields. An entitled Worker can read ja3Hash and ja4 on request.cf.botManagement when available. The fields can be empty on requests without TLS or when Bot Management skips a request.

**Where should I put the API key in a Cloudflare Worker?**

In a secret, set with wrangler secret put MASKBREAK_API_KEY and read as env.MASKBREAK_API_KEY. Do not hard-code it in the script: Worker source is readable by anyone with dashboard access and usually lives in a repository. It must never reach browser-side JavaScript, where it becomes someone else’s free quota.

**What happens if the fraud API is slow at the edge?**

You should already have aborted. Put a deadline on every outbound call (the guide uses three seconds) and treat abort, network error, non-2xx and unparseable JSON as allow. A Worker sits in front of every request on its route, so failing closed there takes the whole route down rather than one handler.

**Can a Worker detect residential proxies?**

Not from connection metadata alone. A residential proxy exits through a genuine consumer connection, so the ASN belongs to a real ISP and the geolocation is real. Assess the route with independent proxy intelligence. For a live form submission, combine that result with browser evidence before deciding how to handle the action.

KT

Written by

 [Kaspar Tomson](https://maskbreak.com/about) Founder, Maskbreak

Kaspar runs the detection pipeline and the antidetect harness at Maskbreak, the fraud detection API built by Sentinel Edge Networks LTD. He buys and runs the same antidetect browsers, proxy services and automation frameworks that fraud operators use, points them at the detector, and publishes what fired and what did not.

[LinkedIn](https://www.linkedin.com/in/kaspar-tomson-80a45842a)[GitHub](https://github.com/sentinelsup)[Contact](https://maskbreak.com/contact)

## Paste it in, then watch the *verdicts*

The public sk_test_sandbox key returns the documented allow, review and block shapes with no account, so the failure path is testable before you go live; SDKs for Node, Python and PHP, or plain HTTP. The [Free plan](https://maskbreak.com/signup?next=%2Fdashboard%3Fsetup%3Dcloudflare%23integration) includes 10,000 visitor checks a month with no card, and setup starts in watch mode, so nothing is blocked until you turn blocking on.

[Get started free](https://maskbreak.com/signup?next=%2Fdashboard%3Fsetup%3Dcloudflare%23integration)[Read the API docs](https://maskbreak.com/api)
