Better to post it here we can t formally

Better to post it here: we can't formally/directly support folks via DM, but others may be able to help 🙂
104 Replies
lokiwind
lokiwind13mo ago
export interface Env {
DB: D1Database;
}

export default {
async fetch(request: Request, env: Env) {
// Check if the custom-verified-bot header is set to "true"
if (request.headers.get("custom-verified-bot") === "true") {
// If it is, return the result of calling fetch(request)
return fetch(request);
}

// Get the IP address from the request headers
const ip = request.headers.get('CF-Connecting-IP');

// Check if there are at least 3 rows with the same time value for this IP address
let results;
try {
const stmt = env.DB.prepare("SELECT time FROM (SELECT time, count(*) as cnt FROM accesslog WHERE ip = ?1 GROUP BY time) WHERE cnt >= 3").bind(ip);
results = (await stmt.all()).results;
} catch (error: any) {
console.error(`Error while checking rows: ${error}`);
return Response.json({ message: `Error while checking rows: ${error.stack}` });
}

// If there are at least 3 rows, add the IP address to the Cloudflare rule and delete rows from the database
if (results && results.length > 0) {
try {
const options = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Auth-Email': 'lokiwind26@gmail.com',
'X-Auth-Key': 'XXX'
},
body: JSON.stringify({
"configuration": {"target": "ip", "value": ip},
"mode": "challenge",
"notes": "Rate limit block."
})
};
await fetch('https://api.cloudflare.com/client/v4/accounts/8aXXXX/firewall/access_rules/rules', options);
} catch (error: any) {
console.error(`Error while adding IP address to Cloudflare rule: ${error}`);
return Response.json({ message: `Error while adding IP address to Cloudflare rule: ${error.stack}` });
}

try {
const deleteStmt = env.DB.prepare('DELETE FROM accesslog WHERE ip = ?1').bind(ip);
await deleteStmt.run();
} catch (error: any) {
console.error(`Error while deleting rows from database: ${error}`);
return Response.json({ message: `Error while deleting rows from database: ${error.stack}` });
}

return Response.json({ message: 'Rows deleted' });
} else {
// If there are fewer than 3 rows, insert a new row into the accesslog table with the current time and path
const now = new Date();
const time = `${now.getHours()}:${now.getMinutes()}:${now.getSeconds()}`;
let { pathname } = new URL(request.url);
pathname = pathname || '/';
if (
!request.url.endsWith('/favicon.ico') &&
!request.url.endsWith('/style.css') &&
!request.url.endsWith('/script.js') &&
pathname !== '/dzziqEPxnCcWmU0R/bkIiX3dl0JVgB7mw' &&
pathname !== '/service_worker.js' &&
pathname !== '/robots.txt'
) {
try {
await env.DB.prepare(
"INSERT INTO accesslog (ip, time, path) VALUES (?1, ?2, ?3)"
).bind(ip, time, pathname).run();
} catch (error: any) {
console.error(`Error while inserting row into accesslog table: ${error}`);
return Response.json({ message: `Error while inserting row into accesslog table: ${error.stack}` });
}
}

return fetch(request);
}
},
};
export interface Env {
DB: D1Database;
}

export default {
async fetch(request: Request, env: Env) {
// Check if the custom-verified-bot header is set to "true"
if (request.headers.get("custom-verified-bot") === "true") {
// If it is, return the result of calling fetch(request)
return fetch(request);
}

// Get the IP address from the request headers
const ip = request.headers.get('CF-Connecting-IP');

// Check if there are at least 3 rows with the same time value for this IP address
let results;
try {
const stmt = env.DB.prepare("SELECT time FROM (SELECT time, count(*) as cnt FROM accesslog WHERE ip = ?1 GROUP BY time) WHERE cnt >= 3").bind(ip);
results = (await stmt.all()).results;
} catch (error: any) {
console.error(`Error while checking rows: ${error}`);
return Response.json({ message: `Error while checking rows: ${error.stack}` });
}

// If there are at least 3 rows, add the IP address to the Cloudflare rule and delete rows from the database
if (results && results.length > 0) {
try {
const options = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Auth-Email': 'lokiwind26@gmail.com',
'X-Auth-Key': 'XXX'
},
body: JSON.stringify({
"configuration": {"target": "ip", "value": ip},
"mode": "challenge",
"notes": "Rate limit block."
})
};
await fetch('https://api.cloudflare.com/client/v4/accounts/8aXXXX/firewall/access_rules/rules', options);
} catch (error: any) {
console.error(`Error while adding IP address to Cloudflare rule: ${error}`);
return Response.json({ message: `Error while adding IP address to Cloudflare rule: ${error.stack}` });
}

try {
const deleteStmt = env.DB.prepare('DELETE FROM accesslog WHERE ip = ?1').bind(ip);
await deleteStmt.run();
} catch (error: any) {
console.error(`Error while deleting rows from database: ${error}`);
return Response.json({ message: `Error while deleting rows from database: ${error.stack}` });
}

return Response.json({ message: 'Rows deleted' });
} else {
// If there are fewer than 3 rows, insert a new row into the accesslog table with the current time and path
const now = new Date();
const time = `${now.getHours()}:${now.getMinutes()}:${now.getSeconds()}`;
let { pathname } = new URL(request.url);
pathname = pathname || '/';
if (
!request.url.endsWith('/favicon.ico') &&
!request.url.endsWith('/style.css') &&
!request.url.endsWith('/script.js') &&
pathname !== '/dzziqEPxnCcWmU0R/bkIiX3dl0JVgB7mw' &&
pathname !== '/service_worker.js' &&
pathname !== '/robots.txt'
) {
try {
await env.DB.prepare(
"INSERT INTO accesslog (ip, time, path) VALUES (?1, ?2, ?3)"
).bind(ip, time, pathname).run();
} catch (error: any) {
console.error(`Error while inserting row into accesslog table: ${error}`);
return Response.json({ message: `Error while inserting row into accesslog table: ${error.stack}` });
}
}

return fetch(request);
}
},
};
{ "message": "Error while checking rows: Error: D1_ERROR\n at D1Database._send (worker.js:149:13)\n at async D1PreparedStatement.all (worker.js:215:7)\n at async Object.fetch (worker.js:11:18)" } It works with few users. but it does not work when there are many instant requests.😕
elithrar
elithrar13mo ago
What is “many” here? How are you testing?
lokiwind
lokiwind13mo ago
Instant 5k request I wonder what I'm doing wrong. Does the D1 database have a request limit
elithrar
elithrar13mo ago
5k RPS with (potentially) multiple queries - you're likely going to hit the limits of the alpha right now. You're also (potentially) calling the Rate Limiting API many, many times per 5 minutes, which will cause you to get rate limited there as well.
lokiwind
lokiwind13mo ago
Hmm.Thank you How do you suggest I solve this problem
elithrar
elithrar13mo ago
A rate limiting rule (https://developers.cloudflare.com/waf/rate-limiting-rules/request-rate/) would probably do this for you and be much more scalable (and cheaper...) - e.g. a rule that rate limits IPs by path - https://developers.cloudflare.com/waf/rate-limiting-rules/parameters/
LeftSpace
LeftSpace13mo ago
i agree this solution would cost you a lot. @lokiwind as a price. it'll cost more than you expect if you do it in this way.
lokiwind
lokiwind13mo ago
Konu para değil. D1 limiti
LeftSpace
LeftSpace13mo ago
the first query causes the limit right?
lokiwind
lokiwind13mo ago
Hayır şu sorgu:if (results && results.length > 0) Basit bir ratelimiter kodlamak istedim.
LeftSpace
LeftSpace13mo ago
so the rate limiting api causes issues right
lokiwind
lokiwind13mo ago
Evet
LeftSpace
LeftSpace13mo ago
i don't think it's related to D1 tho :)
lokiwind
lokiwind13mo ago
D1 ile ilgili Sınırları var ..
LeftSpace
LeftSpace13mo ago
bence yanlışin var. rate limit apisinde istek limiti olabilir. bahsettiğin kod oraya post isteği atıyor sonuçta.
lokiwind
lokiwind13mo ago
Orada bir sorun yok
LeftSpace
LeftSpace13mo ago
dediğim gibi 1k+ üzeri yazma yaptım ve bir sorun yaşamadım
lokiwind
lokiwind13mo ago
{ "message": "Error while checking rows: Error: D1_ERROR\n at D1Database._send (worker.js:149:13)\n at async D1PreparedStatement.all (worker.js:215:7)\n at async Object.fetch (worker.js:11:18)" } Hata çıktısı Muhtemelen ben karmaşık bir sorgu yapıyorum ondan da olabilir
LeftSpace
LeftSpace13mo ago
yazdığın sorguyu anlayamadım bile
lokiwind
lokiwind13mo ago
Cloudflare Api 5 dakikada 1200 isteğe izin veriyor Hata aldığımda apiyi test ettim apide bir sorun olmuyor Sanırım D1 sınırlarını aştım
LeftSpace
LeftSpace13mo ago
yazdığın sorguda bir limit yok ama neden öyle peki 1m veri olsa 1m veri mi bekliyorsun?
lokiwind
lokiwind13mo ago
Kodu yazdım workersi websitesinin önüne route ettim Layer 7 yolladım dump oldu
LeftSpace
LeftSpace13mo ago
limitleyip pagelere bolebilirsin SQL queryni belkide tek queryde alabileceğin bir limit vardır
lokiwind
lokiwind13mo ago
Bak şöyle bir şey göstereceğim sana Yardımın için de sağol vaktini alıyorum
LeftSpace
LeftSpace13mo ago
ki zaten giren kişileri ayrı rowlar halinde tutmak yerine belirli bir rowda login count tarzı değer tutabilirsin columnda* ip,logincount,ratelimited gibi bir tablo yaparak queryde ip ile arayıp logincountu alırsın. 3ve uzeriyse örnek. ratelimit apisi calistirirsin
lokiwind
lokiwind13mo ago
lokiwind
lokiwind13mo ago
Benim ip de gözüküyor 🙂
LeftSpace
LeftSpace13mo ago
bu access log peki kullanıcı f5 attiginda yeni ip olarak mı ekliyor. evet öyle eklemis bu mantıksız geldi bana :)
lokiwind
lokiwind13mo ago
evet ve 1 ip 3 ve daha fazla aynı zamanda giriş bulursa Api ile kurala ekleyip Ipye ait verileri siliyor tablodan
LeftSpace
LeftSpace13mo ago
bunu tek bir satırda yapabilirsin.
lokiwind
lokiwind13mo ago
bu 1-2 kişi için çalışıyor ancak anlık 1k veri yolladığımda götü başı kayıyıo
LeftSpace
LeftSpace13mo ago
bu bence tasarım hatası
lokiwind
lokiwind13mo ago
Evet bi test ettim geliştiricem
LeftSpace
LeftSpace13mo ago
D1 olmasa başka bir db olsa bile onuda zorlar.
lokiwind
lokiwind13mo ago
Haklısın
LeftSpace
LeftSpace13mo ago
cfnin ratelimiti neyine yetmiyor :p
lokiwind
lokiwind13mo ago
geçiliyor
LeftSpace
LeftSpace13mo ago
nasıl geçiliyor?
lokiwind
lokiwind13mo ago
şimdi 10 saniyede 10 istek kuralı var 10 saniyede 9 istek gelirse
LeftSpace
LeftSpace13mo ago
ücretsiz kullanırsan öyle evet.
lokiwind
lokiwind13mo ago
Free için bir koruma geliştiriyorum Bazı eklendiler kullanrak Bakalım nasıl olur
LeftSpace
LeftSpace13mo ago
hayirlisi artık ratelimite bile gerek kalmadı cfde
lokiwind
lokiwind13mo ago
Free versiyo için mi konuşuyoruz
LeftSpace
LeftSpace13mo ago
ona emin degilim managed yeterli geliyor bence
lokiwind
lokiwind13mo ago
Piyasada çok sağlam korumalar var da Türkler pek bilmiyor ya da pahalı Ya da az gelişmiş yönetim paneli Ya da Türkçe destek yok Hyperfilter Datadome
LeftSpace
LeftSpace13mo ago
hyperfilterin gelişim nedeni biz olabiliriz
lokiwind
lokiwind13mo ago
Bir arakdaşım orada 400 tl veriyor L7 http ddos alıyor Belelş stresser ile vuruyorlar
LeftSpace
LeftSpace13mo ago
o kadar gelişmiş değildi biz kullanırken. sonra yediğimiz saldırılardan dolayı geliştirmişlerdi bizim için captcha vs getirmislerdi pahalı evet ama hakkını verdi belirli bir dönem
lokiwind
lokiwind13mo ago
Yurtdışı için yine uygun Erdogan doları 20 yaptı
LeftSpace
LeftSpace13mo ago
KSKDKSKKD cloudflare best şuan eskiden böyle değildi hyperfilter gibi çözümler kullaniyorduk
lokiwind
lokiwind13mo ago
Kanka adamlar Chromium kurup onunla saldırmaya başladı çığır aştı eşşekler
LeftSpace
LeftSpace13mo ago
captcha için para ödemesi gerekiyor ama saldırırken:)
lokiwind
lokiwind13mo ago
Evet ama bak şu var Normal kullanıcıya neden captcha göstereyim? Bu en sevmediğim şeu bu koruma değil
LeftSpace
LeftSpace13mo ago
managed attığında gerekirse gösterir diye biliyorum
lokiwind
lokiwind13mo ago
koy recaptcaha gcaptcha cloudflare captcha turnsistel falaan Geçenin alnıını karışlarım Ama mevzu Temiz kullanıcı ile Bot saldırıyı ayırmak
LeftSpace
LeftSpace13mo ago
ben bir zararini görmedim bunun
lokiwind
lokiwind13mo ago
İğreniyorum captchadan Captcha gördüm mü siteyi kapatıyorum
LeftSpace
LeftSpace13mo ago
ip skorun o kadar mı toxic :p
lokiwind
lokiwind13mo ago
Hayır 0.7 en son bi modeme reset atayım :d
LeftSpace
LeftSpace13mo ago
KSKSKDK ben bilmem
lokiwind
lokiwind13mo ago
Var mı elinde gelişmiş bot
LeftSpace
LeftSpace13mo ago
ama yapmaya calistigin rate limit patlar bot?
lokiwind
lokiwind13mo ago
Evet bot
LeftSpace
LeftSpace13mo ago
yok ya benim işim yok dodisle
lokiwind
lokiwind13mo ago
Siteye sok dicem DDoS iyidir ya
LeftSpace
LeftSpace13mo ago
benim siteyi biliyosun değil mi adını vermeyelim
lokiwind
lokiwind13mo ago
memmoli
LeftSpace
LeftSpace13mo ago
adını vermeyelim dedik iyi ki evet sunucuda vardın çıkmışsın :)
lokiwind
lokiwind13mo ago
Aynen Tsden amd nick Hatırlamazsın Ensar falan vardı nolldu onna
LeftSpace
LeftSpace13mo ago
imkanı yok hatirlamamin idk
lokiwind
lokiwind13mo ago
Kanlı bıçaklıydınız sdfsfs
LeftSpace
LeftSpace13mo ago
hangi site bu uygulamaya çalıştığın?
lokiwind
lokiwind13mo ago
yok site varsa botun bi domaine kurucam
LeftSpace
LeftSpace13mo ago
merak etmistim neyse
lokiwind
lokiwind13mo ago
Gelişmiş bi bot konntrolü yapıyot Bot human ayrımı Şuan sadece şeyde açığım var yukarda da bahsettiğim Chromium inidirp makineye Google ile browser attack O saldırı da tekil ip olduğu için kabak giib rate limite takılıyor
LeftSpace
LeftSpace13mo ago
chromium ile yapılan saldırıda site etkileniyorsa vay haline o sitenin :)
lokiwind
lokiwind13mo ago
Neden ki Browser attack bu
LeftSpace
LeftSpace13mo ago
chromiumu cookie almak için vs kullaniyor sanmıştım.
lokiwind
lokiwind13mo ago
js destekleyen gelişmiş saldırı bildiğin makine saldırısı ya google açıp websitesini aratıp istek atıyor insan gibi
LeftSpace
LeftSpace13mo ago
bir tarayıcı ile yapılan istek dodis ağır yüklü olmaz diye düşünüyorum
lokiwind
lokiwind13mo ago
evet dedim zaten rate limite takılıyor
LeftSpace
LeftSpace13mo ago
sonuçta threading vs kullanamaz. siteye zarar veremez yani bana kalirsa
lokiwind
lokiwind13mo ago
ama proxy kullanılıp yapılırsa 3-5 makine ile tek çare tüm kullanıcılara interactive challange 😄
LeftSpace
LeftSpace13mo ago
peki challengeyi adam browserden eliyle geçti diyelim o zaman ne olur eğer dediğin gibiyse
lokiwind
lokiwind13mo ago
Evet ama bunun için ayrı bir yazılım yazması gerekiyor bu saldırı boyutunu küçültür ve challange belli bi süre çözmediğinde kendini yeniliyor ve çözsen bile birdaha challange çıkarıyor bu da cloudflarenin bi artısı
LeftSpace
LeftSpace13mo ago
bu tarz chromium based dodis atan bir site bilmiyorum henüz
lokiwind
lokiwind13mo ago
bu tür yöntemlere karşı Benim bi arkadaşım var Onur Cloudflare magic transist satın aldı NGNİX plus ile Korumalar yapıyor Chromium saldırıları yapıyor Ama tekip ipden sizde rate limiter var
LeftSpace
LeftSpace13mo ago
bak dediğim gibi hadi diyelim 10snlik rate limiti 9 istekle geçti peki ya sonra? dediğin gibi tek ip üzerinden atiyorsa 9 istekte site mi çöker:)
lokiwind
lokiwind13mo ago
Bak ben sana örnek verdim mantığı bu geçmenin bir saniye
LeftSpace
LeftSpace13mo ago
100 tane makine olsa bile saniyede 900 istek mi yapar 900 istekle o site cokuyorsa sorun başka zaten. bu dediğin browser based vsvsvs boş. büyük zarar vericek biseyi yok browser based eskiden yapılırdı js challenge varken.
lokiwind
lokiwind13mo ago
Makine değil proxy ip 1k ip
LeftSpace
LeftSpace13mo ago
chromium actirir cookieleri alır programa gonderirdik olurdu. makine değilse daha zor
lokiwind
lokiwind13mo ago
lokiwind
lokiwind13mo ago
Özel geçelim mi
LeftSpace
LeftSpace13mo ago
elinde mevcut mu bu şuan?
lokiwind
lokiwind13mo ago
Şuanda bu dünyanın parası Browser attack
LeftSpace
LeftSpace13mo ago
valla boşver ya sen kendini yoruyosun captcha görse kullanıcı 1 sn kaybedicek girmek istemiyosa girmesin zaten :)
lokiwind
lokiwind13mo ago
Kimse buna koruma gözüyle bakmaz
LeftSpace
LeftSpace13mo ago
ben kaciyorum kolay gelsin koruma gözüyle bakmasa cf eklemezdi.
lokiwind
lokiwind13mo ago
R10 üzerinde bile adama gülüp geçiyorlar Eyyvallah görüşmek üzere 😍
LeftSpace
LeftSpace13mo ago
r10daki adamlar önce kendini korusun gülüp geçerler sonra .d
lokiwind
lokiwind13mo ago
Orası öyle
LeftSpace
LeftSpace13mo ago
silebilirsen sil burayı ^
lokiwind
lokiwind13mo ago
silelim nereden siliyoruz :d