From a55015ca26dea76f2ce0696d98696f61c5469a97 Mon Sep 17 00:00:00 2001 From: yunyingk Date: Wed, 30 Sep 2026 01:15:09 +0800 Subject: [PATCH 1/6] Reclaim self-update `.old` backups left beside the binary MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Windows cannot rename-replace a running executable, so the win32 update path renames the live image to `.old.` and never deleted it: one full binary (tens of MB) leaked per update, forever. The same file cannot be removed during the update that created it either — it is the executing image — so the sweep runs at the start of every binary-mode invocation instead, which includes the SWR background `update check --bg-save` that runs on its own. Orphaned `.tmp-update-` staging dirs from an interrupted run are swept by the same pass, gated on a one-hour mtime so a staging dir an update is actively downloading into is never pulled out from under it. --- src/cli/commands/update.test.ts | 59 ++++++++++++++++++++++++++++-- src/cli/commands/update.ts | 63 ++++++++++++++++++++++++++++++++- 2 files changed, 119 insertions(+), 3 deletions(-) diff --git a/src/cli/commands/update.test.ts b/src/cli/commands/update.test.ts index 27f1597..6af388f 100644 --- a/src/cli/commands/update.test.ts +++ b/src/cli/commands/update.test.ts @@ -1,8 +1,8 @@ import { describe, expect, test } from "bun:test"; -import { mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; +import { mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, symlinkSync, utimesSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { compareSemVer, getMirrorMode, isHomebrewInstall, isNewerVersion, matchAssetForPlatform } from "./update.js"; +import { compareSemVer, getMirrorMode, isHomebrewInstall, isNewerVersion, matchAssetForPlatform, pruneUpdateLeftovers } from "./update.js"; type Asset = { name: string; downloadUrl: string; size: number }; @@ -72,6 +72,61 @@ describe("update skill install", () => { }); }); +describe("update leftover pruning", () => { + // Windows cannot rename-replace a running executable, so the win32 branch + // renames the live image to `.old.` and — before this helper — + // never removed it: one full binary leaked per update, forever. Cleanup can + // only happen once that image stops executing, i.e. on a later invocation. + test("removes stale .old backups but never the live binary", () => { + const dir = mkdtempSync(join(tmpdir(), "seal-use-prune-old-")); + try { + const binary = join(dir, "seal-use"); + writeFileSync(binary, "current"); + writeFileSync(join(dir, "seal-use.old.1727000000000"), "previous release"); + writeFileSync(join(dir, "my-old-seal-use"), "unrelated file with 'old' in the name"); + + const removed = pruneUpdateLeftovers(binary); + + expect(removed).toEqual(["seal-use.old.1727000000000"]); + expect(readFileSync(binary, "utf8")).toBe("current"); + expect(readFileSync(join(dir, "my-old-seal-use"), "utf8")).toBe("unrelated file with 'old' in the name"); + expect(() => statSync(join(dir, "seal-use.old.1727000000000"))).toThrow(); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); + + test("sweeps only stale staging dirs, leaving a concurrent update's alone", () => { + const dir = mkdtempSync(join(tmpdir(), "seal-use-prune-tmp-")); + try { + const binary = join(dir, "seal-use"); + writeFileSync(binary, "current"); + + const fresh = join(dir, `.tmp-update-${Date.now()}`); + const orphan = join(dir, ".tmp-update-1727000000000"); + mkdirSync(fresh, { recursive: true }); + mkdirSync(orphan, { recursive: true }); + writeFileSync(join(orphan, "half-downloaded.bin"), "x"); + // Backdate the orphan past the one-hour safety window. + const old = new Date(Date.now() - 2 * 60 * 60 * 1000); + utimesSync(orphan, old, old); + + const removed = pruneUpdateLeftovers(binary); + + expect(removed).toEqual([".tmp-update-1727000000000"]); + expect(() => statSync(orphan)).toThrow(); + // A staging dir this run (or a parallel update) may still be writing into. + expect(statSync(fresh).isDirectory()).toBe(true); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); + + test("is a no-op when the binary directory cannot be read", () => { + expect(pruneUpdateLeftovers(join(tmpdir(), "does-not-exist", "seal-use"))).toEqual([]); + }); +}); + describe("update version comparator", () => { test("correctly identifies newer semantic versions", () => { expect(isNewerVersion("0.7.0", "0.6.0")).toBe(true); diff --git a/src/cli/commands/update.ts b/src/cli/commands/update.ts index fee823e..11978b6 100644 --- a/src/cli/commands/update.ts +++ b/src/cli/commands/update.ts @@ -1,4 +1,4 @@ -import { chmodSync, mkdirSync, readdirSync, realpathSync, renameSync, rmSync, unlinkSync, writeFileSync } from "node:fs"; +import { chmodSync, mkdirSync, readdirSync, realpathSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs"; import { basename, dirname, isAbsolute, join, relative } from "node:path"; import { spawn, spawnSync } from "node:child_process"; import { isCompiledBinary } from "../../core/runtime.js"; @@ -177,6 +177,12 @@ export async function handleUpdateCommand(runtime: CliRuntime, options: UpdateOp const platform = detectPlatform(); const arch = detectArch(); + // Every binary-mode invocation sweeps here, not just real updates: the SWR + // background check (`update check --bg-save`) is the only command many users + // ever run after their last update, so it is what reclaims that update's + // `.old.` backup (undeletable while its image was executing). + pruneUpdateLeftovers(process.execPath); + const releases = await fetchGitHubReleases(repo, 30); const release = targetVersion ? (releases.find((r) => r.version === targetVersion || r.tagName === targetVersion || r.tagName === `v${targetVersion}`) ?? @@ -350,6 +356,61 @@ export async function handleUpdateCommand(runtime: CliRuntime, options: UpdateOp } } +/** + * Deletes the debris earlier self-updates left next to the installed binary. + * + * Windows cannot `renameSync`-replace a running executable, so the win32 branch + * first renames the live image to `.old.` and never removes + * it — one full binary (tens of MB) leaked per update. The same file is also + * undeletable *during* that update (it is the executing image), so cleanup runs + * at the start of the next update instead, when nothing holds it open. Orphaned + * `.tmp-update-` staging directories from an interrupted run are + * swept for the same reason. + * + * Best-effort: a locked or already-gone file is skipped, never fatal. Returns + * the entries removed so tests can assert the sweep. + */ +export function pruneUpdateLeftovers(binaryPath: string): string[] { + const dir = dirname(binaryPath); + const base = basename(binaryPath); + const removed: string[] = []; + + let entries: string[]; + try { + entries = readdirSync(dir); + } catch { + return removed; + } + + const now = Date.now(); + for (const entry of entries) { + // `.old.` (e.g. seal-use.exe.old.1727...) and the + // `.tmp-update-` staging dirs this command creates. Never the live + // binary itself: its name has no `.old.` / `tmp-update` marker. + const isStaleBackup = entry.startsWith(`${base}.old.`); + const isOrphanStaging = entry.startsWith(".tmp-update-"); + if (!isStaleBackup && !isOrphanStaging) continue; + + const fullPath = join(dir, entry); + try { + if (isOrphanStaging) { + // A staging dir younger than an hour may belong to an update running + // right now; deleting it out from under that download would break it. + // The `.old.` case needs no such gate: on Windows a live image cannot + // be deleted (the rm throws and is swallowed), and on POSIX no `.old.` + // file is ever written. + if (now - statSync(fullPath).mtimeMs < 60 * 60 * 1000) continue; + } + rmSync(fullPath, { recursive: true, force: true }); + removed.push(entry); + } catch { + // Still locked (its owning process is alive); the next update retries. + } + } + + return removed; +} + /** * Installs the Agent Skill by running the newly installed binary as a child process, then reads * the file back to prove which version actually landed. From 289ef664da23462ce82b49cde75ae1666818cc7d Mon Sep 17 00:00:00 2001 From: yunyingk Date: Wed, 30 Sep 2026 01:15:42 +0800 Subject: [PATCH 2/6] Validate tool params against their schemas on both dispatch paths MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit All 99 registry tools declare a zod schema, and not one of them was ever parsed: `runToolResult` (every CLI command) and `executeSealTool` (`POST /api/tool/:name` and every `/v1/*` route) handed `params` straight to the handler. A missing required field reached the handler as `undefined` and died as an opaque upstream error or a `Cannot read properties of undefined`, and an out-of-range `limit` sailed through to the tenant. Both paths now gate on `parseToolParams`, failing fast with the field path: exit 13 on the CLI, HTTP 400 behind the adapter (structured exit codes map onto statuses instead of collapsing every failure into 500). The HTTP tool endpoint validates before `selectCorp`, which records usage stats to disk — a request that can never succeed should cause no writes. Two properties keep this a pure addition: the original params are returned rather than zod's parsed output (handlers read undeclared keys — the configure tool accepts `appKey` alongside `apiKey`, which the schema now says out loud), and query strings are coerced to the declared type first, because `/v1/*` passes `url.searchParams` where the schema wants `z.number()`. --- src/cli/helpers.ts | 6 +- src/domains/seal/tools/deploy.ts | 11 ++- src/domains/seal/tools/index.ts | 1 + src/domains/seal/tools/validate.test.ts | 91 +++++++++++++++++++++ src/domains/seal/tools/validate.ts | 104 ++++++++++++++++++++++++ src/http/routes.ts | 41 ++++++++-- src/http/server.test.ts | 26 ++++++ 7 files changed, 272 insertions(+), 8 deletions(-) create mode 100644 src/domains/seal/tools/validate.test.ts create mode 100644 src/domains/seal/tools/validate.ts diff --git a/src/cli/helpers.ts b/src/cli/helpers.ts index 2e75862..c788e96 100644 --- a/src/cli/helpers.ts +++ b/src/cli/helpers.ts @@ -2,7 +2,7 @@ import { getEnterprisesDirCandidates, loadCorpConfigs, loadGlobalConfig, resolve import { resolveCorpConfig } from "../core/config/manager.js"; import { recordCorpUsage } from "../core/stats/usage-tracker.js"; import { createSealClient } from "../core/http/factory.js"; -import { sealTools, type SealTool } from "../domains/seal/tools.js"; +import { sealTools, parseToolParams, type SealTool } from "../domains/seal/tools.js"; import type { CorpConfig, GlobalConfig } from "../core/config/types.js"; import { printJson } from "./printer.js"; import type { OutputOptions } from "./types.js"; @@ -60,6 +60,10 @@ export async function runToolResult( const compactParams = Object.fromEntries( Object.entries(params).filter(([, value]) => value !== undefined) ); + // Schema gate: a missing required field or an out-of-range value fails here + // with exit 13 instead of reaching the handler as `undefined` and surfacing + // as an opaque upstream error. Valid params pass through untouched. + parseToolParams(tool, compactParams); const handler = tool.handler as SealTool["handler"]; return handler(client, compactParams as never, { corp }); } diff --git a/src/domains/seal/tools/deploy.ts b/src/domains/seal/tools/deploy.ts index b6e19af..e9f4148 100644 --- a/src/domains/seal/tools/deploy.ts +++ b/src/domains/seal/tools/deploy.ts @@ -86,8 +86,15 @@ export const deployTools = [ name: "seal_deploy_hosecloud_configure", description: "自动探测平台并保存【Seal AI 审批发布到合思费控】集成配置", parameters: z.object({ - apiKey: z.string().describe("合思 API Key (appKey)"), - apiSecret: z.string().describe("合思 API Secret (appSecurity)"), + // Optional in the schema because the handler accepts two spellings of the + // same credential (`apiKey`, or the legacy `appKey` alias) and enforces + // that one pair is present itself — see the check right below. Marking + // only `apiKey` required would reject `appKey` payloads the handler has + // always accepted. + apiKey: z.string().optional().describe("合思 API Key (appKey)"), + apiSecret: z.string().optional().describe("合思 API Secret (appSecurity)"), + appKey: z.string().optional().describe("apiKey 的旧写法,等价"), + appSecurity: z.string().optional().describe("apiSecret 的旧写法,等价"), signKey: z.string().optional().describe("集成 signKey,不提供则自动生成"), outboundName: z.string().optional().describe("出站消息名称(合思审批流节点中显示)"), specificationId: z.string().optional(), diff --git a/src/domains/seal/tools/index.ts b/src/domains/seal/tools/index.ts index 78afd58..5250e29 100644 --- a/src/domains/seal/tools/index.ts +++ b/src/domains/seal/tools/index.ts @@ -10,6 +10,7 @@ import { deployTools } from "./deploy.js"; import { preferenceTools } from "./preference.js"; export * from "./helpers.js"; +export * from "./validate.js"; export const sealTools = [ ...identityTools, diff --git a/src/domains/seal/tools/validate.test.ts b/src/domains/seal/tools/validate.test.ts new file mode 100644 index 0000000..86d1399 --- /dev/null +++ b/src/domains/seal/tools/validate.test.ts @@ -0,0 +1,91 @@ +import { describe, expect, test } from "bun:test"; +import { CliError } from "../../../core/errors.js"; +import { findSealTool, parseToolParams, type SealTool } from "./index.js"; + +function tool(name: string): SealTool { + const found = findSealTool(name); + if (!found) throw new Error(`test fixture missing tool: ${name}`); + return found; +} + +/** Asserts rejection and returns the message so tests can check its wording. */ +function rejectsWith(toolName: string, params: Record): string { + try { + parseToolParams(tool(toolName), params); + } catch (error) { + expect(error).toBeInstanceOf(CliError); + expect((error as CliError).exitCode).toBe(13); + return (error as CliError).message; + } + throw new Error(`expected ${toolName} to reject ${JSON.stringify(params)}`); +} + +describe("parseToolParams", () => { + test("accepts valid params and returns the exact object it was given", () => { + const target = tool("seal_user_create"); + const params = { name: "张三", phone: "13800001111", departmentIds: ["d1"] }; + + // Identity matters: handlers read keys the schema does not declare, so the + // gate must pass its input through, never zod's (stripped) parse output. + expect(parseToolParams(target, params)).toBe(params); + }); + + test("names the missing required field instead of letting the handler crash on undefined", () => { + const message = rejectsWith("seal_user_create", { phone: "13800001111" }); + expect(message).toContain("seal_user_create"); + expect(message).toContain("name"); + }); + + test("enforces the value bound a handler would otherwise silently accept", () => { + // limit is capped at 100 in the schema; nothing in the handler checks it. + const message = rejectsWith("seal_approval_runs_search", { limit: 9999 }); + expect(message).toContain("limit"); + }); + + test("coerces query-string values before checking, without touching the original", () => { + const target = tool("seal_approval_runs_search"); + const params = { limit: "50", includeBridge: "true" } as Record; + + // /v1/* passes url.searchParams through: everything arrives as a string, + // but the schema declares z.number() / z.boolean(). Without coercion every + // REST route would 400 on its own documented query params. + expect(parseToolParams(target, params)).toBe(params); + expect(params.limit).toBe("50"); + expect(params.includeBridge).toBe("true"); + }); + + test("still rejects a string that merely looks like a wire value", () => { + const message = rejectsWith("seal_approval_runs_search", { limit: "abc" }); + expect(message).toContain("limit"); + }); + + test("coerces a comma-separated query value into the array the schema wants", () => { + // `?fields=id,code` on /v1/approval/rules: today the handler receives a + // string and pickRuleFields iterates its characters, returning empty + // objects. Validation splits it so the documented form actually works. + expect(parseToolParams(tool("seal_approval_rules_list"), { fields: "id,code" })).toEqual({ + fields: "id,code" + }); + expect(rejectsWith("seal_approval_rules_list", { fields: "id,not-a-field" })).toContain("fields"); + }); + + test("ignores undeclared keys rather than rejecting the request", () => { + // z.object is non-strict: an extra HTTP body key is a compatibility + // non-event, not an error. This gate checks declared params only. + const target = tool("seal_approval_runs_search"); + expect(parseToolParams(target, { status: "TERMINATED", corp: "corp-a", stray: 1 })).toBeTypeOf("object"); + }); + + test("lets the legacy credential aliases through to the handler that supports them", () => { + // seal_deploy_hosecloud_configure has always accepted appKey/appSecurity + // alongside apiKey/apiSecret; a schema that declared only apiKey as + // required would have blocked that documented path. + expect(() => + parseToolParams(tool("seal_deploy_hosecloud_configure"), { + appKey: "key-1", + appSecurity: "secret-1", + mode: "assisted" + }) + ).not.toThrow(); + }); +}); diff --git a/src/domains/seal/tools/validate.ts b/src/domains/seal/tools/validate.ts new file mode 100644 index 0000000..3f81fd3 --- /dev/null +++ b/src/domains/seal/tools/validate.ts @@ -0,0 +1,104 @@ +import { z } from "zod"; +import { validationError } from "../../../core/errors.js"; +import type { SealTool } from "./index.js"; + +/** + * Checks one invocation's params against the schema its tool declares, then + * returns the params unchanged. + * + * Both dispatch paths — `runToolResult` (every CLI command) and + * `executeSealTool` (`POST /api/tool/:name`, every `/v1/*` route) — used to + * hand `params` straight to `handler`, so a required field could be missing, a + * limit could be `999999`, or a typo'd HTTP body key could sail through and + * surface later as an opaque upstream error or a `Cannot read properties of + * undefined`. The schema is now the gate, failing fast with the offending field + * path (exit `13` on the CLI, HTTP `400` behind the adapter). + * + * Two deliberate properties: + * + * - **Original params are returned, not `result.data`.** Handlers read keys the + * schema does not declare — `seal_deploy_hosecloud_configure` accepts the + * legacy `appKey`/`appSecurity` aliases alongside `apiKey`/`apiSecret` — and + * zod's default strip would silently drop them. Validation must never change + * what a working handler receives, only block what would have failed anyway. + * - **Undeclared keys never fail.** `z.object` is non-strict, so an extra HTTP + * body key is ignored rather than rejected; this is a correctness check, not + * an API-compatibility verdict. + * + * Before rejecting, wire-format values are coerced to the shape the schema + * declares (see {@link coerceWireTypes}) because `/v1/*` query strings arrive + * entirely as strings while the schema says `z.number()`. + */ +export function parseToolParams(tool: SealTool, params: Record): Record { + const result = tool.parameters.safeParse(coerceWireTypes(tool.parameters, params)); + if (result.success) return params; + + const detail = result.error.issues + .map((issue) => `${issue.path.length ? issue.path.join(".") : "(root)"}: ${issue.message}`) + .join("; "); + throw validationError(`Invalid parameters for ${tool.name}: ${detail}`); +} + +/** + * Rewrites string-shaped query/body values into the type the schema declares + * for that key: `"10"` → `10` for `z.number()`, `"true"` → `true` for + * `z.boolean()`, `"id,code"` → `["id", "code"]` for `z.array()`. + * + * Query strings carry no types, so without this every `/v1/*` route that passes + * `url.searchParams` through would fail against `z.number().int()` — while a + * value that merely looks wrong (`"abc"` for a number) is left alone so zod + * reports it instead of hiding it behind a NaN. + * + * Only top-level keys are touched: nested params arrive as parsed JSON (already + * typed), and skipping declared-but-uncoercible leaves errors to zod rather + * than guessing. + */ +function coerceWireTypes(schema: z.ZodType, params: Record): Record { + const shape = (schema as z.ZodObject).shape; + if (!shape) return params; + + const coerced = { ...params }; + for (const [key, def] of Object.entries(shape)) { + const value = coerced[key]; + if (typeof value !== "string" || value === "") continue; + + const target = unwrapType(def); + if (target === "number" && /^[+-]?\d+(?:\.\d+)?$/.test(value.trim())) { + coerced[key] = Number(value.trim()); + } else if (target === "boolean") { + if (value === "true") coerced[key] = true; + else if (value === "false") coerced[key] = false; + } else if (target === "array") { + const items = value.split(",").map((item) => item.trim()).filter(Boolean); + if (items.length) coerced[key] = items; + } + } + return coerced; +} + +/** + * Resolves a field's concrete type name, stepping through `optional` / + * `default` / `nullable` wrappers: `"limit: optional"` → `"number"`. + * + * zod v4 exposes `type` on the schema instance but keeps `innerType` on + * `_def`, so both shapes are read — a wrapper reached via `_def.innerType` is + * an instance again, and an object reached by other means may be a bare def. + */ +function unwrapType(schema: unknown): string | undefined { + let current = schema as + | { type?: string; innerType?: unknown; _def?: { type?: string; innerType?: unknown } } + | undefined; + + // Depth bound: wrappers nest shallowly in practice; anything deeper is a + // shape this helper should decline to interpret rather than chase. + for (let depth = 0; current && depth < 8; depth++) { + const def = current._def ?? current; + const type = def.type ?? current.type; + if (type === "optional" || type === "default" || type === "nullable") { + current = (def.innerType ?? current.innerType) as typeof current; + continue; + } + return type; + } + return undefined; +} diff --git a/src/http/routes.ts b/src/http/routes.ts index d060c36..5eb2216 100644 --- a/src/http/routes.ts +++ b/src/http/routes.ts @@ -8,17 +8,39 @@ 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, type SealTool } from "../domains/seal/tools.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", "*"); @@ -133,12 +155,18 @@ export async function handleHttpRequest(req: IncomingMessage, res: ServerRespons } 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; + // 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); @@ -154,7 +182,10 @@ export async function handleHttpRequest(req: IncomingMessage, res: ServerRespons 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); + // 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); } } diff --git a/src/http/server.test.ts b/src/http/server.test.ts index c0c6546..131c97e 100644 --- a/src/http/server.test.ts +++ b/src/http/server.test.ts @@ -1,6 +1,7 @@ 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; @@ -64,6 +65,31 @@ describe("HTTP Server", () => { 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); From 97bf3301a379f88817c6e48db66e586ca8dd358e Mon Sep 17 00:00:00 2001 From: yunyingk Date: Wed, 30 Sep 2026 01:16:12 +0800 Subject: [PATCH 3/6] Keep `seal-use probe`'s stdout to a single JSON document MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `runProbe` wrote its progress notes and three separate JSON blobs to stdout, so every consumer parsing the output — `seal-use probe | jq`, the Agent Harness — got prose interleaved with data. The command is also in the help registry, so this was a documented command breaking its own contract. The probe now returns one `ProbeResult` and the command prints it through `printJson`; the `[probe] …` narration moves to stderr, which is the diagnostics channel. The dev-script entry point keeps the same payload and its exit code. Classified read-only too: `probe` reads tenant state and writes nothing, but the allow-list had no entry, so the MCP read-only tool refused it. Its trailing token is an enterprise selector rather than a verb, so the matcher accepts the bare form and bare-plus-selector while still refusing a third token. --- src/cli/commands/probe.ts | 4 +- src/cli/read-only.test.ts | 8 +++ src/cli/read-only.ts | 13 ++++ src/probe.test.ts | 124 ++++++++++++++++++++++++++++++++++++++ src/probe.ts | 60 ++++++++++++------ 5 files changed, 190 insertions(+), 19 deletions(-) create mode 100644 src/probe.test.ts diff --git a/src/cli/commands/probe.ts b/src/cli/commands/probe.ts index 4432061..4b2b3f8 100644 --- a/src/cli/commands/probe.ts +++ b/src/cli/commands/probe.ts @@ -1,8 +1,10 @@ import { runProbe } from "../../probe.js"; import { stringOption } from "../parser.js"; +import { printJson } from "../printer.js"; import type { ParsedArgs } from "../types.js"; export async function handleProbeCommand(action: string | undefined, maybeName: string | undefined, args: ParsedArgs) { const corpId = maybeName ?? stringOption(args.options.corp) ?? (action && action !== "--corp" ? action : undefined); - await runProbe({ corpId }); + // One JSON document on stdout; runProbe narrates progress on stderr only. + printJson(await runProbe({ corpId })); } diff --git a/src/cli/read-only.test.ts b/src/cli/read-only.test.ts index 806dd1b..1085410 100644 --- a/src/cli/read-only.test.ts +++ b/src/cli/read-only.test.ts @@ -128,6 +128,14 @@ describe("CLI read-only classification", () => { expect(isReadOnlyCliCommand(["openapi", "extra"])).toBe(false); }); + test("probe is read-only bare or with its enterprise selector, but not beyond", () => { + // `seal-use probe []` takes a selector, not a verb: the allow-list + // entry covers the bare form and the selector form is matched separately. + expect(isReadOnlyCliCommand(["probe"])).toBe(true); + expect(isReadOnlyCliCommand(["probe", "corp-a"])).toBe(true); + expect(isReadOnlyCliCommand(["probe", "corp-a", "extra"])).toBe(false); + }); + test("refuses command lines that cannot be parsed", () => { expect(isReadOnlyCliCommand(["--json"])).toBe(false); }); diff --git a/src/cli/read-only.ts b/src/cli/read-only.ts index 474d02b..a5e17e9 100644 --- a/src/cli/read-only.ts +++ b/src/cli/read-only.ts @@ -81,9 +81,20 @@ const READ_ONLY_COMMANDS: Record = { skill: ["dump", "status"], service: ["status", "logs"], doctor: ["", "guide", "paths", "tenant", "auth"], + // Bare form only; the optional trailing `` selector is handled by + // SELECTOR_POSITIONAL_AREAS below, since a bare entry matches no tokens. + probe: [""], openapi: [""] }; +/** + * Areas whose trailing positional is an enterprise selector, not a subcommand: + * `seal-use probe []` has no verb to list, so its read form is the bare + * command plus at most that one selector. A second token is not a form the area + * accepts at all, and falls through to the refusal below. + */ +const SELECTOR_POSITIONAL_AREAS = new Set(["probe"]); + /** * Read-only commands handled by the CLI outside the help registry (no area/subcommand shape). * `help` is limited to the bare form on purpose: `help ` adds nothing over the skill docs. @@ -110,6 +121,8 @@ export function isReadOnlyCliCommand(argv: string[]): boolean { } if (actionTokens.length === 0 && TOP_LEVEL_READ_ONLY.has(area)) return true; + // The `` selector form; the bare form falls through to the `""` entry. + if (SELECTOR_POSITIONAL_AREAS.has(area) && actionTokens.length === 1) return true; const allowed = READ_ONLY_COMMANDS[area]; if (!allowed) return false; diff --git a/src/probe.test.ts b/src/probe.test.ts new file mode 100644 index 0000000..e0165a3 --- /dev/null +++ b/src/probe.test.ts @@ -0,0 +1,124 @@ +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 { runCli } from "./cli/runner.js"; + +const ENV_KEYS = ["SEAL_USE_ENTERPRISES_DIR", "SEAL_USE_CONFIG_FILE", "SEAL_USE_TOKEN_STORE", "SEAL_DISABLE_BG_UPDATE"] as const; +const ORIGINAL_ENV: Record = Object.fromEntries(ENV_KEYS.map((key) => [key, process.env[key]])); +const ORIGINAL_FETCH = globalThis.fetch; +const tempDirs: string[] = []; + +afterEach(() => { + globalThis.fetch = ORIGINAL_FETCH; + for (const key of ENV_KEYS) { + if (ORIGINAL_ENV[key] === undefined) delete process.env[key]; + else process.env[key] = ORIGINAL_ENV[key]!; + } + for (const dir of tempDirs.splice(0)) rmSync(dir, { recursive: true, force: true }); +}); + +function makeProbeEnv(corpId = "demo-corp"): string { + const dir = mkdtempSync(join(tmpdir(), "seal-use-probe-test-")); + tempDirs.push(dir); + writeFileSync( + join(dir, `${corpId}.json`), + JSON.stringify({ + id: corpId, + name: "Demo Corp", + source: { type: "seal", token: "seal-token", sealUrl: `https://${corpId}.sealai.cc` } + }) + ); + + process.env.SEAL_USE_ENTERPRISES_DIR = dir; + process.env.SEAL_USE_CONFIG_FILE = join(dir, "config.json"); + process.env.SEAL_USE_TOKEN_STORE = join(dir, "tokens.json"); + process.env.SEAL_DISABLE_BG_UPDATE = "1"; + return dir; +} + +type Route = (url: string) => Response | undefined; + +/** Routes the four upstream calls a probe makes; unhandled URLs fail loudly. */ +function mockSealApi(route: Route): void { + globalThis.fetch = (async (input: RequestInfo | URL) => { + const url = input instanceof Request ? input.url : String(input); + const response = route(url); + if (!response) throw new Error(`probe test received an unexpected request: ${url}`); + return response; + }) as typeof fetch; +} + +function json(payload: unknown, status = 200): Response { + return new Response(JSON.stringify(payload), { + status, + headers: { "Content-Type": "application/json" } + }); +} + +function okApi(): Route { + return (url) => { + if (url.includes("/api/v1/auth/me")) { + return json({ + user: { id: "user-1", tenantId: "tenant-1", name: "Tester" }, + tenant: { id: "tenant-1", name: "Demo Tenant" } + }); + } + if (url.includes("/api/v1/rules")) { + return json({ + rules: [{ id: "rule-1", description: "差旅报销规则", scope: "travel", strictness: "MUST_FOLLOW" }], + hasPendingDeletes: false + }); + } + if (url.includes("/api/v1/knowledge/articles")) return json({ articles: [], total: 0 }); + if (url.includes("/api/v1/agent/ai-approval/config")) return json({ tone: "precise" }); + return undefined; + }; +} + +describe("seal-use probe stream contract", () => { + test("writes exactly one JSON document to stdout and narrates on stderr", async () => { + makeProbeEnv(); + mockSealApi(okApi()); + + const result = await runCli(["probe", "demo-corp"]); + + expect(result.exitCode).toBe(0); + // The whole contract: if the [probe] prose still reached stdout, this + // parse would throw instead of yielding the payload. + const payload = JSON.parse(result.stdout) as Record; + expect(result.stdout).not.toContain("[probe]"); + + expect(payload.corp).toEqual({ id: "demo-corp", name: "Demo Corp", sourceType: "seal" }); + expect(payload.enterprise).toMatchObject({ + provider: "seal", + sealUrl: "https://demo-corp.sealai.cc", + tenantName: "Demo Tenant" + }); + expect(payload.summary).toEqual({ + rules: 1, + hasPendingRuleDeletes: false, + documents: 0, + documentsTotal: 0, + stylePreferences: "ok" + }); + + expect(result.stderr).toContain("[probe] corp=demo-corp source=seal"); + expect(result.stderr).toContain("[probe] approval context summary"); + }); + + test("reports a failing style-preferences endpoint in the payload instead of throwing", async () => { + makeProbeEnv(); + mockSealApi((url) => { + const ok = okApi()(url); + return url.includes("/api/v1/agent/ai-approval/config") ? json({ error: "upstream broke" }, 500) : ok; + }); + + const result = await runCli(["probe", "demo-corp"]); + + expect(result.exitCode).toBe(0); + const payload = JSON.parse(result.stdout) as Record; + expect(payload.summary.stylePreferences).toContain("error:"); + expect(payload.summary.rules).toBe(1); + }); +}); diff --git a/src/probe.ts b/src/probe.ts index f8b7505..faf57a7 100644 --- a/src/probe.ts +++ b/src/probe.ts @@ -1,10 +1,25 @@ import { getEnterprisesDirCandidates, loadCorpConfigs, loadGlobalConfig } from "./core/config/loader.js"; import { resolveCorpConfig } from "./core/config/manager.js"; import { createSealClient } from "./core/http/factory.js"; +import type { SealEnterpriseConfig } from "./core/auth/types.js"; import { resolveLiveSealEnterpriseConfig } from "./domains/seal/source.js"; import { getApprovalContext } from "./domains/seal/api.js"; +import { printJson } from "./cli/printer.js"; -export async function runProbe(options: { corpId?: string } = {}) { +/** One probe run's payload — the entire stdout of `seal-use probe`. */ +export type ProbeResult = { + corp: { id: string; name: string; sourceType: string }; + enterprise: SealEnterpriseConfig; + summary: { + rules: number; + hasPendingRuleDeletes: boolean; + documents: number; + documentsTotal?: number; + stylePreferences: string; + }; +}; + +export async function runProbe(options: { corpId?: string } = {}): Promise { const corps = loadCorpConfigs(); const globalConfig = loadGlobalConfig(); const corp = resolveCorpConfig( @@ -17,11 +32,13 @@ export async function runProbe(options: { corpId?: string } = {}) { getEnterprisesDirCandidates() ); - console.log(`[probe] corp=${corp.id} source=${corp.source.type}`); + // Progress notes go to stderr: stdout carries the JSON payload alone, so + // `seal-use probe | jq` keeps working (it previously held three prose lines + // interleaved with three JSON blobs). + console.error(`[probe] corp=${corp.id} source=${corp.source.type}`); const enterprise = await resolveLiveSealEnterpriseConfig(corp); - console.log("[probe] seal enterprise"); - console.log(JSON.stringify(enterprise, null, 2)); + console.error("[probe] seal enterprise"); const client = await createSealClient(corp); const context = await getApprovalContext(client, { @@ -29,23 +46,30 @@ export async function runProbe(options: { corpId?: string } = {}) { stylePreferencesEndpoint: corp.seal.endpoints.approvalStylePreferences }); - console.log("[probe] approval context summary"); - console.log(JSON.stringify({ - rules: context.rules.rules.length, - hasPendingRuleDeletes: context.rules.hasPendingDeletes, - documents: context.documents.articles.length, - documentsTotal: context.documents.total, - stylePreferences: context.stylePreferences.ok - ? "ok" - : `error: ${context.stylePreferences.error}` - }, null, 2)); + console.error("[probe] approval context summary"); + + return { + corp: { id: corp.id, name: corp.name, sourceType: corp.source.type }, + enterprise, + summary: { + rules: context.rules.rules.length, + hasPendingRuleDeletes: context.rules.hasPendingDeletes, + documents: context.documents.articles.length, + documentsTotal: context.documents.total, + stylePreferences: context.stylePreferences.ok + ? "ok" + : `error: ${context.stylePreferences.error}` + } + }; } if (import.meta.main) { const args = process.argv.slice(2); const corpId = args[0] === "--corp" ? args[1] : args[0]; - runProbe({ corpId }).catch((error) => { - console.error(error instanceof Error ? error.message : error); - process.exit(1); - }); + runProbe({ corpId }) + .then((result) => printJson(result)) + .catch((error) => { + console.error(error instanceof Error ? error.message : error); + process.exit(1); + }); } From faf26b4c5b6bdb9f37877ba0cd742f621e4295ed Mon Sep 17 00:00:00 2001 From: yunyingk Date: Wed, 30 Sep 2026 01:16:25 +0800 Subject: [PATCH 4/6] Fail the suite when code writes outside the stdout allow-list MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The stdout contract was enforced by review alone, which is how `probe` shipped prose on the machine channel: 161 output sites and no test ever asked which stream they used. This test scans `src/` for `console.log` / `process.stdout.write` calls and fails on any file outside the documented exceptions — `printer.ts` (the machine-channel writer), the two document-dump commands (`doctor guide`, `skill dump`), and the entry points that echo the captured result. Asserted in both directions: a new writer fails, and an allow-listed file that stops writing fails too, so the exception list cannot outlive its justification. --- src/streams.test.ts | 78 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 src/streams.test.ts diff --git a/src/streams.test.ts b/src/streams.test.ts new file mode 100644 index 0000000..4325ecd --- /dev/null +++ b/src/streams.test.ts @@ -0,0 +1,78 @@ +import { describe, expect, test } from "bun:test"; +import { readdirSync, readFileSync } from "node:fs"; +import { join, relative } from "node:path"; + +/** + * The stdout contract, enforced as a test rather than as review vigilance. + * + * `stdout` is the machine channel: the Agent Harness parses it directly into + * typed payloads, so a stray `console.log("[probe] …")` between two JSON blobs + * breaks every consumer (the repo shipped exactly that bug in `seal-use probe`). + * Diagnostics belong on `stderr`, which needs no permission. + * + * The allow-list below mirrors the exceptions AGENTS.md already documents: + * `printer.ts` is *the* machine-channel writer (`printJson` / `printHelp`), the + * two document-dump commands are exempt because their output *is* a document, + * and `cli.ts` / `server.ts` are the entry points that echo the captured result. + * + * Both directions are asserted: a new writer fails the test, and an exception + * whose file stopped writing fails too, so the list cannot rot. + */ + +const SRC_DIR = join(import.meta.dir); + +const STDOUT_WRITERS = new Set([ + "cli/printer.ts", + "cli/commands/doctor.ts", + "cli/commands/skill.ts", + "cli.ts", + "server.ts" +]); + +const STDOUT_CALL = /(^|[^.\w])console\.log\s*\(|process\.stdout\.write\s*\(/; + +function listTypeScriptFiles(dir: string): string[] { + const found: string[] = []; + for (const entry of readdirSync(dir, { withFileTypes: true })) { + if (entry.name.startsWith(".")) continue; + const full = join(dir, entry.name); + if (entry.isDirectory()) found.push(...listTypeScriptFiles(full)); + else if (entry.isFile() && entry.name.endsWith(".ts")) found.push(full); + } + return found; +} + +function codeLines(source: string): string[] { + // Comments may legitimately discuss console.log; only executable code counts. + return source + .replace(/\/\*[\s\S]*?\*\//g, "") + .replace(/^[ \t]*\/\/.*$/gm, "") + .split("\n"); +} + +describe("stdout stream contract", () => { + test("nothing writes to stdout outside the documented machine channel", () => { + const violations: string[] = []; + const actualWriters = new Set(); + + for (const file of listTypeScriptFiles(SRC_DIR)) { + const rel = relative(SRC_DIR, file).split("\\").join("/"); + if (rel.endsWith(".test.ts") || rel.endsWith(".generated.ts")) continue; + + codeLines(readFileSync(file, "utf8")).forEach((line, index) => { + if (!STDOUT_CALL.test(line)) return; + actualWriters.add(rel); + if (!STDOUT_WRITERS.has(rel)) { + violations.push(`${rel}:${index + 1}: ${line.trim()}`); + } + }); + } + + expect(violations).toEqual([]); + + // An allow-listed file that no longer writes to stdout has lost its reason + // to be exempt; drop it rather than let the exception outlive the code. + const staleExceptions = [...STDOUT_WRITERS].filter((file) => !actualWriters.has(file)); + expect(staleExceptions).toEqual([]); + }); +}); From d530f9a47be612f9e33f2fc6b990677c3b4a3fe3 Mon Sep 17 00:00:00 2001 From: yunyingk Date: Wed, 30 Sep 2026 01:17:12 +0800 Subject: [PATCH 5/6] Stop advertising the session header no handler reads MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The adapter's CORS allow-list offered `X-Seal-Home-Session` and openapi declared it as a `localSession` security scheme required on every operation — while no handler ever consulted the header and the scheme's own description admitted it authenticates nothing. Generated clients would fabricate a token for a check that does not exist, and a browser client sending it could fail a preflight against a header the server no longer offers. Remove the header from the allow-list (it now mirrors the two headers this adapter actually reads), drop the scheme and its `security` requirement, and state the trust model plainly in `info.description` where an API consumer sees it. SECURITY.md keeps the authoritative wording and points at that paragraph instead of at a scheme that no longer exists. The local-adapter stance itself is untouched: no authentication is added, per `.agents/rules/security-posture.md`. --- SECURITY.md | 4 ++-- dist/openapi.json | 15 +-------------- openapi/openapi.yaml | 17 +++++------------ src/http/routes.ts | 7 ++++++- src/http/server.test.ts | 5 +++++ 5 files changed, 19 insertions(+), 29 deletions(-) diff --git a/SECURITY.md b/SECURITY.md index 26a88d3..203dd3a 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -35,8 +35,8 @@ than described here. `seal-use service start` serve `/api/cli`, `/v1/*` and `/shutdown` on `127.0.0.1:8787` with no token check and `Access-Control-Allow-Origin: *`; the adapter acts with the credentials already stored on the machine. It is a local automation surface. Keep it bound to loopback, and do not - run it on a shared or multi-user host. See the `securitySchemes.localSession` note in - `openapi/openapi.yaml`. + run it on a shared or multi-user host. The OpenAPI document declares no security scheme — it + says so in `info.description` rather than advertising a header nothing checks. - **Self-update and the install script do not verify signatures.** `seal-use update` downloads a release binary and replaces the running executable; `scripts/install.sh` compares `checksums.txt` but only warns on a mismatch. Prefer the direct GitHub source diff --git a/dist/openapi.json b/dist/openapi.json index b03df1b..9a773f9 100644 --- a/dist/openapi.json +++ b/dist/openapi.json @@ -3,7 +3,7 @@ "info": { "title": "seal-use Wrapped API", "version": "0.10.40", - "description": "HTTP contract for the seal-use wrapped backend API, served by the local HTTP adapter\n(`seal-use http`, or the `seal-use service start` daemon; default http://127.0.0.1:8787).\n\nThese endpoints describe the stable wrapped API for frontend developers and agents. They are\nnot the raw downstream Seal endpoints: seal-use is responsible for enterprise selection,\nsource authentication, response compaction, and diagnostics-friendly fields.\n\nEvery operation declares `x-implementation-status`, so a caller can tell what the running\nadapter actually serves:\n\n- `implemented` — routed by `src/http/routes.ts` today. `src/http/openapi-implementation.test.ts`\n fails when an `implemented` operation has no matching route.\n- `planned` — contract-only, designed but not routed yet. Calling it returns 404.\n\nThe same capabilities are reachable through the CLI, and through the optional MCP server when\nit is enabled.\n" + "description": "HTTP contract for the seal-use wrapped backend API, served by the local HTTP adapter\n(`seal-use http`, or the `seal-use service start` daemon; default http://127.0.0.1:8787).\n\nThese endpoints describe the stable wrapped API for frontend developers and agents. They are\nnot the raw downstream Seal endpoints: seal-use is responsible for enterprise selection,\nsource authentication, response compaction, and diagnostics-friendly fields.\n\nEvery operation declares `x-implementation-status`, so a caller can tell what the running\nadapter actually serves:\n\n- `implemented` — routed by `src/http/routes.ts` today. `src/http/openapi-implementation.test.ts`\n fails when an `implemented` operation has no matching route.\n- `planned` — contract-only, designed but not routed yet. Calling it returns 404.\n\nThe same capabilities are reachable through the CLI, and through the optional MCP server when\nit is enabled.\n\nAuthentication: none. The adapter answers every request with the enterprise credentials already\nstored on this machine, and never checks who is calling — so keep it on loopback (the default)\nand never expose the port to a network or an origin you do not control. The full trust model is\nin SECURITY.md, \"Trust model and documented limitations\".\n" }, "servers": [ { @@ -11,11 +11,6 @@ "description": "Local HTTP adapter (`seal-use http`, or the `seal-use service start` daemon). Loopback-only by default." } ], - "security": [ - { - "localSession": [] - } - ], "tags": [ { "name": "Corps", @@ -2777,14 +2772,6 @@ } }, "components": { - "securitySchemes": { - "localSession": { - "type": "apiKey", - "in": "header", - "name": "X-Seal-Home-Session", - "description": "Reserved header. The local adapter does not currently authenticate requests: it acts with\nthe credentials already stored on this machine for the selected enterprise. Keep it bound\nto loopback (`--host 127.0.0.1`) and do not expose the port to a network or an origin you\ndo not control.\n" - } - }, "parameters": { "CorpId": { "name": "corpId", diff --git a/openapi/openapi.yaml b/openapi/openapi.yaml index cb689e3..18e70ea 100644 --- a/openapi/openapi.yaml +++ b/openapi/openapi.yaml @@ -19,11 +19,14 @@ info: The same capabilities are reachable through the CLI, and through the optional MCP server when it is enabled. + + Authentication: none. The adapter answers every request with the enterprise credentials already + stored on this machine, and never checks who is calling — so keep it on loopback (the default) + and never expose the port to a network or an origin you do not control. The full trust model is + in SECURITY.md, "Trust model and documented limitations". servers: - url: http://localhost:8787 description: Local HTTP adapter (`seal-use http`, or the `seal-use service start` daemon). Loopback-only by default. -security: - - localSession: [] tags: - name: Corps description: Local enterprise configuration selection. @@ -40,16 +43,6 @@ tags: paths: $ref: ./paths/index.yaml components: - securitySchemes: - localSession: - type: apiKey - in: header - name: X-Seal-Home-Session - description: | - Reserved header. The local adapter does not currently authenticate requests: it acts with - the credentials already stored on this machine for the selected enterprise. Keep it bound - to loopback (`--host 127.0.0.1`) and do not expose the port to a network or an origin you - do not control. parameters: $ref: ./components/parameters.yaml responses: diff --git a/src/http/routes.ts b/src/http/routes.ts index 5eb2216..bb012f7 100644 --- a/src/http/routes.ts +++ b/src/http/routes.ts @@ -45,7 +45,12 @@ export async function handleHttpRequest(req: IncomingMessage, res: ServerRespons // 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"); + // 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); diff --git a/src/http/server.test.ts b/src/http/server.test.ts index 131c97e..676db51 100644 --- a/src/http/server.test.ts +++ b/src/http/server.test.ts @@ -102,5 +102,10 @@ describe("HTTP Server", () => { 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"); }); }); From b8de4cc8009fbd77dac795b0956b7e682d37a7de Mon Sep 17 00:00:00 2001 From: yunyingk Date: Wed, 30 Sep 2026 01:17:39 +0800 Subject: [PATCH 6/6] Correct README drift and check the docs against the dispatcher MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit README documented commands the dispatcher no longer accepts: `seal-use tool ` and `seal-use tools list` were both dropped in v0.10.39 while the README kept telling readers to run them (verified: both answer "Unknown command"). It also described `./enterprises` as loaded by default, which a test explicitly asserts is *not*, claimed the HTTP adapter does not serve the OpenAPI document it serves at `/openapi.json`, described `service start` as a stdio wrapper rather than the HTTP adapter it runs, and said the MCP server advertises exactly one tool when it advertises two (and none without `SEAL_USE_MCP_ENABLED`). Each claim was rewritten against the code. The `seal-use update` paragraph now describes all three installation modes instead of only the source-checkout one. To keep the docs from drifting again, the suite now scans README, AGENTS.md, SECURITY.md, the skill references, and the `.agents/rules` for `seal-use ` and fails if any area is not dispatchable — it flags `tool` and `tools` on the pre-fix README, so the check is live rather than decorative. --- README.md | 33 +++++++++-------- src/cli/docs-commands.test.ts | 69 +++++++++++++++++++++++++++++++++++ 2 files changed, 87 insertions(+), 15 deletions(-) create mode 100644 src/cli/docs-commands.test.ts diff --git a/README.md b/README.md index 834c4fa..6897ac8 100644 --- a/README.md +++ b/README.md @@ -39,7 +39,7 @@ After installation: seal-use version # Check version seal-use skill install # Install Agent skill to ~/.agents/skills/seal-use seal-use mcp-config # Print an MCP server snippet (for Cursor / Claude Desktop / Codex) -seal-use update # Future self-update directly from GitHub Release +seal-use update # Self-update (GitHub Releases binary, Homebrew, or source) ``` ## Source Setup & Development @@ -81,7 +81,7 @@ Create a user-level Hose enterprise config that works from any directory: mkdir -p ~/.config/seal-use/enterprises seal-use corps add-hose-persistent --json '{"name":"企业名称","domain":"https://app.ekuaibao.com","appKey":"...","appSecurity":"...","proxyStaffBizId":"corpId:staffId"}' seal-use auth diagnose --corp -seal-use tools list +seal-use corps list ``` `corps add-hose-persistent` verifies by default before writing the config. It uses the Hose OpenAPI credential response to derive the corporation ID, then checks provisional auth, Seal SSO, and Seal `whoami`. Pass `"force":true` or `"verify":false` only when you intentionally want to write a config that may fail later. @@ -129,7 +129,7 @@ Update an existing checkout: seal-use update ``` -`seal-use update` runs `git pull --ff-only`, installs dependencies, and restarts the local service if it was running. +`seal-use update` adapts to how it was installed: from a source checkout it runs `git pull --ff-only` and refreshes dependencies with `bun install`; a standalone binary downloads the matching GitHub Release asset and replaces itself; a Homebrew install upgrades through `brew upgrade seal-use`. Each mode stops the local service while updating and starts it again on success if one was running. Because `npm link` makes the global command a symlink into your checkout, **updating the checkout is sufficient** — no reinstall step required. The symlink continues to point to the updated source. @@ -144,7 +144,7 @@ The canonical plugin skill lives at `skills/seal-use`. There is no in-repo `.age ## ZCode Plugin -The repository is also a ZCode plugin. Install `seal-use` from the `yingqing-plugins` marketplace in **Settings → Plugin Management**, or add this repository as a local plugin directory while developing. The plugin ships the `skills/seal-use` skill; it has no MCP surface — use `seal-use mcp` (or the `mcp-config` snippet) if you want MCP locally. +The repository is also a ZCode plugin. Install `seal-use` from the `yingqing-plugins` marketplace in **Settings → Plugin Management**, or add this repository as a local plugin directory while developing. The plugin ships the `skills/seal-use` skill; it has no MCP surface. For MCP locally, paste the snippet from `seal-use mcp-config` into your host — it starts `seal-use mcp` with `SEAL_USE_MCP_ENABLED=true`, which the server needs before it exposes any tool. The plugin exposes no MCP tools. The `seal_cli` / `seal_cli_write` tools exist only on the local MCP server started by `seal-use mcp` (or by whatever host consumes the `mcp-config` snippet), where they accept the same command syntax as the global CLI. @@ -157,7 +157,7 @@ bun run build:binary ## CLI -Use the CLI from skills, shell scripts, or agents. CLI intentionally keeps the full fine-grained tool list available through `seal-use tool `. +Use the CLI from skills, shell scripts, or agents. Domain commands such as `seal-use approval-runs ...`, `seal-use rules ...`, and `seal-use documents ...` wrap the shared tool registry, so the CLI, the HTTP adapter, and the MCP server all end up running the same tool handler with the same validation. ```bash seal-use version @@ -165,11 +165,9 @@ seal-use config paths seal-use config get seal-use config mode stateless seal-use config mode stateful --corp -seal-use tools list seal-use corps list seal-use auth diagnose --corp seal-use approval-runs summary --corp --date 2026-06-08 --timezone Asia/Shanghai -seal-use tool seal_approval_runs_summary --corp --json '{"date":"2026-06-08","timezone":"Asia/Shanghai"}' ``` CLI output is JSON on stdout. Errors are written to stderr. @@ -177,8 +175,8 @@ CLI output is JSON on stdout. Errors are written to stderr. Enterprise config lookup: - If `SEAL_USE_ENTERPRISES_DIR` is set, only that directory is loaded. -- Otherwise `./enterprises` and `~/.config/seal-use/enterprises` are merged. -- User-level configs override same-ID configs from `./enterprises`. +- Otherwise the test directory (`seal-use config test-dir`) and `~/.config/seal-use/enterprises` are merged; a `./enterprises` folder in the working directory is **not** read unless an env var points at it. +- A user-level config overrides a same-ID config from the test directory. Global enterprise selection is stateless by default. Its configuration is stored in `~/.config/seal-use/config.json` (override with `SEAL_USE_CONFIG_FILE`). In stateless mode, @@ -191,7 +189,7 @@ Use `seal-use auth diagnose --corp ` when login fails in stateless mode. ## Wrapped API Documentation -The OpenAPI source under `openapi/` describes the planned HTTP contract for a seal-use wrapped API. The current implementation exposes a local MCP server over stdio (`seal-use mcp`) and does not listen on the OpenAPI server URL. It is intentionally not the raw downstream Seal API: endpoints are named around seal-use concepts such as corps, auth diagnosis, approval context, run summaries, document URLs, and Langfuse bridge hints. +The OpenAPI source under `openapi/` describes the HTTP contract for the seal-use wrapped API, and the local HTTP adapter serves it live: `GET /openapi.json` returns the bundled contract and `GET /docs` serves an interactive reference, so the document is not merely aspirational. Each operation carries `x-implementation-status` — `implemented` operations are routed by `src/http/routes.ts` today (a test fails if one has no matching route), while `planned` ones are contract-only and return 404 until they are built. It is intentionally not the raw downstream Seal API: endpoints are named around seal-use concepts such as corps, auth diagnosis, approval context, run summaries, document URLs, and Langfuse bridge hints. Source files are split by domain: @@ -225,7 +223,7 @@ Service state is stored under `~/.config/seal-use/`: - `service.pid` - `service.log` -The service is intentionally local and currently acts as a lifecycle wrapper for a long-lived stdio/MCP process; it does not expose the HTTP/OpenAPI contract. It is useful as a stable process lifecycle for future warmed caches and update/restart workflows; normal CLI commands still work without it. +The service is intentionally local: `service start` runs the same HTTP adapter as `seal-use http` in the background, serving `/docs`, `/openapi.json`, `POST /api/cli`, `POST /api/tool/:name`, `/v1/*`, and `/shutdown` on `127.0.0.1:8787` (loopback by default). It is useful as a stable process lifecycle for update/restart workflows and as a base URL for a local frontend; normal CLI commands still work without it. ## Enterprise Config @@ -257,7 +255,12 @@ The service is intentionally local and currently acts as a lifecycle wrapper for Most users do not need MCP. The public/shared path is the global `seal-use` CLI plus the optional local service. -The MCP server advertises exactly one tool, `seal_cli`: +The MCP server exposes two tools — and only when `SEAL_USE_MCP_ENABLED=true`, which is what the `seal-use mcp-config` snippet carries; without that flag `tools/list` answers with an empty list: + +- `seal_cli` runs read-only commands and refuses anything that mutates tenant state, self-updates, or starts a server. +- `seal_cli_write` runs the same dispatcher with mutating commands available; confirm the exact command with the user before calling it. + +Both take the command as a string: ```json { @@ -265,11 +268,11 @@ The MCP server advertises exactly one tool, `seal_cli`: } ``` -It runs the same CLI dispatcher as the global binary, so read operations, write operations, `config`, `service`, and `update` remain available. Write-operation confirmations and explicit enterprise-ID rules continue to be defined by this skill. +Both run the same CLI dispatcher as the global binary, so `config`, `service`, and `update` behave exactly as they do on the command line. Write-operation confirmations and explicit enterprise-ID rules continue to be defined by this skill. ## CLI-First Architecture -All Agent and automation capabilities are accessed through standard `seal-use ` CLI invocations (or through the single `seal_cli` MCP tool passing the command string). Internal domain services output pure, parseable JSON on `stdout`, with human diagnostics and suggestions routed to `stderr`. +All Agent and automation capabilities are accessed through standard `seal-use ` CLI invocations (or through the `seal_cli` / `seal_cli_write` MCP tools passing the command string). Internal domain services output pure, parseable JSON on `stdout`, with human diagnostics and suggestions routed to `stderr`. Key CLI command groups: - **`seal-use corps ...`**: enterprise tenant management, onboarding, switching, and assistance link intake. @@ -312,7 +315,7 @@ When `_langfuseTraceId` exists, downstream tools should fetch the trace directly - Prefer Bun-native commands in this repository: `bun run check`, `bun test`, and `seal-use ...`. `npm run check` may work, but Bun is the project runtime and lockfile owner. - Keep CLI entry points thin. Shared behavior belongs in `src/core` and `src/domains`; `src/cli.ts` should only handle command parsing, process lifecycle, and JSON output. - Do not print diagnostic text to stdout from the MCP server. MCP uses stdout as the protocol stream; use stderr for server diagnostics. -- Keep the MCP exported surface to the single `seal_cli` router; command knowledge belongs in this skill and its focused references. +- Keep the MCP exported surface to the `seal_cli` (read-only) and `seal_cli_write` (mutating) pair; command knowledge belongs in this skill and its focused references. - Prefer CLI or script processing for large tool responses. For daily approval questions, call `seal-use approval-runs summary --corp ...` instead of reading long `seal_approval_runs_search` output manually. - Keep broad search tools compact by default. Add explicit opt-in flags such as `includeBridge` for verbose fields that are useful only in deeper debugging. - When Seal API timestamp filters are uncertain, filter again in tool code by `createdAt` and explicit timezone before presenting date-based answers. diff --git a/src/cli/docs-commands.test.ts b/src/cli/docs-commands.test.ts new file mode 100644 index 0000000..03f8b60 --- /dev/null +++ b/src/cli/docs-commands.test.ts @@ -0,0 +1,69 @@ +import { describe, expect, test } from "bun:test"; +import { readFileSync, readdirSync } from "node:fs"; +import { join } from "node:path"; +import { KNOWN_AREAS, UPDATE_ALIASES } from "./runner.js"; + +/** + * Documentation cross-check: every command a maintained doc shows a reader must + * still dispatch. + * + * The hand-written docs drifted once already — README kept documenting + * `seal-use tool ` and `seal-use tools list` for two releases after + * the dispatcher dropped both areas, and it described `./enterprises` as loaded + * when a test explicitly asserts it is not. Nothing failed, so nothing got + * fixed. This test turns the docs into a checked claim. + * + * Scope is deliberate: `CHANGELOG.md` records history (old commands belong + * there) and `docs/proposals/` is forward-looking by definition, so both are + * excluded. Commands are read from code spans (`` `seal-use area …` ``) and + * from example lines, which is where a reader would copy one from — bare prose + * like "the seal-use wrapped API" is not a command and is not matched. + */ + +const REPO_ROOT = join(import.meta.dir, "..", ".."); + +const DOC_FILES = [ + "README.md", + "AGENTS.md", + "SECURITY.md", + "skills/seal-use/SKILL.md", + ...readdirSync(join(REPO_ROOT, "skills/seal-use/references")).map( + (name) => `skills/seal-use/references/${name}` + ), + ...readdirSync(join(REPO_ROOT, ".agents/rules")).map((name) => `.agents/rules/${name}`) +]; + +/** + * Names the dispatcher accepts before the `KNOWN_AREAS` gate — `seal-use help`, + * `seal-use version` — plus `v`. Everything else must be a known area; update + * spellings (`upgrade`, `self-update`, …) come from UPDATE_ALIASES. + */ +const EARLY_DISPATCH = new Set(["version", "v", "help"]); + +function referencedAreas(markdown: string): Set { + const found = new Set(); + // Inline code spans: `seal-use …` + for (const match of markdown.matchAll(/`seal-use ([a-z][a-z0-9-]*)/g)) found.add(match[1]!); + // Example lines a reader would copy and paste. + for (const match of markdown.matchAll(/^\s*seal-use ([a-z][a-z0-9-]*)/gm)) found.add(match[1]!); + return found; +} + +function isDispatchable(area: string): boolean { + return KNOWN_AREAS.has(area) || UPDATE_ALIASES.has(area) || EARLY_DISPATCH.has(area); +} + +describe("documentation references live commands", () => { + test("every `seal-use ` in the maintained docs is dispatchable", () => { + const stale: Record = {}; + + for (const file of DOC_FILES) { + const unknown = [...referencedAreas(readFileSync(join(REPO_ROOT, file), "utf8"))] + .filter((area) => !isDispatchable(area)) + .sort(); + if (unknown.length) stale[file] = unknown; + } + + expect(stale).toEqual({}); + }); +});