diff --git a/.gitignore b/.gitignore index ac8dad2..a282911 100644 --- a/.gitignore +++ b/.gitignore @@ -15,6 +15,9 @@ tmp/ .local/ /reports/ +# WorkBuddy workspace data (memory logs, project state) — keep on disk, never commit +.workbuddy/ + # Developer-only build-time credentials for compile-time injection — never committed .env.langfuse .env diff --git a/skills/seal-use/SKILL.md b/skills/seal-use/SKILL.md index 729b898..0ffd8e3 100644 --- a/skills/seal-use/SKILL.md +++ b/skills/seal-use/SKILL.md @@ -155,6 +155,7 @@ seal-use langfuse observation # 最后才取焦点 | 导出审核记录 Excel、额外人工审批流、高级筛选或导出任务等待 | `references/approval-run-export.md` | 只查命令语法时读 `cli.md`;报告与复核台账走 `report-templates.md` | | 单号对应费用是否入库、数据管理费用明细、费用库检索或记录关联 | `references/expense-data.md` | 明确要求审批结论时,再读 `approval-run-lightweight.md` | | CLI 参数、退出码或命令语法 | `references/cli.md` | 只查业务流程时不要加载本文件 | +| 租户禁用/启用、企业已停用、命令提示「已禁用」 | `references/tenant-status.md` | 只查命令语法时读 `cli.md` | | Webhook 资源包(ZIP/Excel 结构、附件校验、策略配置) | `references/webhook-resource-pack.md` | 只查命令语法时读 `cli.md`,不要加载本文件 | | 规则数量、摘要列表、历史规则、编号重排或规则搜索 | `references/rule-lightweight.md` | 需要质量评分/模糊表述检查时,改读 `rule-lint.md` | | 制度/知识文档(`documents`)、正文文件导出编辑、文档更新/删除或本地快照 | `references/documents.md` | 只查命令参数时读 `cli.md` | diff --git a/skills/seal-use/references/cli.md b/skills/seal-use/references/cli.md index 6708d06..1d70341 100644 --- a/skills/seal-use/references/cli.md +++ b/skills/seal-use/references/cli.md @@ -46,6 +46,8 @@ seal-use corps current [--corp ] seal-use corps switch seal-use corps mark --env [--dry-run] [--confirm] seal-use corps rename --name +seal-use corps disable [--dry-run] [--confirm] +seal-use corps enable [--dry-run] [--confirm] seal-use corps bind-test [--confirm] [--force] seal-use corps bind-test --corp [--confirm] [--force] seal-use corps unbind-test [] [--confirm] diff --git a/skills/seal-use/references/tenant-status.md b/skills/seal-use/references/tenant-status.md new file mode 100644 index 0000000..3853f0e --- /dev/null +++ b/skills/seal-use/references/tenant-status.md @@ -0,0 +1,56 @@ +# 租户启用 / 禁用状态 + +适用信号:企业已停用、需要临时封禁某个租户、命令报「已禁用」、想确认禁用后还能不能搜到该企业。 + +## 状态定义 + +企业配置文件(`~/.config/seal-use/enterprises/*.json`)顶层的 `active` 字段: + +```json +{ + "id": "acme", + "name": "Acme Corporation", + "active": false, + "source": { "type": "hose", "...": "..." } +} +``` + +- 字段在**企业**上,不在 `source` 里。合思来源(`type: "hose"`)与 Seal 本源(`type: "seal"`)共用同一个开关,行为完全一致,不存在某一来源例外。 +- **字段缺失 = 启用**。旧配置零迁移;读取和任何配置更新都会把缺省值物化成显式的 `active: true`。 +- **字段值非法 = 禁用(fail-closed)**。`"false"` 字符串、`null`、`0`、对象等任何非布尔值都归一化为 `active: false`。配置文件**不会**被丢弃,企业仍可检索并显示 `active: false`,指向它的命令一律阻断,stderr 告警并给出修复命令。绝不会把写坏的值当成启用。 +- 显式 `active: false` = 禁用。不要靠删除配置文件、改文件名或清空凭据来「禁用」,那会破坏检索可见性与恢复路径。 + +## 命令 + +```bash +seal-use corps disable --dry-run # 预览,不写文件 +seal-use corps disable --confirm # 实际禁用 +seal-use corps enable --confirm # 恢复 +``` + +- 不加 `--confirm` / `--yes` 会返回退出码 `10`(确认门)。 +- `--dry-run` 返回 `preview: true` 与 `changesDiff: { before, after }`,不写配置。 +- 这两个命令是**唯一**能解析禁用企业的命令;没有它们,禁用后无法恢复。 + +## 行为口径(严格遵守) + +| 场景 | 结果 | +| --- | --- | +| `corps list` / `corps search` / `corps find` | 禁用企业**仍可检索**,输出带 `active: false`。禁用不影响搜索可见性 | +| 任何显式指定该企业 ID 的命令 | **统一阻断、不执行**,退出码 `14`,stderr 提示 `seal-use corps enable --confirm` | +| `corps enable` / `corps disable` | 允许执行(唯一豁免) | + +阻断发生在企业解析处(`resolveCorpConfig`),早于创建 HTTP client、认证续期和任何业务 handler,因此不会有网络请求或副作用。覆盖: + +- CLI 所有 `--corp ` 与位置参数形式(查询、写操作、绑定、同步、诊断、本地导出任务); +- MCP 的 `seal_use` 与 `seal_use_write` 两个网关; +- stateful 模式下 `defaultCorpId` 指向禁用企业、或无显式 ID 时兜底命中的第一个企业; +- webhook 重放的 `--source-corp` / `--target-corp` 以及能力注册表中的等价解析; +- 本地 `rules lint --file` 与 `report --ledger` 的降级分支不会吞掉该阻断。 + +## 排查步骤 + +1. `seal-use corps search <关键词>` 确认企业仍在列表中并读取 `active` 字段。 +2. 若确需操作该企业:`seal-use corps enable --confirm`。这个值非法时同样有效——该命令会把字段重写为 `true`,一并修复坏配置。 +3. 若确需保持禁用,不要绕过闸门(不要直接改 ID、不要复制配置换新 ID)。解除封禁是唯一正当路径。 +4. 退出码 `14` 属安全守卫拦截,不是认证失败(`11`)或参数错误(`2`)。若看到 `13`「No enterprise config found」,说明整个配置文件被跳过(JSON 格式错误或必填字段缺失),与本开关无关。详见 `references/cli.md`。 diff --git a/src/cli/commands/corps.ts b/src/cli/commands/corps.ts index d13532d..daf17ed 100644 --- a/src/cli/commands/corps.ts +++ b/src/cli/commands/corps.ts @@ -1,4 +1,5 @@ import { usageError } from "../../core/errors.js"; +import { handleCorpActive } from "./corps/active.js"; import { handleCorpBindings } from "./corps/bindings.js"; import { handleCorpOnboarding, extractKeysFromLinkAction, showCorpKeysAction } from "./corps/onboarding.js"; import { handleCorpOverview } from "./corps/overview.js"; @@ -14,6 +15,7 @@ export async function handleCorpsCommand( args: ParsedArgs ) { if (await handleCorpOverview(action, maybeName, args)) return; + if (await handleCorpActive(action, maybeName, args)) return; if (await handleCorpBindings(action, maybeName, args)) return; if (await handleCorpSync(action, maybeName, args)) return; if (await handleCorpOnboarding(action, maybeName, args)) return; diff --git a/src/cli/commands/corps/active.ts b/src/cli/commands/corps/active.ts new file mode 100644 index 0000000..998c3c1 --- /dev/null +++ b/src/cli/commands/corps/active.ts @@ -0,0 +1,63 @@ +import { updateCorpConfig } from "../../../core/config/loader.js"; +import { confirmationRequired, usageError } from "../../../core/errors.js"; +import { booleanOption, dryRunOption, stringOption } from "../../parser.js"; +import { printJson } from "../../printer.js"; +import type { ParsedArgs } from "../../types.js"; + +/** + * Tenant availability switch for both `hose` and `seal` sources. + * + * This is the ONLY command surface allowed to resolve a disabled tenant: without + * it, `corps enable` could not restore an enterprise that the gate now blocks. + * All other commands resolve through `selectCorp()` and are refused upstream. + */ +export async function handleCorpActive( + action: string | undefined, + maybeName: string | undefined, + args: ParsedArgs +): Promise { + if (action !== "disable" && action !== "enable") return false; + + const corpId = maybeName ?? stringOption(args.options.corp); + if (!corpId) { + throw usageError(`Usage: seal-use corps ${action} [--dry-run] [--confirm]`); + } + + const targetActive = action === "enable"; + const { selectCorp } = await import("../../helpers.js"); + const corp = selectCorp(corpId, { allowDisabled: true }); + const previousActive = corp.active ?? true; + + if (dryRunOption(args)) { + printJson({ + preview: true, + dryRun: true, + mutation: `corps ${action}`, + corpId: corp.id, + corpName: corp.name, + sourceType: corp.source.type, + changesDiff: { before: previousActive, after: targetActive }, + note: "禁用只阻断显式指定该企业 ID 的命令,不影响 corps list/search 的检索可见性。" + }); + return true; + } + + const confirmed = booleanOption(args.options.confirm) === true || booleanOption(args.options.yes) === true; + if (!confirmed) { + throw confirmationRequired( + `Refusing to ${action} enterprise '${corp.name}' (${corp.id}) without --confirm.`, + `seal-use corps ${action} ${corp.id} --confirm` + ); + } + + const updated = updateCorpConfig(corp.id, { active: targetActive }); + printJson({ + success: true, + id: updated.id, + name: updated.name, + sourceType: updated.source.type, + active: updated.active, + previousActive + }); + return true; +} diff --git a/src/cli/commands/corps/overview.ts b/src/cli/commands/corps/overview.ts index 7cc3fbe..dd3b687 100644 --- a/src/cli/commands/corps/overview.ts +++ b/src/cli/commands/corps/overview.ts @@ -35,6 +35,9 @@ export async function handleCorpOverview( } const corpId = stringOption(args.options.corp); + // Deliberately NOT filtered by `active`: disabling a tenant gates command + // execution at corp resolution, never discovery. Keep disabled enterprises + // searchable for both `hose` and `seal` sources and just surface the flag. const allCorps = loadCorpConfigs(); const globalConfig = loadGlobalConfig(); const currentCorpId = corpId ?? ( @@ -88,6 +91,7 @@ export async function handleCorpOverview( printJson(displayList.map((item) => ({ id: item.id, name: item.name, + active: item.active ?? true, environment: item.environment ?? "production", sourceType: item.source.type, provider: (item.source as any).provider ?? item.source.type, @@ -113,6 +117,7 @@ export async function handleCorpOverview( printJson({ id: corp.id, name: corp.name, + active: corp.active ?? true, environment: corp.environment ?? "production", configFile, seal: { @@ -139,6 +144,7 @@ export async function handleCorpOverview( printJson({ id: corp.id, name: corp.name, + active: corp.active ?? true, environment: corp.environment ?? "production", sourceType: corp.source.type, provider: (corp.source as any).provider ?? corp.source.type, diff --git a/src/cli/commands/corps/tenant-active.test.ts b/src/cli/commands/corps/tenant-active.test.ts new file mode 100644 index 0000000..353ea92 --- /dev/null +++ b/src/cli/commands/corps/tenant-active.test.ts @@ -0,0 +1,291 @@ +import { afterEach, describe, expect, test } from "bun:test"; +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { runCli } from "../../runner.js"; +import { selectCorp } from "../../helpers.js"; +import { getEnterprisesDirCandidates, loadCorpConfigs, loadGlobalConfig } from "../../../core/config/loader.js"; +import { resolveCorpConfig } from "../../../core/config/manager.js"; +import { resolveReplayCorpPair } from "../../../domains/seal/replay/webhook.js"; + +const ENV_KEYS = [ + "SEAL_USE_ENTERPRISES_DIR", + "SEAL_USE_CONFIG_FILE", + "SEAL_USE_TOKEN_STORE", + "SEAL_USE_USAGE_FILE", + "SEAL_DISABLE_BG_UPDATE" +] as const; + +const ORIGINAL_ENV = Object.fromEntries(ENV_KEYS.map((key) => [key, process.env[key]])); +const ORIGINAL_FETCH = globalThis.fetch; +const tempDirs: string[] = []; + +afterEach(() => { + for (const key of ENV_KEYS) { + const value = ORIGINAL_ENV[key]; + if (value === undefined) delete process.env[key]; + else process.env[key] = value; + } + globalThis.fetch = ORIGINAL_FETCH; + for (const dir of tempDirs.splice(0)) rmSync(dir, { recursive: true, force: true }); +}); + +const SOURCE_VARIANTS = [ + { + label: "hose", + source: { + type: "hose", + domain: "https://app.ekuaibao.com", + appKey: "app-key", + appSecurity: "app-security", + corpId: "ID01", + staffId: "ID01:STAFF01" + } + }, + { + label: "seal", + source: { + type: "seal", + token: "seal-token", + sealUrl: "https://acme.sealai.cc" + } + } +] as const; + +function setup(): { root: string; enterprises: string } { + const root = mkdtempSync(join(tmpdir(), "seal-tenant-active-")); + tempDirs.push(root); + const enterprises = join(root, "enterprises"); + mkdirSync(enterprises, { recursive: true }); + process.env.SEAL_USE_ENTERPRISES_DIR = enterprises; + process.env.SEAL_USE_CONFIG_FILE = join(root, "config.json"); + process.env.SEAL_USE_TOKEN_STORE = join(root, "tokens.json"); + process.env.SEAL_USE_USAGE_FILE = join(root, "usage.json"); + process.env.SEAL_DISABLE_BG_UPDATE = "1"; + return { root, enterprises }; +} + +function writeCorp( + dir: string, + options: { + id: string; + name: string; + source: Record; + active?: unknown; + } +): string { + const payload: Record = { + id: options.id, + name: options.name, + source: options.source, + seal: { url: "https://acme.sealai.cc" }, + auth: { refreshTtl: 300 } + }; + if (options.active !== undefined) payload.active = options.active; + const path = join(dir, `${options.id}.json`); + writeFileSync(path, JSON.stringify(payload)); + return path; +} + +function corpFile(dir: string, id: string): Record { + return JSON.parse(readFileSync(join(dir, `${id}.json`), "utf-8")); +} + +/** Fail loudly if a command reaches any upstream API: a blocked command must never execute. */ +function guardNetwork(): { calls: () => number } { + let calls = 0; + globalThis.fetch = (async () => { + calls += 1; + throw new Error("network request must not happen for a disabled tenant"); + }) as unknown as typeof globalThis.fetch; + return { calls: () => calls }; +} + +/** Commands that explicitly name the tenant id, spanning local/corp/client handlers. */ +function commandsNamingCorp(id: string): string[][] { + return [ + ["corps", "get", id], + ["corps", "current", "--corp", id], + ["corps", "mark", id, "--env", "test"], + ["corps", "rename", id, "--name", "Renamed"], + ["contacts", "departments", "--corp", id], + ["rules", "list", "--corp", id], + ["documents", "list", "--corp", id], + ["billing", "status", "--corp", id], + ["webhook", "list", "--corp", id], + ["source", "config", "--corp", id], + ["auth", "status", "--corp", id] + ]; +} + +describe("tenant active state: both sources share one gate", () => { + for (const { label, source } of SOURCE_VARIANTS) { + const id = `acme-${label}`; + const name = `Acme ${label} Corporation`; + + test(`${label}: disabled tenant stays visible in corps list and search`, async () => { + const { enterprises } = setup(); + writeCorp(enterprises, { id, name, source, active: false }); + + const listed = await runCli(["corps", "list", "--all"]); + expect(listed.exitCode).toBe(0); + expect(JSON.parse(listed.stdout)).toContainEqual(expect.objectContaining({ + id, name, active: false, sourceType: label + })); + + const searched = await runCli(["corps", "search", "Acme", "--strict"]); + expect(searched.exitCode).toBe(0); + const matches = JSON.parse(searched.stdout) as Array<{ id: string; active: boolean }>; + expect(matches.find((item) => item.id === id)).toMatchObject({ id, active: false }); + }); + + test(`${label}: every command explicitly naming the disabled tenant is blocked without executing`, async () => { + const { enterprises } = setup(); + writeCorp(enterprises, { id, name, source, active: false }); + const network = guardNetwork(); + + for (const command of commandsNamingCorp(id)) { + const result = await runCli(command); + expect({ command, exitCode: result.exitCode }).toEqual({ command, exitCode: 14 }); + expect(result.isError).toBe(true); + expect(result.stdout).toBe(""); + expect(result.stderr).toContain("已禁用"); + expect(result.stderr).toContain(`seal-use corps enable ${id}`); + } + + expect(network.calls()).toBe(0); + }); + + test(`${label}: a malformed active value fails closed without hiding the enterprise`, async () => { + const { enterprises } = setup(); + writeCorp(enterprises, { id, name, source, active: "false" }); + const network = guardNetwork(); + + const listed = await runCli(["corps", "list", "--all"]); + expect(listed.exitCode).toBe(0); + expect(JSON.parse(listed.stdout)).toContainEqual(expect.objectContaining({ + id, name, active: false, sourceType: label + })); + expect(listed.stderr).toContain("active 字段值非法"); + + // The block reports a disabled tenant (14), not a missing config (13), + // and the enterprise never disappears from discovery. + const blocked = await runCli(["corps", "get", id]); + expect(blocked.exitCode).toBe(14); + expect(blocked.stdout).toBe(""); + expect(blocked.stderr).toContain("已禁用"); + expect(network.calls()).toBe(0); + + const recovered = await runCli(["corps", "enable", id, "--confirm"]); + expect(recovered.exitCode).toBe(0); + expect(corpFile(enterprises, id).active).toBe(true); + }); + + test(`${label}: an active tenant with the same source still runs through corp resolution`, async () => { + const { enterprises } = setup(); + writeCorp(enterprises, { id, name, source, active: true }); + + const result = await runCli(["corps", "get", id]); + expect(result.exitCode).toBe(0); + expect(JSON.parse(result.stdout)).toMatchObject({ id, active: true }); + }); + + test(`${label}: disable/enable lifecycle with dry-run and confirmation gate`, async () => { + const { enterprises } = setup(); + writeCorp(enterprises, { id, name, source }); + + const preview = await runCli(["corps", "disable", id, "--dry-run"]); + expect(preview.exitCode).toBe(0); + expect(JSON.parse(preview.stdout)).toMatchObject({ + preview: true, + dryRun: true, + mutation: "corps disable", + corpId: id, + sourceType: label, + changesDiff: { before: true, after: false } + }); + expect(corpFile(enterprises, id).active).toBeUndefined(); + + const unconfirmed = await runCli(["corps", "disable", id]); + expect(unconfirmed.exitCode).toBe(10); + expect(corpFile(enterprises, id).active).toBeUndefined(); + + const disabled = await runCli(["corps", "disable", id, "--confirm"]); + expect(disabled.exitCode).toBe(0); + expect(JSON.parse(disabled.stdout)).toMatchObject({ id, active: false, previousActive: true }); + expect(corpFile(enterprises, id).active).toBe(false); + + // Re-enabling must work even though the tenant is disabled: this is the + // single documented exemption from the block. + const enabled = await runCli(["corps", "enable", id, "--confirm"]); + expect(enabled.exitCode).toBe(0); + expect(JSON.parse(enabled.stdout)).toMatchObject({ id, active: true, previousActive: false }); + expect(corpFile(enterprises, id).active).toBe(true); + + const afterEnable = await runCli(["corps", "get", id]); + expect(afterEnable.exitCode).toBe(0); + }); + + test(`${label}: a stateful default pointing at a disabled tenant is blocked`, async () => { + const { root, enterprises } = setup(); + writeCorp(enterprises, { id, name, source, active: false }); + writeFileSync(join(root, "config.json"), JSON.stringify({ + stateful: true, + defaultCorpId: id + })); + const network = guardNetwork(); + + const result = await runCli(["contacts", "departments"]); + expect(result.exitCode).toBe(14); + expect(result.stdout).toBe(""); + expect(network.calls()).toBe(0); + }); + + test(`${label}: replay refuses a disabled source or target corp through both selectors`, () => { + const { enterprises } = setup(); + const activeId = `active-${label}`; + const disabledId = `off-${label}`; + writeCorp(enterprises, { id: activeId, name: "Active Corp", source, active: true }); + writeCorp(enterprises, { id: disabledId, name: "Disabled Corp", source, active: false }); + const activeCorp = selectCorp(activeId); + + // CLI replay path: `selectCorp` is passed straight into resolveReplayCorpPair. + expect(() => resolveReplayCorpPair( + { sourceCorpId: activeId, targetCorpId: disabledId, activeCorp, force: true }, + selectCorp + )).toThrow("已禁用"); + expect(() => resolveReplayCorpPair( + { sourceCorpId: disabledId, targetCorpId: activeId, activeCorp, force: true }, + selectCorp + )).toThrow("已禁用"); + + // Capability registry replay path builds its own resolveCorpConfig selector. + const capabilitySelector = (id?: string) => resolveCorpConfig( + loadCorpConfigs(), + { + stateful: loadGlobalConfig().stateful, + defaultCorpId: loadGlobalConfig().defaultCorpId, + corpId: id + }, + getEnterprisesDirCandidates() + ); + expect(() => resolveReplayCorpPair( + { sourceCorpId: activeId, targetCorpId: disabledId, activeCorp, force: true }, + capabilitySelector + )).toThrow("已禁用"); + }); + + test(`${label}: local lint/ledger fallbacks cannot swallow a disabled-tenant block`, async () => { + const { enterprises } = setup(); + writeCorp(enterprises, { id, name, source, active: false }); + + const lint = await runCli(["rules", "lint", "--file", "rules.json", "--corp", id]); + expect(lint.exitCode).toBe(14); + expect(lint.stderr).toContain("已禁用"); + + const ledger = await runCli(["report", "validate", "--ledger", "ledger.xlsx", "--corp", id]); + expect(ledger.exitCode).toBe(14); + expect(ledger.stderr).toContain("已禁用"); + }); + } +}); diff --git a/src/cli/commands/report.ts b/src/cli/commands/report.ts index e9faa6b..b8c1ec0 100644 --- a/src/cli/commands/report.ts +++ b/src/cli/commands/report.ts @@ -6,6 +6,7 @@ import { runCapabilityResult } from "../helpers.js"; import { booleanOption, numberOption, stringOption } from "../parser.js"; import { outputOptions, printJson } from "../printer.js"; import { CliError, usageError } from "../../core/errors.js"; +import { isCorpDisabledError } from "../../core/config/active.js"; import { BUILTIN_MONTHLY_TEMPLATE, exportReportPackage, @@ -36,7 +37,10 @@ export async function handleLocalReportCommand(action: string | undefined, args: try { const { selectCorp } = await import("../helpers.js"); corp = selectCorp(corpId); - } catch { + } catch (error) { + // Ledger/review work is tenant-free, but if the caller explicitly named a + // disabled enterprise, the block must still stand instead of falling back. + if (isCorpDisabledError(error)) throw error; corp = { corpId, id: corpId, diff --git a/src/cli/help.ts b/src/cli/help.ts index c4b598b..4da0cbf 100644 --- a/src/cli/help.ts +++ b/src/cli/help.ts @@ -98,6 +98,28 @@ export const HELP_REGISTRY: AreaHelp[] = [ ], description: "Safely updates the display name of a configured enterprise without modifying underlying files manually." }, + { + name: "disable", + group: "企业配置", + summary: "Disable a tenant without removing it from enterprise search", + usage: ["seal-use corps disable [--dry-run] [--confirm]"], + options: [ + { flag: "--dry-run", description: "Preview the active-state change without writing local config" }, + { flag: "--confirm", description: "Confirm the state change (required for live execution)" } + ], + description: "Sets active=false on a Hose or Seal enterprise. The enterprise stays visible in `corps list/search`, but every command that explicitly resolves its ID is refused until it is enabled again." + }, + { + name: "enable", + group: "企业配置", + summary: "Re-enable a disabled tenant", + usage: ["seal-use corps enable [--dry-run] [--confirm]"], + options: [ + { flag: "--dry-run", description: "Preview the active-state change without writing local config" }, + { flag: "--confirm", description: "Confirm the state change (required for live execution)" } + ], + description: "Sets active=true. This is the only command allowed to resolve a disabled enterprise, so a disabled tenant can always be restored." + }, { name: "bind-test", group: "测试配对与验证", diff --git a/src/cli/helpers.ts b/src/cli/helpers.ts index 2202c68..2e34d92 100644 --- a/src/cli/helpers.ts +++ b/src/cli/helpers.ts @@ -10,7 +10,7 @@ import type { CorpConfig, GlobalConfig } from "../core/config/types.js"; import { printJson } from "./printer.js"; import type { OutputOptions } from "./types.js"; -export function selectCorp(corpId?: string): CorpConfig { +export function selectCorp(corpId?: string, options: { allowDisabled?: boolean } = {}): CorpConfig { const corps = loadCorpConfigs(); const globalConfig = loadGlobalConfig(); const corp = resolveCorpConfig( @@ -18,7 +18,8 @@ export function selectCorp(corpId?: string): CorpConfig { { stateful: globalConfig.stateful, defaultCorpId: globalConfig.defaultCorpId, - corpId + corpId, + allowDisabled: options.allowDisabled }, getEnterprisesDirCandidates() ); diff --git a/src/cli/runner.ts b/src/cli/runner.ts index dcbadea..3476419 100755 --- a/src/cli/runner.ts +++ b/src/cli/runner.ts @@ -6,6 +6,7 @@ import type { CorpConfig } from "../core/config/types.js"; import { VERSION_INFO } from "../version.js"; import { isUpdateCacheExpired, loadUpdateCache, triggerBackgroundUpdateCheck } from "../core/update-cache.js"; import { classifyCliError, usageError, validationError } from "../core/errors.js"; +import { isCorpDisabledError } from "../core/config/active.js"; import { booleanOption, materialPackFilePolicyOptions, @@ -313,7 +314,10 @@ async function dispatch(argv: string[], runtime: CliRuntime) { let corp: CorpConfig; try { corp = (await import("./helpers.js")).selectCorp(stringOption(args.options.corp)); - } catch { + } catch (error) { + // Local lint tolerates a missing enterprise config, but a disabled tenant + // is an explicit block: never degrade into the synthetic workspace corp. + if (isCorpDisabledError(error)) throw error; corp = { id: "local", name: "Local Workspace", diff --git a/src/core/config/active.ts b/src/core/config/active.ts new file mode 100644 index 0000000..081314f --- /dev/null +++ b/src/core/config/active.ts @@ -0,0 +1,38 @@ +import { CliError, safetyBlocked } from "../errors.js"; +import type { CorpConfig } from "./types.js"; + +/** `safetyBlocked` exit code. Shared so local command fallbacks can re-throw this block. */ +export const CORP_DISABLED_EXIT_CODE = 14; + +/** + * Legacy configs and `as CorpConfig` fixtures omit `active`. Only an explicit + * `false` disables a tenant, so nothing that never set the field can be blocked + * by accident. + */ +export function isCorpActive(corp: CorpConfig): boolean { + return corp.active !== false; +} + +/** + * The single tenant gate. `resolveCorpConfig` calls this on every resolution + * path (explicit `--corp`, stateful default, first-corp fallback, replay + * source/target resolution, background export workers), which is what makes the + * block uniform across the CLI and both MCP gateways. + * + * `corps enable` / `corps disable` resolve with `allowDisabled: true`; they are + * the only commands that may touch a disabled tenant, otherwise a disabled + * tenant could never be restored. + */ +export function assertCorpActive(corp: CorpConfig): void { + if (isCorpActive(corp)) return; + + throw safetyBlocked( + `企业「${corp.name}」(${corp.id}) 已禁用,命令未执行。启用后才能继续对该企业执行操作。`, + `seal-use corps enable ${corp.id} --confirm` + ); +} + +/** True for the structured block thrown by {@link assertCorpActive}. */ +export function isCorpDisabledError(error: unknown): error is CliError { + return error instanceof CliError && error.exitCode === CORP_DISABLED_EXIT_CODE; +} diff --git a/src/core/config/loader.test.ts b/src/core/config/loader.test.ts index 3ac74c8..c95089c 100644 --- a/src/core/config/loader.test.ts +++ b/src/core/config/loader.test.ts @@ -300,6 +300,80 @@ describe("loadCorpConfigs", () => { }); }); +describe("loadCorpConfigs tenant active materialization", () => { + const sources = [ + { + label: "hose", + source: { + type: "hose", + domain: "https://app.ekuaibao.com", + appKey: "app-key", + appSecurity: "app-security", + corpId: "ID01", + staffId: "ID01:STAFF01" + } + }, + { + label: "seal", + source: { type: "seal", token: "seal-token", sealUrl: "https://seal.sealai.cc" } + } + ]; + + test("materializes active=true for legacy configs of both sources and keeps explicit false", () => { + const dir = makeTempDir(); + for (const { label, source } of sources) { + writeFileSync(join(dir, `${label}-legacy.json`), JSON.stringify({ + id: `${label}-legacy`, name: `${label} Legacy`, source + })); + writeFileSync(join(dir, `${label}-disabled.json`), JSON.stringify({ + id: `${label}-disabled`, name: `${label} Disabled`, active: false, source + })); + } + process.env.SEAL_USE_ENTERPRISES_DIR = dir; + + const byId = new Map(loadCorpConfigs().map((item) => [item.id, item])); + for (const { label } of sources) { + expect(byId.get(`${label}-legacy`)?.active).toBe(true); + expect(byId.get(`${label}-disabled`)?.active).toBe(false); + } + }); + + test("a malformed active value loads as disabled without dropping the enterprise", () => { + const dir = makeTempDir(); + process.env.SEAL_USE_ENTERPRISES_DIR = dir; + for (const { label, source } of sources) { + writeFileSync(join(dir, `${label}-malformed.json`), JSON.stringify({ + id: `${label}-malformed`, name: `${label} Malformed`, active: "false", source + })); + } + + const byId = new Map(loadCorpConfigs().map((item) => [item.id, item])); + for (const { label } of sources) { + expect(byId.has(`${label}-malformed`)).toBe(true); + expect(byId.get(`${label}-malformed`)?.active).toBe(false); + } + // Fail-closed is NOT a parse failure: the file must never be skipped. + expect(getLastCorpConfigLoadIssues()).toEqual([]); + }); + + test("updateCorpConfig writes an explicit active value for both sources", () => { + const dir = makeTempDir(); + process.env.SEAL_USE_ENTERPRISES_DIR = dir; + for (const { label, source } of sources) { + writeFileSync(join(dir, `${label}-update.json`), JSON.stringify({ + id: `${label}-update`, name: `${label} Update`, source + })); + const updated = updateCorpConfig(`${label}-update`, { active: false }); + expect(updated.active).toBe(false); + expect(JSON.parse(readFileSync(join(dir, `${label}-update.json`), "utf-8")).active).toBe(false); + + const restored = updateCorpConfig(`${label}-update`, { active: true }); + expect(restored.active).toBe(true); + expect(JSON.parse(readFileSync(join(dir, `${label}-update.json`), "utf-8")).active).toBe(true); + } + }); +}); + describe("syncLegacyEnterprisesDir", () => { test("migrates files from legacy to primary and deletes legacy when > 7 days old", () => { const primary = makeTempDir(); diff --git a/src/core/config/loader.ts b/src/core/config/loader.ts index c03aadc..e96d5a8 100644 --- a/src/core/config/loader.ts +++ b/src/core/config/loader.ts @@ -93,6 +93,9 @@ let lastCorpLoadIssues: CorpConfigLoadIssue[] = []; // Files already warned about this process: loadCorpConfigs runs several times // per invocation (selection, dispatch, tool handlers), so warn each file once. const warnedCorpFiles = new Set(); +// A malformed `active` value is normalized to disabled instead of dropping the +// whole file. Track those separately so the warning names the right remedy. +const warnedActiveCorpFiles = new Set(); /** * Issues from the most recent loadCorpConfigs() call. A malformed file must not @@ -112,6 +115,7 @@ function loadCorpConfigEntries(): Array<{ config: CorpConfig; path: string }> { const dirs = resolveEnterprisesDirs(); const byId = new Map(); const issues: CorpConfigLoadIssue[] = []; + const activeWarnings: Array<{ dir: string; file: string; corpId: string }> = []; for (const dir of dirs) { for (const file of readdirSync(dir) @@ -119,13 +123,26 @@ function loadCorpConfigEntries(): Array<{ config: CorpConfig; path: string }> { .filter((item) => !item.startsWith("example."))) { const fullPath = join(dir, file); let corp: CorpConfig; + let activeMalformed = false; try { const content = readFileSync(fullPath, "utf-8"); - corp = CorpConfigSchema.parse(JSON.parse(content)); + const raw = JSON.parse(content) as Record; + const parsed = CorpConfigSchema.parse(raw); + // `CorpConfigSchema.active` is fail-closed: a non-boolean value parses + // to `false` instead of rejecting the file. Detect it here so the user + // learns why the tenant became unusable and how to fix it. + activeMalformed = "active" in raw && typeof raw.active !== "boolean"; + // Materialize the tenant availability default so every config read from + // disk carries an explicit boolean. Legacy files without `active` stay + // enabled; `false` (explicit or normalized) gates command execution. + corp = { ...parsed, active: parsed.active ?? true }; } catch (error) { issues.push({ dir, file, reason: error instanceof Error ? error.message : String(error) }); continue; } + if (activeMalformed) { + activeWarnings.push({ dir, file, corpId: corp.id }); + } byId.set(corp.id, { config: corp, path: fullPath }); } } @@ -144,6 +161,19 @@ function loadCorpConfigEntries(): Array<{ config: CorpConfig; path: string }> { console.error(`👉 Next action: seal-use doctor (检查配置文件格式与权限)`); } + const freshActive = activeWarnings.filter((item) => { + const key = `${item.dir}/${item.file}`; + if (warnedActiveCorpFiles.has(key)) return false; + warnedActiveCorpFiles.add(key); + return true; + }); + for (const item of freshActive) { + console.error( + `⚠️ 企业配置 ${item.dir}/${item.file} 的 active 字段值非法(只能是 true/false),企业 ${item.corpId} 已按禁用处理;仍可检索,但指向它的命令会被阻断。` + ); + console.error(`👉 Next action: seal-use corps enable ${item.corpId} --confirm (或把配置修正为 "active": true)`); + } + return Array.from(byId.values()); } @@ -268,6 +298,9 @@ export function updateCorpConfig(corpId: string, patch: Partial): Co } } const validated = CorpConfigSchema.parse(merged); - writeSecureFile(filePath, `${JSON.stringify(validated, null, 2)}\n`); - return validated; + // Keep `active` explicit on disk after any config update (including ones that + // predate the field), matching the materialized value from loadCorpConfigs(). + const normalized: CorpConfig = { ...validated, active: validated.active ?? true }; + writeSecureFile(filePath, `${JSON.stringify(normalized, null, 2)}\n`); + return normalized; } diff --git a/src/core/config/manager.test.ts b/src/core/config/manager.test.ts index 8e1913f..dba785a 100644 --- a/src/core/config/manager.test.ts +++ b/src/core/config/manager.test.ts @@ -1,4 +1,6 @@ import { describe, expect, test } from "bun:test"; +import { CliError } from "../errors.js"; +import { isCorpActive } from "./active.js"; import { CorpConfig } from "./types.js"; import { CorpContext, resolveCorpConfig } from "./manager.js"; @@ -99,3 +101,82 @@ describe("resolveCorpConfig", () => { ).id).toBe("corp-b"); }); }); + +describe("resolveCorpConfig tenant gate", () => { + const variants: Array<{ label: string; source: CorpConfig["source"] }> = [ + { + label: "hose", + source: { + type: "hose", + domain: "https://app.ekuaibao.com", + appKey: "app-key", + appSecurity: "app-security", + corpId: "ID01", + staffId: "ID01:STAFF01" + } + }, + { + label: "seal", + source: { + type: "seal", + token: "seal-token", + sealUrl: "https://off.sealai.cc", + expiresIn: 3600, + staffId: "seal" + } + } + ]; + + const withSource = (id: string, source: CorpConfig["source"], active?: boolean): CorpConfig => + ({ ...corp(id), source, active }); + + for (const { label, source } of variants) { + test(`${label}: blocks an explicitly disabled corp with exit 14 and a recovery hint`, () => { + const disabled = withSource("off", source, false); + expect(isCorpActive(disabled)).toBe(false); + + let caught: unknown; + try { + resolveCorpConfig([disabled], { stateful: false, corpId: "off" }); + } catch (error) { + caught = error; + } + + expect(caught).toBeInstanceOf(CliError); + expect((caught as CliError).exitCode).toBe(14); + expect((caught as CliError).message).toContain("已禁用"); + expect((caught as CliError).nextAction).toContain("seal-use corps enable off"); + }); + + test(`${label}: blocks case-insensitive and by-name resolution of a disabled corp`, () => { + const disabled = { ...withSource("Off-Corp", source, false), name: "Disabled Corp" }; + expect(() => resolveCorpConfig([disabled], { stateful: false, corpId: "off-corp" })).toThrow("已禁用"); + expect(() => resolveCorpConfig([disabled], { stateful: false, corpId: "disabled corp" })).toThrow("已禁用"); + }); + + test(`${label}: blocks a disabled stateful default and first-corp fallback`, () => { + const disabled = withSource("off", source, false); + expect(() => resolveCorpConfig( + [disabled, corp("on")], + { stateful: true, defaultCorpId: "off" } + )).toThrow("已禁用"); + expect(() => resolveCorpConfig([disabled, corp("on")], { stateful: true })).toThrow("已禁用"); + }); + + test(`${label}: allowDisabled resolves a disabled corp for status management only`, () => { + const disabled = withSource("off", source, false); + expect(resolveCorpConfig( + [disabled], { stateful: false, corpId: "off", allowDisabled: true } + ).id).toBe("off"); + }); + + test(`${label}: an active corp is unaffected by a disabled one in the same directory`, () => { + const disabled = withSource("off", source, false); + const enabled = withSource("on", source, true); + expect(resolveCorpConfig( + [disabled, enabled], { stateful: false, corpId: "on" } + ).id).toBe("on"); + expect(resolveCorpConfig([corp("legacy")], { stateful: false, corpId: "legacy" }).id).toBe("legacy"); + }); + } +}); diff --git a/src/core/config/manager.ts b/src/core/config/manager.ts index 5cd300b..0114339 100644 --- a/src/core/config/manager.ts +++ b/src/core/config/manager.ts @@ -1,11 +1,26 @@ import { validationError } from "../errors.js"; +import { assertCorpActive } from "./active.js"; import { CorpConfig, GlobalConfig } from "./types.js"; +export type CorpResolveOptions = Pick & { + corpId?: string; + /** Only the tenant status-management commands (`corps enable/disable`) may resolve a disabled corp. */ + allowDisabled?: boolean; +}; + export function resolveCorpConfig( corps: CorpConfig[], - options: Pick & { corpId?: string }, + options: CorpResolveOptions, candidates: string[] = [] ): CorpConfig { + // Every successful lookup passes through the same gate. This is the single + // choke point for CLI commands, MCP gateway commands, replay source/target + // resolution and background workers — a disabled tenant is never executable. + const accept = (found: CorpConfig): CorpConfig => { + if (!options.allowDisabled) assertCorpActive(found); + return found; + }; + const requestedCorpId = options.corpId?.trim() || undefined; const configuredCorpId = options.stateful ? options.defaultCorpId?.trim() || undefined @@ -14,11 +29,11 @@ export function resolveCorpConfig( if (selectedCorpId) { const exact = corps.find((item) => item.id === selectedCorpId); - if (exact) return exact; + if (exact) return accept(exact); const caseInsensitive = corps.find((item) => item.id.toLowerCase() === selectedCorpId.toLowerCase()); - if (caseInsensitive) return caseInsensitive; + if (caseInsensitive) return accept(caseInsensitive); const byName = corps.find((item) => item.name.toLowerCase() === selectedCorpId.toLowerCase()); - if (byName) return byName; + if (byName) return accept(byName); throw validationError(`No enterprise config found for ${selectedCorpId}`); } @@ -28,7 +43,7 @@ export function resolveCorpConfig( } const firstCorp = corps[0]; - if (firstCorp) return firstCorp; + if (firstCorp) return accept(firstCorp); throw validationError("No enterprise config found. Add a non-example JSON file under one of: " + (candidates.length ? candidates.join(", ") : "the configured enterprise directories")); diff --git a/src/core/config/types.test.ts b/src/core/config/types.test.ts index d1c6cb9..0d2c0f6 100644 --- a/src/core/config/types.test.ts +++ b/src/core/config/types.test.ts @@ -5,6 +5,7 @@ import { SealCookieMapSchema, SealHeaderMapSchema } from "./types.js"; +import { isCorpActive } from "./active.js"; describe("CorpConfigSchema", () => { test("accepts Hose key/password aliases", () => { @@ -180,6 +181,72 @@ describe("CorpConfigSchema", () => { }); }); +describe("CorpConfigSchema.active (parity across sources)", () => { + const variants = [ + { + label: "hose", + source: { + type: "hose" as const, + domain: "https://app.ekuaibao.com", + appKey: "app-key", + appSecurity: "app-security", + corpId: "ID01", + staffId: "ID01:STAFF01" + } + }, + { + label: "seal", + source: { + type: "seal" as const, + token: "seal-token", + sealUrl: "https://seal.sealai.cc" + } + } + ]; + + for (const { label, source } of variants) { + test(`${label}: a legacy config without active stays enabled`, () => { + const config = CorpConfigSchema.parse({ + id: `${label}-legacy`, + name: "Legacy Corp", + source + }); + + expect(String(config.source.type)).toBe(label); + expect(config.active).toBeUndefined(); + expect(isCorpActive(config)).toBe(true); + }); + + test(`${label}: accepts explicit active true and false`, () => { + const enabled = CorpConfigSchema.parse({ + id: `${label}-on`, name: "Enabled Corp", source, active: true + }); + const disabled = CorpConfigSchema.parse({ + id: `${label}-off`, name: "Disabled Corp", source, active: false + }); + + expect(enabled.active).toBe(true); + expect(isCorpActive(enabled)).toBe(true); + expect(disabled.active).toBe(false); + expect(isCorpActive(disabled)).toBe(false); + }); + + test(`${label}: a malformed active value fails closed to disabled instead of dropping the config`, () => { + for (const malformed of ["false", "true", null, 0, 1, {}, []]) { + const result = CorpConfigSchema.safeParse({ + id: `${label}-bad`, name: "Bad Corp", source, active: malformed + }); + + if (!result.success) { + throw new Error(`config rejected for active=${JSON.stringify(malformed)}`); + } + expect(result.data.active).toBe(false); + expect(isCorpActive(result.data)).toBe(false); + } + }); + } +}); + describe("Seal custom header schemas", () => { test("rejects an Authorization header supplied through config", () => { expect(SealHeaderMapSchema.safeParse({ Authorization: "Bearer x" }).success).toBe(false); diff --git a/src/core/config/types.ts b/src/core/config/types.ts index 2f19dac..31cc024 100644 --- a/src/core/config/types.ts +++ b/src/core/config/types.ts @@ -112,6 +112,17 @@ export const CorpEnvironmentSchema = z.enum(["production", "test"]).default("pro export const CorpConfigSchema = z.object({ id: z.string(), name: z.string(), + // Tenant availability gate. It lives on the enterprise, NOT on a source, so + // `hose` and `seal` sources share exactly one switch and cannot diverge. + // Fail-closed three-way semantics: + // - absent -> undefined -> enabled (legacy configs, hand-built + // CorpConfig objects; materialized to true on read) + // - explicit boolean -> used as-is + // - malformed value -> `.catch(false)` -> DISABLED, never silently enabled + // A bad value must not drop the whole file (which would hide the enterprise + // from search and surface as a misleading "no enterprise config found"). + // Disabling never affects `corps list/search` visibility. + active: z.boolean().optional().catch(false), seal: SealEndpointSchema, source: SealSourceSchema, auth: CorpAuthConfigSchema, diff --git a/src/core/embedded-skill.generated.ts b/src/core/embedded-skill.generated.ts index 3f07eaa..e88644d 100644 --- a/src/core/embedded-skill.generated.ts +++ b/src/core/embedded-skill.generated.ts @@ -27,7 +27,8 @@ import file23 from "../../skills/seal-use/references/rule-lightweight.md" with { import file24 from "../../skills/seal-use/references/rule-lint.md" with { type: "text" }; import file25 from "../../skills/seal-use/references/sealai-browser-rum.md" with { type: "text" }; import file26 from "../../skills/seal-use/references/staging-simulation-workflow.md" with { type: "text" }; -import file27 from "../../skills/seal-use/references/webhook-resource-pack.md" with { type: "text" }; +import file27 from "../../skills/seal-use/references/tenant-status.md" with { type: "text" }; +import file28 from "../../skills/seal-use/references/webhook-resource-pack.md" with { type: "text" }; export const EMBEDDED_SKILL_TEXT_FILES: Record = { "SKILL.md": file0, @@ -51,7 +52,8 @@ export const EMBEDDED_SKILL_TEXT_FILES: Record = { "references/rule-lint.md": file24, "references/sealai-browser-rum.md": file25, "references/staging-simulation-workflow.md": file26, - "references/webhook-resource-pack.md": file27, + "references/tenant-status.md": file27, + "references/webhook-resource-pack.md": file28, }; export const EMBEDDED_SKILL_ASSET_PATHS: Record = { @@ -91,5 +93,6 @@ export const EMBEDDED_SKILL_ALL_PATHS = [ "references/rule-lint.md", "references/sealai-browser-rum.md", "references/staging-simulation-workflow.md", + "references/tenant-status.md", "references/webhook-resource-pack.md", ]; diff --git a/src/server.test.ts b/src/server.test.ts index a473e09..41308a5 100644 --- a/src/server.test.ts +++ b/src/server.test.ts @@ -1,7 +1,9 @@ import { describe, expect, test } from "bun:test"; import { Client, InMemoryTransport } from "@modelcontextprotocol/client"; import { spawnSync } from "node:child_process"; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; +import { join } from "node:path"; import { fileURLToPath } from "node:url"; import { createServer, @@ -207,6 +209,68 @@ describe("seal-use MCP server", () => { } }); + test("both MCP gateways refuse commands naming a disabled tenant", async () => { + const root = mkdtempSync(join(tmpdir(), "seal-mcp-disabled-tenant-")); + const enterprises = join(root, "enterprises"); + mkdirSync(enterprises, { recursive: true }); + writeFileSync(join(enterprises, "off.json"), JSON.stringify({ + id: "off", + name: "Disabled Corp", + active: false, + seal: { url: "https://off.sealai.cc" }, + source: { type: "seal", token: "seal-token", sealUrl: "https://off.sealai.cc" }, + auth: { refreshTtl: 300 } + })); + + const envKeys = [ + "SEAL_USE_ENTERPRISES_DIR", + "SEAL_USE_CONFIG_FILE", + "SEAL_USE_TOKEN_STORE", + "SEAL_DISABLE_BG_UPDATE" + ] as const; + const originals = Object.fromEntries(envKeys.map((key) => [key, process.env[key]])); + process.env.SEAL_USE_ENTERPRISES_DIR = enterprises; + process.env.SEAL_USE_CONFIG_FILE = join(root, "config.json"); + process.env.SEAL_USE_TOKEN_STORE = join(root, "tokens.json"); + process.env.SEAL_DISABLE_BG_UPDATE = "1"; + + const server = createServer({ enableCli: true }); + const client = new Client({ name: "seal-use-disabled-tenant-test", version: "1.0.0" }); + const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); + + try { + await Promise.all([ + server.connect(serverTransport), + client.connect(clientTransport) + ]); + + const read = await client.callTool({ + name: SEAL_USE_MCP_TOOL_NAME, + arguments: { command: "seal-use corps get off" } + }); + expect(read.isError).toBe(true); + const readText = (read.content as Array<{ type: "text"; text: string }>)[0]?.text ?? ""; + expect(readText).toContain("已禁用"); + expect(readText).toContain("seal-use corps enable off"); + + const write = await client.callTool({ + name: SEAL_USE_MCP_WRITE_TOOL_NAME, + arguments: { command: "seal-use rules list --corp off" } + }); + expect(write.isError).toBe(true); + const writeText = (write.content as Array<{ type: "text"; text: string }>)[0]?.text ?? ""; + expect(writeText).toContain("已禁用"); + } finally { + await Promise.allSettled([client.close(), server.close()]); + for (const key of envKeys) { + const value = originals[key]; + if (value === undefined) delete process.env[key]; + else process.env[key] = value; + } + rmSync(root, { recursive: true, force: true }); + } + }); + test("does not advertise tools when MCP is disabled", async () => { const server = createServer({ enableCli: false }); const client = new Client({ name: "seal-home-disabled-test", version: "1.0.0" });