feat: 新增租户 active 状态与统一禁用闸门
This commit is contained in:
1 parent
634f0e2b78
commit
0ff3d9a313
21 files changed
+855
-14
No files matched your search
@@ -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;
|
||||
|
||||
@@ -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<boolean> {
|
||||
if (action !== "disable" && action !== "enable") return false;
|
||||
|
||||
const corpId = maybeName ?? stringOption(args.options.corp);
|
||||
if (!corpId) {
|
||||
throw usageError(`Usage: seal-use corps ${action} <corpId> [--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;
|
||||
}
|
||||
@@ -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,
|
||||
|
||||
@@ -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<string, unknown>;
|
||||
active?: unknown;
|
||||
}
|
||||
): string {
|
||||
const payload: Record<string, unknown> = {
|
||||
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<string, unknown> {
|
||||
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("已禁用");
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -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,
|
||||
|
||||
@@ -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 <corpId> [--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 <corpId> [--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: "测试配对与验证",
|
||||
|
||||
+3
-2
@@ -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()
|
||||
);
|
||||
|
||||
+5
-1
@@ -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",
|
||||
|
||||
Reference in new issue
Block a user