- scripts/build/build-docs.mjs:固定 @scalar/api-reference@1.25.101, 下载后按 SHA-256 校验,生成 src/packaging/generated/ scalar-standalone.js.txt(2.7 MiB,随 git 提交)。 - embedded-docs.ts 用 with { type: text } 内嵌;后缀 .txt 避开 Bun 对 .js / .html 的非字符串类型推断。 - renderDocsHtml() 把 script src 从 cdn.jsdelivr.net 换成 /static/scalar.js;routes.ts 新增该路由返回内嵌 JS 并带 24h 缓存。 保留原 <script id="api-reference"> 结构,Scalar 定位逻辑不变。 - 加 CSP(connect-src 'self' 等):Scalar 内置的「加载示例规范」 分支会 fetch jsdelivr 的 galaxy.yaml,本页 data-url 指向本地 /openapi.json 不走该分支,CSP 再兜底确保任何情况下无外网请求。 - 新增 docs.test.ts 3 例;更新 README、packaging README、 build README;package.json 加 docs:fetch 脚本。 二进制体积 +2.9 MB(67.5 → 70.4 MB)。 校验:bun test 1114 pass / 0 fail,check、check:readme 36/36; 编译产物实测 GET /docs 200 且零 CDN,GET /static/scalar.js 200 / application/javascript / 2685520 字节且 SHA-256 与生成物一致, /openapi.json 200。 本次只合入 main,不打 tag、不发版。
285 lines
9.3 KiB
TypeScript
285 lines
9.3 KiB
TypeScript
import type { IncomingMessage, ServerResponse } from "node:http";
|
|
import { URL } from "node:url";
|
|
import { runCli } from "../cli/runner.js";
|
|
import { runAiProCli } from "../aipro-cli.js";
|
|
import { loadCorpConfigs, loadGlobalConfig } from "../core/config/loader.js";
|
|
import { getOpenApiSchema } from "../packaging/embedded-openapi.js";
|
|
import { getAiProWebUiHtml } from "../packaging/embedded-webui.js";
|
|
import { getScalarStandaloneJs } from "../packaging/embedded-docs.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,
|
|
options: { app?: "hose-use" | "hose-aipro" } = {}
|
|
): Promise<void> {
|
|
const isAiPro = options.app === "hose-aipro";
|
|
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,
|
|
isAiPro
|
|
? {
|
|
name: "hose-aipro",
|
|
version: VERSION,
|
|
description: "合思 AI PRO 确定性审批仲裁网关 HTTP 服务",
|
|
health: "/health",
|
|
endpoints: {
|
|
cli: "POST /api/cli",
|
|
status: "GET /v1/status",
|
|
},
|
|
}
|
|
: {
|
|
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: isAiPro ? "hose-aipro" : "hose-use",
|
|
version: VERSION,
|
|
timestamp: new Date().toISOString(),
|
|
});
|
|
return;
|
|
}
|
|
|
|
if (isAiPro && method === "GET" && pathname === "/v1/status") {
|
|
const statusRes = await runAiProCli(["status", "--json"]);
|
|
let parsedData: any = {};
|
|
try {
|
|
parsedData = JSON.parse(statusRes.stdout);
|
|
} catch {
|
|
parsedData = { stdout: statusRes.stdout };
|
|
}
|
|
sendJson(res, 200, parsedData);
|
|
return;
|
|
}
|
|
|
|
// AI PRO 本地 Web 控制台:单文件内嵌,仅监听 127.0.0.1
|
|
if (isAiPro && method === "GET" && (pathname === "/report" || pathname.startsWith("/report/"))) {
|
|
sendHtml(res, 200, getAiProWebUiHtml());
|
|
return;
|
|
}
|
|
|
|
// /docs 的 Scalar 运行时由本地提供,彻底去掉 CDN 依赖
|
|
if (method === "GET" && pathname === "/static/scalar.js") {
|
|
sendJavascript(res, 200, getScalarStandaloneJs());
|
|
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 = isAiPro ? await runAiProCli(cliArgs) : 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 sendJavascript(res: ServerResponse, status: number, source: string): void {
|
|
if (res.headersSent) return;
|
|
res.writeHead(status, {
|
|
"Content-Type": "application/javascript; charset=utf-8",
|
|
"Content-Length": Buffer.byteLength(source, "utf-8"),
|
|
"Cache-Control": "public, max-age=86400",
|
|
});
|
|
res.end(source);
|
|
}
|
|
|
|
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);
|
|
});
|
|
});
|
|
}
|