A self-learning, AI-driven DNS-over-HTTPS resolver that runs at the edge. 40+ threat subsystems. A living brain. Zero dependencies.
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.
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.
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.
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.
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.
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.
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.
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 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) │ │ │ └─────────────────────────────────┘ │ └─────────────────────────────────────────────────────────────────────┘
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.
Adaptive user count estimation. Tracks real concurrent users per minute with noise-aware prediction. Drives threshold scaling.
Upper Confidence Bound algorithm selects upstream resolvers. Balances exploration vs. exploitation. Learns per-colo optimal choice.
Query sequence prediction. Learns domain co-occurrence patterns to pre-warm the cache before the next query arrives.
Online mean/variance computation without storing history. Anomaly scoring uses dual Welford on count + delta simultaneously.
Models upstream reliability over time. Shape and scale parameters updated per upstream to predict failure probability.
Reinforcement agent for upstream policy. Reward = fast clean response. Penalty = error, timeout, NX rate spike. Adapts routing dynamically.
7-day × 24-hour traffic pattern matrix. Learns when your traffic peaks. Used for anomaly baseline and predictive scaling.
Combines DGA, phishing, and bot priors into a unified threat posterior. Updates per observation using Bayes' rule.
Full brain serialized to KV + D1 every 30 minutes. Survives worker restarts, redeployments, and isolate rotations with zero learning loss.
Every subsystem runs on every request. Signals are aggregated into a Composite Threat Score (CTS) that drives automatic responses.
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
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=…"
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"
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
Full REST API for intelligence, configuration, brain management, and observability. All endpoints require auth token if DNS_TOKEN_SECRET is configured.
/ and /dns-query are identicalEvery 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.
Runs on Cloudflare Workers free tier for low traffic. Scales globally to every Cloudflare PoP automatically.
# 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
# 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"
437 KB of pure JavaScript. No npm. No build step. No external packages. Ships as a single ES Module.
This worker was designed, architected, and refined through hundreds of iterative sessions with two AI systems — pushing Cloudflare Workers to their absolute limit.
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.
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.
Built with curiosity. Hardened through iteration. Vibe coded with Claude (Anthropic) and Gemini (Google).