import { NextResponse } from "next/server"; import crypto from "crypto"; import db from "@/lib/db"; function hashPassword(password: string, saltHex?: string) { const salt = saltHex ? Buffer.from(saltHex, "hex") : crypto.randomBytes(16); const hash = crypto.pbkdf2Sync(password, salt, 120_000, 32, "sha256"); return { saltHex: salt.toString("hex"), hashHex: hash.toString("hex") }; } function verifyPassword(password: string, stored: string) { const [saltHex, hashHex] = stored.split(":"); const { hashHex: check } = hashPassword(password, saltHex); return crypto.timingSafeEqual(Buffer.from(hashHex, "hex"), Buffer.from(check, "hex")); } export async function POST(req: Request) { const body = await req.json(); const { action, username, password } = body as { action: "SIGNUP" | "LOGIN" | "LOGOUT"; username?: string; password?: string; }; if (action === "LOGOUT") { const res = NextResponse.json({ success: true }); res.cookies.set("session", "", { httpOnly: true, path: "/", maxAge: 0 }); return res; } if (!username || !password) { return NextResponse.json({ error: "Missing username/password" }, { status: 400 }); } if (action === "SIGNUP") { const existing = db.prepare("SELECT id FROM users WHERE username = ?").get(username); if (existing) return NextResponse.json({ error: "Username already taken" }, { status: 400 }); const count = db.prepare("SELECT COUNT(*) as c FROM users").get() as any; const role = count.c === 0 ? "dm" : "player"; const { saltHex, hashHex } = hashPassword(password); const password_hash = `${saltHex}:${hashHex}`; const userId = db .prepare("INSERT INTO users (username, password_hash, role) VALUES (?, ?, ?)") .run(username, password_hash, role).lastInsertRowid as number; return NextResponse.json({ success: true, userId, role }); } if (action === "LOGIN") { const user = db.prepare("SELECT id, username, password_hash, role FROM users WHERE username = ?").get(username) as any; if (!user) return NextResponse.json({ error: "Invalid login" }, { status: 400 }); if (!verifyPassword(password, user.password_hash)) { return NextResponse.json({ error: "Invalid login" }, { status: 400 }); } // create session token const token = crypto.randomBytes(32).toString("hex"); const expires = new Date(Date.now() + 1000 * 60 * 60 * 24 * 14); // 14 days db.prepare("INSERT INTO sessions (token, user_id, expires_at) VALUES (?, ?, ?)") .run(token, user.id, expires.toISOString()); const res = NextResponse.json({ success: true, user: { id: user.id, username: user.username, role: user.role }, }); res.cookies.set("session", token, { httpOnly: true, sameSite: "lax", path: "/", expires, }); return res; } return NextResponse.json({ error: "Invalid action" }, { status: 400 }); }