diff --git a/bun.lock b/bun.lock index 7f2d86f..0f12120 100644 --- a/bun.lock +++ b/bun.lock @@ -5,6 +5,7 @@ "": { "name": "scibowl-next", "dependencies": { + "js-cookie": "^3.0.5", "next": "16.1.6", "react": "19.2.3", "react-dom": "19.2.3", @@ -12,6 +13,7 @@ }, "devDependencies": { "@tailwindcss/postcss": "^4", + "@types/js-cookie": "^3.0.6", "@types/node": "^20", "@types/react": "^19", "@types/react-dom": "^19", @@ -221,6 +223,8 @@ "@types/estree": ["@types/estree@1.0.8", "", {}, "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w=="], + "@types/js-cookie": ["@types/js-cookie@3.0.6", "", {}, "sha512-wkw9yd1kEXOPnvEeEV1Go1MmxtBJL0RR79aOTAApecWFVu7w0NNXNqhcWgvw2YgZDYadliXkl14pa3WXw5jlCQ=="], + "@types/json-schema": ["@types/json-schema@7.0.15", "", {}, "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA=="], "@types/json5": ["@types/json5@0.0.29", "", {}, "sha512-dRLjCWHYg4oaA77cxO64oO+7JwCwnIzkZPdrrC71jQmQtlhM556pwKo5bUzqvZndkVbeFLIIi+9TC40JNF5hNQ=="], @@ -581,6 +585,8 @@ "jiti": ["jiti@2.6.1", "", { "bin": { "jiti": "lib/jiti-cli.mjs" } }, "sha512-ekilCSN1jwRvIbgeg/57YFh8qQDNbwDb9xT/qu2DAHbFFZUicIl4ygVaAvzveMhMVr3LnpSKTNnwt8PoOfmKhQ=="], + "js-cookie": ["js-cookie@3.0.5", "", {}, "sha512-cEiJEAEoIbWfCZYKWhVwFuvPX1gETRYPw6LlaTKoxD3s2AkXzkCjnp6h0V77ozyqj0jakteJ4YqDJT830+lVGw=="], + "js-tokens": ["js-tokens@4.0.0", "", {}, "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ=="], "js-yaml": ["js-yaml@4.1.1", "", { "dependencies": { "argparse": "^2.0.1" }, "bin": { "js-yaml": "bin/js-yaml.js" } }, "sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA=="], diff --git a/next.config.ts b/next.config.ts index e9ffa30..9e73100 100644 --- a/next.config.ts +++ b/next.config.ts @@ -1,7 +1,31 @@ -import type { NextConfig } from "next"; +import type { NextConfig } from 'next'; const nextConfig: NextConfig = { - /* config options here */ + async headers() { + return [ + { + source: '/:path*', + headers: [ + { + key: 'X-Content-Type-Options', + value: 'nosniff', + }, + { + key: 'X-Frame-Options', + value: 'DENY', + }, + { + key: 'X-XSS-Protection', + value: '1; mode=block', + }, + { + key: 'Referrer-Policy', + value: 'strict-origin-when-cross-origin', + }, + ], + }, + ]; + }, }; -export default nextConfig; +export default nextConfig; \ No newline at end of file diff --git a/package.json b/package.json index 99759f5..5f2af25 100644 --- a/package.json +++ b/package.json @@ -9,6 +9,7 @@ "lint": "eslint" }, "dependencies": { + "js-cookie": "^3.0.5", "next": "16.1.6", "react": "19.2.3", "react-dom": "19.2.3", @@ -16,6 +17,7 @@ }, "devDependencies": { "@tailwindcss/postcss": "^4", + "@types/js-cookie": "^3.0.6", "@types/node": "^20", "@types/react": "^19", "@types/react-dom": "^19", diff --git a/src/app/api/room/create/route.ts b/src/app/api/room/create/route.ts index 5bb8b5c..8b0b4bd 100644 --- a/src/app/api/room/create/route.ts +++ b/src/app/api/room/create/route.ts @@ -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 } + ); + } } \ No newline at end of file diff --git a/src/app/api/room/join/route.ts b/src/app/api/room/join/route.ts index 08ca73e..0d2b270 100644 --- a/src/app/api/room/join/route.ts +++ b/src/app/api/room/join/route.ts @@ -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); } \ No newline at end of file diff --git a/src/lib/rate-limit.ts b/src/lib/rate-limit.ts new file mode 100644 index 0000000..555b689 --- /dev/null +++ b/src/lib/rate-limit.ts @@ -0,0 +1,50 @@ +// Simple in-memory rate limiter +interface RateLimitEntry { + count: number; + resetTime: number; +} + +const rateLimitStore = new Map(); + +// 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'; +} \ No newline at end of file diff --git a/src/lib/rooms.ts b/src/lib/rooms.ts index 4379df8..5256eb0 100644 --- a/src/lib/rooms.ts +++ b/src/lib/rooms.ts @@ -75,4 +75,18 @@ export function leaveRoom(code: string, playerId: string) { console.log('👋 Player left room:', code, 'Remaining players:', room?.players.size); } return result; -} \ No newline at end of file +} + +// 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 \ No newline at end of file diff --git a/src/lib/validation.ts b/src/lib/validation.ts new file mode 100644 index 0000000..cc983a4 --- /dev/null +++ b/src/lib/validation.ts @@ -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'); \ No newline at end of file