"use strict"; const http = require("node:http"); const fs = require("node:fs"); const path = require("node:path"); const PORT = 8080; const PUBLIC_DIR = path.join(__dirname, "public"); const MAX_BODY_BYTES = 64 * 1024; const MAX_MESSAGES = 20; const MAX_MESSAGE_LENGTH = 8000; const REQUEST_TIMEOUT_MS = 60_000; const securityHeaders = { "Content-Security-Policy": "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'", "X-Content-Type-Options": "nosniff", "X-Frame-Options": "DENY", "Referrer-Policy": "no-referrer", }; function sendJson(res, statusCode, value) { res.writeHead(statusCode, { ...securityHeaders, "Cache-Control": "no-store", "Content-Type": "application/json; charset=utf-8", }); res.end(JSON.stringify(value)); } function readJson(req) { return new Promise((resolve, reject) => { let body = ""; let tooLarge = false; req.setEncoding("utf8"); req.on("data", (chunk) => { if (tooLarge) return; body += chunk; if (Buffer.byteLength(body, "utf8") > MAX_BODY_BYTES) { tooLarge = true; } }); req.on("end", () => { if (tooLarge) { reject(Object.assign(new Error("Request body too large"), { statusCode: 413 })); return; } try { resolve(JSON.parse(body)); } catch { reject(Object.assign(new Error("Invalid JSON"), { statusCode: 400 })); } }); req.on("error", () => { reject(Object.assign(new Error("Unable to read request"), { statusCode: 400 })); }); }); } function validateMessages(value) { if (!value || !Array.isArray(value.messages)) { return "Cần gửi danh sách messages."; } if (value.messages.length === 0 || value.messages.length > MAX_MESSAGES) { return `Cuộc trò chuyện cần có từ 1 đến ${MAX_MESSAGES} tin nhắn.`; } for (const message of value.messages) { if ( !message || !["user", "assistant"].includes(message.role) || typeof message.content !== "string" || message.content.trim().length === 0 || message.content.length > MAX_MESSAGE_LENGTH ) { return "Tin nhắn không hợp lệ hoặc vượt quá giới hạn độ dài."; } } if (value.messages.at(-1).role !== "user") { return "Tin nhắn cuối cùng phải là câu hỏi của bạn."; } return null; } function extractText(response) { if (typeof response.output_text === "string" && response.output_text.trim()) { return response.output_text.trim(); } const parts = []; for (const item of response.output || []) { if (item.type !== "message" || !Array.isArray(item.content)) continue; for (const content of item.content) { if (content.type === "output_text" && typeof content.text === "string") { parts.push(content.text); } } } return parts.join("\n").trim(); } async function handleChat(req, res) { const model = process.env.MODEL?.trim(); const apiKey = process.env.API_KEY?.trim(); if (!model || !apiKey) { sendJson(res, 503, { error: "Chưa cấu hình MODEL hoặc API_KEY cho container.", }); return; } let payload; try { payload = await readJson(req); } catch (error) { sendJson(res, error.statusCode || 400, { error: error.message }); return; } const validationError = validateMessages(payload); if (validationError) { sendJson(res, 400, { error: validationError }); return; } let upstream; try { upstream = await fetch("https://api.openai.com/v1/responses", { method: "POST", headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json", }, body: JSON.stringify({ model, input: payload.messages.map(({ role, content }) => ({ role, content })), store: false, }), signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS), }); } catch (error) { if (error.name === "AbortError" || error.name === "TimeoutError") { sendJson(res, 504, { error: "OpenAI phản hồi quá thời gian chờ. Hãy thử lại." }); } else { sendJson(res, 502, { error: "Không thể kết nối tới OpenAI." }); } return; } if (!upstream.ok) { if (upstream.status === 401 || upstream.status === 403) { sendJson(res, 502, { error: "OpenAI từ chối yêu cầu. Hãy kiểm tra API_KEY và quyền truy cập model." }); } else if (upstream.status === 429) { sendJson(res, 502, { error: "OpenAI đang giới hạn yêu cầu hoặc hết quota. Hãy kiểm tra billing và thử lại." }); } else { sendJson(res, 502, { error: `OpenAI không xử lý được yêu cầu (HTTP ${upstream.status}).` }); } return; } let result; try { result = await upstream.json(); } catch { sendJson(res, 502, { error: "OpenAI trả về dữ liệu không hợp lệ." }); return; } const text = extractText(result); if (!text) { sendJson(res, 502, { error: "Model không trả về nội dung văn bản." }); return; } sendJson(res, 200, { text }); } function serveStatic(res, fileName, contentType) { const filePath = path.join(PUBLIC_DIR, fileName); fs.readFile(filePath, (error, contents) => { if (error) { sendJson(res, 500, { error: "Không thể tải giao diện." }); return; } res.writeHead(200, { ...securityHeaders, "Cache-Control": "no-cache", "Content-Type": contentType, }); res.end(contents); }); } const server = http.createServer((req, res) => { const requestUrl = new URL(req.url, "http://localhost"); if (req.method === "GET" && requestUrl.pathname === "/health") { sendJson(res, 200, { status: "ok" }); return; } if (req.method === "GET" && requestUrl.pathname === "/") { serveStatic(res, "index.html", "text/html; charset=utf-8"); return; } if (req.method === "GET" && requestUrl.pathname === "/app.js") { serveStatic(res, "app.js", "text/javascript; charset=utf-8"); return; } if (req.method === "GET" && requestUrl.pathname === "/styles.css") { serveStatic(res, "styles.css", "text/css; charset=utf-8"); return; } if (req.method === "POST" && requestUrl.pathname === "/api/chat") { void handleChat(req, res); return; } sendJson(res, 404, { error: "Không tìm thấy đường dẫn." }); }); server.listen(PORT, "0.0.0.0", () => { process.stdout.write(`OpenAI chat demo listening on port ${PORT}\n`); }); for (const signal of ["SIGINT", "SIGTERM"]) { process.on(signal, () => server.close(() => process.exit(0))); }