Documentation / Integrations · Cloudflare

Cloudflare Workers: decide before origin.

A Worker sees the request before the origin does. That is the right place to score and enforce — as long as you are honest about what the edge can and cannot see.

Last updated

What the Worker has

Edge evidence is request evidence. Interaction evidence still comes from the page collector.
SignalSourceUse
Visitor IPcf-connecting-ipNetwork context and proxy detection.
Countrycf-ipcountryGeo and timezone cross-checks.
Headersrequest.headersUser agent, language, sec-fetch-*.
Cookiescookie headerReturn session; weak-session checks.
Not availableHeader order, TLS JA3, mouse or typingDo not invent it; omit the field.

The Worker

WorkerMinimal scoring example
interface Env {
  VOLANCE_PUBLIC_KEY: string;
  VOLANCE_SECRET_KEY: string;
  ORIGIN_URL: string;
}

let cachedManifest: { sid: string; manifest: string; expiresAt: number } | null = null;

async function getManifest(env: Env) {
  if (cachedManifest && cachedManifest.expiresAt > Date.now()) return cachedManifest;
  const response = await fetch('https://app.volance.com/api/trace/session', {
    headers: { authorization: 'Bearer ' + env.VOLANCE_PUBLIC_KEY },
  });
  if (!response.ok) throw new Error('session manifest failed');
  const body = await response.json();
  cachedManifest = {
    sid: body.sessionId,
    manifest: body.manifest,
    expiresAt: Date.now() + 50 * 60 * 1000,
  };
  return cachedManifest;
}

export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    const url = new URL(request.url);
    const session = await getManifest(env);

    const scored = await fetch('https://app.volance.com/api/trace/score', {
      method: 'POST',
      headers: {
        authorization: 'Bearer ' + env.VOLANCE_SECRET_KEY,
        'content-type': 'application/json',
      },
      body: JSON.stringify({
        publicKey: env.VOLANCE_PUBLIC_KEY,
        sid: session.sid,
        manifest: session.manifest,
        page: url.pathname,
        requestSignals: {
          visitorIp: request.headers.get('cf-connecting-ip') || undefined,
          proxyHeaders: request.headers.has('x-forwarded-for') ? ['x-forwarded-for'] : [],
          cookiePresent: request.headers.has('cookie'),
          visitorUserAgent: request.headers.get('user-agent') || undefined,
          acceptLanguage: request.headers.get('accept-language') || undefined,
          secFetchSite: request.headers.get('sec-fetch-site') || undefined,
          secFetchMode: request.headers.get('sec-fetch-mode') || undefined,
        },
      }),
      signal: AbortSignal.timeout(800),
    });

    const origin = new Request(env.ORIGIN_URL + url.pathname + url.search, request);
    if (!scored.ok) return fetch(origin);

    const result = await scored.json();
    if (result.action === 'block') return new Response('Forbidden', { status: 403 });

    const response = await fetch(origin);
    if (result.action === 'flag') {
      const copy = new Response(response.body, response);
      copy.headers.set('x-volance-verdict', 'flag');
      return copy;
    }
    return response;
  },
};

Manifest caching

The manifest is a signed capability valid for one hour, not a visitor identity. Reusing it is allowed; quota is metered per scoring call. The module-level cache is per isolate; use KV or the Cache API if you need one across isolates. A 50-minute expiry leaves room for clock and network skew.

What the edge cannot see

No JS environment, no pointer or typing cadence, no original header order unless your edge exposes it. Passing a fabricated value is worse than omitting the field: a missing check is honest, a fake one is a lie in the evidence. Use the page collector for interaction evidence and the Worker for the request decision.

Enforcing a 402

If the caller is an agent and your policy says charge, the scoring endpoint is not the tool; the agent decision endpoint is. It returns a paymentRequired challenge your Worker can send as a 402. Keep the decisions separate: a score says how human the request looks; a charge says what access costs. The agent monetization guide covers the flow.

Failure modes

The Worker is a dependency in front of origin.
FailureReasonable response
Manifest failsServe origin with a degraded header; do not take the site down.
Score times outFail open on reads, step up or fail closed on writes and spend.
Origin loopsRoute the Worker only on the intended paths; use an explicit origin URL.
429Back off; a 429 is not a billable score.
Stale verdictKeep the TTL short; a block should reflect the request in front of you.

Related

Free to start. 10,000 scores a month, one project, no credit card.

Get started free