Cloudflare Workers · DNS-over-HTTPS · AI-Powered

DNS Worker

A self-learning, AI-driven DNS-over-HTTPS resolver that runs at the edge. 40+ threat subsystems. A living brain. Zero dependencies.

RFC 8484 DoH AI Brain v7 Edge Native 40+ Subsystems Self-Healing Zero Dependencies
40+
Threat Subsystems
19
D1 DB Tables
437KB
Single File
522
Functions

Everything in one Worker

From RFC-compliant DoH resolution to a multi-armed bandit upstream router — all running in a single Cloudflare Worker isolate, globally distributed at the edge.

🌐

DNS-over-HTTPS Core

Full RFC 8484 compliance. GET and POST. Stale-while-revalidate caching (5s–3600s). Negative caching. Multi-upstream racing up to 6 resolvers. Hedge requests. CNAME chain tracking. PTR loop protection. Optional response encryption and HMAC token auth.

🧠

Self-Learning AI Brain

Kalman filter · UCB bandit · Markov chain prediction · Welford online stats · Weibull survival model · Q-learning RL agent · Bayesian fusion · Softmax scoring. The brain persists across worker restarts and compounds intelligence over time.

🛡️

40+ Threat Subsystems

DGA detection, DNS tunnel entropy analysis, rebinding protection, homoglyph detection, answer drift monitoring, per-client behavioral profiling, reputation scoring, burst detection, cross-signal escalation, and more — all running on every request.

📊

Adaptive Routing

Three LB modes — HYPER_SONIC, BALANCED, FLOOD-GUARD — switched automatically by brain stress. UCB bandit learns per-upstream reward. Cloudflare colo-affinity locking. Circuit breaker per upstream with auto-recovery. NX penalty scoring.

💾

Budget-Aware Storage

KV + D1 with full daily budget accounting. Soft caps, hard limits, token bucket rate limiting. EOD drain. Bidirectional KV↔D1 healing. 100,000 D1 writes/day · 1,000 KV writes/day · 200,000 worker events/day — all tracked and protected.

🔧

Self-Healing

Emergency isolation mode. Memory pressure LRU eviction. Panic recovery with state preservation. D1 error backpressure with exponential backoff. Auto-declared incidents with resolution tracking. Health endpoint with 100+ live metrics.

Request pipeline

Every DNS request passes through a layered pipeline — from auth and rate limiting, through the full threat detection stack, into the AI routing brain, and out to the winning upstream resolver.

CLIENT
DoH GET/POST
AUTH
HMAC token
RATE LIMIT
CRL / PCB
THREAT SCAN
40+ signals
AI BRAIN
UCB routing
RACE ENGINE
Up to 6 DoH
SWR CACHE
KV + D1
RESPONSE
RFC 8484
CLIENT  (DoH GET / POST  application/dns-message)
    │
    ▼
┌─────────────────────────────────────────────────────────────────────┐
│                   CLOUDFLARE WORKER  (edge isolate)                  │
│                                                                     │
│  ┌──────────────┐    ┌─────────────────┐    ┌──────────────────┐   │
│  │ HMAC Auth    │───▶│  CRL Rate Limit  │───▶│  PCB Behavior  │   │
│  │ Token check  │    │  Per-IP flood   │    │  Client profile  │   │
│  └──────────────┘    └─────────────────┘    └────────┬─────────┘   │
│                                                       │             │
│  ┌────────────────────────────────────────────────────▼───────────┐ │
│  │                   THREAT DETECTION PIPELINE                   │ │
│  │                                                                 │ │
│  │  DGA→ENTROPY→HOMOGLYPH→REBIND→REP→DRIFT→QTA→XVAL→...  │ │
│  │                                                                 │ │
│  │  Composite Threat Score (CTS 0–100) ──▶ Block / Allow / Flag  │ │
│  └────────────────────────────────────────────────────┬───────────┘ │
│                                                        │             │
│  ┌─────────────────────────────────────────────────────▼──────────┐ │
│  │                     AI ROUTING BRAIN                          │ │
│  │                                                                 │ │
│  │  Kalman(users) · UCB(upstream) · Markov(predict) · RL(adapt)  │ │
│  │  Weibull(survival) · Welford(stats) · Seasonal(rhythm)        │ │
│  │  Anomaly(score) · Stress(0-1) ──▶ Mode selection              │ │
│  └─────────────────────────────────────────────────────┬──────────┘ │
│                                                         │            │
│  ┌──────────────────────────────────────────────────────▼─────────┐ │
│  │                MULTI-UPSTREAM RACE ENGINE                     │ │
│  │                                                                │ │
│  │   [DoH-1] ──┐                                                 │ │
│  │   [DoH-2] ──┼──▶ fastest response wins ──▶ validate ──▶ learn │ │
│  │   [DoH-3] ──┘        circuit breaker per upstream             │ │
│  └──────────────────────────────────────────────────────┬────────┘ │
│                                                          │           │
│  ┌─────────────────────────────────┐   ┌────────────────▼────────┐  │
│  │  KV Store  (brain + edge cache) │   │  SWR Cache (TTL 5–3600s) │  │
│  └──────────────┬──────────────────┘   └─────────────────────────┘  │
│                 │                                                     │
│  ┌──────────────▼──────────────────┐                                 │
│  │  D1 SQLite  (19 tables persist) │                                 │
│  └─────────────────────────────────┘                                 │
└─────────────────────────────────────────────────────────────────────┘

A living, learning system

The brain runs a continuous feedback loop on every request. Every resolved query is a training signal. Every anomaly sharpens the reflexes. Every upstream response is a reward or penalty.

Kalman Filter

Adaptive user count estimation. Tracks real concurrent users per minute with noise-aware prediction. Drives threshold scaling.

UCB Bandit

Upper Confidence Bound algorithm selects upstream resolvers. Balances exploration vs. exploitation. Learns per-colo optimal choice.

Markov Chain

Query sequence prediction. Learns domain co-occurrence patterns to pre-warm the cache before the next query arrives.

Welford Stats

Online mean/variance computation without storing history. Anomaly scoring uses dual Welford on count + delta simultaneously.

Weibull Survival

Models upstream reliability over time. Shape and scale parameters updated per upstream to predict failure probability.

Q-Learning RL

Reinforcement agent for upstream policy. Reward = fast clean response. Penalty = error, timeout, NX rate spike. Adapts routing dynamically.

Seasonal Rhythm

7-day × 24-hour traffic pattern matrix. Learns when your traffic peaks. Used for anomaly baseline and predictive scaling.

Bayesian Fusion

Combines DGA, phishing, and bot priors into a unified threat posterior. Updates per observation using Bayes' rule.

Brain Continuity

Full brain serialized to KV + D1 every 30 minutes. Survives worker restarts, redeployments, and isolate rotations with zero learning loss.

Brain Stress Modes

ULTRA_INSTINCT_ZEN
stress < 0.30
Relaxed thresholds · full learning · maximum cache warming · low confidence threshold (0.70)
COGNITIVE_BALANCE
0.30 – 0.60
Balanced defense / performance · standard scoring · confidence threshold 0.85
NEURAL_SHIELD_ACTIVE
0.60 – 0.85
Tightened scoring · reduced logging · elevated confidence threshold · contracted logic state
SENTINEL_OVERDRIVE
stress > 0.85
Aggressive blocking · auto-block rate max · confidence threshold 0.95 · engaging all defenses
EMERGENCY_ISOLATION
triggered
Maximum lockdown · shed all non-critical load · preserved state · sustained attack or resource exhaustion

How It Learns Over Time

DAY 1
Starts cold. Equal-weight upstream selection. No reputation data. Seasonal model is empty. Brain begins observing every query.
WEEK 1
UCB bandit has learned which upstream is fastest per Cloudflare colo. Seasonal model has first rhythm estimates. Common domains identified and promoted to allow-list. DGA fast-path growing.
MONTH 1
Reputation scores meaningful for thousands of domains. Markov chain predicting next queries with real accuracy. Kalman filter tracking user count accurately. Weibull models calibrated per upstream. Behavioral profiles built for regular clients.
ONGOING
Intelligence compounds. Every request sharpens reflexes. Swarm shares anonymized intel across isolates. Brain survives restarts with full continuity. The longer it runs, the smarter it gets.

40+ Threat Subsystems

Every subsystem runs on every request. Signals are aggregated into a Composite Threat Score (CTS) that drives automatic responses.

DGA
Domain Generation Algorithm
Entropy + n-gram ML scoring against legitimate TLD distributions
PCB
Per-Client Behavior
Burst, flood, and timing fingerprinting per IP
CRL
Client Rate Limiting
Adaptive per-IP flood control with soft and hard thresholds
REP
Reputation Engine
Per-domain score with EWMA decay — good and bad history tracked
QTA
Query Type Abuse
ANY/TXT/NULL record tunnel detection
CREP
Client Reputation
Cross-request behavioral scoring for persistent client profiling
ENTROPY
DNS Tunnel Entropy
Payload randomness detection — catches data exfiltration via DNS
REBIND
DNS Rebinding
Detects private/loopback IPs in answers — blocks SSRF vectors
HOMOGLYPH
Unicode Lookalikes
IDN abuse — confusable character and script-mix detection
DRIFT
Answer Drift
Detects BGP hijack and cache poisoning via cross-upstream comparison
PERS
Persistent Hijack
Cross-request consistency checking for sustained hijack detection
CAP
Capability Probing
Detects resolver enumeration and capability fingerprinting attacks
HEATMAP
Domain Frequency
24-hour rolling heatmap drives proactive cache warming
XVAL
Cross-Validator
Upstream answer disagreement detection — flags anomalous responses
FINGERPRINT
Client Fingerprint
Behavioral classification — distinguishes humans, bots, and scrapers
GEO
Geo Affinity
Cloudflare PoP-aware routing — learns best upstream per colo
RPSF
RPS Forecasting
Velocity + trend prediction — alerts before traffic spikes land
CSC
Cross-Signal Escalation
Correlates multiple weak signals into high-confidence threat escalation
CQTA
Compound QTA
Multi-signal query type abuse scoring — catches slow tunnel attacks
DCQ
Duplicate Consecutive
Detects abusive duplicate query patterns from single clients
PRSD
Pattern Subdomain
Detects DGA-style subdomain generation under legitimate parents
URDM
Upstream Response Dist.
Monitors upstream response distribution for statistical anomalies

Composite Threat Score (CTS)

NOMINAL
0–24
Pass through · observe
ELEVATED
25–49
Log · monitor · flag for review
HIGH
50–74
Apply rate restrictions · throttle
CRITICAL
75–89
Hard block · alert · reputation hit
EMERGENCY
90–100
Maximum isolation · auto-block IP

Append to the path. That's it.

Append your token or master key as the last segment of the URL. Both work identically — same position, same format, same everything.

https://your-worker.workers.dev/dns-query/<token-or-masterkey>
https://your-worker.workers.dev/admin/<token-or-masterkey>
https://your-worker.workers.dev/api/intelligence/<token-or-masterkey>
https://your-worker.workers.dev/<token-or-masterkey>         ← same as /dns-query

Generated Token — normal use

Set DNS_TOKEN_SECRET. Generate time-limited tokens via the /admin dashboard UI or the API. Tokens are HMAC-SHA256 signed, valid ±2 hours, and path-scoped.

# Generate a token (using master key to auth)
curl "https://…/api/token/<masterkey>?path=/admin"
# → { "fullPath": "/admin/67f1a2b3<64-hex>" }

# Then use it exactly like a master key
curl "https://…/admin/67f1a2b3<64-hex-chars>"
curl "https://…/dns-query/67f1a2b3<64-hex-chars>?dns=…"
TOKEN FORMAT — 72 HEX CHARS
TIMESTAMP
8 chars
hex epoch
HMAC-SHA256 SIGNATURE
64 chars
signs: timestamp + path

Master Key — fallback / emergency

Set DNS_MASTER_KEY to any string you choose. Use it the same way as a generated token — just append to the path. Never expires. Reach for it when a generated token has expired or isn't working.

wrangler secret put DNS_MASTER_KEY
# → enter: mysecretmasterkey

# Identical usage to a generated token
curl "https://…/admin/mysecretmasterkey"
curl "https://…/dns-query/mysecretmasterkey?dns=…"
curl "https://…/api/intelligence/mysecretmasterkey"
⚠️ Never expires — keep it secret. Rotate by updating the Wrangler secret and redeploying.

Generate a token locally (Node.js)

async function generateToken(secret, path) {
  const ts = (Date.now()/1000|0).toString(16).padStart(8, '0');
  const key = await crypto.subtle.importKey(
    'raw', new TextEncoder().encode(secret),
    { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']
  );
  const sig = await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(ts + path));
  const token = ts + [...new Uint8Array(sig)].map(b => b.toString(16).padStart(2, '0')).join('');
  console.log(`https://your-worker.workers.dev${path}/${token}`);
}

generateToken('your-DNS_TOKEN_SECRET', '/admin');
generateToken('your-DNS_TOKEN_SECRET', '/dns-query');
generateToken('your-DNS_TOKEN_SECRET', '/api');  // covers all /api/* routes
No secrets set? The worker runs in open-access mode — no auth required on any endpoint.

70+ endpoints

Full REST API for intelligence, configuration, brain management, and observability. All endpoints require auth token if DNS_TOKEN_SECRET is configured.

Core DNS

GET/POST//<token>DoH resolver — / and /dns-query are identical
GET/POST/dns-query/<token>DoH resolver — RFC 8484 GET & POST
GET/admin/<token>Health dashboard — JSON or HTML with 100+ live metrics
GET/test/<token>Test query against all upstreams simultaneously

AI & Brain

GET/api/aiFull AI state snapshot
GET/api/ai/exportExport brain state as JSON
POST/api/ai/importImport brain state (migration / backup restore)
POST/api/ai/prunePrune expired D1 noise records
GET/api/ai-learningAI learning event log (90 days)

Threat Intelligence

GET/api/intelligenceFull threat intelligence snapshot
GET/api/reputationDomain reputation table
GET/api/dga/testScore a domain through the DGA classifier
GET/api/fingerprintsClient behavioral fingerprint table
GET/api/securitySecurity event summary across all subsystems
GET/POST/api/intel-exportCross-worker intelligence synchronization

Traffic & Heatmap

GET/api/heatmapFull 24-hour domain frequency heatmap
GET/api/heatmap-topTop domains by request frequency
GET/api/hot-domainsCurrently trending / hot domains
GET/api/usersUser count estimates + Kalman AI tracking state
GET/api/swarmSwarm intelligence snapshot across isolates

System & Config

GET/api/configActive runtime configuration
GET/POST/api/blocklistView or add blocked domains
GET/POST/api/whitelistView or add whitelisted domains
POST/api/reset-cbManually reset upstream circuit breaker
GET/api/incidentCurrent and recent incidents with timeline
GET/api/d1-usageD1 budget usage log (90 days)
GET/api/slaSLA metrics and breach history

Budget-aware persistence

Every write is accounted for. Soft caps trigger graceful degradation. Hard limits prevent billing surprises. The system always knows exactly how many writes it has left today.

D1 Writes / Day
100K
Soft cap → hard limit · EOD drain · storage pressure tracking
KV Writes / Day
1,000
Token bucket rate limiting · priority writes preserved
Worker Events / Day
200K
Hard cap · soft cap · graceful shed on approach

D1 Tables (19)

d1_generic
KV fallback + brain state
d1_rep
Domain reputation
d1_crep
Client reputation
d1_geo
Colo affinity data
d1_heatmap
Domain frequency
d1_common
Common allow-list
d1_block
Blocked domains
d1_whitelist
Whitelisted domains
d1_ans
Answer novelty
d1_pers
Upstream personalities
d1_profile
Client profiles
d1_autoblock
Auto-block state
d1_crl
Rate limit state
d1_drift
Answer drift history
d1_stats
Aggregate stats
d1_budget_ai
AI budget accounting
d1_usage_log
D1 usage log
d1_usage_log
D1 usage log
ai_learning_log
AI learning events

Ship it to the edge

Runs on Cloudflare Workers free tier for low traffic. Scales globally to every Cloudflare PoP automatically.

Quick Deploy

# 1. Create KV namespace
wrangler kv:namespace create DNS_KV

# 2. Create D1 database
wrangler d1 create dns-worker-db

# 3. Run schema migrations
wrangler d1 execute dns-worker-db \
  --file=./schema.sql

# 4. Deploy
wrangler deploy

# 5. Set secrets
wrangler secret put DNS_TOKEN_SECRET
wrangler secret put DNS_CACHE_SECRET

Demo — Live Requests

# DNS queries return binary wire format.
# Use --output - to pipe, or /test for JSON.

# Resolve example.com A — binary output
curl --output - \
  "https://x.xoox.workers.dev/dns-query/abir\
?dns=AAABAAABAAAAAAAAB2V4YW1wbGUDY29tAAABAAE"

# Inspect raw bytes
curl --output - "https://x.xoox.workers.dev/dns-query/abir\
?dns=AAABAAABAAAAAAAAB2V4YW1wbGUDY29tAAABAAE" | xxd | head
# 00000000: 0000 8180 0001 0001 ...  .............exa
# 00000020: 0100 0100 000e 1000 045d b8d8 22   ].."

# /test — human-readable JSON
curl "https://x.xoox.workers.dev/test/abir\
?dns=cloudflare.com&type=A"
# → { "allOk": true, "upstreams": [...scores, latency] }

# Health dashboard
curl "https://x.xoox.workers.dev/admin/abir"

# AI brain state
curl "https://x.xoox.workers.dev/api/ai/abir"

Environment Variables

Binding / VariableTypePurpose
DNS_KVKV NamespaceBrain state + edge cache (required)
D1_DBD1 DatabasePersistent storage — 19 tables (required)
DNS_TOKEN_SECRETSecretHMAC auth for API endpoints
DNS_CACHE_SECRETSecretAES encryption key for cached responses
DNS_WORKER_NAMEVariableIsolate identity for swarm (default: "default")
EXPECTED_USERSVariableUser count hint — "AI" for auto-detect

One file. No dependencies.

437 KB of pure JavaScript. No npm. No build step. No external packages. Ships as a single ES Module.

LayerTechnology
RuntimeCloudflare Workers — V8 isolates, global edge
ProtocolDNS-over-HTTPS · RFC 8484
Edge CacheCloudflare KV (key-value)
DatabaseCloudflare D1 (SQLite at the edge)
AI / MLKalman · UCB · Markov · Weibull · Q-RL · Welford · Bayes
LanguageJavaScript — ES Modules, no transpilation
DependenciesZero — single self-contained file
File size437 KB · 522 functions · 3 minified lines
Vibe coded withClaude (Anthropic) + Gemini (Google)

Vibe coded with AI

This worker was designed, architected, and refined through hundreds of iterative sessions with two AI systems — pushing Cloudflare Workers to their absolute limit.

✦ Claude by Anthropic
×
✦ Gemini by Google

Architecture decisions, algorithm selection, subsystem design, bug hunting, and optimization — all done through iterative AI-assisted sessions. The code reflects hundreds of refinement cycles guided by prompts, pushed back on by both models, and synthesized into a coherent system.

What is this, really?

"An experiment in pushing Cloudflare Workers to their absolute limit — packing a full AI-driven threat intelligence platform into a single JavaScript file with zero npm dependencies."

It started as a simple DNS-over-HTTPS proxy. A clean implementation of RFC 8484 that ran upstream queries in parallel and cached the results. That was version 1.

Then came the question: what if it learned which upstream was faster? That was the UCB bandit. Then: what if it could detect malicious domains? That was DGA. Then: what if it could predict the next query? That was Markov. Then: what if it survived restarts? That was brain continuity.

Hundreds of AI-assisted iterations later, it has a Kalman filter estimating concurrent users in real time, a Weibull survival model predicting upstream failure probability, a Q-learning agent adapting routing policy on the fly, and 40+ threat detection subsystems scoring every request before it ever touches an upstream resolver.

Every subsystem abbreviation — DGA, PCB, CRL, CREP, RPSF, URDM, CSC, CQTA — represents a real detection or optimization algorithm, running on every single DNS query, under a millisecond, at the edge closest to your users.

"Intelligence compounds. The longer it runs, the sharper its reflexes."

Built with curiosity. Hardened through iteration. Vibe coded with Claude (Anthropic) and Gemini (Google).