import type { IncomingMessage, ServerResponse } from "node:http"; import { URL } from "node:url"; import { runCli } from "../cli/runner.js"; import { loadCorpConfigs, loadGlobalConfig } from "../core/config/loader.js"; import { getOpenApiSchema } from "../core/embedded-openapi.js"; import { tokenizeCommand, normalizeCliArgs } from "../server.js"; import { VERSION } from "../version.js"; import { renderDocsHtml } from "./docs.js"; export async function handleHttpRequest(req: IncomingMessage, res: ServerResponse): Promise { // 1. CORS headers res.setHeader("Access-Control-Allow-Origin", "*"); res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, PATCH"); res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Hose-Corp"); if (req.method === "OPTIONS") { res.writeHead(204); res.end(); return; } const host = req.headers.host || "localhost"; const protocol = req.headers["x-forwarded-proto"] || "http"; const url = new URL(req.url || "/", `${protocol}://${host}`); const pathname = url.pathname.replace(/\/+$/, "") || "/"; const method = (req.method || "GET").toUpperCase(); try { // 2. Metadata & Health if (method === "GET" && pathname === "/") { sendJson(res, 200, { name: "hose-use", version: VERSION, description: "合思/易快报企业级 CLI 工具与底层 SDK HTTP 服务", docs: "/docs", openapi: "/openapi.json", rawOpenapi: "/raw-openapi.json", health: "/health", endpoints: { cli: "POST /api/cli", corps: "GET /v1/corps", }, }); return; } if (method === "GET" && pathname === "/health") { sendJson(res, 200, { status: "ok", name: "hose-use", version: VERSION, timestamp: new Date().toISOString(), }); return; } if (method === "GET" && pathname === "/docs") { sendHtml(res, 200, renderDocsHtml()); return; } if (method === "GET" && pathname === "/openapi.json") { sendJson(res, 200, getOpenApiSchema("wrapped")); return; } if (method === "GET" && pathname === "/raw-openapi.json") { sendJson(res, 200, getOpenApiSchema("raw")); return; } // 3. Command Execution Endpoint: POST /api/cli if (method === "POST" && pathname === "/api/cli") { const body = (await parseJsonBody(req)) as Record | null; const command = (typeof body?.command === "string" ? body.command : "").trim(); if (!command) { sendError(res, 400, "Missing 'command' property in request body"); return; } const tokens = tokenizeCommand(command); const cliArgs = normalizeCliArgs(tokens); const result = await runCli(cliArgs); let parsedData: unknown = undefined; const trimmedStdout = result.stdout.trim(); try { if (trimmedStdout.startsWith("{") || trimmedStdout.startsWith("[")) { parsedData = JSON.parse(trimmedStdout); } } catch { // keep string } sendJson(res, result.exitCode === 0 ? 200 : 400, { success: result.exitCode === 0, stdout: result.stdout, stderr: result.stderr, exitCode: result.exitCode, ...(parsedData !== undefined ? { data: parsedData } : {}), }); return; } // 4. RESTful: GET /v1/corps if (method === "GET" && pathname === "/v1/corps") { const configs = loadCorpConfigs(); const globalConfig = loadGlobalConfig(); sendJson(res, 200, { count: configs.length, mode: globalConfig.stateful ? "stateful" : "stateless", defaultCorpId: globalConfig.defaultCorpId, corps: configs.map((c) => ({ id: c.id, name: c.name, source: c.source, staffId: c.credentials.staffId, baseUrl: c.baseUrl, expiresAt: c.auth?.expiresAt || c.session?.expTime, })), }); return; } sendError(res, 404, `Cannot ${method} ${pathname}. Visit /docs for available endpoints.`); } catch (err: unknown) { const message = err instanceof Error ? err.message : String(err); sendError(res, 500, message); } } function sendJson(res: ServerResponse, status: number, data: unknown): void { if (res.headersSent) return; const payload = JSON.stringify(data, null, 2); res.writeHead(status, { "Content-Type": "application/json; charset=utf-8", "Content-Length": Buffer.byteLength(payload, "utf-8"), }); res.end(payload); } function sendHtml(res: ServerResponse, status: number, html: string): void { if (res.headersSent) return; res.writeHead(status, { "Content-Type": "text/html; charset=utf-8", "Content-Length": Buffer.byteLength(html, "utf-8"), }); res.end(html); } function sendError(res: ServerResponse, status: number, message: string): void { sendJson(res, status, { error: true, message }); } async function parseJsonBody(req: IncomingMessage): Promise { return new Promise((resolve, reject) => { let raw = ""; req.on("data", (chunk) => { raw += chunk; if (raw.length > 5 * 1024 * 1024) { // 5MB max payload reject(new Error("Request payload too large (max 5MB)")); } }); req.on("end", () => { if (!raw.trim()) { resolve(null); return; } try { resolve(JSON.parse(raw)); } catch (err) { reject(new Error(`Invalid JSON body: ${err instanceof Error ? err.message : String(err)}`)); } }); req.on("error", (err) => { reject(err); }); }); }