Remove the local HTTP adapter, service daemon, and OpenAPI contract

This commit is contained in:
gitea committed 2026-09-30 15:24:19 +08:00
1 parent 560e185bc0
commit 54895e5095
42 files changed
+61 -8602

No files matched your search

-9
View File
@@ -196,15 +196,6 @@ describe("CLI version & help handling", () => {
expect(parsed.fileCount).toBeGreaterThan(5);
});
test("openapi command outputs embedded OpenAPI specification", () => {
const result = runCli(["openapi"]);
expect(result.status).toBe(0);
const parsed = JSON.parse(result.stdout.trim());
expect(parsed.openapi).toBe("3.1.0");
expect(parsed.info.title).toContain("seal-use");
expect(parsed.paths).toHaveProperty("/v1/corps");
});
test("update check subcommand outputs structured check payload", () => {
const result = runCli(["update", "check"]);
expect(result.status).toBe(0);
-23
View File
@@ -1,23 +0,0 @@
import { numberOption, stringOption } from "../parser.js";
import type { ParsedArgs } from "../types.js";
import { startHttpServer } from "../../http/server.js";
export async function handleHttpCommand(args: ParsedArgs) {
const port = numberOption(args.options.port) ?? numberOption(args.options.p);
const host = stringOption(args.options.host) ?? stringOption(args.options.h);
const server = await startHttpServer({ port, host });
// Handle graceful shutdown
const shutdown = () => {
server.close(() => {
process.exit(0);
});
};
process.on("SIGINT", shutdown);
process.on("SIGTERM", shutdown);
// Keep alive
await new Promise(() => {});
}
-8
View File
@@ -1,8 +0,0 @@
import { getOpenApiSchema } from "../../core/embedded-openapi.js";
import { outputOptions, printJson } from "../printer.js";
import type { ParsedArgs } from "../types.js";
export function handleOpenApiCommand(args: ParsedArgs) {
const schema = getOpenApiSchema();
printJson(schema, { ...outputOptions(args.options), allowFull: true });
}
-34
View File
@@ -1,34 +0,0 @@
import { homedir } from "node:os";
import { join } from "node:path";
import { VERSION } from "../../version.js";
import { runServiceCommand } from "../service.js";
import { printJson } from "../printer.js";
import { numberOption, stringOption } from "../parser.js";
import type { CliRuntime, ParsedArgs } from "../types.js";
export const STATE_DIR = join(homedir(), ".config", "seal-use");
export async function handleServiceCommand(
action: string | undefined,
runtime: CliRuntime,
args?: ParsedArgs
) {
const port = args ? numberOption(args.options.port) ?? numberOption(args.options.p) : undefined;
const host = args ? stringOption(args.options.host) ?? stringOption(args.options.h) : undefined;
const maxLines = args ? numberOption(args.options.lines) ?? numberOption(args.options.n) : undefined;
const result = await runServiceCommand(
action,
{
appRoot: runtime.appRoot,
entryFile: runtime.entryFile,
stateDir: STATE_DIR,
version: VERSION,
launcher: runtime.launcher,
port,
host
},
{ maxLines }
);
if (result !== undefined) printJson(result);
}
+36 -77
View File
@@ -6,9 +6,7 @@ import { normalizeBeijingIso } from "../../core/config/timestamps.js";
import { readInstalledSkillVersion } from "../../core/embedded-skill.js";
import { saveUpdateCache } from "../../core/update-cache.js";
import { VERSION, IS_RELEASE } from "../../version.js";
import { runServiceCommand, serviceStatus, type ServiceConfig } from "../service.js";
import { printJson } from "../printer.js";
import { STATE_DIR } from "./service.js";
import type { CliRuntime } from "../types.js";
const DEFAULT_GITHUB_REPO = "yunyingk/seal-use";
@@ -27,14 +25,6 @@ export type UpdateOptions = {
};
export async function handleUpdateCommand(runtime: CliRuntime, options: UpdateOptions = {}) {
const serviceConfig = {
appRoot: runtime.appRoot,
entryFile: runtime.entryFile,
stateDir: STATE_DIR,
version: VERSION,
launcher: runtime.launcher
};
const repo = options.repo
|| process.env[GITHUB_REPO_ENV]?.trim()
|| process.env[LEGACY_GITHUB_REPO_ENV]?.trim()
@@ -140,9 +130,6 @@ export async function handleUpdateCommand(runtime: CliRuntime, options: UpdateOp
return;
}
const wasRunning = serviceStatus(serviceConfig).running;
if (wasRunning) await runServiceCommand("stop", serviceConfig);
try {
runCommand("git", ["-C", runtime.appRoot, "pull", "--ff-only"]);
} catch (err) {
@@ -150,11 +137,8 @@ export async function handleUpdateCommand(runtime: CliRuntime, options: UpdateOp
}
runCommand("bun", ["install"], { cwd: runtime.appRoot });
if (wasRunning) await runServiceCommand("start", serviceConfig);
printJson({
updated: true,
serviceRestarted: wasRunning,
version: VERSION,
mode: "source"
});
@@ -164,7 +148,7 @@ export async function handleUpdateCommand(runtime: CliRuntime, options: UpdateOp
// 3. Homebrew managed mode
if (isHomebrewInstall()) {
try {
await handleHomebrewUpdate(options, serviceConfig, repo, targetVersion);
await handleHomebrewUpdate(options, repo, targetVersion);
return;
} catch (err) {
console.error(
@@ -276,9 +260,6 @@ export async function handleUpdateCommand(runtime: CliRuntime, options: UpdateOp
}
// Download binary or archive
const wasRunning = serviceStatus(serviceConfig).running;
if (wasRunning) await runServiceCommand("stop", serviceConfig);
const execPath = process.execPath;
const execDir = dirname(execPath);
const tmpDir = join(execDir, `.tmp-update-${Date.now()}`);
@@ -320,8 +301,6 @@ export async function handleUpdateCommand(runtime: CliRuntime, options: UpdateOp
renameSync(newBinaryPath, execPath);
}
if (wasRunning) await runServiceCommand("start", serviceConfig);
// Refresh the Agent Skill from the binary that is now on disk — never from this process.
//
// `renameSync` above advanced the file at `execPath`, but this process keeps executing the
@@ -342,7 +321,6 @@ export async function handleUpdateCommand(runtime: CliRuntime, options: UpdateOp
updated: true,
fromVersion: VERSION,
toVersion: latestVersion,
serviceRestarted: wasRunning,
skillSynced: skillSync.targetDir ?? false,
skillVersion: skillSync.version ?? false,
mode: "binary"
@@ -509,7 +487,6 @@ export function isHomebrewInstall(
async function handleHomebrewUpdate(
options: UpdateOptions,
serviceConfig: ServiceConfig,
repo: string,
targetVersion?: string
): Promise<void> {
@@ -575,66 +552,49 @@ async function handleHomebrewUpdate(
console.error("ℹ️ 检测到当前 seal-use 由 Homebrew 管理。");
console.error("📦 正在通过 Homebrew 极速更新: brew update && brew upgrade seal-use ...");
const wasRunning = serviceStatus(serviceConfig).running;
if (wasRunning) await runServiceCommand("stop", serviceConfig);
const installedBefore = homebrewInstalledVersion();
const alreadyLatestBeforeUpdate = installedBefore
? !isNewerVersion(latestVersion, installedBefore)
: false;
let alreadyLatest = alreadyLatestBeforeUpdate;
let updateError: unknown;
try {
// `brew update` refreshes all configured taps. Passing a tap name here is
// parsed as a formula upgrade by newer Homebrew versions (and fails with
// "No available formula ... tap").
const tapUpdate = await runHomebrewCommand(
["update"],
"🔄 [1/2] 正在刷新 Homebrew 软件源(可能需要几分钟)..."
);
// `brew update` refreshes all configured taps. Passing a tap name here is
// parsed as a formula upgrade by newer Homebrew versions (and fails with
// "No available formula ... tap").
const tapUpdate = await runHomebrewCommand(
["update"],
"🔄 [1/2] 正在刷新 Homebrew 软件源(可能需要几分钟)..."
);
if (tapUpdate.status !== 0) {
const msg = tapUpdate.stderr?.trim() || tapUpdate.stdout?.trim();
throw new Error(`brew update failed (exit ${tapUpdate.status}): ${msg || "unknown error"}`);
}
// 2. Upgrade the formula
const upgradeRes = await runHomebrewCommand(
["upgrade", "seal-use"],
"⬆️ [2/2] 正在升级 seal-use..."
);
const outCombined = `${upgradeRes.stdout || ""} ${upgradeRes.stderr || ""}`;
const brewReportsAlreadyLatest =
outCombined.includes("already installed") || outCombined.includes("latest version already installed");
if (upgradeRes.status !== 0 && !brewReportsAlreadyLatest) {
throw new Error(
`brew upgrade seal-use failed (exit ${upgradeRes.status}): ${upgradeRes.stderr.trim() || upgradeRes.stdout.trim()}`
);
}
const installedVersion = homebrewInstalledVersion();
if (installedVersion && isNewerVersion(latestVersion, installedVersion)) {
throw new Error(
`Homebrew still has seal-use v${installedVersion}; expected v${latestVersion}. ` +
"Refresh the tap and run `brew upgrade seal-use` again."
);
}
alreadyLatest = alreadyLatestBeforeUpdate;
} catch (err) {
updateError = err;
throw err;
} finally {
// Restart only when the update itself succeeded: a throw from `finally`
// would swallow the original update error, and logging over it would hide
// the real failure. A restart failure after a failed update is already
// reported by runServiceCommand on stderr.
if (wasRunning && !updateError) {
await runServiceCommand("start", serviceConfig);
}
if (tapUpdate.status !== 0) {
const msg = tapUpdate.stderr?.trim() || tapUpdate.stdout?.trim();
throw new Error(`brew update failed (exit ${tapUpdate.status}): ${msg || "unknown error"}`);
}
// 2. Upgrade the formula
const upgradeRes = await runHomebrewCommand(
["upgrade", "seal-use"],
"⬆️ [2/2] 正在升级 seal-use..."
);
const outCombined = `${upgradeRes.stdout || ""} ${upgradeRes.stderr || ""}`;
const brewReportsAlreadyLatest =
outCombined.includes("already installed") || outCombined.includes("latest version already installed");
if (upgradeRes.status !== 0 && !brewReportsAlreadyLatest) {
throw new Error(
`brew upgrade seal-use failed (exit ${upgradeRes.status}): ${upgradeRes.stderr.trim() || upgradeRes.stdout.trim()}`
);
}
const installedVersion = homebrewInstalledVersion();
if (installedVersion && isNewerVersion(latestVersion, installedVersion)) {
throw new Error(
`Homebrew still has seal-use v${installedVersion}; expected v${latestVersion}. ` +
"Refresh the tap and run `brew upgrade seal-use` again."
);
}
alreadyLatest = alreadyLatestBeforeUpdate;
// Refresh installed skill through new binary
try {
spawnSync("seal-use", ["skill", "install"], { stdio: "ignore" });
@@ -653,7 +613,6 @@ async function handleHomebrewUpdate(
previousVersion: VERSION,
latestVersion,
mode: "homebrew",
serviceRestarted: wasRunning,
message: alreadyLatest
? `seal-use is already at the latest version v${latestVersion} in Homebrew`
: `Successfully upgraded seal-use to v${latestVersion} via Homebrew`
+4 -30
View File
@@ -202,25 +202,14 @@ describe("help coverage", () => {
}
});
test("service lifecycle exposes area and command help", () => {
const area = renderHelp(["service"]);
expect(area).toContain("seal-use service - Background HTTP service lifecycle");
expect(area).toContain("seal-use service start");
expect(area).toContain("seal-use service logs");
expect(renderHelp(["service", "logs"])).toContain("seal-use service logs");
});
test("stop shortcut and server alias resolve to help", () => {
expect(renderHelp(["stop"])).toContain("seal-use stop");
expect(renderHelp(["server"])).toContain("seal-use mcp");
});
test("global help is generated from the registry and lists lifecycle commands", () => {
test("global help is generated from the registry", () => {
const help = renderHelp([]);
expect(help).toContain("seal-use CLI");
expect(help).toContain("seal-use version");
expect(help).toContain("seal-use service start");
expect(help).toContain("seal-use stop");
});
test("config aliases resolve to the documented commands", () => {
@@ -229,28 +218,13 @@ describe("help coverage", () => {
});
test("singleton areas do not advertise a nonexistent subcommand help", () => {
expect(renderHelp(["http"])).not.toContain("<command> --help");
expect(renderHelp(["stop"])).not.toContain("<command> --help");
expect(renderHelp(["mcp-config"])).not.toContain("<command> --help");
expect(renderHelp(["probe"])).not.toContain("<command> --help");
expect(renderHelp(["corps"])).toContain("Run 'seal-use corps <command> --help'");
});
});
describe("CLI help execution for lifecycle commands", () => {
test("seal-use service --help prints service commands with exitCode 0", async () => {
const result = await runCli(["service", "--help"]);
expect(result.exitCode).toBe(0);
expect(result.isError).toBe(false);
expect(result.stdout).toContain("seal-use service start");
expect(result.stdout).toContain("seal-use service status");
});
test("seal-use stop --help prints stop help with exitCode 0", async () => {
const result = await runCli(["stop", "--help"]);
expect(result.exitCode).toBe(0);
expect(result.isError).toBe(false);
expect(result.stdout).toContain("seal-use stop");
});
describe("CLI help execution for domain commands", () => {
test("approval-runs --help prints updated count and export parameter usage", async () => {
const result = await runCli(["approval-runs", "--help"]);
expect(result.exitCode).toBe(0);
-76
View File
@@ -1166,82 +1166,6 @@ export const HELP_REGISTRY: AreaHelp[] = [
}
]
},
{
area: "http",
title: "HTTP server",
description: "Run interactive HTTP server.",
commands: [
{
name: "",
summary: "Start HTTP daemon",
usage: [
"seal-use http [--port 8787] [--host 127.0.0.1]",
"seal-use serve [--port 8787]"
]
}
]
},
{
area: "service",
title: "Background HTTP service lifecycle",
description: "Start, stop, restart, inspect, and read logs from the standalone seal-use HTTP service daemon.",
commands: [
{
name: "start",
summary: "Start the background service daemon",
usage: ["seal-use service start [--port 8787] [--host 127.0.0.1]"]
},
{
name: "stop",
summary: "Stop the background service daemon",
usage: ["seal-use service stop"]
},
{
name: "restart",
summary: "Restart the background service daemon",
usage: ["seal-use service restart [--port 8787] [--host 127.0.0.1]"]
},
{
name: "status",
summary: "Show service daemon status",
usage: ["seal-use service status"]
},
{
name: "logs",
summary: "Print recent service daemon logs",
usage: ["seal-use service logs [--lines 50]"]
},
{
name: "run",
summary: "Run the service in the foreground",
usage: ["seal-use service run [--port 8787] [--host 127.0.0.1]"]
}
]
},
{
area: "stop",
title: "Stop the background service",
description: "Shortcut for stopping the background seal-use HTTP service daemon.",
commands: [
{
name: "",
summary: "Stop the background service daemon",
usage: ["seal-use stop"]
}
]
},
{
area: "openapi",
title: "OpenAPI specification",
description: "Output embedded OpenAPI JSON specification.",
commands: [
{
name: "",
summary: "Print OpenAPI schema",
usage: ["seal-use openapi"]
}
]
},
{
area: "doctor",
title: "System diagnostic and environment health check",
-7
View File
@@ -61,7 +61,6 @@ describe("CLI read-only classification", () => {
["deploy", "hosecloud", "status", "--corp", "corp-a"],
["preferences", "get"],
["doctor", "tenant", "--corp", "corp-a"],
["openapi"],
["version"],
["mcp-config"]
]) {
@@ -93,12 +92,8 @@ describe("CLI read-only classification", () => {
["users", "create"],
["config", "test-dir", "corp-a"],
["skill", "install"],
["service", "start"],
["service", "run"],
["mcp"],
["http"],
["update"],
["stop"],
["auth", "keys"],
["analytics", "analyze", "record-1"],
["tool", "seal_approval_rule_create", "--json", "{}"],
@@ -124,8 +119,6 @@ describe("CLI read-only classification", () => {
expect(isReadOnlyCliCommand(["doctor"])).toBe(true);
expect(isReadOnlyCliCommand(["doctor", "guide"])).toBe(true);
expect(isReadOnlyCliCommand(["doctor", "unknown-subcommand"])).toBe(false);
// `openapi` is allow-listed as the bare form only.
expect(isReadOnlyCliCommand(["openapi", "extra"])).toBe(false);
});
test("probe is read-only bare or with its enterprise selector, but not beyond", () => {
+2 -4
View File
@@ -24,7 +24,7 @@ const AREA_ALIASES: Record<string, string> = {
* Deliberately excluded even though they look harmless: anything that writes local config
* (`corps switch`, `config test-dir`, `config mode <value>`, `config lint <subaction>`), mints
* or prints credentials (`auth keys`, `corps keys`),
* self-updates (`update`), or stands up a long-running server (`http`, `mcp`, `service run`).
* self-updates (`update`), or stands up a long-running server (`mcp`).
*/
const READ_ONLY_COMMANDS: Record<string, string[]> = {
corps: ["list", "search", "get", "current"],
@@ -80,12 +80,10 @@ const READ_ONLY_COMMANDS: Record<string, string[]> = {
analytics: ["insight", "risks", "performance", "export"],
source: ["config"],
skill: ["dump", "status"],
service: ["status", "logs"],
doctor: ["", "guide", "paths", "tenant", "auth"],
// Bare form only; the optional trailing `<corpId>` selector is handled by
// SELECTOR_POSITIONAL_AREAS below, since a bare entry matches no tokens.
probe: [""],
openapi: [""]
probe: [""]
};
/**
+1 -28
View File
@@ -35,10 +35,6 @@ export const UPDATE_ALIASES = new Set([
export const KNOWN_AREAS = new Set([
"config",
"service",
"stop",
"http",
"serve",
"update",
"corps",
"corp",
@@ -65,7 +61,6 @@ export const KNOWN_AREAS = new Set([
"server",
"mcp-config",
"skill",
"openapi",
"probe",
"doctor",
"changelog",
@@ -74,14 +69,12 @@ export const KNOWN_AREAS = new Set([
export type { CliResult, CliRunOptions } from "./types.js";
const STANDING_COMMANDS = new Set(["http", "server", "web", "mcp"]);
const STANDING_COMMANDS = new Set(["server", "mcp"]);
function isStandingCommand(argv: string[]): boolean {
if (!argv.length) return false;
const first = argv[0]?.toLowerCase();
const second = argv[1]?.toLowerCase();
if (first && STANDING_COMMANDS.has(first)) return true;
if ((first === "service" || first === "daemon") && second === "run") return true;
return false;
}
@@ -204,11 +197,6 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
return;
}
if (area === "openapi") {
(await import("./commands/openapi.js")).handleOpenApiCommand(args);
return;
}
if (area === "mcp-config") {
(await import("./commands/mcp.js")).printMcpConfig();
return;
@@ -244,21 +232,6 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
return;
}
if (area === "service") {
await (await import("./commands/service.js")).handleServiceCommand(action, runtime, args);
return;
}
if (area === "stop") {
await (await import("./commands/service.js")).handleServiceCommand("stop", runtime, args);
return;
}
if (area === "http" || area === "serve") {
await (await import("./commands/http.js")).handleHttpCommand(args);
return;
}
if (isUpdate || area === "changelog") {
if (isUpdate && rawArea !== "update") {
console.error(`⚠️ Notice: '${rawArea}' is an alias for 'seal-use update'. Please use 'seal-use update' instead.`);
-97
View File
@@ -1,97 +0,0 @@
import { afterEach, describe, expect, test } from "bun:test";
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { serviceStatus, readServiceLogs, runServiceCommand } from "./service.js";
const tempDirs: string[] = [];
afterEach(() => {
for (const dir of tempDirs.splice(0)) {
rmSync(dir, { recursive: true, force: true });
}
});
describe("service lifecycle state", () => {
test("clears a stale pid file instead of reporting another process as running", () => {
const stateDir = mkdtempSync(join(tmpdir(), "seal-use-service-"));
tempDirs.push(stateDir);
writeFileSync(join(stateDir, "service.pid"), "999999\n");
const status = serviceStatus({
appRoot: "/tmp/seal-use",
entryFile: "/tmp/seal-use/src/cli.ts",
stateDir,
version: "0.4.2"
});
expect(status.running).toBe(false);
expect(status.pid).toBeUndefined();
expect(status.port).toBe(8787);
expect(status.host).toBe("127.0.0.1");
expect(status.url).toBeUndefined();
});
test("respects custom port and host configuration", () => {
const stateDir = mkdtempSync(join(tmpdir(), "seal-use-service-"));
tempDirs.push(stateDir);
const status = serviceStatus({
appRoot: "/tmp/seal-use",
entryFile: "/tmp/seal-use/src/cli.ts",
stateDir,
version: "0.10.7",
port: 9090,
host: "0.0.0.0"
});
expect(status.port).toBe(9090);
expect(status.host).toBe("0.0.0.0");
});
test("reads service log file lines safely", () => {
const stateDir = mkdtempSync(join(tmpdir(), "seal-use-service-"));
tempDirs.push(stateDir);
const emptyLogs = readServiceLogs({
appRoot: "/tmp/seal-use",
entryFile: "/tmp/seal-use/src/cli.ts",
stateDir
});
expect(emptyLogs.lines).toEqual([]);
expect(emptyLogs.totalLines).toBe(0);
const logFile = join(stateDir, "service.log");
writeFileSync(logFile, "line 1\nline 2\nline 3\nline 4\nline 5\n");
const logs = readServiceLogs(
{
appRoot: "/tmp/seal-use",
entryFile: "/tmp/seal-use/src/cli.ts",
stateDir
},
3
);
expect(logs.totalLines).toBe(5);
expect(logs.lines).toEqual(["line 3", "line 4", "line 5"]);
});
test("runServiceCommand handles logs and status actions", async () => {
const stateDir = mkdtempSync(join(tmpdir(), "seal-use-service-"));
tempDirs.push(stateDir);
const status = await runServiceCommand("status", {
appRoot: "/tmp/seal-use",
entryFile: "/tmp/seal-use/src/cli.ts",
stateDir
});
expect(status).toHaveProperty("running");
const logs = await runServiceCommand("logs", {
appRoot: "/tmp/seal-use",
entryFile: "/tmp/seal-use/src/cli.ts",
stateDir
});
expect(logs).toHaveProperty("lines");
});
});
-279
View File
@@ -1,279 +0,0 @@
import { spawn, execFileSync } from "node:child_process";
import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { formatBeijingIso } from "../core/config/timestamps.js";
import { startHttpServer, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST } from "../http/server.js";
export type ServiceConfig = {
appRoot: string;
entryFile: string;
stateDir: string;
version?: string;
launcher?: {
command: string;
args?: string[];
};
port?: number;
host?: string;
};
export async function runServiceCommand(
action: string | undefined,
config: ServiceConfig,
options: { quiet?: boolean; maxLines?: number } = {}
) {
switch (action) {
case "run":
await runService(config);
return undefined;
case "start":
return startService(config);
case "stop":
case "kill":
case "down":
case "shutdown":
return stopService(config, options);
case "restart":
stopService(config, { quiet: true });
return startService(config);
case "logs":
case "log":
return readServiceLogs(config, options.maxLines);
case "status":
case undefined:
return serviceStatus(config);
default:
throw new Error("Usage: seal-use service <start|stop|restart|status|logs>");
}
}
export function serviceStatus(config: ServiceConfig) {
const pidFile = getPidFile(config);
const metaFile = getMetaFile(config);
const pid = readServicePid(pidFile);
const running = pid ? isSealHomeProcess(pid, config.appRoot) : false;
if (!running) {
if (pid) rmSync(pidFile, { force: true });
if (existsSync(metaFile)) rmSync(metaFile, { force: true });
}
let storedMeta: { port?: number; host?: string; version?: string } | undefined;
if (running && existsSync(metaFile)) {
try {
storedMeta = JSON.parse(readFileSync(metaFile, "utf8"));
} catch {
// ignore
}
}
const port = config.port ?? storedMeta?.port ?? (process.env.PORT ? Number.parseInt(process.env.PORT, 10) : DEFAULT_HTTP_PORT);
const host = config.host ?? storedMeta?.host ?? (process.env.HOST ? process.env.HOST : DEFAULT_HTTP_HOST);
const version = config.version ?? storedMeta?.version;
return {
running,
pid: running ? pid : undefined,
version,
port,
host,
url: running ? `http://${host}:${port}` : undefined,
appRoot: config.appRoot,
stateDir: config.stateDir,
pidFile,
logFile: getLogFile(config)
};
}
export function readServiceLogs(config: ServiceConfig, maxLines = 50) {
const logFile = getLogFile(config);
if (!existsSync(logFile)) {
return {
logFile,
lines: [],
totalLines: 0
};
}
const content = readFileSync(logFile, "utf8");
const allLines = content.split("\n").filter(Boolean);
const lines = allLines.slice(-maxLines);
return {
logFile,
lines,
totalLines: allLines.length
};
}
async function runService(config: ServiceConfig) {
const pidFile = getPidFile(config);
const metaFile = getMetaFile(config);
const logFile = getLogFile(config);
ensureStateDir(config.stateDir);
const port = config.port ?? (process.env.PORT ? Number.parseInt(process.env.PORT, 10) : DEFAULT_HTTP_PORT);
const host = config.host ?? (process.env.HOST ? process.env.HOST : DEFAULT_HTTP_HOST);
writeFileSync(pidFile, `${process.pid}\n`, { mode: 0o600 });
writeFileSync(
metaFile,
JSON.stringify(
{
pid: process.pid,
port,
host,
version: config.version,
startedAt: formatBeijingIso()
},
null,
2
),
{ mode: 0o600 }
);
appendLog(logFile, `service starting on http://${host}:${port} pid=${process.pid}`);
let server: Awaited<ReturnType<typeof startHttpServer>> | null = null;
try {
server = await startHttpServer({ port, host, silent: true });
appendLog(logFile, `service listening pid=${process.pid}`);
} catch (err: unknown) {
appendLog(logFile, `service failed to bind port ${port}: ${err instanceof Error ? err.message : String(err)}`);
if (readServicePid(pidFile) === process.pid) {
rmSync(pidFile, { force: true });
rmSync(metaFile, { force: true });
}
throw err;
}
const cleanup = () => {
if (server) {
server.close();
server = null;
}
if (readServicePid(pidFile) === process.pid) {
rmSync(pidFile, { force: true });
rmSync(metaFile, { force: true });
}
appendLog(logFile, `stopped pid=${process.pid}`);
};
await new Promise<void>((resolve) => {
let stopped = false;
const stop = () => {
if (stopped) return;
stopped = true;
cleanup();
process.off("SIGTERM", stop);
process.off("SIGINT", stop);
resolve();
};
process.once("SIGTERM", stop);
process.once("SIGINT", stop);
});
}
function startService(config: ServiceConfig) {
ensureStateDir(config.stateDir);
const current = serviceStatus(config);
if (current.running) {
return current;
}
const launcher = config.launcher ?? { command: process.execPath, args: [config.entryFile] };
const serviceArgs = [
...(launcher.args ?? []),
"service",
"run"
];
if (config.port) serviceArgs.push("--port", String(config.port));
if (config.host) serviceArgs.push("--host", String(config.host));
const child = spawn(launcher.command, serviceArgs, {
cwd: config.appRoot,
detached: true,
stdio: ["ignore", "ignore", "ignore"],
env: process.env
});
child.unref();
const pidFile = getPidFile(config);
writeFileSync(pidFile, `${child.pid}\n`, { mode: 0o600 });
appendLog(getLogFile(config), `started pid=${child.pid}`);
return { started: true, ...serviceStatus(config) };
}
function stopService(config: ServiceConfig, options: { quiet?: boolean } = {}) {
const pidFile = getPidFile(config);
const metaFile = getMetaFile(config);
const pid = readServicePid(pidFile);
if (!pid || !isSealHomeProcess(pid, config.appRoot)) {
rmSync(pidFile, { force: true });
rmSync(metaFile, { force: true });
return options.quiet ? undefined : { stopped: false, reason: "not running" };
}
process.kill(pid, "SIGTERM");
rmSync(pidFile, { force: true });
rmSync(metaFile, { force: true });
appendLog(getLogFile(config), `stop requested pid=${pid}`);
return options.quiet ? undefined : { stopped: true, pid };
}
/**
* A pid file only proves that *some* process holds that pid. Match the recorded identity as argv
* tokens — the exact `service run` subcommand pair plus a path to this app or a seal-use launcher
* — instead of as substrings anywhere in the command line, so a stale pid cannot make an
* unrelated process look like our daemon and get signalled by `service stop`.
*/
function isSealHomeProcess(pid: number, appRoot: string) {
if (!isProcessRunning(pid)) return false;
try {
const command = execFileSync("ps", ["-p", String(pid), "-o", "command="], { encoding: "utf8" });
const tokens = command.trim().split(/\s+/).filter(Boolean);
const serviceIndex = tokens.indexOf("service");
const runsService = serviceIndex !== -1 && tokens[serviceIndex + 1] === "run";
const isSealUse =
command.includes(appRoot) || tokens.some((token) => /(^|[\\/])(seal-use|seal-home)(\.exe)?$/.test(token));
return runsService && isSealUse;
} catch {
return false;
}
}
function isProcessRunning(pid: number) {
try {
process.kill(pid, 0);
return true;
} catch {
return false;
}
}
function getPidFile(config: ServiceConfig) {
return join(config.stateDir, "service.pid");
}
function getMetaFile(config: ServiceConfig) {
return join(config.stateDir, "service.json");
}
function getLogFile(config: ServiceConfig) {
return join(config.stateDir, "service.log");
}
function readServicePid(path: string): number | undefined {
if (!existsSync(path)) return undefined;
const pid = Number(readFileSync(path, "utf8").trim());
return Number.isInteger(pid) && pid > 0 ? pid : undefined;
}
function ensureStateDir(stateDir: string) {
mkdirSync(stateDir, { recursive: true, mode: 0o700 });
}
function appendLog(path: string, message: string) {
writeFileSync(path, `${formatBeijingIso()} ${message}\n`, { flag: "a", mode: 0o600 });
}
+3 -3
View File
@@ -1,4 +1,4 @@
import type { ServiceConfig } from "./service.js";
import type { LauncherConfig } from "../core/runtime.js";
export type ParsedArgs = {
command: string[];
@@ -21,13 +21,13 @@ export type CliResult = {
export type CliRunOptions = {
appRoot?: string;
entryFile?: string;
launcher?: ServiceConfig["launcher"];
launcher?: LauncherConfig;
};
export type CliRuntime = {
appRoot: string;
entryFile: string;
launcher?: ServiceConfig["launcher"];
launcher?: LauncherConfig;
};
export type CommandContext = {
-8
View File
@@ -68,14 +68,6 @@ export const EMBEDDED_DIRECTORY_SPECS: DirectorySpec[] = [
accessMode: "read-write",
retention: "persistent"
},
{
name: "后台守护服务日志",
category: "config",
standardPath: "~/.config/seal-use/service.log",
purpose: "常驻后台 HTTP 服务守护进程运行输出日志。",
accessMode: "read-write",
retention: "persistent"
},
{
name: "全局命令行程序",
category: "binary",
-12
View File
@@ -1,12 +0,0 @@
import { describe, expect, test } from "bun:test";
import { getOpenApiSchema } from "./embedded-openapi.js";
describe("embedded-openapi", () => {
test("returns valid OpenAPI 3.x schema object", () => {
const schema = getOpenApiSchema();
expect(schema).toBeDefined();
expect(schema.openapi).toBe("3.1.0");
expect(schema.info).toHaveProperty("title");
expect(schema.paths).toBeDefined();
});
});
-5
View File
@@ -1,5 +0,0 @@
import openapiSchema from "../../dist/openapi.json" with { type: "json" };
export function getOpenApiSchema(): Record<string, unknown> {
return openapiSchema as Record<string, unknown>;
}
-29
View File
@@ -1,29 +0,0 @@
import { VERSION } from "../version.js";
export function renderDocsHtml(): string {
return `<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
<title>Seal Home API Docs (v${VERSION})</title>
<link rel="icon" type="image/svg+xml" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><text y='.9em' font-size='90'>🦭</text></svg>" />
<style>
body {
margin: 0;
padding: 0;
background-color: #0f172a;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
}
</style>
</head>
<body>
<script
id="api-reference"
data-url="/openapi.json"
data-configuration='{"theme":"purple","layout":"modern","showSidebar":true}'
src="https://cdn.jsdelivr.net/npm/@scalar/api-reference@1.25.101/dist/browser/standalone.js"
></script>
</body>
</html>`;
}
-106
View File
@@ -1,106 +0,0 @@
import { describe, expect, test } from "bun:test";
import { readFileSync } from "node:fs";
import { join } from "node:path";
import { getOpenApiSchema } from "../core/embedded-openapi.js";
// The bundled contract is what consumers read: `seal-use http` serves it at /openapi.json and
// `dist/openapi.json` is committed. It had drifted from the adapter in both directions — it
// documented /v1/approval/rules/{ruleId} PATCH/DELETE and /v1/approval/documents* that no route
// serves (a caller following it gets 404), and it omitted /v1/approval-runs/stats, which the
// adapter does serve. Marking each operation here turns that drift into a failing test.
//
// What this proves: every operation claimed `implemented` has a matching route in routes.ts, and
// every exact /v1 route in routes.ts is in the contract. What it does not prove: that a
// `planned` operation's *placeholder* prefix is unrouted (prefix branches are matched loosely),
// nor that an operation's request/response schema matches its handler.
const IMPLEMENTATION_KEY = "x-implementation-status";
const OPERATION_METHODS = ["get", "post", "put", "patch", "delete"] as const;
const VALID_STATUSES = ["implemented", "planned"];
type Operation = { method: string; path: string; status: string };
function collectOperations(): Operation[] {
const schema = getOpenApiSchema() as {
paths?: Record<string, Record<string, unknown>>;
};
const operations: Operation[] = [];
for (const [path, pathItem] of Object.entries(schema.paths ?? {})) {
for (const method of OPERATION_METHODS) {
const operation = pathItem[method];
if (operation === undefined) continue;
if (typeof operation !== "object" || operation === null) continue;
const status = (operation as Record<string, unknown>)[IMPLEMENTATION_KEY];
operations.push({ method, path, status: typeof status === "string" ? status : "" });
}
}
return operations;
}
const routesSource = readFileSync(join(import.meta.dir, "routes.ts"), "utf8");
/** Literals compared with `pathname === "…"`, i.e. routes with no path parameters. */
function exactRouteLiterals(): string[] {
return Array.from(routesSource.matchAll(/pathname === "([^"]+)"/g), (match) => match[1]!).filter(
(literal) => literal.startsWith("/v1/")
);
}
/** Prefix literals compared with `pathname.startsWith("…")`, which carry the path parameters. */
function prefixRouteLiterals(): string[] {
return Array.from(routesSource.matchAll(/pathname\.startsWith\("([^"]+)"\)/g), (match) => match[1]!);
}
describe("OpenAPI contract vs HTTP adapter", () => {
test("every operation declares its implementation status", () => {
const operations = collectOperations();
expect(operations.length).toBeGreaterThan(40);
for (const { method, path, status } of operations) {
expect({ method, path, status, valid: VALID_STATUSES.includes(status) }).toEqual({
method,
path,
status,
valid: true
});
}
});
test("both statuses are in use, so the marking cannot go vacuous", () => {
const operations = collectOperations();
const implemented = operations.filter((operation) => operation.status === "implemented");
const planned = operations.filter((operation) => operation.status === "planned");
// A minimum count fails loudly if `planned` operations are mass-promoted by accident.
expect(implemented.length).toBeGreaterThanOrEqual(15);
expect(planned.length).toBeGreaterThanOrEqual(15);
});
test("every operation claimed implemented is actually routed", () => {
const exactLiterals = new Set(exactRouteLiterals());
const prefixLiterals = new Set(prefixRouteLiterals());
for (const { method, path, status } of collectOperations()) {
if (status !== "implemented") continue;
// `/v1/approval-runs/{recordId}/result` is served by the `/v1/approval-runs/` prefix
// branch, so a placeholder path is proven by its static prefix rather than by equality.
const hasPlaceholder = path.includes("{");
const prefix = path.split("/{")[0]!;
const routed = hasPlaceholder
? prefixLiterals.has(`${prefix}/`)
: exactLiterals.has(path);
expect({ method, path, routed }).toEqual({ method, path, routed: true });
}
});
test("every exact /v1 route is documented", () => {
const documented = new Set(collectOperations().map((operation) => operation.path));
for (const literal of exactRouteLiterals()) {
expect({ literal, documented: documented.has(literal) }).toEqual({ literal, documented: true });
}
});
});
-485
View File
@@ -1,485 +0,0 @@
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 { findSealCapability, parseCapabilityParams, type SealCapability } from "../domains/seal/capabilities.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 executeSealCapability(tool: SealCapability, client: KyInstance, params: any, corp: CorpConfig): Promise<unknown> {
// 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.
parseCapabilityParams(tool, params);
const handler = tool.handler as (client: KyInstance, params: any, context: { corp: CorpConfig }) => Promise<unknown>;
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 = findSealCapability(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. `executeSealCapability`
// performs the same check afterwards — the early call exists purely to
// win this ordering, not to duplicate the guarantee.
parseCapabilityParams(tool, params);
const corpId = extractCorpId(req, url, body);
const corp = selectCorp(corpId);
const client = await createSealClient(corp);
const output = await executeSealCapability(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<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 = findSealCapability("seal_whoami")!;
const data = await executeSealCapability(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 = findSealCapability("seal_session_get")!;
const data = await executeSealCapability(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 = findSealCapability("seal_approval_runs_summary")!;
const data = await executeSealCapability(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 = findSealCapability("seal_approval_runs_stats")!;
const data = await executeSealCapability(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 = findSealCapability("seal_approval_run_pick")!;
const data = await executeSealCapability(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 = findSealCapability("seal_approval_run_url_get")!;
const data = await executeSealCapability(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 = findSealCapability("seal_approval_run_get")!;
const data = await executeSealCapability(tool, client, { recordId, ...queryParams }, corp);
sendJson(res, 200, data);
return true;
}
if (sub === "attachments") {
const tool = findSealCapability("seal_approval_run_attachments_get")!;
const data = await executeSealCapability(tool, client, { recordId, ...queryParams }, corp);
sendJson(res, 200, data);
return true;
}
if (sub === "cited-rules") {
const tool = findSealCapability("seal_approval_run_cited_rules_get")!;
const data = await executeSealCapability(tool, client, { recordId, ...queryParams }, corp);
sendJson(res, 200, data);
return true;
}
if (sub === "document-summary") {
const tool = findSealCapability("seal_approval_run_document_summary_get")!;
const data = await executeSealCapability(tool, client, { recordId, ...queryParams }, corp);
sendJson(res, 200, data);
return true;
}
if (sub === "result") {
const tool = findSealCapability("seal_approval_run_result_get")!;
const data = await executeSealCapability(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 = findSealCapability("seal_approval_runs_search")!;
const data = await executeSealCapability(
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 = findSealCapability("seal_approval_rules_list")!;
const data = await executeSealCapability(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 = findSealCapability("seal_simulation_batches_list")!;
const data = await executeSealCapability(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 = findSealCapability("seal_simulation_batch_create")!;
const data = await executeSealCapability(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 = findSealCapability("seal_simulation_batch_get")!;
const data = await executeSealCapability(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 = findSealCapability("seal_preference_get")!;
const data = await executeSealCapability(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 = findSealCapability("seal_preference_decision_update")!;
const data = await executeSealCapability(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>> {
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 } : {})
});
}
-111
View File
@@ -1,111 +0,0 @@
import { describe, expect, test, afterAll, beforeAll } from "bun:test";
import type { Server } from "node:http";
import { startHttpServer } from "./server.js";
import { httpStatusForCliExit } from "./routes.js";
describe("HTTP Server", () => {
let server: Server;
const testPort = 18787;
const baseUrl = `http://127.0.0.1:${testPort}`;
beforeAll(async () => {
server = await startHttpServer({ port: testPort, host: "127.0.0.1", silent: true });
});
afterAll(async () => {
await new Promise<void>((resolve) => server.close(() => resolve()));
});
test("GET / returns service overview and CORS headers", async () => {
const res = await fetch(`${baseUrl}/`);
expect(res.status).toBe(200);
expect(res.headers.get("access-control-allow-origin")).toBe("*");
const json = (await res.json()) as any;
expect(json.name).toBe("seal-use");
expect(json.docs).toBe("/docs");
expect(json.openapi).toBe("/openapi.json");
expect(json.health).toBe("/health");
});
test("GET /health returns status ok", async () => {
const res = await fetch(`${baseUrl}/health`);
expect(res.status).toBe(200);
const json = (await res.json()) as any;
expect(json.status).toBe("ok");
expect(json.name).toBe("seal-use");
});
test("GET /openapi.json returns valid OpenAPI 3.1 schema", async () => {
const res = await fetch(`${baseUrl}/openapi.json`);
expect(res.status).toBe(200);
const json = (await res.json()) as any;
expect(json.openapi).toBe("3.1.0");
expect(json.info.title).toBe("seal-use Wrapped API");
});
test("GET /docs returns HTML API reference page", async () => {
const res = await fetch(`${baseUrl}/docs`);
expect(res.status).toBe(200);
expect(res.headers.get("content-type")).toContain("text/html");
const html = await res.text();
expect(html).toContain("<html");
expect(html).toContain("api-reference");
});
test("POST /api/cli executes seal-use commands", async () => {
const res = await fetch(`${baseUrl}/api/cli`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ command: "version" })
});
expect(res.status).toBe(200);
const json = (await res.json()) as any;
expect(json.success).toBe(true);
expect(json.exitCode).toBe(0);
expect(json.data.name).toBe("seal-use");
});
test("POST /api/tool/:name rejects invalid params with 400 before touching an enterprise", async () => {
const res = await fetch(`${baseUrl}/api/tool/seal_user_create`, {
method: "POST",
headers: { "Content-Type": "application/json" },
// `name` is required by the tool's schema; without the schema gate this
// reached the handler as `undefined` and died as an opaque 500.
body: JSON.stringify({ phone: "13800001111" })
});
expect(res.status).toBe(400);
const json = (await res.json()) as any;
expect(json.error).toBe(true);
expect(json.message).toContain("seal_user_create");
expect(json.message).toContain("name");
});
test("maps structured CLI exit codes onto HTTP statuses", () => {
expect(httpStatusForCliExit(1)).toBe(500);
expect(httpStatusForCliExit(2)).toBe(400);
expect(httpStatusForCliExit(10)).toBe(403);
expect(httpStatusForCliExit(11)).toBe(401);
expect(httpStatusForCliExit(12)).toBe(413);
expect(httpStatusForCliExit(13)).toBe(400);
expect(httpStatusForCliExit(14)).toBe(403);
});
test("GET /v1/corps returns enterprise list", async () => {
const res = await fetch(`${baseUrl}/v1/corps`);
expect(res.status).toBe(200);
const json = (await res.json()) as any;
expect(json).toHaveProperty("count");
expect(Array.isArray(json.corps)).toBe(true);
});
test("OPTIONS / handles CORS preflight", async () => {
const res = await fetch(`${baseUrl}/v1/corps`, { method: "OPTIONS" });
expect(res.status).toBe(204);
expect(res.headers.get("access-control-allow-methods")).toContain("GET");
const allowHeaders = res.headers.get("access-control-allow-headers") ?? "";
expect(allowHeaders).toContain("X-Seal-Corp");
// Advertises only headers a handler reads: the historic reserved session
// header was never consulted, and the openapi no longer claims otherwise.
expect(allowHeaders).not.toContain("X-Seal-Home-Session");
});
});
-47
View File
@@ -1,47 +0,0 @@
import { createServer, type Server } from "node:http";
import { handleHttpRequest } from "./routes.js";
import { redactSensitiveText } from "../core/redact.js";
import { VERSION } from "../version.js";
export type HttpServerOptions = {
port?: number;
host?: string;
silent?: boolean;
};
export const DEFAULT_HTTP_PORT = 8787;
export const DEFAULT_HTTP_HOST = "127.0.0.1";
export async function startHttpServer(options: HttpServerOptions = {}): Promise<Server> {
const port = options.port ?? (process.env.PORT ? Number.parseInt(process.env.PORT, 10) : DEFAULT_HTTP_PORT);
const host = options.host ?? (process.env.HOST ? process.env.HOST : DEFAULT_HTTP_HOST);
const server = createServer(async (req, res) => {
try {
await handleHttpRequest(req, res);
} catch (err) {
if (!res.headersSent) {
res.writeHead(500, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: true, message: redactSensitiveText(err instanceof Error ? err.message : String(err)) }));
}
}
});
return new Promise((resolve, reject) => {
server.on("error", (err) => {
reject(err);
});
server.listen(port, host, () => {
if (!options.silent) {
console.error(`\n🚀 seal-use HTTP Server (v${VERSION}) started`);
console.error(` URL: http://${host}:${port}`);
console.error(` Docs: http://${host}:${port}/docs`);
console.error(` OpenAPI: http://${host}:${port}/openapi.json`);
console.error(` CLI Exec: POST http://${host}:${port}/api/cli`);
console.error(` REST API: http://${host}:${port}/v1/...\n`);
}
resolve(server);
});
});
}