working ish wihotu cookies
This commit is contained in:
@@ -1,7 +1,37 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { createRoom } from '@/lib/rooms';
|
||||
import { rateLimit, getClientIdentifier } from '@/lib/rate-limit';
|
||||
import { createRoomSchema } from '@/lib/validation';
|
||||
|
||||
export async function POST() {
|
||||
const { code, moderatorId } = createRoom();
|
||||
return NextResponse.json({ code, moderatorId });
|
||||
export async function POST(req: Request) {
|
||||
try {
|
||||
// Rate limit: max 5 rooms per IP per hour
|
||||
const clientId = getClientIdentifier(req);
|
||||
const rateLimitResult = rateLimit(`create:${clientId}`, 5, 3600000);
|
||||
|
||||
if (!rateLimitResult.success) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Too many rooms created. Try again later.' },
|
||||
{ status: 429 }
|
||||
);
|
||||
}
|
||||
|
||||
// Validate request (empty body is fine for create)
|
||||
const body = await req.json().catch(() => ({}));
|
||||
createRoomSchema.parse(body);
|
||||
|
||||
const { code, moderatorId } = createRoom();
|
||||
|
||||
return NextResponse.json({
|
||||
code,
|
||||
moderatorId,
|
||||
remaining: rateLimitResult.remaining
|
||||
});
|
||||
} catch (error: unknown) {
|
||||
console.error('Create room error:', error);
|
||||
return NextResponse.json(
|
||||
{ error: 'Failed to create room' },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,13 +1,47 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { joinRoom } from '@/lib/rooms';
|
||||
import { rateLimit, getClientIdentifier } from '@/lib/rate-limit';
|
||||
import { joinRoomSchema } from '@/lib/validation';
|
||||
|
||||
export async function POST(req: Request) {
|
||||
const { code, playerName } = await req.json();
|
||||
const result = joinRoom(code, playerName);
|
||||
|
||||
if (!result) {
|
||||
return NextResponse.json({ error: 'Room not found' }, { status: 404 });
|
||||
try {
|
||||
// Rate limit: max 20 join attempts per IP per minute
|
||||
const clientId = getClientIdentifier(req);
|
||||
const rateLimitResult = rateLimit(`join:${clientId}`, 20, 60000);
|
||||
|
||||
if (!rateLimitResult.success) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Too many attempts. Slow down.' },
|
||||
{ status: 429 }
|
||||
);
|
||||
}
|
||||
|
||||
const body = await req.json();
|
||||
const validatedData = joinRoomSchema.parse(body);
|
||||
|
||||
const result = joinRoom(validatedData.code, validatedData.playerName);
|
||||
|
||||
if (!result) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Room not found or inactive' },
|
||||
{ status: 404 }
|
||||
);
|
||||
}
|
||||
|
||||
return NextResponse.json(result);
|
||||
} catch (error: any) {
|
||||
console.error('Join room error:', error);
|
||||
|
||||
if (error.name === 'ZodError') {
|
||||
return NextResponse.json(
|
||||
{ error: error.errors[0].message },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
return NextResponse.json(
|
||||
{ error: 'Invalid request' },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
return NextResponse.json(result);
|
||||
}
|
||||
50
src/lib/rate-limit.ts
Normal file
50
src/lib/rate-limit.ts
Normal file
@@ -0,0 +1,50 @@
|
||||
// Simple in-memory rate limiter
|
||||
interface RateLimitEntry {
|
||||
count: number;
|
||||
resetTime: number;
|
||||
}
|
||||
|
||||
const rateLimitStore = new Map<string, RateLimitEntry>();
|
||||
|
||||
// Clean up old entries every minute
|
||||
setInterval(() => {
|
||||
const now = Date.now();
|
||||
for (const [key, value] of rateLimitStore.entries()) {
|
||||
if (now > value.resetTime) {
|
||||
rateLimitStore.delete(key);
|
||||
}
|
||||
}
|
||||
}, 60000);
|
||||
|
||||
export function rateLimit(
|
||||
identifier: string,
|
||||
maxRequests: number = 10,
|
||||
windowMs: number = 60000
|
||||
): { success: boolean; remaining: number } {
|
||||
const now = Date.now();
|
||||
const entry = rateLimitStore.get(identifier);
|
||||
|
||||
if (!entry || now > entry.resetTime) {
|
||||
// New window
|
||||
rateLimitStore.set(identifier, {
|
||||
count: 1,
|
||||
resetTime: now + windowMs,
|
||||
});
|
||||
return { success: true, remaining: maxRequests - 1 };
|
||||
}
|
||||
|
||||
if (entry.count >= maxRequests) {
|
||||
return { success: false, remaining: 0 };
|
||||
}
|
||||
|
||||
entry.count++;
|
||||
return { success: true, remaining: maxRequests - entry.count };
|
||||
}
|
||||
|
||||
export function getClientIdentifier(req: Request): string {
|
||||
// Try to get real IP (works with most proxies)
|
||||
const forwarded = req.headers.get('x-forwarded-for');
|
||||
const realIp = req.headers.get('x-real-ip');
|
||||
|
||||
return forwarded?.split(',')[0] || realIp || 'unknown';
|
||||
}
|
||||
@@ -75,4 +75,18 @@ export function leaveRoom(code: string, playerId: string) {
|
||||
console.log('👋 Player left room:', code, 'Remaining players:', room?.players.size);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
// Auto-cleanup inactive rooms after 2 hours
|
||||
setInterval(() => {
|
||||
const now = Date.now();
|
||||
const twoHours = 2 * 60 * 60 * 1000;
|
||||
|
||||
for (const [code, room] of rooms.entries()) {
|
||||
const age = now - room.createdAt.getTime();
|
||||
if (age > twoHours || (!room.isActive && age > 300000)) {
|
||||
rooms.delete(code);
|
||||
console.log('🗑️ Cleaned up room:', code);
|
||||
}
|
||||
}
|
||||
}, 300000); // Check every 5 minutes
|
||||
24
src/lib/validation.ts
Normal file
24
src/lib/validation.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
export const createRoomSchema = z.object({});
|
||||
|
||||
export const joinRoomSchema = z.object({
|
||||
code: z.string()
|
||||
.length(6, 'Room code must be 6 characters')
|
||||
.regex(/^[A-Z0-9]+$/, 'Invalid room code format'),
|
||||
playerName: z.string()
|
||||
.min(1, 'Name is required')
|
||||
.max(20, 'Name too long')
|
||||
.regex(/^[a-zA-Z0-9\s]+$/, 'Name contains invalid characters')
|
||||
.transform(val => val.trim()),
|
||||
});
|
||||
|
||||
export const roomActionSchema = z.object({
|
||||
action: z.enum(['close', 'leave']),
|
||||
moderatorId: z.string().optional(),
|
||||
playerId: z.string().optional(),
|
||||
});
|
||||
|
||||
export const roomCodeSchema = z.string()
|
||||
.length(6, 'Invalid room code')
|
||||
.regex(/^[A-Z0-9]+$/, 'Invalid room code format');
|
||||
Reference in New Issue
Block a user