export default { async fetch(request, env) { // ================= CORS ================= if (request.method === "OPTIONS") { return new Response(null, { headers: { "Access-Control-Allow-Origin": "https://apps-lulu-ai.pages.dev", "Access-Control-Allow-Methods": "POST,OPTIONS", "Access-Control-Allow-Headers": "Content-Type", "Access-Control-Allow-Credentials": "true" } }); } // ================= METHOD CHECK ================= if (request.method !== "POST") { return new Response("Method Not Allowed", { status: 405 }); } // ================= PARSE BODY ================= let body; try { body = await request.json(); } catch { return json({ error: "Invalid JSON" }); } const { name, email, password } = body; if (!email || !password) { return json({ error: "Missing email or password" }); } // ================= CHECK EXISTING USER ================= const existing = await env.DB.prepare( "SELECT id FROM lulu_users WHERE email=?" ).bind(email).first(); if (existing) { return json({ error: "Email already exists" }); } // ================= CREATE USER ================= const hashed = await hash(password); await env.DB.prepare( "INSERT INTO lulu_users (name,email,password,tokens) VALUES (?,?,?,1000)" ).bind( name || "Teacher", email, hashed ).run(); // ================= CREATE SESSION ================= const session = crypto.randomUUID(); await env.DB.prepare( "UPDATE lulu_users SET session=? WHERE email=?" ).bind(session, email).run(); // ================= SUCCESS RESPONSE ================= return new Response( JSON.stringify({ success: true }), { headers: { "Content-Type": "application/json", "Set-Cookie": createCookie(session), "Access-Control-Allow-Origin": "https://apps-lulu-ai.pages.dev", "Access-Control-Allow-Credentials": "true" } } ); } }; // ================= HELPERS ================= function json(data) { return new Response(JSON.stringify(data), { headers: { "Content-Type": "application/json" } }); } async function hash(text) { const buf = await crypto.subtle.digest( "SHA-256", new TextEncoder().encode(text) ); return [...new Uint8Array(buf)] .map(b => b.toString(16).padStart(2, "0")) .join(""); } function createCookie(session) { return ( `lulu_session=${session}; ` + `Path=/; ` + `HttpOnly; ` + `Secure; ` + `SameSite=None; ` + `Max-Age=604800` ); }