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
ScoringDecisionaudit 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.
Architecture overview
Section titled “Architecture overview”| Component | Role | Tech |
|---|---|---|
| Form Worker | Submission intake, multi-layer fraud detection, risk scoring | Hono on Workers, D1, KV |
| ML Worker | Email fraud classification, feature extraction, model inference | Hono on Workers, D1, 3x KV, Containers |
| Service Binding | Worker-to-Worker RPC (zero overhead, same-thread execution) | WorkerEntrypoint from cloudflare:workers |
| Turnstile | CAPTCHA validation, ephemeral device IDs (Enterprise) | Cloudflare Turnstile |
| Bot Management | JA4 fingerprints, bot scores, JS (JavaScript) detection (Enterprise) | Cloudflare Bot Management |
Detection layers
Section titled “Detection layers”The fraud pipeline runs in four phases. Each layer is independent - failure in one doesn’t block the others.
Layer 0: blacklist fast path
Section titled “Layer 0: blacklist fast path”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 firstasync 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 };}Layer 1: email fraud via ML (RPC)
Section titled “Layer 1: email fraud via ML (RPC)”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 bindingasync 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 }}Layer 2: ephemeral ID behavioral signals
Section titled “Layer 2: ephemeral ID behavioral signals”Collects three signals from D1 using Turnstile’s ephemeral device ID (Enterprise) to detect volume abuse:
| Signal | Query | Detection |
|---|---|---|
| Submission count | Count submissions by ephemeral ID in 24h | Form stuffing from same device |
| Validation frequency | Count Turnstile validations by ephemeral ID in 1h | Rapid-fire CAPTCHA solving |
| IP diversity | Count distinct IPs per ephemeral ID in 24h | VPN/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 }}Layer 3: JA4 TLS fingerprint analysis
Section titled “Layer 3: JA4 TLS fingerprint analysis”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-layer | Scope | Window | Threshold | Catches |
|---|---|---|---|---|
| 4a: IP Clustering | Same JA4 + same IP/subnet | 1 hour | 2+ ephemeral IDs | Bot farm on single network |
| 4b: Rapid Global | Same JA4, any IP | 5 min | 3+ ephemeral IDs | VPN-hopping automation |
| 4c: Extended Global | Same JA4, any IP | 1 hour | 5+ ephemeral IDs | Slow 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;}Risk scoring
Section titled “Risk scoring”All signals feed into a 10-component weighted score. The architecture ensures every decision is auditable - the full breakdown is stored alongside each submission.
Score components and weights
Section titled “Score components and weights”| Component | Weight | Source | What it measures |
|---|---|---|---|
| Token Replay | 0.28 | Turnstile | Reused CAPTCHA token (binary: 0 or 100) |
| Email Fraud | 0.14 | ML Worker RPC | ML-classified email fraud probability |
| Ephemeral ID | 0.15 | D1 query | Submission volume from same device |
| Validation Frequency | 0.10 | D1 query | CAPTCHA solve rate from same device |
| IP Diversity | 0.07 | D1 query | IP rotation from same device |
| JA4 Session Hopping | 0.06 | D1 query + Bot Mgmt | TLS fingerprint clustering |
| IP Rate Limit | 0.07 | D1 query | Browser-switching OR email diversity from same IP |
| Header Fingerprint | 0.07 | Request headers | Header pattern reuse across ephemeral IDs |
| TLS Anomaly | 0.04 | D1 + Bot Mgmt | Fingerprint baseline deviation |
| Latency Mismatch | 0.02 | Request timing | Geo 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 };}Scoring pipeline
Section titled “Scoring pipeline”Weight redistribution
Section titled “Weight redistribution”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 signalsconst normalizationFactor = 1.0 / (1.0 - inactiveWeight);
for (const component of activeComponents) { component.contribution = component.score * component.weight * normalizationFactor;}Corroboration bonus
Section titled “Corroboration bonus”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},Deterministic block floors
Section titled “Deterministic block floors”Certain triggers immediately floor the score at the block threshold, regardless of the weighted calculation. Each has qualification requirements to prevent false positives:
| Trigger | Qualification |
|---|---|
token_replay | Always qualifies (fail-secure) |
turnstile_failed | Always qualifies (fail-secure) |
email_fraud | Self-sufficient (ML confidence) |
ephemeral_id_fraud | Requires elevated ephemeral ID score AND validation frequency |
ja4_session_hopping | Requires raw score at least 140 AND IP rate limit score at least 25 |
validation_frequency | Requires ephemeral ID score above threshold |
Dual scoring modes
Section titled “Dual scoring modes”| Mode | Behavior | Use case |
|---|---|---|
defensive | Deterministic triggers can override weighted score | Production default |
additive | Purely weighted, no overrides | A/B testing, tuning |
Decision audit trail
Section titled “Decision audit trail”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; };}Block trigger priority
Section titled “Block trigger priority”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.
| Priority | Condition | blockTrigger | detectionType |
|---|---|---|---|
| 1 | ML email decision = block | email_fraud | email_fraud_detection |
| 2 | Ephemeral submission count exceeds threshold | ephemeral_id_fraud | ephemeral_id_tracking |
| 3 | Validation count exceeds frequency threshold | validation_frequency | ephemeral_id_tracking |
| 4 | Validation burst (5+ validations, fewer than 2 submissions) | validation_frequency | ephemeral_id_tracking |
| 5 | Unique IP count exceeds IP diversity threshold | ip_diversity | ephemeral_id_tracking |
| 6 | JA4 clustering detected | ja4_session_hopping | ja4_fingerprinting |
| 7 | Fingerprint anomaly triggered | per-signal | fingerprint_anomaly |
IP rate limit is intentionally excluded as a block trigger (see note above).
Duplicate email handling
Section titled “Duplicate email handling”Duplicate email submissions use a tiered approach that distinguishes user error from automated probing:
| Attempt | Response | Blacklist | Rationale |
|---|---|---|---|
| 1st-2nd | 409 Conflict with friendly message | Low-confidence tracking entry (24h) | Likely user re-submission |
| 3rd+ | 429 Too Many Requests with wait time | High-confidence entry with progressive timeout | Automated 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.
Input validation and sanitisation
Section titled “Input validation and sanitisation”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
+1prefix), 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();}ML email classification
Section titled “ML email classification”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.
Feature vector
Section titled “Feature vector”Features span ten categories:
| Category | Examples | Count |
|---|---|---|
| Sequential | sequential_confidence, plus_risk | 2 |
| Local Part | local_length, digit_ratio, has_year_suffix, alpha_prefix_naturalness, digit_position_ratio | 5 |
| Identity | name_similarity_score, name_token_overlap, name_in_email | 3 |
| Geo | geo_language_mismatch, geo_timezone_mismatch, geo_anomaly_score | 3 |
| MX/Provider | mx_has_records, mx_record_count, mx_provider_* (8 one-hot), provider_is_free, provider_is_disposable | 12 |
| Domain/TLD | tld_risk_score, domain_reputation_score, entropy_score | 3 |
| Linguistic | pronounceability, vowel_ratio, max_consonant_cluster, repeated_char_ratio, syllable_estimate, impossible_cluster_count | 6 |
| Structure | has_word_boundaries, segment_count, avg_segment_length, segments_without_vowels_ratio | 4 |
| Statistical | unique_char_ratio, vowel_gap_ratio, max_digit_run, bigram_entropy | 4 |
| N-gram | ngram_bigram_score, ngram_trigram_score, ngram_overall_score, ngram_confidence, ngram_risk_score, ngram_is_natural | 6 |
ML middleware pipeline
Section titled “ML middleware pipeline”Detectors
Section titled “Detectors”The 48 features are produced by specialised detector modules. Each operates independently and returns structured results.
Sequential pattern detection
Section titled “Sequential pattern detection”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.
Dated pattern detection
Section titled “Dated pattern detection”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.
| Category | Year Age | Risk | Example |
|---|---|---|---|
future | negative (year > current) | 0.95 | user2027@ |
recent_timestamp | 0-2 | 0.90 | user2025@ |
underage | 3-12 | 0.70 | user2015@ |
plausible_birth_year | 13-65 | 0.20 | john1990@ |
elderly_birth_year | 66-100 | 0.40 | user1940@ |
ancient | >100 | 0.80 | user1900@ |
Linguistic feature extraction
Section titled “Linguistic feature extraction”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/wclassification (e.g.,yis 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.”
N-gram naturalness
Section titled “N-gram naturalness”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.
Benford’s Law analysis
Section titled “Benford’s Law analysis”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.
MX resolution
Section titled “MX resolution”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 viaAbortController(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 encodedmx_provider_*flags (8 providers: Google, Microsoft, iCloud, Yahoo, Zoho, Proton, self-hosted, other). Cache bounded to 10k entries with LRU (least recently used) eviction.
Production model configuration
Section titled “Production model configuration”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 atmaxRisk(0.85) and flagged if abovewarnZoneMin(0.6). Prevents overconfident predictions on novel patterns.
Risk heuristics override
Section titled “Risk heuristics override”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.
| Heuristic | Block Threshold | Warn Threshold | Score Offset |
|---|---|---|---|
| TLD (top-level domain) risk | 0.9+ | 0.8+ | +0.10 |
| Domain reputation | 0.95+ | 0.85+ | +0.08 |
| Sequential confidence | 0.98+ | 0.9+ | +0.05 |
| Digit ratio | 0.9+ | 0.8+ | +0.05 |
| Plus-addressing abuse | 0.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;}Random Forest inference at the edge
Section titled “Random Forest inference at the edge”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}Platt calibration
Section titled “Platt calibration”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.
Model fallback
Section titled “Model fallback”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.
Global fraud detection middleware
Section titled “Global fraud detection middleware”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 globallyapp.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});Service binding RPC pattern
Section titled “Service binding RPC pattern”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.
ML Worker: exposing the RPC entrypoint
Section titled “ML Worker: exposing the RPC entrypoint”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 };Form Worker: calling via service binding
Section titled “Form Worker: calling via service binding”Wrangler config:
{ "services": [ { "binding": "FRAUD_DETECTOR", "service": "markov-mail", "entrypoint": "FraudDetectionService", }, ],}Calling the service:
// env.FRAUD_DETECTOR is typed as the RPC interfaceconst 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.
Progressive timeout and blacklisting
Section titled “Progressive timeout and blacklisting”When a submission is blocked, the offending identifiers are blacklisted with escalating TTLs:
| Offense | Timeout | Cumulative |
|---|---|---|
| 1st | 1 hour | 1h |
| 2nd | 4 hours | 5h |
| 3rd | 8 hours | 13h |
| 4th | 12 hours | 25h |
| 5th+ | 24 hours | 49h+ |
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.
Blacklist lifecycle
Section titled “Blacklist lifecycle”Configuration
Section titled “Configuration”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):
{ "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.
Wrangler bindings reference
Section titled “Wrangler bindings reference”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", },}Database schema
Section titled “Database schema”Form Worker (5 tables)
Section titled “Form Worker (5 tables)”| Table | Purpose | Key columns |
|---|---|---|
submissions | Form data + 42 metadata fields | email, ephemeral_id, risk_score_breakdown, ja4, bot_score |
turnstile_validations | Every validation attempt | token_hash (UNIQUE), detection_type, risk_score_breakdown |
fraud_blacklist | Progressive mitigation cache | email, ephemeral_id, ja4, ip_address, expires_at, detection_confidence |
fraud_blocks | Pre-Turnstile forensic log | detection_type, fraud_signals_json |
fingerprint_baselines | TLS fingerprint anomaly baselines | ja4_bucket, asn_bucket, hit_count |
ML Worker (5 tables)
Section titled “ML Worker (5 tables)”| Table | Purpose |
|---|---|
validations | Every email validation with all signals and features (86 columns) |
training_samples | Auto-collected 48-feature vectors from live validations, with labels and source tracking |
training_metrics | Model training history: accuracy, precision, recall, F1, FPR (false positive rate), anomaly detection |
ab_test_metrics | Experiment tracking for model variants |
admin_metrics | Configuration 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.
Scheduled tasks
Section titled “Scheduled tasks”The ML Worker uses two cron triggers to run three background tasks:
| Cron Expression | Schedule | Task |
|---|---|---|
0 */6 * * * | Every 6 hours | Refresh disposable domain list from external GitHub sources (71k+ domains stored in KV) |
0 */6 * * * | Every 6 hours | Prune validation records older than 30 days from D1 (GDPR (General Data Protection Regulation) compliance) |
0 3 * * SUN | Sundays 3AM UTC | Automated 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.
Model training pipeline
Section titled “Model training pipeline”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.
Container-based retraining (production)
Section titled “Container-based retraining (production)”A weekly cron (Sundays 3AM UTC (Coordinated Universal Time)) triggers the TrainerContainer Durable Object, which runs a Bun-based Docker container. The container:
- Fetches the current training dataset from the Worker’s D1 database (auto-collected feature vectors from every
/validatecall) - Trains a new Random Forest using a TypeScript CART implementation with Gini impurity, random feature subsampling, and conflict-zone weighting
- Applies Platt calibration via Newton-Raphson optimisation on OOB predictions
- Runs guardrails (
recall >= 95%,FPR <= 5%,FNR <= 5%) - Uploads the validated model to KV (propagates globally within 60 seconds)
- Prunes training samples older than 14 days
If guardrails fail, the existing model remains active and a training failure event is logged.
Offline CLI pipeline (development)
Section titled “Offline CLI pipeline (development)”For initial training and major model changes, an offline Python/CLI toolchain produces the model artifact.
Training data
Section titled “Training data”| Source | Rows | Label |
|---|---|---|
| Enron email corpus (cleaned) | 172,806 | legit |
| Synthetic (legit filler) | 327,194 | legit |
| Synthetic (fraud) | 500,000 | fraud |
| Total | 1,000,000 | 50/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 toolchain
Section titled “CLI toolchain”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.tsTraining workflow
Section titled “Training workflow”Step 1: Feature export - Extract 48-feature vectors from the canonical dataset:
npm run cli features:export -- --input data/main.csv --output tmp/features.csvStep 2: Train - scikit-learn RandomForestClassifier with conflict-zone weighting:
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-splitKey training parameters:
- Conflict-zone weighting: Samples with
bigram_entropy > 3.0ANDdomain_reputation_score >= 0.6get 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
LogisticRegressionon OOB predictions to produce well-calibrated probabilities. Outputsinterceptandcoefstored 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).
Production model artifact
Section titled “Production model artifact”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.
A/B testing framework
Section titled “A/B testing framework”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.
Experiment configuration
Section titled “Experiment configuration”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[]; };}Traffic assignment
Section titled “Traffic assignment”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.
CLI management
Section titled “CLI management”npm run cli ab:create # Create and upload experiment config to KVnpm run cli ab:status # Check active experiment statusnpm run cli ab:analyze # Compare variant performance from D1 metricsnpm run cli ab:stop # End experiment and remove from KVAnalytics dashboard
Section titled “Analytics dashboard”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.
Design principles
Section titled “Design principles”| Principle | Implementation |
|---|---|
| Fail-open by default | Signal collection, ML scoring, blacklist writes - all return safe baselines on error |
| Fail-secure for definitives | Token replay and Turnstile validation block on error (assume reused/invalid) |
| Weight redistribution | Inactive signals don’t suppress the score - their weight shifts to active ones |
| Transparent decisions | Every score stores a full ScoringDecision audit trail with each adjustment step |
| Per-request tracing | A unique request ID generated at entry threads through all DB (database) writes for forensic correlation |
| Config-driven thresholds | All magic numbers live in a mergeable config with auto-normalisation for weights |
| Progressive mitigation | Escalating timeouts instead of permanent bans - reduces false positive impact |
| Single code path | RPC entrypoint constructs a synthetic HTTP request through the same Hono handler as direct API calls |
| Monitoring mode | Action override flag runs all detection and logs decisions without blocking - safe rollout for new rules |
Extending the system
Section titled “Extending the system”| Task | Steps |
|---|---|
| Add a detection layer | 1. 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 feature | 1. 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 thresholds | 1. 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 test | 1. 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 rule | 1. Add rule to risk-heuristics.json (threshold, decision, reason, offset) 2. Upload to KV 3. Rule takes effect within 60 seconds (no redeploy) |
| Safe rollout | 1. 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 |
From scoring to operations
Section titled “From scoring to operations”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.
Event-scoring vs actor-centric operations
Section titled “Event-scoring vs actor-centric operations”| Dimension | What a scoring-only system misses | Pattern that closes it |
|---|---|---|
| Campaign / actor footprints | It 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 classification | A 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 tier | One 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 tracking | If 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-repetition | Learning 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 = inbound | Blocking 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 signal | A 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.
What scoring-first already gets right
Section titled “What scoring-first already gets right”- 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
ScoringDecisionaudit trail and hot-reloadable config and heuristics.
On Supabase: the same layers in Postgres
Section titled “On Supabase: the same layers in Postgres”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-codesandhostnamefrom the response (captcha.goL18-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.
- The browser solves Turnstile and sends the token to the edge Worker.
- 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.
- The browser signs up with the verdict in
options.data, which reaches the before-user-created hook5 asuser_metadata. - 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.
- 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.
Which piece runs where
Section titled “Which piece runs where”| Workers system | On Supabase | Notes |
|---|---|---|
| D1 blacklist, progressive timeouts | abuse.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 layer | Device ID from the signed verdict | Signups, validations and IPs per device feed forminator’s ephemeral layer. |
scoring.ts | abuse.score() in SQL | Same inputs and outputs, number for number (see evidence). |
ip-rate-limiting.ts | Velocity counts in the hook | Recorded, never a block on their own. The two network counts stop at 200 per lookup by default (configurable), the others at 50. |
| markov-mail RPC | pg_net call to its /validate | Retried on 5xx, 429 and timeout, per pg_net under load. |
footprint.ts (unwired) | Footprint sweep every 5 minutes, retroactive on add, review queue | Full 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, 429 | Tiers allow < watch < quarantine < ban | The 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. |
| none | Password-verification hook9 | A 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. |
| none | abuse.send_guard for send hooks | The 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.
What the port does not decide
Section titled “What the port does not decide”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:
| Campaign | Bots at watch or above % | Bots at quarantine % | Legit flagged % |
|---|---|---|---|
| Residential proxies, anonymous | 0.0 | 0.0 | 0.0 |
| Three datacenter /24s, anonymous | 67.5 | 0.0 | 0.0 |
| Two throwaway domains, residential IPs | 86.7 | 0.0 | 0.0 |
| 40 addresses retried after failed or denied signups | 80.0 | 0.0 | 0.0 |
| Three datacenter /24s and two throwaway domains | 86.7 | 71.0 | 0.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.
Reading the numbers
Section titled “Reading the numbers”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 devices | Kit | Bots flagged % | Legit flagged % |
|---|---|---|---|
| 5 / 50 / 600 | hook only, no verdict | 0.0 / 0.0 / 0.0 | 0.0 |
| 5 / 50 / 600 | verdict, device threshold 2 | 99.2 / 91.7 / 37.0 | 10.2 (8.8-10.7) |
| 5 / 50 / 600 | verdict, device threshold 3 | 98.3 / 83.3 / 10.5 | 0.0 |
| any | threshold 2 + footprint on a distinct bot JA4 | 100.0 | 10.2 (8.8-10.7) |
| any | threshold 2 + footprint on a copied Chrome JA4 | 100.0 | 55.8 (54.4-56.0) |
| any | as above, legit users sign up with an email | 100.0 | 9.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):
| Path | Prior events | p50 ms | p95 ms |
|---|---|---|---|
| hook only | 0 / 10k / 100k | 0.204 / 0.139 / 0.200 | 0.262 / 0.166 / 0.219 |
| with verdict | 0 / 10k / 100k | 0.345 / 0.275 / 0.286 | 0.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.
Evidence
Section titled “Evidence”The kit’s source is not linked; the author is the guarantor of the rows marked tested.
| Claim | How it was checked | Status |
|---|---|---|
| The before-user-created hook runs outside the signup transaction; a deny returned (not raised) keeps the hook’s own event row | signup.go L180-L188 and hooks.go L35-L50; local e2e: 403 to the client, no auth.users row, the deny event present | tested locally |
options.data reaches the hook as user_metadata | local e2e with a verdict minted by the Worker’s signer; two hosted projects with plain test data (nested object, array, boolean)7 | tested |
Anonymous sign-ins reach the hook with no app_metadata.provider | local 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.ts | 1,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 107 | tested |
The SQL footprint matcher matches footprint.ts | 600 cases from forminator’s own functions; a planted pivot-floor change failed cases 62, 104, 110 and 112 | tested |
A ban through auth.users.banned_until is honoured | local e2e: refresh 400, password sign-in user_banned | tested locally |
| A quarantined user’s write is refused at once while the old token is still valid | local e2e through the Data API: 403 | tested locally |
The password-verification hook receives the client IP, and a reject reaches the client with its message | local e2e through the password grant | tested locally; hosted needs Teams or Enterprise |
| Hosted CAPTCHA discards the ephemeral ID | captcha.go L18-L22 | code read |
GoTrue copies signup options.data into auth.users and auth.identities; a BEFORE trigger on each removes the verdict | local e2e: after a signup with a verdict, neither row holds it and the hook still saw it | tested 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 it | local e2e: the decoded signup JWT had the verdict in user_metadata until the token hook dropped it | tested 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_timeout | hookspgfunc.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 200 | tested 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 500 | local e2e through GoTrue: quarantined user’s SMS refused with 429, nothing delivered | tested locally |
| A banned user’s password-recovery request still reaches the send-email hook | local e2e: GoTrue called the hook, the guard refused with 429 | tested locally |
| A verdict minted by the reference Worker verifies in the hook | local e2e with Turnstile’s response stubbed | tested 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 ignored | two 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 projects7 | tested |
An HTTP hook’s 200 with http_code 403 or 429 reaches the client with that status; a 400 reply becomes 500 unexpected_failure | two runs on throwaway projects7 | tested |
| The JA4 in Supabase’s edge logs follows the client that called the Worker, not the Worker; the hook payload carries none | one 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 requests | tested once |
Related docs
Section titled “Related docs”- 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.
References
Section titled “References”-
Cloudflare, “Service bindings,” Cloudflare Docs. https://developers.cloudflare.com/workers/runtime-apis/bindings/service-bindings/ ↩
-
Cloudflare, “Workers RPC,” Cloudflare Docs. https://developers.cloudflare.com/workers/runtime-apis/rpc/ ↩
-
Supabase, “Custom Domains,” Supabase Docs. https://supabase.com/docs/guides/platform/custom-domains ↩
-
Cloudflare, “Ephemeral IDs,” Cloudflare Turnstile Docs. https://developers.cloudflare.com/turnstile/additional-configuration/ephemeral-id/ ↩
-
Supabase, “Before User Created Hook,” Supabase Docs. https://supabase.com/docs/guides/auth/auth-hooks/before-user-created-hook ↩
-
Supabase, “Rate limits,” Supabase Docs. https://supabase.com/docs/guides/auth/rate-limits ↩
-
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
-
Supabase, “Custom Access Token Hook,” Supabase Docs. https://supabase.com/docs/guides/auth/auth-hooks/custom-access-token-hook ↩
-
Supabase, “Password Verification Hook,” Supabase Docs. https://supabase.com/docs/guides/auth/auth-hooks/password-verification-hook ↩
-
Supabase, “Send SMS Hook,” Supabase Docs. https://supabase.com/docs/guides/auth/auth-hooks/send-sms-hook ↩