Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 | /**
* Rate Limiting Utilities
* レート制限ユーティリティ
*
* このファイルは開発環境用のシンプルなインメモリレート制限実装です。
* 本番環境ではUpstash Redisなどの分散キャッシュを使用することを推奨します。
*
* Production Setup with Upstash:
* 1. Install: npm install @upstash/ratelimit @upstash/redis
* 2. Set env vars: UPSTASH_REDIS_REST_URL, UPSTASH_REDIS_REST_TOKEN
* 3. Replace implementations below with Upstash Ratelimit
*/
interface RateLimitConfig {
interval: number; // Time window in milliseconds
maxRequests: number; // Max requests per interval
}
interface RateLimitEntry {
count: number;
resetAt: number;
}
/**
* In-memory rate limiter (for development)
* 本番環境では使用しないでください - メモリリークの可能性があります
*/
class InMemoryRateLimiter {
private store: Map<string, RateLimitEntry> = new Map();
private cleanupInterval: NodeJS.Timeout;
constructor() {
// Clean up expired entries every 5 minutes
this.cleanupInterval = setInterval(() => {
this.cleanup();
}, 5 * 60 * 1000);
}
private cleanup(): void {
const now = Date.now();
for (const [key, entry] of this.store.entries()) {
if (entry.resetAt < now) {
this.store.delete(key);
}
}
}
async check(
identifier: string,
config: RateLimitConfig
): Promise<{ success: boolean; limit: number; remaining: number; reset: number }> {
const now = Date.now();
const entry = this.store.get(identifier);
if (!entry || entry.resetAt < now) {
// First request or expired window - reset
this.store.set(identifier, {
count: 1,
resetAt: now + config.interval,
});
return {
success: true,
limit: config.maxRequests,
remaining: config.maxRequests - 1,
reset: now + config.interval,
};
}
// Within window - increment
entry.count += 1;
this.store.set(identifier, entry);
return {
success: entry.count <= config.maxRequests,
limit: config.maxRequests,
remaining: Math.max(0, config.maxRequests - entry.count),
reset: entry.resetAt,
};
}
destroy(): void {
clearInterval(this.cleanupInterval);
this.store.clear();
}
}
// Singleton instance
let rateLimiter: InMemoryRateLimiter | null = null;
function getRateLimiter(): InMemoryRateLimiter {
if (!rateLimiter) {
rateLimiter = new InMemoryRateLimiter();
}
return rateLimiter;
}
/**
* Rate limit configurations
*/
export const RateLimitConfigs = {
// POST requests (create operations)
post: {
interval: 60 * 60 * 1000, // 1 hour
maxRequests: 10, // 10 posts per hour
},
// Comment requests
comment: {
interval: 60 * 60 * 1000, // 1 hour
maxRequests: 30, // 30 comments per hour
},
// API requests (general)
api: {
interval: 60 * 1000, // 1 minute
maxRequests: 60, // 60 requests per minute
},
// Authentication attempts
auth: {
interval: 15 * 60 * 1000, // 15 minutes
maxRequests: 5, // 5 attempts per 15 minutes
},
} as const;
/**
* Check rate limit for an identifier
*
* @param identifier - Unique identifier (user ID, IP address, etc.)
* @param config - Rate limit configuration
* @returns Rate limit status
*/
export async function checkRateLimit(
identifier: string,
config: RateLimitConfig = RateLimitConfigs.api
): Promise<{ success: boolean; limit: number; remaining: number; reset: number }> {
const limiter = getRateLimiter();
return limiter.check(identifier, config);
}
/**
* Get rate limit identifier from request
* ユーザーIDまたはIPアドレスからレート制限の識別子を取得
*
* @param userId - User ID (if authenticated)
* @param ip - IP address
* @param prefix - Prefix for the identifier
* @returns Rate limit identifier
*/
export function getRateLimitIdentifier(
userId: string | undefined,
ip: string | undefined,
prefix: string = "api"
): string {
if (userId) {
return `${prefix}:user:${userId}`;
}
if (ip) {
return `${prefix}:ip:${ip}`;
}
return `${prefix}:anonymous`;
}
/**
* Example usage in API route:
*
* ```typescript
* import { checkRateLimit, getRateLimitIdentifier, RateLimitConfigs } from "@/lib/rate-limit";
* import { createError, ErrorCodes } from "@/lib/api-error";
*
* export async function POST(request: NextRequest) {
* const session = await requireAuth();
* const ip = request.headers.get("x-forwarded-for") || request.headers.get("x-real-ip");
*
* // Check rate limit
* const identifier = getRateLimitIdentifier(session.user.id, ip || undefined, "post");
* const rateLimit = await checkRateLimit(identifier, RateLimitConfigs.post);
*
* if (!rateLimit.success) {
* throw createError(ErrorCodes.RATE_LIMIT_EXCEEDED);
* }
*
* // Add rate limit headers
* const response = NextResponse.json({ data });
* response.headers.set("X-RateLimit-Limit", rateLimit.limit.toString());
* response.headers.set("X-RateLimit-Remaining", rateLimit.remaining.toString());
* response.headers.set("X-RateLimit-Reset", new Date(rateLimit.reset).toISOString());
*
* return response;
* }
* ```
*
* Production Setup with Upstash:
*
* ```typescript
* import { Ratelimit } from "@upstash/ratelimit";
* import { Redis } from "@upstash/redis";
*
* const redis = Redis.fromEnv();
*
* export const postRatelimit = new Ratelimit({
* redis,
* limiter: Ratelimit.slidingWindow(10, "1 h"),
* analytics: true,
* });
*
* // Usage in route:
* const { success, limit, remaining, reset } = await postRatelimit.limit(identifier);
* ```
*/
|