import { isIpInDatacenterBlocks } from './asBlocks.js'; import { isIP, isIPv4, isIPv6 } from 'node:net'; import type { RequestEvent } from '@sveltejs/kit'; import type { RateLimiterPlugin, Rate } from 'sveltekit-rate-limiter/server'; export function getClientIp(eventOrReq: RequestEvent | Request): string { const headers = 'request' in eventOrReq ? eventOrReq.request.headers : eventOrReq.headers; // x-real-ip is set authoritatively by the upstream reverse proxy on the host const xRealIp = headers.get('x-real-ip'); if (xRealIp && isIP(xRealIp.trim())) return xRealIp.trim(); const xForwardedFor = headers.get('x-forwarded-for'); if (xForwardedFor) { const first = xForwardedFor.split(',')[0].trim(); if (isIP(first)) return first; } if ('getClientAddress' in eventOrReq && typeof eventOrReq.getClientAddress === 'function') { try { const addr = eventOrReq.getClientAddress(); if (addr && isIP(addr)) return addr; } catch { // getClientAddress might throw if address header is unconfigured } } return '127.0.0.1'; } export function isPrivateOrLocalIp(ip: string): boolean { if (!ip || ip === 'localhost' || ip === '::1' || ip === '127.0.0.1') return true; if ( ip.startsWith('10.') || ip.startsWith('192.168.') || ip.startsWith('172.16.') || ip.startsWith('172.17.') || ip.startsWith('172.18.') || ip.startsWith('172.19.') || ip.startsWith('172.2') || ip.startsWith('172.30.') || ip.startsWith('172.31.') ) { return true; } const lower = ip.toLowerCase(); if (lower.startsWith('fc') || lower.startsWith('fd') || lower.startsWith('fe80')) return true; return false; } export function getSubnetKey(ip: string): string { if (isPrivateOrLocalIp(ip)) { return ip; } if (isIPv4(ip)) { const parts = ip.split('.'); return `${parts[0]}.${parts[1]}.${parts[2]}.0/24`; } if (isIPv6(ip)) { return getIpv6Prefix64(ip); } return ip; } function getIpv6Prefix64(ip: string): string { const lower = ip.toLowerCase(); if (lower.startsWith('::ffff:')) { const v4 = ip.substring(7); if (isIPv4(v4)) return getSubnetKey(v4); } const parts = ip.split('::'); const left = parts[0] ? parts[0].split(':') : []; const right = parts.length > 1 && parts[1] ? parts[1].split(':') : []; const missing = 8 - (left.length + right.length); const full = [...left, ...Array(Math.max(0, missing)).fill('0'), ...right].map((h) => h.padStart(4, '0') ); return `${full.slice(0, 4).join(':')}::/64`; } interface AsnCacheEntry { isHosting: boolean; org?: string; checkedAt: number; } const asnCache = new Map(); const ASN_CACHE_TTL = 24 * 60 * 60 * 1000; // 24 hours const HOSTING_KEYWORDS = [ 'hetzner', 'ovh', 'digitalocean', 'linode', 'akamai', 'vultr', 'choopa', 'frantech', 'buyvm', 'contabo', 'leaseweb', 'scaleway', 'online sas', 'amazon', 'aws', 'google', 'gcp', 'microsoft', 'azure', 'oracle', 'hostinger', 'kamatera', 'rackspace', 'cloudflare', 'fastly', 'm247', 'cogent', 'datapacket', 'hostkey', 'tzulo', 'serverius', 'worldstream' ]; export async function isDatacenterOrProxy(ip: string): Promise { if (isPrivateOrLocalIp(ip)) return false; // Fast in-memory check against periodically fetched ipverse CIDR blocks if (isIpInDatacenterBlocks(ip)) { return true; } const subnetKey = getSubnetKey(ip); const cached = asnCache.get(subnetKey); if (cached && Date.now() - cached.checkedAt < ASN_CACHE_TTL) { return cached.isHosting; } try { const controller = new AbortController(); const timeoutId = setTimeout(() => controller.abort(), 2000); // ip-api.com returns hosting / proxy status const res = await fetch( `http://ip-api.com/json/${encodeURIComponent(ip)}?fields=status,message,as,asname,hosting,proxy`, { signal: controller.signal } ); clearTimeout(timeoutId); if (!res.ok) return false; const data = (await res.json()) as { status?: string; as?: string; asname?: string; hosting?: boolean; proxy?: boolean; }; if (data.status === 'success') { const asStr = `${data.as ?? ''} ${data.asname ?? ''}`.toLowerCase(); const matchesKeyword = HOSTING_KEYWORDS.some((kw) => asStr.includes(kw)); const isHosting = !!data.hosting || !!data.proxy || matchesKeyword; asnCache.set(subnetKey, { isHosting, org: data.asname || data.as, checkedAt: Date.now() }); return isHosting; } } catch (err) { // On timeout or lookup failure, fail open so legitimate users aren't blocked console.log(`ASN lookup failed for ${ip}: ${err}`); } return false; } export class SubnetRateLimiter implements RateLimiterPlugin { rate: Rate | Rate[]; constructor(rate: Rate | Rate[]) { this.rate = rate; } async hash(event: RequestEvent) { const ip = getClientIp(event); return getSubnetKey(ip); } } export class SubnetUserAgentRateLimiter implements RateLimiterPlugin { rate: Rate | Rate[]; constructor(rate: Rate | Rate[]) { this.rate = rate; } async hash(event: RequestEvent) { const ua = event.request.headers.get('user-agent'); if (!ua) return false; const ip = getClientIp(event); return `${getSubnetKey(ip)}_${ua}`; } } export class GlobalCooldown { private lastActionTime = 0; private minIntervalMs: number; constructor(minIntervalSeconds: number) { this.minIntervalMs = minIntervalSeconds * 1000; } check(): { allowed: boolean; retryAfter: number } { const now = Date.now(); const elapsed = now - this.lastActionTime; if (elapsed < this.minIntervalMs) { const retryAfter = Math.ceil((this.minIntervalMs - elapsed) / 1000); return { allowed: false, retryAfter }; } return { allowed: true, retryAfter: 0 }; } record(): void { this.lastActionTime = Date.now(); } } export class SlidingWindowLimiter { private timestamps: number[] = []; private maxHits: number; private windowMs: number; constructor(maxHits: number, windowSeconds: number) { this.maxHits = maxHits; this.windowMs = windowSeconds * 1000; } check(): { allowed: boolean; retryAfter: number } { const now = Date.now(); this.timestamps = this.timestamps.filter((t) => now - t < this.windowMs); if (this.timestamps.length >= this.maxHits) { const oldest = this.timestamps[0]; const retryAfter = Math.ceil((oldest + this.windowMs - now) / 1000); return { allowed: false, retryAfter }; } return { allowed: true, retryAfter: 0 }; } record(): void { const now = Date.now(); this.timestamps = this.timestamps.filter((t) => now - t < this.windowMs); this.timestamps.push(now); } } // Guestbook: max 1 post every 30 seconds site-wide export const guestbookGlobalCooldown = new GlobalCooldown(30); // Bother me: max 2 notifications every 20 seconds site-wide export const botherGlobalCooldown = new SlidingWindowLimiter(2, 20); interface SubnetHistoryEntry { timestamps: number[]; } const botherSubnetHistory = new Map(); export function checkBotherSubnetLimit( subnetKey: string, maxPerHour = 3 ): { allowed: boolean; retryAfter: number } { const now = Date.now(); const oneHourAgo = now - 60 * 60 * 1000; const entry = botherSubnetHistory.get(subnetKey) || { timestamps: [] }; entry.timestamps = entry.timestamps.filter((t) => t > oneHourAgo); if (entry.timestamps.length >= maxPerHour) { const oldest = entry.timestamps[0]; const retryAfter = Math.ceil((oldest + 60 * 60 * 1000 - now) / 1000); return { allowed: false, retryAfter }; } return { allowed: true, retryAfter: 0 }; } export function recordBotherSubnet(subnetKey: string): void { const now = Date.now(); const entry = botherSubnetHistory.get(subnetKey) || { timestamps: [] }; entry.timestamps.push(now); botherSubnetHistory.set(subnetKey, entry); } interface BanEntry { hits: number; bannedUntil: number; lastSeen: number; } const honeypotViolations = new Map(); const BAN_THRESHOLD = 3; // Ban after N = 3 honeypot hits const BAN_DURATION_MS = 24 * 60 * 60 * 1000; // 24-hour ban const VIOLATION_WINDOW_MS = 60 * 60 * 1000; // 1-hour window to accumulate hits export function isSubnetBanned(subnetKey: string): boolean { const entry = honeypotViolations.get(subnetKey); if (!entry) return false; const now = Date.now(); if (now < entry.bannedUntil) { return true; } if (now - entry.lastSeen > VIOLATION_WINDOW_MS) { honeypotViolations.delete(subnetKey); } return false; } export function recordHoneypotViolation(subnetKey: string): boolean { const now = Date.now(); const entry = honeypotViolations.get(subnetKey) || { hits: 0, bannedUntil: 0, lastSeen: now }; if (now < entry.bannedUntil) { entry.lastSeen = now; honeypotViolations.set(subnetKey, entry); return true; } if (now - entry.lastSeen > VIOLATION_WINDOW_MS) { entry.hits = 0; } entry.hits += 1; entry.lastSeen = now; if (entry.hits >= BAN_THRESHOLD) { entry.bannedUntil = now + BAN_DURATION_MS; console.log(`[BAN] Subnet ${subnetKey} banned for 24h (${entry.hits} honeypot hits)`); honeypotViolations.set(subnetKey, entry); return true; } honeypotViolations.set(subnetKey, entry); return false; }