Cloudfare adex worker in out link direct redirect code

export default { async fetch(request, env) { const ip = request.headers.get("cf-connecting-ip") || "0.0.0.0"; const ua = (request.headers.get("user-agent") || "").toLowerCase(); const u = new URL(request.url); const newLink = u.searchParams.get("url"); const FALLBACK_URL = "https://kasworld-aero.blogspot.com"; /* -------- BOT FILTER -------- */ const badBots = ["curl", "wget", "spider", "crawler"]; if (badBots.some(b => ua.includes(b))) { return new Response("Blocked", { status: 403 }); } /* -------- RATE LIMIT (SILENT) -------- */ const rateKey = "rate:" + ip; let rate = await env.LINKS_DB.get(rateKey, { type: "json" }) || { count: 0, time: Date.now() }; let abuse = false; if (Date.now() - rate.time < 60000) { rate.count++; if (rate.count > 30) abuse = true; } else { rate = { count: 1, time: Date.now() }; } await env.LINKS_DB.put(rateKey, JSON.stringify(rate), { expirationTtl: 120 }); /* -------- LOAD DB -------- */ let db = await env.LINKS_DB.get("links", { type: "json" }) || []; /* -------- SELECT TARGET FOR WEIGHT -------- */ const targetUrl = abuse ? FALLBACK_URL : newLink || FALLBACK_URL; /* -------- WEIGHT ADD -------- */ let found = db.find(i => i.url === targetUrl); if (found) { found.weight += 1; } else { db.push({ url: targetUrl, weight: 1 }); } /* -------- WEIGHTED POOL -------- */ let pool = []; db.forEach(i => { for (let j = 0; j < i.weight; j++) pool.push(i.url); }); if (!pool.length) { await env.LINKS_DB.put("links", JSON.stringify(db)); return Response.redirect(FALLBACK_URL, 302); } /* -------- RANDOM PICK -------- */ const selected = pool[Math.floor(Math.random() * pool.length)]; /* -------- DECREASE WEIGHT -------- */ for (let i = 0; i < db.length; i++) { if (db[i].url === selected) { db[i].weight--; if (db[i].weight <= 0) db.splice(i, 1); break; } } await env.LINKS_DB.put("links", JSON.stringify(db)); return Response.redirect(selected, 302); } };