跳到正文
cccskills
免费在 GitHub 公开

rate-limit-abuse-prevention

Expert guide for API rate limiting, bot protection, DDoS mitigation, brute-force prevention, and abuse detection / Panduan ahli untuk rate limiting API, perlindungan bot, mitigasi DDoS, pencegahan brute-force, dan deteksi penyalahgunaan.

中文简介正在准备中。当前显示原文说明。

集成工具CloudflareRedis
查看安装方法

包含的文件(1)

  • SKILL.md14.3 KB

SKILL.md(原文)

安装前可以查看交给 AI 代理的指令内容。

Rate Limit & Abuse Prevention (2026 Edition)

English | Bahasa Indonesia


<a name="english"></a>

English

Orchestration & Integration

  • Threat Defense & Red Teaming: autonomous-red-teamer, prompt-injection-firewall, zero-trust-secret-vault
  • Identity & Authentication: authentication-identity-expert, compliance-gdpr-privacy-expert
  • API Architecture & Backend: api-design-expert, js-backend-expert, api-gateway-proxy-expert
  • Edge Infrastructure & DDoS: cloud-hosting-expert, cloudflare-workers-expert
  • SaaS Billing & Quotas: saas-billing, doku-payment-gateway, payment-gateway-expert
  • Lifecycle & Hardening: production-ready-hardener, brainstorming, zero-to-prod-orchestrator, session-memory-manager

Description

Production-grade guide for protecting APIs and web applications from abuse, overuse, and attacks. Covers rate limiting algorithms (Token Bucket, Sliding Window), Upstash Ratelimit, bot protection (Cloudflare Turnstile, hCaptcha), DDoS mitigation at edge, brute-force login prevention, API key management & usage quotas, and response headers (X-RateLimit, Retry-After).

Trigger Conditions

Activate this skill when:

  • Implementing API rate limiting for public or authenticated endpoints.
  • Adding bot protection (CAPTCHA) to forms (login, signup, contact).
  • Setting up DDoS protection at the edge (Cloudflare, Vercel).
  • Preventing brute-force attacks on authentication endpoints.
  • Implementing API key issuance and usage quotas for SaaS.
  • Building tiered rate limits based on subscription plans.

Rate Limiting Algorithm Comparison

AlgorithmBehaviorBest ForBurst Handling
Fixed WindowResets counter at interval boundarySimple endpointsAllows double burst at window edge
Sliding WindowRolling window, smooth distributionAPI endpointsSmooth, no edge burst
Token BucketTokens refill at fixed rateHigh-throughput APIsAllows controlled bursts
Leaky BucketProcesses at fixed rate, queues excessStream processingNo bursts, constant rate

Recommendation: Use Sliding Window for most API endpoints. Use Token Bucket for endpoints that should allow burst traffic.


1. Upstash Ratelimit (Edge-Compatible)

// lib/ratelimit.ts
import { Ratelimit } from '@upstash/ratelimit';
import { Redis } from '@upstash/redis';

const redis = Redis.fromEnv();

// Different rate limiters for different tiers
export const rateLimiters = {
  /** Public API: 10 requests per 10 seconds */
  public: new Ratelimit({
    redis,
    limiter: Ratelimit.slidingWindow(10, '10s'),
    prefix: 'rl:public',
    analytics: true,
  }),

  /** Authenticated API: 100 requests per minute */
  authenticated: new Ratelimit({
    redis,
    limiter: Ratelimit.slidingWindow(100, '1m'),
    prefix: 'rl:auth',
    analytics: true,
  }),

  /** Pro tier: 1000 requests per minute */
  pro: new Ratelimit({
    redis,
    limiter: Ratelimit.slidingWindow(1000, '1m'),
    prefix: 'rl:pro',
    analytics: true,
  }),

  /** Login endpoint: 5 attempts per 15 minutes */
  login: new Ratelimit({
    redis,
    limiter: Ratelimit.slidingWindow(5, '15m'),
    prefix: 'rl:login',
  }),

  /** Password reset: 3 per hour */
  passwordReset: new Ratelimit({
    redis,
    limiter: Ratelimit.slidingWindow(3, '1h'),
    prefix: 'rl:pwreset',
  }),
};
// middleware.ts (Next.js)
import { NextResponse, type NextRequest } from 'next/server';
import { rateLimiters } from '@/lib/ratelimit';

export async function middleware(request: NextRequest) {
  if (request.nextUrl.pathname.startsWith('/api/')) {
    const ip = request.headers.get('x-forwarded-for') ?? request.ip ?? '127.0.0.1';
    const identifier = ip;

    const limiter = request.nextUrl.pathname.startsWith('/api/auth/login')
      ? rateLimiters.login
      : rateLimiters.public;

    const { success, limit, remaining, reset } = await limiter.limit(identifier);

    if (!success) {
      return NextResponse.json(
        { error: 'Too many requests', retryAfter: Math.ceil((reset - Date.now()) / 1000) },
        {
          status: 429,
          headers: {
            'X-RateLimit-Limit': limit.toString(),
            'X-RateLimit-Remaining': '0',
            'X-RateLimit-Reset': reset.toString(),
            'Retry-After': Math.ceil((reset - Date.now()) / 1000).toString(),
          },
        },
      );
    }

    const response = NextResponse.next();
    response.headers.set('X-RateLimit-Limit', limit.toString());
    response.headers.set('X-RateLimit-Remaining', remaining.toString());
    response.headers.set('X-RateLimit-Reset', reset.toString());
    return response;
  }
}

export const config = { matcher: '/api/:path*' };

2. Tiered Rate Limits for SaaS

// lib/tiered-ratelimit.ts
import { Ratelimit } from '@upstash/ratelimit';

type PlanTier = 'free' | 'pro' | 'enterprise';

const PLAN_LIMITS: Record<PlanTier, { requests: number; window: string }> = {
  free:       { requests: 100,    window: '1h' },
  pro:        { requests: 5000,   window: '1h' },
  enterprise: { requests: 50000,  window: '1h' },
};

export function getRateLimiterForPlan(plan: PlanTier): Ratelimit {
  const config = PLAN_LIMITS[plan];
  return new Ratelimit({
    redis,
    limiter: Ratelimit.slidingWindow(config.requests, config.window as any),
    prefix: `rl:api:${plan}`,
  });
}

// Usage in API route
export async function GET(request: Request) {
  const user = await getAuthUser(request);
  const limiter = getRateLimiterForPlan(user.plan);
  const { success, remaining } = await limiter.limit(user.id);

  if (!success) {
    return Response.json({
      error: 'Rate limit exceeded',
      upgrade: user.plan !== 'enterprise' ? 'https://app.example.com/pricing' : undefined,
    }, { status: 429 });
  }

  return Response.json({ success: true, message: 'Request processed within rate limit allocation.' });
}

3. Bot Protection (Cloudflare Turnstile)

// components/turnstile.tsx
'use client';

import { Turnstile } from '@marsidev/react-turnstile';

interface TurnstileWidgetProps {
  onVerify: (token: string) => void;
}

export function TurnstileWidget({ onVerify }: TurnstileWidgetProps) {
  return (
    <Turnstile
      siteKey={process.env.NEXT_PUBLIC_TURNSTILE_SITE_KEY!}
      onSuccess={onVerify}
      options={{ theme: 'auto', size: 'flexible' }}
    />
  );
}
// Server-side verification
export async function verifyTurnstileToken(token: string, ip?: string): Promise<boolean> {
  const response = await fetch('https://challenges.cloudflare.com/turnstile/v0/siteverify', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      secret: process.env.TURNSTILE_SECRET_KEY,
      response: token,
      remoteip: ip,
    }),
  });

  const data = await response.json();
  return data.success === true;
}

4. Brute-Force Login Prevention

// lib/login-protection.ts
const MAX_ATTEMPTS = 5;
const LOCKOUT_DURATION = 15 * 60; // 15 minutes in seconds
const PROGRESSIVE_DELAYS = [0, 1000, 2000, 4000, 8000]; // Progressive delay per attempt

export async function checkLoginAttempt(email: string, ip: string): Promise<{
  allowed: boolean;
  remainingAttempts: number;
  lockoutEndsAt?: Date;
}> {
  const key = `login-attempts:${email}:${ip}`;
  const attempts = await redis.incr(key);

  if (attempts === 1) {
    await redis.expire(key, LOCKOUT_DURATION);
  }

  if (attempts > MAX_ATTEMPTS) {
    const ttl = await redis.ttl(key);
    return {
      allowed: false,
      remainingAttempts: 0,
      lockoutEndsAt: new Date(Date.now() + ttl * 1000),
    };
  }

  // Progressive delay
  const delay = PROGRESSIVE_DELAYS[Math.min(attempts - 1, PROGRESSIVE_DELAYS.length - 1)];
  if (delay > 0) await new Promise(r => setTimeout(r, delay));

  return { allowed: true, remainingAttempts: MAX_ATTEMPTS - attempts };
}

export async function clearLoginAttempts(email: string, ip: string): Promise<void> {
  await redis.del(`login-attempts:${email}:${ip}`);
}

5. API Key Management

// lib/api-keys.ts
import { nanoid } from 'nanoid';
import { hash, verify } from '@node-rs/argon2';

export async function createApiKey(userId: string, name: string) {
  const rawKey = `sk_live_${nanoid(32)}`;
  const prefix = rawKey.slice(0, 12); // Show prefix for identification
  const hashedKey = await hash(rawKey);

  await db.insert(apiKeys).values({
    userId,
    name,
    prefix,
    hashedKey,
    lastUsedAt: null,
  });

  // Return raw key only once — cannot be retrieved later
  return { key: rawKey, prefix };
}

export async function validateApiKey(rawKey: string) {
  const prefix = rawKey.slice(0, 12);
  const candidates = await db.query.apiKeys.findMany({
    where: and(
      eq(apiKeys.prefix, prefix),
      eq(apiKeys.isRevoked, false),
    ),
  });

  for (const candidate of candidates) {
    if (await verify(candidate.hashedKey, rawKey)) {
      // Update last used timestamp
      await db.update(apiKeys)
        .set({ lastUsedAt: new Date() })
        .where(eq(apiKeys.id, candidate.id));
      return candidate;
    }
  }

  return null;
}

Response Headers Specification

HeaderPurposeExample
X-RateLimit-LimitMax requests allowed100
X-RateLimit-RemainingRemaining requests in window87
X-RateLimit-ResetUnix timestamp when window resets1723382400
Retry-AfterSeconds until retry is allowed (on 429)60

Common Pitfalls to Avoid

Anti-PatternProblemCorrect Approach
Rate limiting by IP onlyShared IPs affect multiple usersCombine IP + user ID + API key
No rate limit on auth endpointsBrute-force attacksStrict limits: 5 attempts / 15 min
Fixed window rate limiting2x burst at window boundaryUse sliding window algorithm
No 429 response headersClients can't implement backoffAlways include Retry-After header
CAPTCHA on every requestTerrible UX, accessibility issuesOnly trigger after suspicious behavior
Rate limit in application onlyStill hits your serverAdd edge-level protection (Cloudflare WAF)

<a name="bahasa-indonesia"></a>

Bahasa Indonesia

Integrasi Orkestrasi

  • Pertahanan Ancaman & Red Teaming: autonomous-red-teamer, prompt-injection-firewall, zero-trust-secret-vault
  • Identitas & Autentikasi: authentication-identity-expert, compliance-gdpr-privacy-expert
  • Arsitektur API & Backend: api-design-expert, js-backend-expert, api-gateway-proxy-expert
  • Infrastruktur Edge & DDoS: cloud-hosting-expert, cloudflare-workers-expert
  • SaaS Billing & Kuota: saas-billing, doku-payment-gateway, payment-gateway-expert
  • Siklus Hidup & Pengerasan: production-ready-hardener, brainstorming, zero-to-prod-orchestrator, session-memory-manager

Deskripsi

Panduan tingkat produksi untuk melindungi API dan aplikasi web dari penyalahgunaan, beban berlebih, dan serangan cyber. Mencakup algoritma rate limiting (Token Bucket, Sliding Window), Upstash Ratelimit (kompatibel edge), perlindungan bot (Cloudflare Turnstile), mitigasi DDoS, pencegahan brute-force login, manajemen API key & kuota penggunaan, serta format header respons standar (X-RateLimit, Retry-After).

Kondisi Pemicu

Aktifkan skill ini ketika:

  • Mengimplementasikan pembatasan laju (Rate Limiting) pada API publik atau terotentikasi.
  • Menambahkan verifikasi bot tanpa CAPTCHA yang menyusahkan (Cloudflare Turnstile) pada formulir.
  • Mencegah serangan brute-force credential stuffing pada endpoint otentikasi.
  • Menetapkan kuota pemanggilan API bertingkat berdasarkan paket langganan SaaS pengguna.

Implementasi Pola Kunci (TypeScript)

1. Rate Limiting di Edge dengan Upstash Redis & Next.js Middleware

// lib/pembatas-laju.ts
import { Ratelimit } from '@upstash/ratelimit';
import { Redis } from '@upstash/redis';

const redis = Redis.fromEnv();

export const pembatasLaju = {
  publik: new Ratelimit({
    redis,
    limiter: Ratelimit.slidingWindow(20, '10s'),
    prefix: 'rl:publik',
  }),
  login: new Ratelimit({
    redis,
    limiter: Ratelimit.slidingWindow(5, '15m'), // Maks 5 percobaan per 15 menit
    prefix: 'rl:login',
  }),
};
// middleware.ts
import { NextResponse, type NextRequest } from 'next/server';
import { pembatasLaju } from '@/lib/pembatas-laju';

export async function middleware(request: NextRequest) {
  if (request.nextUrl.pathname.startsWith('/api/')) {
    const ip = request.headers.get('x-forwarded-for') ?? '127.0.0.1';
    const isLogin = request.nextUrl.pathname.startsWith('/api/auth/login');
    const limiter = isLogin ? pembatasLaju.login : pembatasLaju.publik;

    const { success, limit, remaining, reset } = await limiter.limit(ip);

    if (!success) {
      return NextResponse.json(
        { error: 'Terlalu banyak permintaan. Silakan coba lagi nanti.' },
        {
          status: 429,
          headers: {
            'X-RateLimit-Limit': limit.toString(),
            'X-RateLimit-Remaining': '0',
            'X-RateLimit-Reset': reset.toString(),
            'Retry-After': Math.ceil((reset - Date.now()) / 1000).toString(),
          },
        }
      );
    }

    const response = NextResponse.next();
    response.headers.set('X-RateLimit-Limit', limit.toString());
    response.headers.set('X-RateLimit-Remaining', remaining.toString());
    return response;
  }
}

2. Verifikasi Token Bot Cloudflare Turnstile di Sisi Server

export async function verifikasiTurnstile(token: string, ipPengguna: string): Promise<boolean> {
  const formData = new FormData();
  formData.append('secret', process.env.TURNSTILE_SECRET_KEY!);
  formData.append('response', token);
  formData.append('remoteip', ipPengguna);

  const res = await fetch('https://challenges.cloudflare.com/turnstile/v0/siteverify', {
    method: 'POST',
    body: formData,
  });

  const hasil = await res.json();
  return hasil.success === true;
}

评价

还没有评价。欢迎分享你的使用感受。

评论

无需登录即可发表。欢迎分享使用感受、提问,或说明在哪些环境下无法运行。

还没有评论。来写第一条吧。

提交后会立即公开。请勿填写邮箱、电话等个人信息。URL 最多 2 个。

0 / 1000 字

此表单受 reCAPTCHA 保护,适用 Google 的隐私权政策和服务条款。

同一仓库的技能

Expert guide for automated and manual Web Accessibility (a11y) testing — axe-core, Pa11y, Playwright a11y, screen reader testing, and WCAG 2.2 Level AA/AAA compliance / Panduan ahli pengujian aksesibilitas web.

中文简介正在准备中。当前显示原文说明。

roedyrustam/vibes-plug1122026年10月22日 更新

Expert guide for intelligent model cascading and routing — complexity-scored task routing from Fast (Composer 2.5, Grok 4.7/4.6) to Medium (Gemini 4 Argon, GPT-5.6 Sol, Claude Opus 5.5) and High (Claude Sonnet 5.5, Claude Fable 5.1, Muse Wonder) / Panduan ahli untuk kaskade dan routing model cerdas.

中文简介正在准备中。当前显示原文说明。

roedyrustam/vibes-plug1122026年10月22日 更新

Expert guide for intelligent model cascading and routing — complexity-scored task routing from Flash/Haiku to Sonnet/Opus/Astra, dynamic escalation with quality gates, 40-60% token cost reduction while maintaining output quality / Panduan ahli untuk kaskade dan routing model cerdas — routing tugas berbasis skor kompleksitas dari Flash/Haiku ke Sonnet/Opus/Astra, eskalasi dinamis dengan gerbang kualitas, pengurangan biaya token 40-60% dengan kualitas output terjaga.

中文简介正在准备中。当前显示原文说明。

roedyrustam/vibes-plug1122026年10月22日 更新

Master guide for Affective Computing, emotional AI, and real-time sentiment analysis through native multimodal tokens (voice intonation and facial micro-expressions) / Panduan utama komputasi afektif, AI emosional, dan analisis sentimen real-time melalui token multimodal native.

中文简介正在准备中。当前显示原文说明。

roedyrustam/vibes-plug1122026年10月22日 更新

Expert guide for Affective Computing, emotional AI, and real-time sentiment analysis through native multimodal tokens (voice intonation and facial micro-expressions) / Panduan ahli komputasi afektif, AI emosional, dan analisis sentimen real-time melalui token multimodal native.

中文简介正在准备中。当前显示原文说明。

roedyrustam/vibes-plug1122026年10月22日 更新

Expert guide for AI-assisted coding workflows — agentic code generation, multi-agent code swarms, self-healing CI/CD, automated PR review, spec-to-code pipelines, codebase knowledge graphs, and human-in-the-loop approval gates / Panduan ahli untuk workflow pengkodean berbasis AI — generasi kode agentic, code swarm multi-agen, CI/CD self-healing, review PR otomatis, pipeline spec-to-code, knowledge graph codebase, dan gate persetujuan human-in-the-loop.

中文简介正在准备中。当前显示原文说明。

roedyrustam/vibes-plug1122026年10月22日 更新

查看 roedyrustam 的全部技能

报告此技能的问题