Skip to content

CloudflareWorkers, caching and APIreference

We have fraud detection at home

How forminator and markov-mail implement multi-layer fraud detection for form submissions on Cloudflare Workers. Two Workers - one handling form submissions with multi-layer detection and 10-component risk scoring, the other running a 48-feature Random Forest classifier on email addresses with automated weekly retraining - connected via RPC (remote procedure call) service bindings.

This is a reference template for building similar systems. All patterns are derived from production code.

TL;DR:

  • Two Workers carry the system: the form Worker runs the submission pipeline and the 10-component risk scoring, and the ML (machine learning) Worker runs a 48-feature Random Forest email classifier. They talk over a Worker-to-Worker RPC service binding, which executes on the same thread of the same server.
  • Detection runs in layers: a local D1 blacklist fast path skips the Turnstile API (application programming interface) call for identifiers already known bad, then the ML email check, the ephemeral-ID signals and the JA4 TLS (Transport Layer Security) fingerprint analysis each contribute one score component.
  • Component failures fail open - an unavailable ML Worker scores 0 risk for its component and its weight is redistributed to the remaining active signals - while token replay and Turnstile validation stay fail-secure.
  • Weights, thresholds and detection parameters live in a mergeable config and are auto-normalised to sum to 1.0 after any override; block/allow comes from deterministic floors and a corroboration bonus on top of the weighted score.
  • Decisions are written to a ScoringDecision audit trail, and the model behind them is a 20-tree Random Forest serialised as JSON (JavaScript Object Notation) in KV (Cloudflare Workers KV), guarded before deploy on accuracy, KV’s 25 MB value limit and feature alignment.
  • On Supabase the same layers run in the project’s Postgres behind Supabase Auth hooks, and the edge Worker hands the signup hook a signed summary of what only it can see (the Turnstile device ID (identifier), JA4). See On Supabase: the same layers in Postgres.

BrowserBlacklistBot MgmtTurnstileToken ReplaycleancleanTurnstile APIvalidateCollect Signalseph_idML WorkerRPCScore (10w)scoreD1
ComponentRoleTech
Form WorkerSubmission intake, multi-layer fraud detection, risk scoringHono on Workers, D1, KV
ML WorkerEmail fraud classification, feature extraction, model inferenceHono on Workers, D1, 3x KV, Containers
Service BindingWorker-to-Worker RPC (zero overhead, same-thread execution)WorkerEntrypoint from cloudflare:workers
TurnstileCAPTCHA validation, ephemeral device IDs (Enterprise)Cloudflare Turnstile
Bot ManagementJA4 fingerprints, bot scores, JS (JavaScript) detection (Enterprise)Cloudflare Bot Management

The fraud pipeline runs in four phases. Each layer is independent - failure in one doesn’t block the others.

BlacklistToken Replayclean429 + BlacklisthitTurnstilecleanWrite RecordpassDuplicate?Collect Signalsunique3x+Email (RPC)Ephemeral IDJA4 FingerprintIP + FingerprintWeighted ScoreThreshold?201belowabove

Pre-Turnstile check against a TTL-based blacklist. Matches on email, ephemeral ID, JA4 fingerprint, or IP (Internet Protocol) address (checked in that priority order, most specific first). Returns in single-digit milliseconds and short-circuits the entire pipeline.

// Check order: most specific identifier first
async function checkPreValidationBlock(
ephemeralId: string | null,
remoteIp: string,
ja4: string | null,
email: string | null,
db: D1Database,
): Promise<PreValidationResult> {
const identifiers = [
{ type: "email", value: email },
{ type: "ephemeral_id", value: ephemeralId },
{ type: "ja4", value: ja4 },
{ type: "ip_address", value: remoteIp },
].filter((id) => id.value != null);
for (const { type, value } of identifiers) {
const entry = await db
.prepare(
`SELECT * FROM fraud_blacklist
WHERE identifier_type = ? AND identifier_value = ?
AND expires_at > ?`,
)
.bind(type, value, new Date().toISOString())
.first();
if (entry && ["high", "medium"].includes(entry.confidence)) {
return {
blocked: true,
reason: entry.detection_type,
confidence: entry.confidence,
};
}
}
return { blocked: false };
}

The form Worker calls the ML Worker via a service binding. The RPC call has zero overhead per Cloudflare’s documentation - both Workers execute on the same thread of the same server.

// Form Worker: call ML Worker via service binding
async function checkEmailFraud(
email: string,
env: Env,
request?: Request,
): Promise<EmailFraudResult | null> {
try {
// Pass request headers so ML Worker has access to
// geo, network, and bot management signals
const headers: Record<string, string | null> = {};
if (request?.cf) {
headers["cf-ipcountry"] = request.headers.get("cf-ipcountry");
headers["cf-connecting-ip"] = request.headers.get("cf-connecting-ip");
// ... additional cf headers for fingerprinting
}
const result = await env.FRAUD_DETECTOR.validate({
email,
consumer: "form-worker",
flow: "submission",
headers,
});
return {
riskScore: result.riskScore * 100, // ML returns 0-1, scoring expects 0-100
decision: result.decision,
signals: result.signals,
};
} catch {
return null; // Fail-open: ML unavailable = 0 risk
}
}

Collects three signals from D1 using Turnstile’s ephemeral device ID (Enterprise) to detect volume abuse:

SignalQueryDetection
Submission countCount submissions by ephemeral ID in 24hForm stuffing from same device
Validation frequencyCount Turnstile validations by ephemeral ID in 1hRapid-fire CAPTCHA solving
IP diversityCount distinct IPs per ephemeral ID in 24hVPN/proxy (virtual private network) rotation from same device
async function collectEphemeralIdSignals(
ephemeralId: string,
db: D1Database,
config: FraudDetectionConfig,
): Promise<EphemeralIdSignals> {
try {
const [submissions, validations, ips] = await Promise.all([
db
.prepare(
`SELECT COUNT(*) as count FROM submissions
WHERE ephemeral_id = ? AND created_at > datetime('now', '-24 hours')`,
)
.bind(ephemeralId)
.first<{ count: number }>(),
db
.prepare(
`SELECT COUNT(*) as count FROM turnstile_validations
WHERE ephemeral_id = ? AND validated_at > datetime('now', '-1 hour')`,
)
.bind(ephemeralId)
.first<{ count: number }>(),
db
.prepare(
`SELECT COUNT(DISTINCT ip) as count FROM (
SELECT ip_address as ip FROM submissions
WHERE ephemeral_id = ? AND created_at > datetime('now', '-24 hours')
UNION
SELECT ip_address as ip FROM turnstile_validations
WHERE ephemeral_id = ? AND validated_at > datetime('now', '-24 hours')
)`,
)
.bind(ephemeralId, ephemeralId)
.first<{ count: number }>(),
]);
return {
submissionCount: submissions?.count ?? 1,
validationCount: validations?.count ?? 1,
uniqueIPCount: ips?.count ?? 1,
};
} catch {
return { submissionCount: 1, validationCount: 1, uniqueIPCount: 1 }; // Fail-open baseline
}
}

Uses Bot Management’s JA4 fingerprint (Enterprise) to detect session hopping - multiple distinct devices sharing the same TLS fingerprint, which indicates automated tooling.

Three sub-layers with increasing scope:

Sub-layerScopeWindowThresholdCatches
4a: IP ClusteringSame JA4 + same IP/subnet1 hour2+ ephemeral IDsBot farm on single network
4b: Rapid GlobalSame JA4, any IP5 min3+ ephemeral IDsVPN-hopping automation
4c: Extended GlobalSame JA4, any IP1 hour5+ ephemeral IDsSlow distributed attacks
interface ClusteringAnalysis {
ja4: string;
ephemeralCount: number;
submissionCount: number;
timeSpanMinutes: number;
avgBotScore: number | null;
}
function calculateCompositeRiskScore(
analysis: ClusteringAnalysis,
config: FraudDetectionConfig,
): number {
let rawScore = 0;
// Signal 1: Clustering (multiple devices sharing JA4)
if (analysis.ephemeralCount >= 2) {
let clusterScore = 80;
// Household mitigation: halve score if bot score indicates human
if (analysis.avgBotScore && analysis.avgBotScore >= 50 && !isRapid) {
clusterScore = Math.round(clusterScore / 2);
}
rawScore += clusterScore;
}
// Signal 2: Velocity (submissions too close together)
if (analysis.timeSpanMinutes < config.ja4.velocityThreshold) {
rawScore += 60;
}
// Signal 3a: Global anomaly (high IP distribution + local clustering)
if (ja4Signals?.ips_quantile_1h > config.ja4.ipsQuantileThreshold) {
rawScore += 50;
}
// Signal 3b: Bot pattern (high request volume + local clustering)
if (ja4Signals?.reqs_quantile_1h > config.ja4.reqsQuantileThreshold) {
rawScore += 40;
}
// Max raw = 230, normalized to 0-100 by scoring module
return rawScore;
}

All signals feed into a 10-component weighted score. The architecture ensures every decision is auditable - the full breakdown is stored alongside each submission.

ComponentWeightSourceWhat it measures
Token Replay0.28TurnstileReused CAPTCHA token (binary: 0 or 100)
Email Fraud0.14ML Worker RPCML-classified email fraud probability
Ephemeral ID0.15D1 querySubmission volume from same device
Validation Frequency0.10D1 queryCAPTCHA solve rate from same device
IP Diversity0.07D1 queryIP rotation from same device
JA4 Session Hopping0.06D1 query + Bot MgmtTLS fingerprint clustering
IP Rate Limit0.07D1 queryBrowser-switching OR email diversity from same IP
Header Fingerprint0.07Request headersHeader pattern reuse across ephemeral IDs
TLS Anomaly0.04D1 + Bot MgmtFingerprint baseline deviation
Latency Mismatch0.02Request timingGeo vs network latency inconsistency

Weights must sum to 1.0. The system auto-normalises after config overrides.

The IP Rate Limit component is a composite of two sub-signals - submission frequency per IP and email diversity per IP - combined via Math.max(). The email diversity signal detects form spam with unique emails from the same address:

async function collectEmailDiversitySignal(
remoteIp: string,
db: D1Database,
config: FraudDetectionConfig,
): Promise<{ distinctEmails: number; riskScore: number }> {
const result = await db
.prepare(
`SELECT COUNT(DISTINCT email) as count FROM submissions
WHERE remote_ip = ? AND created_at > datetime('now', '-1 hour')`,
)
.bind(remoteIp)
.first<{ count: number }>();
const distinctEmails = (result?.count ?? 0) + 1; // +1 for current submission
let riskScore: number;
if (distinctEmails <= 1) riskScore = 0;
else if (distinctEmails === 2)
riskScore = 20; // Could be household
else if (distinctEmails === 3)
riskScore = 60; // Suspicious
else riskScore = 100; // Definite form spam
return { distinctEmails, riskScore };
}
10 ComponentsRedistributebaseCorroborationnormalizedDeterministicadjustedFinal 0-100Threshold?AllowbelowBlockabove

When signals are inactive (at baseline), their weight is redistributed proportionally to active signals. This prevents the score from being suppressed when some detection layers aren’t available (e.g., no Enterprise features, ML Worker down).

// Identify inactive signals (at baseline values)
const inactiveWeight = components
.filter((c) => c.score === 0 || c.score === baselineForComponent(c))
.reduce((sum, c) => sum + c.weight, 0);
// Redistribute to active signals
const normalizationFactor = 1.0 / (1.0 - inactiveWeight);
for (const component of activeComponents) {
component.contribution =
component.score * component.weight * normalizationFactor;
}

When 3+ independent signals score above a threshold (default: 30), a bonus (default: +15 points) is added. This rewards convergent evidence from different detection methods. All three parameters are configurable via risk.corroboration in the config:

corroboration: {
threshold: 30, // Minimum component score to count as "corroborating"
minSignals: 3, // Number of corroborating signals required
bonus: 15, // Flat bonus added to the score when triggered
},

Certain triggers immediately floor the score at the block threshold, regardless of the weighted calculation. Each has qualification requirements to prevent false positives:

TriggerQualification
token_replayAlways qualifies (fail-secure)
turnstile_failedAlways qualifies (fail-secure)
email_fraudSelf-sufficient (ML confidence)
ephemeral_id_fraudRequires elevated ephemeral ID score AND validation frequency
ja4_session_hoppingRequires raw score at least 140 AND IP rate limit score at least 25
validation_frequencyRequires ephemeral ID score above threshold
ModeBehaviorUse case
defensiveDeterministic triggers can override weighted scoreProduction default
additivePurely weighted, no overridesA/B testing, tuning

Every score adjustment is recorded:

interface ScoringDecision {
baseScore: number; // Raw weighted sum
normalizedScore: number; // After weight redistribution
adjustedScore: number; // After corroboration bonus
finalScore: number; // After deterministic floors
weightRedistribution?: {
inactiveWeight: number;
normalizationFactor: number;
};
corroborationBonus?: {
applied: boolean;
bonus: number;
corroboratingSignals: string[];
};
deterministicBlock?: {
trigger: string;
qualified: boolean;
};
}

When the final score exceeds the block threshold, a blockTrigger is assigned based on which signal was the primary cause. The evaluation order matters - it determines the detection type recorded for forensic analysis and the user-facing error message.

PriorityConditionblockTriggerdetectionType
1ML email decision = blockemail_fraudemail_fraud_detection
2Ephemeral submission count exceeds thresholdephemeral_id_fraudephemeral_id_tracking
3Validation count exceeds frequency thresholdvalidation_frequencyephemeral_id_tracking
4Validation burst (5+ validations, fewer than 2 submissions)validation_frequencyephemeral_id_tracking
5Unique IP count exceeds IP diversity thresholdip_diversityephemeral_id_tracking
6JA4 clustering detectedja4_session_hoppingja4_fingerprinting
7Fingerprint anomaly triggeredper-signalfingerprint_anomaly

IP rate limit is intentionally excluded as a block trigger (see note above).

Duplicate email submissions use a tiered approach that distinguishes user error from automated probing:

AttemptResponseBlacklistRationale
1st-2nd409 Conflict with friendly messageLow-confidence tracking entry (24h)Likely user re-submission
3rd+429 Too Many Requests with wait timeHigh-confidence entry with progressive timeoutAutomated probing pattern

The escalation happens because the blacklist tracks duplicate attempts per email+IP combination. On the 3rd attempt, the system calculates a progressive timeout and adds a high-confidence blacklist entry that triggers the Layer 0 fast path for subsequent requests.


All form inputs pass through Zod schema validation and HTML (HyperText Markup Language) sanitisation before entering the fraud detection pipeline.

Schema validation (Zod):

  • Names: 1-50 chars, Unicode-aware pattern (\p{L}\s'-)
  • Email: max 100 chars, standard format
  • Phone: optional, normalised to E.164 format (strip non-digits, add +1 prefix), validated against ^\+[1-9]\d{1,14}$
  • Address: optional, country required if any address field present
  • Date of birth: optional, YYYY-MM-DD, must be 18-120 years old

HTML sanitisation applied to all text inputs:

function sanitizeString(input: string): string {
return input
.replace(/<[^>]*>?/g, "") // Strip HTML tags
.replace(/&#?\w+;/g, "") // Strip HTML entities
.replace(/javascript\s*:/gi, "") // Strip javascript: URIs
.replace(/data\s*:/gi, "") // Strip data: URIs
.replace(/on\w+\s*=/gi, "") // Strip inline event handlers
.trim();
}

The ML Worker extracts a 48-dimension feature vector from an email address and scores it with a Random Forest classifier. It serves as both a standalone HTTP (Hypertext Transfer Protocol) API and an RPC service.

Features span ten categories:

CategoryExamplesCount
Sequentialsequential_confidence, plus_risk2
Local Partlocal_length, digit_ratio, has_year_suffix, alpha_prefix_naturalness, digit_position_ratio5
Identityname_similarity_score, name_token_overlap, name_in_email3
Geogeo_language_mismatch, geo_timezone_mismatch, geo_anomaly_score3
MX/Providermx_has_records, mx_record_count, mx_provider_* (8 one-hot), provider_is_free, provider_is_disposable12
Domain/TLDtld_risk_score, domain_reputation_score, entropy_score3
Linguisticpronounceability, vowel_ratio, max_consonant_cluster, repeated_char_ratio, syllable_estimate, impossible_cluster_count6
Structurehas_word_boundaries, segment_count, avg_segment_length, segments_without_vowels_ratio4
Statisticalunique_char_ratio, vowel_gap_ratio, max_digit_run, bigram_entropy4
N-gramngram_bigram_score, ngram_trigram_score, ngram_overall_score, ngram_confidence, ngram_risk_score, ngram_is_natural6
POST /validateemail?pass throughnoLoad from KVyes48 FeaturesRandom ForestPlatt CalOOD?HeuristicsDecisionD1asyncRoute Handler

The 48 features are produced by specialised detector modules. Each operates independently and returns structured results.

Identifies user123, test001, account42 style emails. Two patterns: trailing numbers (/^(.+?)(\d+)$/) and middle numbers with separators (/^(.+?)[._-](\d+)[._-](.+)$/).

Confidence factors: sequence length (+0.25 to +0.7), leading zeros (+0.3), digit ratio (+0.1 to +0.2), common bot bases (+0.25). Threshold: confidence >= 0.4 marks as sequential.

Exemptions (reduce false positives):

  • Birth years (1940-present, ages 13-100): john1990@ is not sequential
  • Small memorable numbers (3 or fewer digits, base 4+ chars, no leading zeros, no common base): mike42@ is not sequential

Common bot bases: test, user, account, email, temp, demo, admin, guest, trial, sample, hello, service, team, info, support, member.

Identifies date components in email local parts. Five format patterns checked in priority order (most specific first): full date (20241031), month+year (oct2024), four-digit year (2024), leading year (2024.username), two-digit year (24).

Age-aware classification assigns low risk to birth years and high risk to recent years.

CategoryYear AgeRiskExample
futurenegative (year > current)0.95user2027@
recent_timestamp0-20.90user2025@
underage3-120.70user2015@
plausible_birth_year13-650.20john1990@
elderly_birth_year66-1000.40user1940@
ancient>1000.80user1900@

Three feature groups measuring how “natural” an email local part looks:

  • Linguistic: Pronounceability (composite: vowel ratio, consonant cluster penalties, impossible cluster detection), vowel/consonant ratios, max cluster lengths, syllable estimate. Context-dependent y/w classification (e.g., y is a vowel when not adjacent to vowels).
  • Structure: Word boundary detection (., _, -), segment count and length statistics, segments-without-vowels ratio.
  • Statistical: Shannon entropy, bigram entropy (character pair transition randomness - higher = more suspicious), digit ratio, unique character ratio.

18 allowed consonant clusters (e.g., sch, str, thr, ght, tch, nch). Clusters of 3+ consonants not containing an allowed pattern are counted as “impossible.”

Bigram and trigram frequency analysis across 8 language groups (English, Spanish, French, German, Italian, Portuguese, Romanised, and a universal/mixed set). Input is NFD-normalised (Unicode Normalization Form D) to strip diacritics while preserving base characters, reducing false positives on international names. Scores how likely a character sequence is to appear in natural text for each language, taking the best match. Language detection uses suffix-based heuristics (e.g., -ez for Spanish, -stein for German, -ovich for Russian). Higher naturalness = lower fraud risk.

Checks whether the first-digit distribution of numbers in an email batch follows Benford’s Law (P(d) = log10(1 + 1/d)). Natural registrations follow this distribution; sequential/automated generation produces uniform distribution.

Method: chi-square goodness-of-fit test (df=8) with critical value at 0.05 significance (15.507). Requires minimum 30 digit samples for statistical validity. Used primarily in batch analysis rather than individual scoring.

Resolves the email domain’s MX (mail exchange) records to classify the provider and detect suspicious hosting:

  • Resolution: Cloudflare DNS-over-HTTPS (Hypertext Transfer Protocol Secure) (cloudflare-dns.com/dns-query) with 500ms fetch timeout via AbortController (wrapped in a 1500ms middleware timeout with background retry)
  • Caching: In-memory with 15-minute TTL (time to live). Concurrent requests for the same domain are deduplicated via an inflight map.
  • Provider classification: Google, Microsoft, iCloud, Yahoo, Zoho, Proton, self-hosted (MX points to own domain), other. Provider is determined by the MX exchange hostname patterns.
  • Features produced: mx_has_records, mx_record_count, and one-hot encoded mx_provider_* flags (8 providers: Google, Microsoft, iCloud, Yahoo, Zoho, Proton, self-hosted, other). Cache bounded to 10k entries with LRU (least recently used) eviction.

The ML Worker’s behavior is controlled by a config loaded from KV:

{
"riskThresholds": { "block": 0.88, "warn": 0.56 },
"actionOverride": null,
"adjustments": {
"professionalEmailFactor": 0.5,
"professionalDomainFactor": 0.5,
"professionalAbnormalityFactor": 0.6
},
"ood": { "maxRisk": 0.85, "warnZoneMin": 0.6 }
}
  • actionOverride: Set to "allow" for monitoring mode - runs all detection and logs decisions but never blocks. Required for a safe rollout of a new model or config change.
  • adjustments: Professional email patterns (name-based addresses at reputable domains) get their risk score multiplied by these factors, reducing false positives on legitimate business emails.
  • ood (out-of-distribution): When the model encounters feature vectors outside its training distribution, risk is capped at maxRisk (0.85) and flagged if above warnZoneMin (0.6). Prevents overconfident predictions on novel patterns.

A post-model safety net that can override ML decisions based on simple threshold rules. Loaded from KV (risk-heuristics.json) with 60-second cache TTL, falling back to hardcoded defaults.

HeuristicBlock ThresholdWarn ThresholdScore Offset
TLD (top-level domain) risk0.9+0.8++0.10
Domain reputation0.95+0.85++0.08
Sequential confidence0.98+0.9++0.05
Digit ratio0.9+0.8++0.05
Plus-addressing abuse0.8+-+0.03

Each rule has a threshold, decision (warn or block), direction (gte or lte), and minScoreOffset. Rules are applied after model scoring - they can elevate a score but never reduce it. The KV-based config means you can add or adjust heuristics without redeploying.

interface HeuristicRule {
threshold: number;
decision: "warn" | "block";
reason: string;
direction?: "gte" | "lte"; // Default: gte
minScoreOffset?: number;
}

The model (20 decision trees of the classification-and-regression (CART) kind, trained both offline via scikit-learn and online via a container-based TypeScript implementation) is serialised as JSON and stored in KV. The Worker evaluates it using iterative tree traversal (not recursive, to avoid stack limits on the edge runtime).

type CompactTreeNode =
| { t: "l"; v: number } // Leaf: fraud probability
| { t: "n"; f: string; v: number; l: CompactTreeNode; r: CompactTreeNode }; // Split node
function predictForestScore(
model: ForestModel,
features: Record<string, number>,
): number {
const maxDepth = Math.min(model.meta.config?.max_depth ?? 20, 50);
let total = 0;
for (const tree of model.forest) {
let node = tree;
let depth = 0;
// Iterative traversal (no recursion)
while (node.t === "n" && depth < maxDepth) {
const featureValue = features[node.f] ?? 0;
node = featureValue <= node.v ? node.l : node.r; // scikit-learn convention
depth++;
}
total += node.t === "l" ? node.v : 0.5; // Fallback if depth exceeded
}
return total / model.forest.length; // Average probability across trees
}

Raw forest outputs are calibrated using Platt scaling (sigmoid fit on out-of-bag predictions from training). This converts raw vote averages into well-calibrated probabilities:

calibrated = 1 / (1 + exp(-(intercept + coef * raw_score)))

Calibration parameters (intercept, coef) are stored in the model’s metadata and applied automatically during inference. The production model’s calibration was fitted on 50,000 out-of-bag (OOB) samples.

The middleware uses Random Forest as primary and Decision Tree as fallback. If both models are unavailable (KV failure), the system applies a degraded “warn floor” score and fires an ops alert. This ensures the detection pipeline never silently passes traffic unscored.

Instead of wiring fraud detection per-route, a Hono middleware runs on every POST request that contains an email field:

async function fraudDetectionMiddleware(c: Context, next: Next) {
if (c.req.method !== "POST" || c.get("skipFraudDetection")) {
return next();
}
const body = await c.req.raw
.clone()
.json()
.catch(() => null);
const email = body?.email;
if (!email) return next();
// Load model from KV, extract features, score, decide
const features = buildFeatureVector(email, c.req);
const score = predictForestScore(model, features);
const calibrated = applyPlattCalibration(score, model.meta.calibration);
const decision =
calibrated >= threshold
? "block"
: calibrated >= warnThreshold
? "warn"
: "allow";
c.set("fraudDetection", { score: calibrated, decision, signals });
return next();
}
// Register globally
app.use("/*", fraudDetectionMiddleware);

Routes that need to opt out (e.g., dashboard auth) set a context flag:

app.post("/dashboard/auth", (c) => {
c.set("skipFraudDetection", true);
// ... handle auth
});

The two Workers communicate via Cloudflare’s service bindings,1 which use Workers RPC2 built on Cap’n Proto. Per the docs, there is zero overhead - both Workers execute on the same thread of the same server.

import { WorkerEntrypoint } from "cloudflare:workers";
class FraudDetectionService extends WorkerEntrypoint<Env> {
// RPC method callable by other Workers
async validate(request: {
email: string;
consumer?: string;
flow?: string;
headers?: Record<string, string | null>;
}): Promise<ValidationResult> {
// Reconstruct an HTTP request from RPC args
// This reuses the same Hono handler for both HTTP and RPC
const httpRequest = new Request("http://localhost/validate", {
method: "POST",
headers: this.buildHeaders(request.headers),
body: JSON.stringify({
email: request.email,
consumer: request.consumer,
}),
});
const response = await app.fetch(httpRequest, this.env, this.ctx);
return response.json() as Promise<ValidationResult>;
}
// Standard HTTP handler (for direct API access)
async fetch(request: Request): Promise<Response> {
return app.fetch(request, this.env, this.ctx);
}
}
export { FraudDetectionService };

Wrangler config:

{
"services": [
{
"binding": "FRAUD_DETECTOR",
"service": "markov-mail",
"entrypoint": "FraudDetectionService",
},
],
}

Calling the service:

// env.FRAUD_DETECTOR is typed as the RPC interface
const result = await env.FRAUD_DETECTOR.validate({
email: submittedEmail,
consumer: "form-worker",
flow: "submission",
headers: extractCfHeaders(request),
});

RPC requires compatibility_date of 2024-04-03 or later.


When a submission is blocked, the offending identifiers are blacklisted with escalating TTLs:

OffenseTimeoutCumulative
1st1 hour1h
2nd4 hours5h
3rd8 hours13h
4th12 hours25h
5th+24 hours49h+
function calculateProgressiveTimeout(
offenseCount: number,
config: FraudDetectionConfig,
): number {
const schedule = config.timeouts.schedule; // [3600, 14400, 28800, 43200, 86400]
const index = Math.min(offenseCount, schedule.length - 1);
return schedule[index];
}

Blacklist entries store multiple identifiers (email, ephemeral ID, JA4, IP) and are checked on the fast path before any Turnstile API call. Each subsequent hit updates last_seen_at and increments offense_count.

BlockedWrite EntryActive?Layer 0next hitExpiredTTLlowEscalatehigh/medCleared

All thresholds, weights, and detection parameters live in a centralised config with environment overrides. The override is deep-merged with defaults at every nesting level.

const DEFAULT_CONFIG = {
risk: {
mode: "defensive" as "defensive" | "additive",
blockThreshold: 70,
levels: {
low: { min: 0, max: 39 },
medium: { min: 40, max: 69 },
high: { min: 70, max: 100 },
},
corroboration: {
threshold: 30, // Min score to count as corroborating
minSignals: 3, // Signals required to trigger bonus
bonus: 15, // Flat bonus added
},
weights: {
tokenReplay: 0.28,
emailFraud: 0.14,
ephemeralId: 0.15,
validationFrequency: 0.1,
ipDiversity: 0.07,
ja4SessionHopping: 0.06,
ipRateLimit: 0.07,
headerFingerprint: 0.07,
tlsAnomaly: 0.04,
latencyMismatch: 0.02,
},
},
detection: {
ephemeralIdSubmissionThreshold: 2,
validationFrequencyBlockThreshold: 3,
ipRateLimitThreshold: 3,
},
timeouts: {
schedule: [3600, 14400, 28800, 43200, 86400],
maximum: 86400,
},
};

Override via FRAUD_CONFIG environment variable (partial objects merge with defaults):

wrangler.jsonc
{
"vars": {
"FRAUD_CONFIG": {
"risk": {
"blockThreshold": 60,
"weights": { "emailFraud": 0.2 },
},
},
},
}

After merging, weights are auto-normalised to sum to 1.0 if the override creates an imbalance.


Minimal binding configuration for the two-Worker system:

// Form Worker (forminator) wrangler.jsonc
{
"name": "forminator",
"compatibility_date": "2025-11-12",
"d1_databases": [
{
"binding": "DB",
"database_name": "DB",
},
],
"services": [
{
"binding": "FRAUD_DETECTOR",
"service": "markov-mail",
"entrypoint": "FraudDetectionService",
},
],
"kv_namespaces": [{ "binding": "FORM_CONFIG" }],
"assets": {
"binding": "ASSETS",
"directory": "./frontend/dist",
},
}
// ML Worker (markov-mail) wrangler.jsonc
{
"name": "markov-mail",
"compatibility_date": "2024-10-11",
"d1_databases": [
{
"binding": "DB",
"database_name": "markov-db",
},
],
"kv_namespaces": [
{ "binding": "CONFIG" },
{ "binding": "DISPOSABLE_DOMAINS_LIST" },
{ "binding": "TLD_LIST" },
],
"containers": [
{
"class_name": "TrainerContainer",
"image": "./container/Dockerfile",
"max_instances": 1,
},
],
"durable_objects": {
"bindings": [
{
"name": "TRAINER",
"class_name": "TrainerContainer",
},
],
},
"triggers": {
"crons": ["0 */6 * * *", "0 3 * * SUN"],
},
"assets": {
"directory": "./public/",
"binding": "ASSETS",
},
}

TablePurposeKey columns
submissionsForm data + 42 metadata fieldsemail, ephemeral_id, risk_score_breakdown, ja4, bot_score
turnstile_validationsEvery validation attempttoken_hash (UNIQUE), detection_type, risk_score_breakdown
fraud_blacklistProgressive mitigation cacheemail, ephemeral_id, ja4, ip_address, expires_at, detection_confidence
fraud_blocksPre-Turnstile forensic logdetection_type, fraud_signals_json
fingerprint_baselinesTLS fingerprint anomaly baselinesja4_bucket, asn_bucket, hit_count
TablePurpose
validationsEvery email validation with all signals and features (86 columns)
training_samplesAuto-collected 48-feature vectors from live validations, with labels and source tracking
training_metricsModel training history: accuracy, precision, recall, F1, FPR (false positive rate), anomaly detection
ab_test_metricsExperiment tracking for model variants
admin_metricsConfiguration change audit log

The training_samples table drives the automated retraining loop. Each validation writes a feature vector with an auto-assigned label (known_disposable, known_provider, or model) keyed by a unique email hash. Manual review labels get 5x weight during training. Samples older than 14 days are pruned after each retraining cycle.


The ML Worker uses two cron triggers to run three background tasks:

Cron ExpressionScheduleTask
0 */6 * * *Every 6 hoursRefresh disposable domain list from external GitHub sources (71k+ domains stored in KV)
0 */6 * * *Every 6 hoursPrune validation records older than 30 days from D1 (GDPR (General Data Protection Regulation) compliance)
0 3 * * SUNSundays 3AM UTCAutomated model retraining via TrainerContainer Durable Object (see training pipeline below)
export default {
async scheduled(
controller: ScheduledController,
env: Env,
ctx: ExecutionContext,
) {
// Domain refresh + data pruning run on every cron trigger
ctx.waitUntil(updateDisposableDomains(env));
ctx.waitUntil(pruneOldValidations(env.DB, 30));
// Weekly retraining runs only on the Sunday schedule
if (controller.cron === "0 3 * * SUN") {
ctx.waitUntil(triggerContainerRetraining(env));
}
},
};

The weekly retraining task sends training parameters (nTrees: 20, maxDepth: 6, minSamplesLeaf: 20, conflictWeight: 20) to the TrainerContainer Durable Object, which runs a full pipeline: fetch live training data from D1, train a new Random Forest, run guardrails, and upload the validated model to KV. After success, training samples older than 14 days are pruned.


The Random Forest is trained through two complementary pipelines: an automated container-based pipeline that retrains weekly on live production data, and an offline CLI (command-line interface) pipeline for initial training and major model revisions.

A weekly cron (Sundays 3AM UTC (Coordinated Universal Time)) triggers the TrainerContainer Durable Object, which runs a Bun-based Docker container. The container:

  1. Fetches the current training dataset from the Worker’s D1 database (auto-collected feature vectors from every /validate call)
  2. Trains a new Random Forest using a TypeScript CART implementation with Gini impurity, random feature subsampling, and conflict-zone weighting
  3. Applies Platt calibration via Newton-Raphson optimisation on OOB predictions
  4. Runs guardrails (recall >= 95%, FPR <= 5%, FNR <= 5%)
  5. Uploads the validated model to KV (propagates globally within 60 seconds)
  6. Prunes training samples older than 14 days

If guardrails fail, the existing model remains active and a training failure event is logged.

For initial training and major model changes, an offline Python/CLI toolchain produces the model artifact.

SourceRowsLabel
Enron email corpus (cleaned)172,806legit
Synthetic (legit filler)327,194legit
Synthetic (fraud)500,000fraud
Total1,000,00050/50 balanced

Synthetic data is generated with deterministic seeds for reproducibility. Fraud patterns include sequential, dated, high-entropy, disposable domain, and plus-addressing variants. The Enron corpus provides real-world legitimate email diversity.

cli/commands/
model/ train_forest.py, calibrate.ts, pipeline.ts, guardrail.ts
features/ export.ts (feature vector CSV generation)
data/ synthetic.ts, clean_enron.ts, domains.ts
deploy/ deploy.ts, status.ts
ab/ create.ts, analyze.ts, status.ts, stop.ts
test/ api.ts, batch.ts, cron.ts, detectors.ts
Enron 172Kmain.csv 1MSynth 327KSynth 500Kfeatures:exportfeatures.csvRF 20 treesPlatt CalGuardrailsfailUpload KVpassWorker ~60s

Step 1: Feature export - Extract 48-feature vectors from the canonical dataset:

Terminal window
npm run cli features:export -- --input data/main.csv --output tmp/features.csv

Step 2: Train - scikit-learn RandomForestClassifier with conflict-zone weighting:

Terminal window
python cli/commands/model/train_forest.py \
--input tmp/features.csv \
--output config/production/random-forest.json \
--n-trees 20 --max-depth 6 --min-samples-leaf 20 \
--conflict-weight 20.0 --no-split

Key training parameters:

  • Conflict-zone weighting: Samples with bigram_entropy > 3.0 AND domain_reputation_score >= 0.6 get 20x weight. These are the overlap-region cases where legitimate and fraudulent emails look similar - forcing the forest to learn deeper patterns in this zone.
  • --no-split: Trains on 100% of data for production (uses OOB predictions for calibration instead of a held-out set).
  • Platt calibration: Fits LogisticRegression on OOB predictions to produce well-calibrated probabilities. Outputs intercept and coef stored in model metadata.

Step 3: Guardrails - Validate model before deployment (accuracy, size under KV 25MB limit, feature alignment).

Step 4: Deploy - Upload model JSON to KV. The Worker picks it up within 60 seconds (KV eventual consistency).

The serialised model contains metadata for runtime validation:

{
"meta": {
"version": "5.0.0-48feat",
"features": ["avg_segment_length", "bigram_entropy", "digit_ratio", "...48 total..."],
"tree_count": 20,
"nTrees": 20,
"maxDepth": 6,
"feature_importance": {
"provider_is_disposable": 0.160,
"domain_reputation_score": 0.142,
"digit_position_ratio": 0.119,
"digit_ratio": 0.072,
"name_token_overlap": 0.057,
"max_digit_run": 0.056,
"bigram_entropy": 0.051,
"has_year_suffix": 0.047,
"provider_is_free": 0.040,
"entropy_score": 0.033
},
"calibration": {
"method": "platt",
"intercept": -4.5568,
"coef": 8.9711,
"samples": 50000
},
"config": {
"n_trees": 20,
"max_depth": 6,
"min_samples_leaf": 20,
"conflict_weight": 20.0,
"conflict_entropy_threshold": 3.0,
"conflict_reputation_threshold": 0.6,
"no_split": true,
"oob_calibration": true
}
},
"forest": ["...20 serialized decision trees..."]
}

Top 5 features by importance: disposable domain flag (0.160), domain reputation (0.142), digit position ratio (0.119), digit ratio (0.072), name-token overlap (0.057). The digit_position_ratio feature - measuring where digits appear relative to the local part length - was introduced in the 48-feature model and ranks 3rd by importance; it distinguishes john1990@ (birth year at end) from 2024signup@ (timestamp at start). Geo features (language/timezone mismatch) have near-zero importance in the current model - they contribute to heuristic overrides instead.


The ML Worker includes a fully implemented A/B testing framework for comparing model variants. Experiments are configured in KV and use consistent hash-based traffic splitting.

interface ABTestConfig {
experimentId: string;
description: string;
variants: {
control: { weight: number; config?: Partial<FraudDetectionConfig> };
treatment: { weight: number; config?: Partial<FraudDetectionConfig> };
};
startDate: string; // ISO 8601
endDate: string;
enabled: boolean;
metadata?: {
hypothesis: string;
expectedImpact: string;
successMetrics: string[];
};
}

Variant assignment uses the first 8 hex characters of the request fingerprint hash, converted to a bucket (0-99). Buckets below the treatment weight go to treatment, the rest to control. This ensures the same device consistently sees the same variant.

function getVariant(
fingerprintHash: string,
config: ABTestConfig,
): "control" | "treatment" {
const bucket = parseInt(fingerprintHash.substring(0, 8), 16) % 100;
return bucket < config.variants.treatment.weight ? "treatment" : "control";
}

Variant-specific config overrides are deep-merged with the base config, so experiments can change thresholds, weights, or feature flags independently. Weights must sum to 100.

Terminal window
npm run cli ab:create # Create and upload experiment config to KV
npm run cli ab:status # Check active experiment status
npm run cli ab:analyze # Compare variant performance from D1 metrics
npm run cli ab:stop # End experiment and remove from KV

The ML Worker includes an Astro 5 + React 19 + Tailwind CSS (Cascading Style Sheets) 4 analytics dashboard (19 components) for monitoring fraud detection in production:

  • Metrics grid: Key KPIs (total validations, block rate, warn rate, avg score)
  • Time-series charts: Score distributions and decision trends over time (Recharts)
  • Block reasons breakdown: Which heuristics and model signals trigger blocks
  • Validation table: Drill into individual validation results with full signal details
  • Model comparison: Side-by-side A/B test variant performance
  • Review queue: Manual label review for training sample correction
  • Training panel: Training pipeline control and status monitoring
  • Threshold tuner: Interactive threshold adjustment UI (user interface)
  • Query builder: Ad-hoc SQL (Structured Query Language) queries against the D1 metrics tables
  • System status: Health indicators for model availability, KV connectivity, cron job status
  • Export: Data export in multiple formats

Authentication uses HMAC-signed session cookies (SHA-256 (Secure Hash Algorithm) derived signing key) with 24-hour TTL, HttpOnly/Secure/SameSite=Strict flags, and timing-safe comparison. Login is rate-limited to 5 attempts per minute per IP.


PrincipleImplementation
Fail-open by defaultSignal collection, ML scoring, blacklist writes - all return safe baselines on error
Fail-secure for definitivesToken replay and Turnstile validation block on error (assume reused/invalid)
Weight redistributionInactive signals don’t suppress the score - their weight shifts to active ones
Transparent decisionsEvery score stores a full ScoringDecision audit trail with each adjustment step
Per-request tracingA unique request ID generated at entry threads through all DB (database) writes for forensic correlation
Config-driven thresholdsAll magic numbers live in a mergeable config with auto-normalisation for weights
Progressive mitigationEscalating timeouts instead of permanent bans - reduces false positive impact
Single code pathRPC entrypoint constructs a synthetic HTTP request through the same Hono handler as direct API calls
Monitoring modeAction override flag runs all detection and logs decisions without blocking - safe rollout for new rules

TaskSteps
Add a detection layer1. Implement signal collection function (return baseline on error) 2. Add score component + weight to config 3. Wire into Phase 2 of submission pipeline 4. Add normalisation function in scoring module
Add an ML feature1. Implement extractor in detector module 2. Add to buildFeatureVector() in feature-vector.ts 3. Run features:export to regenerate CSV (comma-separated values) 4. Retrain with train_forest.py (offline) or trigger container retraining 5. Run guardrails 6. Deploy model JSON to KV (no Worker redeploy)
Tune thresholds1. Set mode: 'additive' to disable deterministic overrides 2. Analyze score distributions from stored breakdowns via dashboard 3. Adjust FRAUD_CONFIG in wrangler vars 4. Switch back to mode: 'defensive'
Run an A/B test1. ab:create with hypothesis, traffic split, and variant config overrides 2. Monitor via dashboard model comparison view 3. ab:analyze to compare variant metrics 4. ab:stop and promote winner
Add a heuristic rule1. Add rule to risk-heuristics.json (threshold, decision, reason, offset) 2. Upload to KV 3. Rule takes effect within 60 seconds (no redeploy)
Safe rollout1. Set actionOverride: "allow" in production config 2. Deploy new model or config 3. Monitor decisions in dashboard (logs without blocking) 4. Remove override when confident

A multi-layer scorer rates how risky one submission is. Abuse operations also asks about actors, campaigns, and what happens after a block. Each row below is a generic pattern; the middle column shows where a scoring-first system like this one typically sits.

DimensionWhat a scoring-only system missesPattern that closes it
Campaign / actor footprintsIt can’t see that today’s submission is yesterday’s actor with one signal changed.A footprint - a set of individually weak indicators identifying a campaign - matched N-of-M: a full match auto-actions, a partial match flags a likely pivot (same actor, changed tactic) for review.
Intent classificationA 0-100 score captures how bad, never what kind (monetisation, weaponisation, disruption, reputation-gaming, victimisation).Tag each detection with an intent aspect so the output can be routed and explained by kind as well as by magnitude.
A review tierOne block/allow threshold forces every ambiguous case into either a false positive or a miss.A third review band routes mid-confidence cases to a human queue - “is it good, or just not-bad-yet?”
Return trackingIf banned-actor records are deleted when a timeout lapses, a returning actor looks brand-new and any escalation resets.Operations reduce but never fully delete return-detection data, so repeat offenders keep accumulating history across windows.
Non-repetitionLearning a new pattern only protects against future instances.A retroactive sweep re-runs a newly learned footprint over recent history to catch stragglers - which means retaining enough raw signal to re-evaluate after the fact.
Outbound = inboundBlocking protects the platform; it does nothing for the victim downstream.Report or reset harvested credentials and notify other providers in a distributed kit; a blocked payload is still live elsewhere.
External signalA self-generated blacklist only learns from abuse that already reached you.Ingest external feeds (disposable-email lists, known-bad IPs/JA4) to act on abuse “seen elsewhere first”.

forminator itself ships the footprint matcher as src/lib/footprint.ts (N-of-M bands, pivot and splash detection, update suggestions; added 2026-06-19), but the submission route does not call it, so on Workers it is a library rather than a running layer. The Supabase port below runs it as a scheduled sweep with retroactive matching and a review queue.

  • Reversibility - a non-zero false-positive rate is unavoidable, so remediations should be undoable: escalating timeouts and soft state instead of permanent deletes. Here that is the progressive (self-reversing) timeouts.
  • Codifiability - every decision carries an audit trail and rules live in configuration, never in manual database edits. Here that is the per-decision ScoringDecision audit trail and hot-reloadable config and heuristics.

The Workers system protects a form it owns. Signups on Supabase go to Supabase Auth, and two facts stop the Workers system from simply sitting in front of it:

  • The project’s own Auth endpoint (https://<ref>.supabase.co/auth/v1/signup) keeps answering after a custom domain is set up3, so a bot can skip any proxy on the app’s domain. Locking down Supabase measured this.
  • Supabase’s hosted CAPTCHA verifies Turnstile but keeps only success, error-codes and hostname from the response (captcha.go L18-L22), so the ephemeral device ID4 - the signal that sees through residential proxy rotation - never reaches the project.

The port, a kit of Supabase Auth hooks, moves the layers into the project’s Postgres and enforces them where no request can bypass them: in Auth hooks. The edge Worker does what only it can do and signs the result.

BrowserEdge WorkerTurnstile + JA4Turnstile tokenSupabase AuthsignUp(data)signed verdictbefore-user-createdPostgres functionverify, recordabuse schemaevents, blocklist, tiersRLS on app tablesmy_tier()pg_cronscore, footprintsdecisions, tiers
  1. The browser solves Turnstile and sends the token to the edge Worker.
  2. The Worker verifies the token itself (so it gets the ephemeral ID), reads JA4 and bot score, and returns a short-lived HMAC-signed verdict bound to the signup email.
  3. The browser signs up with the verdict in options.data, which reaches the before-user-created hook5 as user_metadata.
  4. The hook verifies the verdict (signature, expiry, email, single-use nonce), checks the blocklist, records the event with capped velocity counts, and denies only on a blocklist hit or a missing verdict when verdicts are required.
  5. pg_cron scores each signup and sweeps campaign footprints; the resulting tier is read live by RLS (row-level security) policies on the app’s own tables.

With verdicts required, a signup posted straight to the Auth endpoint has none and is refused before any auth.users row exists. OAuth and SSO (single sign-on) signups cannot carry options.data and are exempt.

The kit’s reference Worker can also post the signup itself, with the project’s secret key and Sb-Forwarded-For set to the client’s IP, so the verdict never reaches the browser and, by Auth’s code, its per-IP limits count the end user, not the Worker (the rate-limit key was not measured). Supabase’s docs say the header is honoured only with a secret key and only once IP address forwarding is enabled for the project6. Auth’s own code applies it whenever the setting is on, and does not check the key (sbff.go). On two fresh hosted projects the docs’ rule held anyway (2026-11-12)7, so something in front of Auth, or a deployed Auth version other than the one read, enforces it (not measured). With forwarding on, the before-user-created hook saw Sb-Forwarded-For only from the secret key; publishable, legacy anon and legacy service_role requests got the same address as a signup sent with no header, which the second run matched to the client’s own. A publishable-key request’s X-Forwarded-For was ignored as well; the other keys were not tried with it. With forwarding off, the hook’s ip_address was the leftmost X-Forwarded-For entry the caller sent, with the publishable and with the secret key, so any direct caller chooses the address every IP rule in the kit’s signup hook reads. Turn forwarding on. If Turnstile cannot be verified, the Worker refuses the signup rather than forwarding it unverified.

With Auth’s own CAPTCHA on, secret-key and legacy service_role signups passed with no token and publishable or legacy anon ones got captcha_failed (same runs), so a project can keep Auth’s CAPTCHA for direct callers while the Worker’s forwards pass on the secret key.

Workers systemOn SupabaseNotes
D1 blacklist, progressive timeoutsabuse.blocklist, abuse.escalate (1h, 4h, 8h, 12h, 24h)Emails and devices stored as HMAC (hash-based message authentication code) hashes, never deleted, so a returning actor still matches.
Turnstile ephemeral ID layerDevice ID from the signed verdictSignups, validations and IPs per device feed forminator’s ephemeral layer.
scoring.tsabuse.score() in SQLSame inputs and outputs, number for number (see evidence).
ip-rate-limiting.tsVelocity counts in the hookRecorded, never a block on their own. The two network counts stop at 200 per lookup by default (configurable), the others at 50.
markov-mail RPCpg_net call to its /validateRetried on 5xx, 429 and timeout, per pg_net under load.
footprint.ts (unwired)Footprint sweep every 5 minutes, retroactive on add, review queueFull match raises the tier; a pivot or splash waits for an analyst. Confirming a pivot widens the changed indicator into a set of values, so the next signup from the new range is a full match. The sets are the kit’s own extension: in footprint.ts every indicator must match exactly.
Block, 429Tiers allow < watch < quarantine < banThe custom-access-token hook8 adds a risk_tier claim; RLS reads the live tier because a claim changes only at token refresh. A ban also sets auth.users.banned_until.
nonePassword-verification hook9A valid password from an IP that failed for many other accounts is refused and the user watched; never logs the user out. Teams and Enterprise only.
noneabuse.send_guard for send hooksThe send hooks replace Supabase’s delivery10, so the guard is called by the project’s own hook: bans get nothing, quarantine gets no SMS, per-prefix SMS caps. The kit ships reference send-SMS and send-email hooks as Edge Functions; a quarantined user still gets a recovery email.

Everything installs in monitor mode: every hit is recorded as “would deny” and nothing is refused until the operator switches to enforce.

Without the signed verdict a signup carries only an IP and an email. Two of the ten components are then live - email (0.14) and IP rate limit (0.07) - and the redistribution cap of 2.0x keeps the highest score without a trigger at (14 + 7) x 2 = 42, under the block threshold of 70 (arithmetic from the weights, not a measurement). Only an email classifier block crosses it, through the email-fraud floor. That is forminator’s rule held as written: IP-derived signals never block alone.

The kit adds a second score for what the hook can count. It looks at bursts of signups from one network (a /24 or /64), on one email domain outside the big free-mail providers, or from one address. Each burst scores from a threshold upwards. Bursts from one network count once and can reach watch on their own, never quarantine; two bursts that agree reach quarantine. The scorer decides on the higher of this score and forminator’s.

The thresholds were fitted on replayed traffic. Each starts one above the largest value a legit signup reached on three training seeds and is full at twice its start: carrier NAT reached 40 signups per hour from one /24, and a team of up to 20 onboarding together reached 23 on its domain. They were re-fitted on 2026-11-13 with the network counts’ cap at 200. The results below are from three other seeds: 600 bot signups an hour against about 1,200 legit ones (70% single users, 15% behind four carrier NAT ranges, and the rest households, offices and teams), 3% of them retrying once:

CampaignBots at watch or above %Bots at quarantine %Legit flagged %
Residential proxies, anonymous0.00.00.0
Three datacenter /24s, anonymous67.50.00.0
Two throwaway domains, residential IPs86.70.00.0
40 addresses retried after failed or denied signups80.00.00.0
Three datacenter /24s and two throwaway domains86.771.00.0

The first fit ran with every count capped at 50 an hour. With twice as many users per carrier prefix, legit traffic alone filled that cap, the fit turned the network score off and the datacenter pool went uncaught. With the network counts capped at 200 the same model’s pool reaches watch at 41.0% and pool plus domains reaches quarantine at 50.0%. The cap of 50 also cut the network ramp short, so in the four-range model above the pool scored higher then: 77.0% at watch, 77.5% at quarantine with the domains. The higher cap added 0.016-0.055 ms to the hook’s p50 (difference of medians at 0, 10,000 and 100,000 prior events; at 0 the run ranges overlap) for an anonymous sign-in from a /24 already past the cap (local benchmark, 2026-11-13, 5 runs per cell). These thresholds fit a stated model, not real traffic; re-fit them in monitor mode on the project’s own signups.

Measured 2026-11-12 on a Supabase CLI 3.1.0 local stack (Postgres 17) on a 10-core laptop, load average 2.0-2.6. These are local numbers, not hosted ones.

The replay sent 600 synthetic bot signups and about 1,200 legit ones per run through the hook, the scorer and the footprint sweep, 5 seeds per cell, 135 runs. Every event got a decision, none errored, and every verdict verified. Every bot holds a solved Turnstile token, so CAPTCHA catches none of them by construction, not by measurement. Bots are anonymous sign-ins from a fresh residential IP each; legit traffic is 85% one signup per device, 10% households (two accounts on one device) and 5% behind shared office IPs, signing in anonymously unless the row says email.

Bot farm devicesKitBots flagged %Legit flagged %
5 / 50 / 600hook only, no verdict0.0 / 0.0 / 0.00.0
5 / 50 / 600verdict, device threshold 299.2 / 91.7 / 37.010.2 (8.8-10.7)
5 / 50 / 600verdict, device threshold 398.3 / 83.3 / 10.50.0
anythreshold 2 + footprint on a distinct bot JA4100.010.2 (8.8-10.7)
anythreshold 2 + footprint on a copied Chrome JA4100.055.8 (54.4-56.0)
anyas above, legit users sign up with an email100.09.4 (8.8-10.4)
  • Without the verdict the hook cannot see this campaign at all.
  • With it, the device layer flags every signup after a device’s first, so recall is the share of bot signups landing on a device already used. Its false positives are the households’ second accounts.
  • A footprint catches the rest only when the campaign has a tell the legit traffic lacks. {anonymous, ja4} on a copied Chrome JA4 flags every anonymous Chrome user; when legit users sign up with an email the same footprint adds no false positives, and the 9.4% left is households.
  • What the replay cannot supply is how often a real solver farm reuses device IDs. That number decides real-world recall.

Sync cost of the signup hook, server-side per call, median of 5 runs of 500 calls (path and size order alternating run by run):

PathPrior eventsp50 msp95 ms
hook only0 / 10k / 100k0.204 / 0.139 / 0.2000.262 / 0.166 / 0.219
with verdict0 / 10k / 100k0.345 / 0.275 / 0.2860.481 / 0.300 / 0.324

The p50 stays at or under 0.345 ms up to 100k prior events but is not flat: 10k was the fastest size on both paths. An email signup through the local Auth API with the hooks enabled took a median p50 of 50.9 to 60.0 ms across four invocations of 5 batches of 20; the slowest hook p50 above is under 0.7% of the fastest. A benchmark on 2026-11-13 (load average 3.0-3.6) measured more at 0 prior events at every count cap: 0.237-0.241 ms hook-only and 0.396-0.401 ms with a verdict, under 0.8% of the same signup. The cause was not investigated; the hook had gained a signups-only filter on its counts in between.

The kit’s source is not linked; the author is the guarantor of the rows marked tested.

ClaimHow it was checkedStatus
The before-user-created hook runs outside the signup transaction; a deny returned (not raised) keeps the hook’s own event rowsignup.go L180-L188 and hooks.go L35-L50; local e2e: 403 to the client, no auth.users row, the deny event presenttested locally
options.data reaches the hook as user_metadatalocal e2e with a verdict minted by the Worker’s signer; two hosted projects with plain test data (nested object, array, boolean)7tested
Anonymous sign-ins reach the hook with no app_metadata.providerlocal e2e; on two hosted projects7 an anonymous sign-in with data fired the hook with is_anonymous true (provider not read)tested locally; hosted: the hook fires
abuse.score() matches forminator’s scoring.ts1,000 seeded cases generated by forminator’s own function at the revision current on the run date; a planted change to the 2.0x cap failed cases 11, 67, 81 and 107tested
The SQL footprint matcher matches footprint.ts600 cases from forminator’s own functions; a planted pivot-floor change failed cases 62, 104, 110 and 112tested
A ban through auth.users.banned_until is honouredlocal e2e: refresh 400, password sign-in user_bannedtested locally
A quarantined user’s write is refused at once while the old token is still validlocal e2e through the Data API: 403tested locally
The password-verification hook receives the client IP, and a reject reaches the client with its messagelocal e2e through the password granttested locally; hosted needs Teams or Enterprise
Hosted CAPTCHA discards the ephemeral IDcaptcha.go L18-L22code read
GoTrue copies signup options.data into auth.users and auth.identities; a BEFORE trigger on each removes the verdictlocal e2e: after a signup with a verdict, neither row holds it and the hook still saw ittested locally
The signup’s first access token is built before the stored row is read back, so it still carries options.data; the custom-access-token hook removes the verdict from itlocal e2e: the decoded signup JWT had the verdict in user_metadata until the token hook dropped ittested locally
GoTrue’s hook statement timeout does not bound the before-user-created hook, so a lock on the kit’s table would stall signups without the hook’s own lock_timeouthookspgfunc.go L89-L114 (set local on a connection outside a transaction); local e2e with lock_timeout removed: a signup under the lock ran past 5 s, with it the signup returned 200tested locally
A send hook that answers 200 with an error body gives the client the guard’s status and message; a planted 400 reply gave the client a 500local e2e through GoTrue: quarantined user’s SMS refused with 429, nothing deliveredtested locally
A banned user’s password-recovery request still reaches the send-email hooklocal e2e: GoTrue called the hook, the guard refused with 429tested locally
A verdict minted by the reference Worker verifies in the hooklocal e2e with Turnstile’s response stubbedtested locally
On a hosted project with forwarding off, a client-supplied X-Forwarded-For is the hook’s ip_address (publishable and secret key); with it on, only the secret key’s Sb-Forwarded-For set it and a publishable-key X-Forwarded-For was ignoredtwo runs on throwaway projects7; the publishable-key leg with forwarding on repeated through the kit on a hosted project, two runs (both headers spoofed, neither reached the hook)tested; X-Forwarded-For with forwarding on not sent with the secret, legacy anon or legacy service_role key
A secret-key signup skips Auth’s CAPTCHA (legacy service_role too; publishable and legacy anon get captcha_failed)two runs on throwaway projects7tested
An HTTP hook’s 200 with http_code 403 or 429 reaches the client with that status; a 400 reply becomes 500 unexpected_failuretwo runs on throwaway projects7tested
The JA4 in Supabase’s edge logs follows the client that called the Worker, not the Worker; the hook payload carries noneone hosted run: the Worker’s forwards called from Bun logged Bun’s JA4, the one called from curl logged curl’s, and both matched those clients’ direct requeststested once
  • Caching with Cloudflare Workers - KV’s 25 MB value limit and its eventual consistency, the two properties the serialised model artifact and the hot-reloaded config sit under.
  • Locking down Supabase - the Auth levers the Supabase port builds on, measured: the before-user-created hook, CAPTCHA and Auth rate limits, and why a custom domain gates nothing.
  • pg_net on Supabase under load - the delivery behaviour behind the email-classifier bridge’s retry design.
  1. Cloudflare, “Service bindings,” Cloudflare Docs. https://developers.cloudflare.com/workers/runtime-apis/bindings/service-bindings/ ↩

  2. Cloudflare, “Workers RPC,” Cloudflare Docs. https://developers.cloudflare.com/workers/runtime-apis/rpc/ ↩

  3. Supabase, “Custom Domains,” Supabase Docs. https://supabase.com/docs/guides/platform/custom-domains ↩

  4. Cloudflare, “Ephemeral IDs,” Cloudflare Turnstile Docs. https://developers.cloudflare.com/turnstile/additional-configuration/ephemeral-id/ ↩

  5. Supabase, “Before User Created Hook,” Supabase Docs. https://supabase.com/docs/guides/auth/auth-hooks/before-user-created-hook ↩

  6. Supabase, “Rate limits,” Supabase Docs. https://supabase.com/docs/guides/auth/rate-limits ↩

  7. supabase-lab, “Hook-gated-signup experiment,” supabase-lab runlog, HG01 (2026-11-12, two runs; one region, one vantage, IPv4). https://github.com/erfianugrah/supabase-lab/blob/ed62747/experiments/hook-gated-signup/RUNLOG.md ↩ ↩2 ↩3 ↩4 ↩5 ↩6

  8. Supabase, “Custom Access Token Hook,” Supabase Docs. https://supabase.com/docs/guides/auth/auth-hooks/custom-access-token-hook ↩

  9. Supabase, “Password Verification Hook,” Supabase Docs. https://supabase.com/docs/guides/auth/auth-hooks/password-verification-hook ↩

  10. Supabase, “Send SMS Hook,” Supabase Docs. https://supabase.com/docs/guides/auth/auth-hooks/send-sms-hook ↩