445 lines
15 KiB
TypeScript
445 lines
15 KiB
TypeScript
import type { IncomingMessage, ServerResponse } from "node:http";
|
|
import { URL } from "node:url";
|
|
import type { KyInstance } from "ky";
|
|
import { selectCorp } from "../cli/helpers.js";
|
|
import { runCli } from "../cli/runner.js";
|
|
import type { CorpConfig } from "../core/config/types.js";
|
|
import { getOpenApiSchema } from "../core/embedded-openapi.js";
|
|
import { loadCorpConfigs, loadGlobalConfig } from "../core/config/loader.js";
|
|
import { createSealClient } from "../core/http/factory.js";
|
|
import { findSealTool, sealTools, type SealTool } from "../domains/seal/tools.js";
|
|
import { tokenizeCommand } from "../server.js";
|
|
import { VERSION } from "../version.js";
|
|
import { renderDocsHtml } from "./docs.js";
|
|
|
|
async function executeSealTool(tool: SealTool, client: KyInstance, params: any, corp: CorpConfig): Promise<unknown> {
|
|
const handler = tool.handler as (client: KyInstance, params: any, context: { corp: CorpConfig }) => Promise<unknown>;
|
|
return handler(client, params, { corp });
|
|
}
|
|
|
|
export async function handleHttpRequest(req: IncomingMessage, res: ServerResponse) {
|
|
// 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-Seal-Corp, X-Seal-Home-Session");
|
|
|
|
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. Documentation & Metadata
|
|
if (method === "GET" && pathname === "/") {
|
|
sendJson(res, 200, {
|
|
name: "seal-use",
|
|
version: VERSION,
|
|
description: "Seal tenant operations and approval automation HTTP API",
|
|
docs: "/docs",
|
|
openapi: "/openapi.json",
|
|
health: "/health",
|
|
endpoints: {
|
|
cli: "POST /api/cli",
|
|
tools: "GET /api/tools",
|
|
toolInvoke: "POST /api/tool/:name",
|
|
restV1: "GET/POST /v1/*"
|
|
}
|
|
});
|
|
return;
|
|
}
|
|
|
|
if (method === "GET" && pathname === "/docs") {
|
|
sendHtml(res, 200, renderDocsHtml());
|
|
return;
|
|
}
|
|
|
|
if (method === "GET" && pathname === "/openapi.json") {
|
|
sendJson(res, 200, getOpenApiSchema());
|
|
return;
|
|
}
|
|
|
|
if (method === "GET" && pathname === "/health") {
|
|
sendJson(res, 200, {
|
|
status: "ok",
|
|
version: VERSION,
|
|
name: "seal-use",
|
|
timestamp: new Date().toISOString()
|
|
});
|
|
return;
|
|
}
|
|
|
|
// 3. Command Execution Endpoint: POST /api/cli
|
|
if (method === "POST" && pathname === "/api/cli") {
|
|
const body = await parseJsonBody(req);
|
|
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 = tokens[0] === "seal-use" || tokens[0] === "seal-home" || tokens[0]?.endsWith("/seal-use") || tokens[0]?.endsWith("/seal-home")
|
|
? tokens.slice(1)
|
|
: tokens;
|
|
const result = await runCli(cliArgs);
|
|
|
|
let parsedData: unknown = undefined;
|
|
try {
|
|
if (result.stdout.trim().startsWith("{") || result.stdout.trim().startsWith("[")) {
|
|
parsedData = JSON.parse(result.stdout);
|
|
}
|
|
} catch {
|
|
// keep string
|
|
}
|
|
|
|
sendJson(res, result.isError ? 400 : 200, {
|
|
success: !result.isError,
|
|
stdout: result.stdout,
|
|
stderr: result.stderr,
|
|
exitCode: result.exitCode,
|
|
data: parsedData
|
|
});
|
|
return;
|
|
}
|
|
|
|
// 5. Generic Tool Invocation endpoint (POST /api/tool/:name)
|
|
if (method === "POST" && pathname.startsWith("/api/tool/")) {
|
|
const toolName = pathname.slice("/api/tool/".length).trim();
|
|
const tool = findSealTool(toolName, { includeMcpAliases: true });
|
|
if (!tool) {
|
|
sendError(res, 404, `Tool not found: '${toolName}'`);
|
|
return;
|
|
}
|
|
|
|
const body = (await parseJsonBody(req)) || {};
|
|
const corpId = extractCorpId(req, url, body);
|
|
const corp = selectCorp(corpId);
|
|
const client = await createSealClient(corp);
|
|
|
|
const params = { ...body };
|
|
delete params.corp;
|
|
|
|
const output = await executeSealTool(tool, client, params, corp);
|
|
sendJson(res, 200, output);
|
|
return;
|
|
}
|
|
|
|
// 6. RESTful /v1/* endpoints mapped from OpenAPI
|
|
if (pathname.startsWith("/v1/")) {
|
|
const handled = await handleRestV1(req, res, method, pathname, url);
|
|
if (handled) 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);
|
|
}
|
|
}
|
|
|
|
async function handleRestV1(
|
|
req: IncomingMessage,
|
|
res: ServerResponse,
|
|
method: string,
|
|
pathname: string,
|
|
url: URL
|
|
): Promise<boolean> {
|
|
const queryParams = Object.fromEntries(url.searchParams.entries());
|
|
|
|
// 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,
|
|
sourceType: c.source.type,
|
|
sealUrl: c.seal?.url
|
|
}))
|
|
});
|
|
return true;
|
|
}
|
|
|
|
// GET /v1/whoami
|
|
if (method === "GET" && pathname === "/v1/whoami") {
|
|
const corpId = extractCorpId(req, url, queryParams);
|
|
const corp = selectCorp(corpId);
|
|
const client = await createSealClient(corp);
|
|
const tool = findSealTool("seal_whoami")!;
|
|
const data = await executeSealTool(tool, client, {}, corp);
|
|
sendJson(res, 200, data);
|
|
return true;
|
|
}
|
|
|
|
// GET /v1/session
|
|
if (method === "GET" && pathname === "/v1/session") {
|
|
const corpId = extractCorpId(req, url, queryParams);
|
|
const corp = selectCorp(corpId);
|
|
const client = await createSealClient(corp);
|
|
const tool = findSealTool("seal_session_get")!;
|
|
const data = await executeSealTool(tool, client, {}, corp);
|
|
sendJson(res, 200, data);
|
|
return true;
|
|
}
|
|
|
|
// GET /v1/approval-runs/summary
|
|
if (method === "GET" && pathname === "/v1/approval-runs/summary") {
|
|
const corpId = extractCorpId(req, url, queryParams);
|
|
const corp = selectCorp(corpId);
|
|
const client = await createSealClient(corp);
|
|
const tool = findSealTool("seal_approval_runs_summary")!;
|
|
const data = await executeSealTool(tool, client, queryParams, corp);
|
|
sendJson(res, 200, data);
|
|
return true;
|
|
}
|
|
|
|
// GET /v1/approval-runs/stats
|
|
if (method === "GET" && pathname === "/v1/approval-runs/stats") {
|
|
const corpId = extractCorpId(req, url, queryParams);
|
|
const corp = selectCorp(corpId);
|
|
const client = await createSealClient(corp);
|
|
const tool = findSealTool("seal_approval_runs_stats")!;
|
|
const data = await executeSealTool(tool, client, queryParams, corp);
|
|
sendJson(res, 200, data);
|
|
return true;
|
|
}
|
|
|
|
// GET /v1/approval-runs/pick
|
|
if (method === "GET" && pathname === "/v1/approval-runs/pick") {
|
|
const corpId = extractCorpId(req, url, queryParams);
|
|
const corp = selectCorp(corpId);
|
|
const client = await createSealClient(corp);
|
|
const tool = findSealTool("seal_approval_run_pick")!;
|
|
const data = await executeSealTool(tool, client, queryParams, corp);
|
|
sendJson(res, 200, data);
|
|
return true;
|
|
}
|
|
|
|
// GET /v1/approval-runs/url
|
|
if (method === "GET" && pathname === "/v1/approval-runs/url") {
|
|
const corpId = extractCorpId(req, url, queryParams);
|
|
const corp = selectCorp(corpId);
|
|
const client = await createSealClient(corp);
|
|
const tool = findSealTool("seal_approval_run_url_get")!;
|
|
const data = await executeSealTool(tool, client, queryParams, corp);
|
|
sendJson(res, 200, data);
|
|
return true;
|
|
}
|
|
|
|
// GET /v1/approval-runs/:recordId/*
|
|
if (pathname.startsWith("/v1/approval-runs/")) {
|
|
const parts = pathname.slice("/v1/approval-runs/".length).split("/");
|
|
const recordId = parts[0];
|
|
const sub = parts[1];
|
|
|
|
if (recordId && !["summary", "pick", "stats", "url", "bridge"].includes(recordId)) {
|
|
const corpId = extractCorpId(req, url, queryParams);
|
|
const corp = selectCorp(corpId);
|
|
const client = await createSealClient(corp);
|
|
|
|
if (!sub) {
|
|
const tool = findSealTool("seal_approval_run_get")!;
|
|
const data = await executeSealTool(tool, client, { recordId, ...queryParams }, corp);
|
|
sendJson(res, 200, data);
|
|
return true;
|
|
}
|
|
if (sub === "attachments") {
|
|
const tool = findSealTool("seal_approval_run_attachments_get")!;
|
|
const data = await executeSealTool(tool, client, { recordId, ...queryParams }, corp);
|
|
sendJson(res, 200, data);
|
|
return true;
|
|
}
|
|
if (sub === "cited-rules") {
|
|
const tool = findSealTool("seal_approval_run_cited_rules_get")!;
|
|
const data = await executeSealTool(tool, client, { recordId, ...queryParams }, corp);
|
|
sendJson(res, 200, data);
|
|
return true;
|
|
}
|
|
if (sub === "document-summary") {
|
|
const tool = findSealTool("seal_approval_run_document_summary_get")!;
|
|
const data = await executeSealTool(tool, client, { recordId, ...queryParams }, corp);
|
|
sendJson(res, 200, data);
|
|
return true;
|
|
}
|
|
if (sub === "result") {
|
|
const tool = findSealTool("seal_approval_run_result_get")!;
|
|
const data = await executeSealTool(tool, client, { recordId, ...queryParams }, corp);
|
|
sendJson(res, 200, data);
|
|
return true;
|
|
}
|
|
}
|
|
}
|
|
|
|
// GET /v1/approval-runs
|
|
if (method === "GET" && pathname === "/v1/approval-runs") {
|
|
const corpId = extractCorpId(req, url, queryParams);
|
|
const corp = selectCorp(corpId);
|
|
const client = await createSealClient(corp);
|
|
const tool = findSealTool("seal_approval_runs_search")!;
|
|
const data = await executeSealTool(
|
|
tool,
|
|
client,
|
|
{
|
|
...queryParams,
|
|
limit: queryParams.limit ? Number(queryParams.limit) : undefined,
|
|
offset: queryParams.offset ? Number(queryParams.offset) : undefined,
|
|
includeBridge: queryParams.includeBridge === "true"
|
|
},
|
|
corp
|
|
);
|
|
sendJson(res, 200, data);
|
|
return true;
|
|
}
|
|
|
|
// GET /v1/approval/rules
|
|
if (method === "GET" && pathname === "/v1/approval/rules") {
|
|
const corpId = extractCorpId(req, url, queryParams);
|
|
const corp = selectCorp(corpId);
|
|
const client = await createSealClient(corp);
|
|
const tool = findSealTool("seal_approval_rules_list")!;
|
|
const data = await executeSealTool(tool, client, queryParams, corp);
|
|
sendJson(res, 200, data);
|
|
return true;
|
|
}
|
|
|
|
// GET /v1/simulation/batches
|
|
if (method === "GET" && pathname === "/v1/simulation/batches") {
|
|
const corpId = extractCorpId(req, url, queryParams);
|
|
const corp = selectCorp(corpId);
|
|
const client = await createSealClient(corp);
|
|
const tool = findSealTool("seal_simulation_batches_list")!;
|
|
const data = await executeSealTool(tool, client, queryParams, corp);
|
|
sendJson(res, 200, data);
|
|
return true;
|
|
}
|
|
|
|
// POST /v1/simulation/create-batch
|
|
if (method === "POST" && pathname === "/v1/simulation/create-batch") {
|
|
const body = (await parseJsonBody(req)) || {};
|
|
const corpId = extractCorpId(req, url, body);
|
|
const corp = selectCorp(corpId);
|
|
const client = await createSealClient(corp);
|
|
const tool = findSealTool("seal_simulation_batch_create")!;
|
|
const data = await executeSealTool(tool, client, body, corp);
|
|
sendJson(res, 200, data);
|
|
return true;
|
|
}
|
|
|
|
// GET /v1/simulation/batch/:batchId
|
|
if (method === "GET" && pathname.startsWith("/v1/simulation/batch/")) {
|
|
const parts = pathname.slice("/v1/simulation/batch/".length).split("/");
|
|
const batchId = parts[0];
|
|
if (batchId) {
|
|
const corpId = extractCorpId(req, url, queryParams);
|
|
const corp = selectCorp(corpId);
|
|
const client = await createSealClient(corp);
|
|
const tool = findSealTool("seal_simulation_batch_get")!;
|
|
const data = await executeSealTool(tool, client, { batchId }, corp);
|
|
sendJson(res, 200, data);
|
|
return true;
|
|
}
|
|
}
|
|
|
|
// GET /v1/preferences
|
|
if (method === "GET" && pathname === "/v1/preferences") {
|
|
const corpId = extractCorpId(req, url, queryParams);
|
|
const corp = selectCorp(corpId);
|
|
const client = await createSealClient(corp);
|
|
const tool = findSealTool("seal_preference_get")!;
|
|
const data = await executeSealTool(tool, client, {}, corp);
|
|
sendJson(res, 200, data);
|
|
return true;
|
|
}
|
|
|
|
// POST /v1/preferences/decision
|
|
if (method === "POST" && pathname === "/v1/preferences/decision") {
|
|
const body = (await parseJsonBody(req)) || {};
|
|
const corpId = extractCorpId(req, url, body);
|
|
const corp = selectCorp(corpId);
|
|
const client = await createSealClient(corp);
|
|
const tool = findSealTool("seal_preference_decision_update")!;
|
|
const data = await executeSealTool(tool, client, body, corp);
|
|
sendJson(res, 200, data);
|
|
return true;
|
|
}
|
|
|
|
return false;
|
|
}
|
|
|
|
export function extractCorpId(
|
|
req: IncomingMessage,
|
|
url: URL,
|
|
body?: Record<string, unknown>
|
|
): string | undefined {
|
|
const header = req.headers["x-seal-corp"];
|
|
if (typeof header === "string" && header.trim()) return header.trim();
|
|
const query = url.searchParams.get("corp");
|
|
if (query?.trim()) return query.trim();
|
|
if (body && typeof body.corp === "string" && body.corp.trim()) {
|
|
return body.corp.trim();
|
|
}
|
|
return undefined;
|
|
}
|
|
|
|
export async function parseJsonBody(req: IncomingMessage): Promise<Record<string, unknown>> {
|
|
return new Promise((resolve, reject) => {
|
|
let raw = "";
|
|
req.on("data", (chunk) => {
|
|
raw += chunk;
|
|
if (raw.length > 20 * 1024 * 1024) {
|
|
// 20MB limit
|
|
reject(new Error("Payload too large"));
|
|
}
|
|
});
|
|
req.on("end", () => {
|
|
if (!raw.trim()) {
|
|
resolve({});
|
|
return;
|
|
}
|
|
try {
|
|
resolve(JSON.parse(raw));
|
|
} catch (err) {
|
|
reject(new Error(`Invalid JSON body: ${err instanceof Error ? err.message : String(err)}`));
|
|
}
|
|
});
|
|
req.on("error", reject);
|
|
});
|
|
}
|
|
|
|
export function sendJson(res: ServerResponse, statusCode: number, data: unknown) {
|
|
const json = JSON.stringify(data, null, 2);
|
|
res.writeHead(statusCode, {
|
|
"Content-Type": "application/json; charset=utf-8",
|
|
"Content-Length": Buffer.byteLength(json)
|
|
});
|
|
res.end(json);
|
|
}
|
|
|
|
export function sendHtml(res: ServerResponse, statusCode: number, html: string) {
|
|
res.writeHead(statusCode, {
|
|
"Content-Type": "text/html; charset=utf-8",
|
|
"Content-Length": Buffer.byteLength(html)
|
|
});
|
|
res.end(html);
|
|
}
|
|
|
|
export function sendError(res: ServerResponse, statusCode: number, message: string, details?: unknown) {
|
|
sendJson(res, statusCode, {
|
|
error: true,
|
|
statusCode,
|
|
message,
|
|
...(details !== undefined ? { details } : {})
|
|
});
|
|
}
|