working ish wihotu cookies
This commit is contained in:
6
bun.lock
6
bun.lock
@@ -5,6 +5,7 @@
|
|||||||
"": {
|
"": {
|
||||||
"name": "scibowl-next",
|
"name": "scibowl-next",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"js-cookie": "^3.0.5",
|
||||||
"next": "16.1.6",
|
"next": "16.1.6",
|
||||||
"react": "19.2.3",
|
"react": "19.2.3",
|
||||||
"react-dom": "19.2.3",
|
"react-dom": "19.2.3",
|
||||||
@@ -12,6 +13,7 @@
|
|||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@tailwindcss/postcss": "^4",
|
"@tailwindcss/postcss": "^4",
|
||||||
|
"@types/js-cookie": "^3.0.6",
|
||||||
"@types/node": "^20",
|
"@types/node": "^20",
|
||||||
"@types/react": "^19",
|
"@types/react": "^19",
|
||||||
"@types/react-dom": "^19",
|
"@types/react-dom": "^19",
|
||||||
@@ -221,6 +223,8 @@
|
|||||||
|
|
||||||
"@types/estree": ["@types/estree@1.0.8", "", {}, "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w=="],
|
"@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/json-schema": ["@types/json-schema@7.0.15", "", {}, "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA=="],
|
||||||
|
|
||||||
"@types/json5": ["@types/json5@0.0.29", "", {}, "sha512-dRLjCWHYg4oaA77cxO64oO+7JwCwnIzkZPdrrC71jQmQtlhM556pwKo5bUzqvZndkVbeFLIIi+9TC40JNF5hNQ=="],
|
"@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=="],
|
"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-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=="],
|
"js-yaml": ["js-yaml@4.1.1", "", { "dependencies": { "argparse": "^2.0.1" }, "bin": { "js-yaml": "bin/js-yaml.js" } }, "sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA=="],
|
||||||
|
|||||||
@@ -1,7 +1,31 @@
|
|||||||
import type { NextConfig } from "next";
|
import type { NextConfig } from 'next';
|
||||||
|
|
||||||
const nextConfig: NextConfig = {
|
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;
|
||||||
@@ -9,6 +9,7 @@
|
|||||||
"lint": "eslint"
|
"lint": "eslint"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"js-cookie": "^3.0.5",
|
||||||
"next": "16.1.6",
|
"next": "16.1.6",
|
||||||
"react": "19.2.3",
|
"react": "19.2.3",
|
||||||
"react-dom": "19.2.3",
|
"react-dom": "19.2.3",
|
||||||
@@ -16,6 +17,7 @@
|
|||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@tailwindcss/postcss": "^4",
|
"@tailwindcss/postcss": "^4",
|
||||||
|
"@types/js-cookie": "^3.0.6",
|
||||||
"@types/node": "^20",
|
"@types/node": "^20",
|
||||||
"@types/react": "^19",
|
"@types/react": "^19",
|
||||||
"@types/react-dom": "^19",
|
"@types/react-dom": "^19",
|
||||||
|
|||||||
@@ -1,7 +1,37 @@
|
|||||||
import { NextResponse } from 'next/server';
|
import { NextResponse } from 'next/server';
|
||||||
import { createRoom } from '@/lib/rooms';
|
import { createRoom } from '@/lib/rooms';
|
||||||
|
import { rateLimit, getClientIdentifier } from '@/lib/rate-limit';
|
||||||
|
import { createRoomSchema } from '@/lib/validation';
|
||||||
|
|
||||||
export async function POST() {
|
export async function POST(req: Request) {
|
||||||
const { code, moderatorId } = createRoom();
|
try {
|
||||||
return NextResponse.json({ code, moderatorId });
|
// 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 { NextResponse } from 'next/server';
|
||||||
import { joinRoom } from '@/lib/rooms';
|
import { joinRoom } from '@/lib/rooms';
|
||||||
|
import { rateLimit, getClientIdentifier } from '@/lib/rate-limit';
|
||||||
|
import { joinRoomSchema } from '@/lib/validation';
|
||||||
|
|
||||||
export async function POST(req: Request) {
|
export async function POST(req: Request) {
|
||||||
const { code, playerName } = await req.json();
|
try {
|
||||||
const result = joinRoom(code, playerName);
|
// Rate limit: max 20 join attempts per IP per minute
|
||||||
|
const clientId = getClientIdentifier(req);
|
||||||
if (!result) {
|
const rateLimitResult = rateLimit(`join:${clientId}`, 20, 60000);
|
||||||
return NextResponse.json({ error: 'Room not found' }, { status: 404 });
|
|
||||||
|
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);
|
console.log('👋 Player left room:', code, 'Remaining players:', room?.players.size);
|
||||||
}
|
}
|
||||||
return result;
|
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