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 { formatBeijingIso } from "../core/config/timestamps.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, parseToolParams, type SealTool } from "../domains/seal/tools.js"; import { tokenizeCommand } from "../cli/tokenize.js"; import { redactSensitiveText } from "../core/redact.js"; import { CliError, type CliExitCode } from "../core/errors.js"; import { VERSION } from "../version.js"; import { renderDocsHtml } from "./docs.js"; async function executeSealTool(tool: SealTool, client: KyInstance, params: any, corp: CorpConfig): Promise { // Schema gate for every HTTP caller: a missing required field or bad value // is a client error (400), not an upstream failure discovered mid-handler. parseToolParams(tool, params); const handler = tool.handler as (client: KyInstance, params: any, context: { corp: CorpConfig }) => Promise; return handler(client, params, { corp }); } /** Maps a structured CLI exit code to the HTTP status it means for a caller. */ export function httpStatusForCliExit(exitCode: CliExitCode): number { switch (exitCode) { case 11: return 401; case 12: return 413; case 10: case 14: return 403; case 2: case 13: return 400; default: return 500; } } 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"); // Mirrors the headers this adapter actually consults: `X-Seal-Corp` selects // the enterprise (`extractCorpId`), `Authorization` is kept because generic // clients attach it by default. The historic `X-Seal-Home-Session` is gone — // no handler ever read it, and the adapter has no session to authenticate // (openapi's info.description states that plainly). res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Seal-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. 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: formatBeijingIso() }); return; } if (method === "POST" && (pathname === "/shutdown" || pathname === "/api/shutdown")) { sendJson(res, 200, { success: true, message: "Shutting down seal-use background daemon", pid: process.pid }); setTimeout(() => { process.kill(process.pid, "SIGTERM"); }, 50); 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); if (!tool) { sendError(res, 404, `Tool not found: '${toolName}'`); return; } const body = (await parseJsonBody(req)) || {}; const params = { ...body }; delete params.corp; // Fail fast before `selectCorp`, which records usage stats to disk: a // request that can never succeed should cause no writes. `executeSealTool` // performs the same check afterwards — the early call exists purely to // win this ordering, not to duplicate the guarantee. parseToolParams(tool, params); const corpId = extractCorpId(req, url, body); const corp = selectCorp(corpId); const client = await createSealClient(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); // A structured CLI error names the caller's mistake (bad params, missing // auth, output too large); pass it through as the matching 4xx instead of // letting every failure look like an adapter crash. sendError(res, err instanceof CliError ? httpStatusForCliExit(err.exitCode) : 500, message); } } async function handleRestV1( req: IncomingMessage, res: ServerResponse, method: string, pathname: string, url: URL ): Promise { 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 | 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> { let raw = ""; for await (const chunk of req) { raw += chunk; if (raw.length > 20 * 1024 * 1024) { throw new Error("Payload too large"); } } if (!raw.trim()) return {}; try { return JSON.parse(raw); } catch (err) { throw new Error(`Invalid JSON body: ${err instanceof Error ? err.message : String(err)}`); } } 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: redactSensitiveText(message), ...(details !== undefined ? { details } : {}) }); }