feat: 新增租户 active 状态与统一禁用闸门
This commit is contained in:
1 parent
634f0e2b78
commit
0ff3d9a313
21 files changed
+855
-14
No files matched your search
@@ -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;
|
||||
}
|
||||
@@ -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();
|
||||
|
||||
@@ -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<string>();
|
||||
// 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<string>();
|
||||
|
||||
/**
|
||||
* 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<string, { config: CorpConfig; path: string }>();
|
||||
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<string, unknown>;
|
||||
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<CorpConfig>): 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;
|
||||
}
|
||||
@@ -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");
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -1,11 +1,26 @@
|
||||
import { validationError } from "../errors.js";
|
||||
import { assertCorpActive } from "./active.js";
|
||||
import { CorpConfig, GlobalConfig } from "./types.js";
|
||||
|
||||
export type CorpResolveOptions = Pick<GlobalConfig, "stateful" | "defaultCorpId"> & {
|
||||
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<GlobalConfig, "stateful" | "defaultCorpId"> & { 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"));
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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<string, string> = {
|
||||
"SKILL.md": file0,
|
||||
@@ -51,7 +52,8 @@ export const EMBEDDED_SKILL_TEXT_FILES: Record<string, string> = {
|
||||
"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<string, string> = {
|
||||
@@ -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",
|
||||
];
|
||||
Reference in new issue
Block a user