Files
hose-use/src/http/routes.ts
T

228 lines
7.3 KiB
TypeScript

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 "../packaging/embedded-openapi.js";
import { tokenizeCommand, normalizeCliArgs } from "../server.js";
import { VERSION } from "../version.js";
import { renderDocsHtml } from "./docs.js";
export function isTrustedOrigin(originHeader: string | undefined): boolean {
if (!originHeader) return true; // non-browser / same-origin requests without Origin header
const allowedOriginEnv = process.env.HOSE_HTTP_CORS_ORIGIN?.trim();
if (allowedOriginEnv === "*") return true;
if (allowedOriginEnv && originHeader === allowedOriginEnv) return true;
try {
const parsed = new URL(originHeader);
const host = parsed.hostname.toLowerCase();
return host === "127.0.0.1" || host === "localhost" || host === "::1" || host === "[::1]";
} catch {
return false;
}
}
function checkHttpAuth(req: IncomingMessage): boolean {
const requiredToken = process.env.HOSE_HTTP_TOKEN?.trim();
if (!requiredToken) return true;
const authHeader = req.headers.authorization || "";
return authHeader === `Bearer ${requiredToken}`;
}
export async function handleHttpRequest(req: IncomingMessage, res: ServerResponse): Promise<void> {
const origin = typeof req.headers.origin === "string" ? req.headers.origin : undefined;
const trustedOrigin = isTrustedOrigin(origin);
// 1. CORS headers: only grant CORS to local/trusted origins instead of blind wildcard RCE
if (trustedOrigin) {
res.setHeader("Access-Control-Allow-Origin", origin || "http://127.0.0.1");
res.setHeader("Vary", "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") {
if (!trustedOrigin) {
sendError(res, 403, "Forbidden cross-origin preflight request");
return;
}
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") {
if (!trustedOrigin) {
sendError(res, 403, "Forbidden: untrusted cross-origin request to /api/cli");
return;
}
if (!checkHttpAuth(req)) {
sendError(res, 401, "Unauthorized: valid Bearer token required");
return;
}
const body = (await parseJsonBody(req)) as Record<string, unknown> | 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") {
if (!trustedOrigin) {
sendError(res, 403, "Forbidden: untrusted cross-origin request to /v1/corps");
return;
}
if (!checkHttpAuth(req)) {
sendError(res, 401, "Unauthorized: valid Bearer token required");
return;
}
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<unknown> {
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);
});
});
}