export default { async fetch(request: Request, env: any) { const url = new URL(request.url); const resHeaders = { "Content-Type": "application/json", "Access-Control-Allow-Origin": "*" }; try { if (request.method === "OPTIONS") return new Response(null, { headers: resHeaders }); // --- 1. SEND OTP --- if (url.pathname === "/auth/send-otp" && request.method === "POST") { const { email } = await request.json() as any; if (!email) throw new Error("MISSING_EMAIL_PAYLOAD"); const code = Math.floor(100000 + Math.random() * 900000).toString(); await env.DB.prepare("DELETE FROM verification_codes WHERE email = ?").bind(email).run(); await env.DB.prepare("INSERT INTO verification_codes (email, code) VALUES (?, ?)") .bind(email, code).run(); return new Response(JSON.stringify({ success: true }), { headers: resHeaders }); } // --- 2. VERIFY OTP --- if (url.pathname === "/auth/verify-otp" && request.method === "POST") { const { email, code, password, username } = await request.json() as any; const record = await env.DB.prepare("SELECT * FROM verification_codes WHERE email = ? AND code = ? AND expires_at > datetime('now')") .bind(email, code).first(); if (!record) throw new Error("INVALID_OR_EXPIRED_OTP"); await env.DB.prepare(` INSERT INTO users (username, email, password) VALUES (?, ?, ?) ON CONFLICT(email) DO UPDATE SET password=excluded.password `).bind(username || email.split('@')[0], email, password).run(); return new Response(JSON.stringify({ success: true }), { headers: resHeaders }); } // --- 3. WORD API --- if (url.pathname === "/api/words") { const words = ["velocity", "nitrous", "redline", "clutch", "ignition", "gearbox", "turbo"]; const list = Array.from({length: 20}, () => words[Math.floor(Math.random()*words.length)]); return new Response(JSON.stringify(list), { headers: resHeaders }); } // Fallback for direct URL visits return new Response("Redline Cloud API - Active", { status: 200 }); } catch (err: any) { const errorData = { message: err.message || "Internal Server Error", stack: err.stack || "No stack trace available", time: new Date().toISOString(), path: url.pathname }; // API Error Response if (url.pathname.includes("/auth") || url.pathname.includes("/api")) { return new Response(JSON.stringify({ error: errorData.message }), { status: 500, headers: resHeaders }); } // Nextcloud-Style Error Page return new Response(renderNextcloudError(errorData), { status: 500, headers: { "Content-Type": "text/html" } }); } } } function renderNextcloudError(err: any) { return ` Internal Server Error - Redline Cloud

Internal Server Error

The server was unable to complete your request. If this happens again, please provide the technical details below to your administrator.

Back to Redline Cloud
Request ID: ${err.time.replace(/[^0-9]/g, '').slice(-10)} Error Message: ${err.message} Path: ${err.path} Timestamp: ${err.time}
Stack Trace: ${err.stack}
`; }