import { afterEach, describe, expect, test } from "bun:test"; import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, utimesSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { saveCorpConfig } from "./repository.js"; import { findCorpConfigFile, getLastCorpConfigLoadIssues, loadCorpConfigs, loadGlobalConfig, resolveEnterprisesDir, resolveGlobalConfigFile, saveGlobalConfig, syncLegacyEnterprisesDir, updateCorpConfig } from "./loader.js"; const ORIGINAL_USE_ENV = process.env.SEAL_USE_ENTERPRISES_DIR; const ORIGINAL_HOME_ENV = process.env.SEAL_HOME_ENTERPRISES_DIR; const ORIGINAL_USER_DIR_USE_ENV = process.env.SEAL_USE_USER_ENTERPRISES_DIR; const ORIGINAL_USER_DIR_HOME_ENV = process.env.SEAL_HOME_USER_ENTERPRISES_DIR; const ORIGINAL_CONFIG_FILE_USE_ENV = process.env.SEAL_USE_CONFIG_FILE; const ORIGINAL_CONFIG_FILE_HOME_ENV = process.env.SEAL_HOME_CONFIG_FILE; const ORIGINAL_CWD = process.cwd(); const tempDirs: string[] = []; afterEach(() => { process.chdir(ORIGINAL_CWD); if (ORIGINAL_USE_ENV === undefined) delete process.env.SEAL_USE_ENTERPRISES_DIR; else process.env.SEAL_USE_ENTERPRISES_DIR = ORIGINAL_USE_ENV; if (ORIGINAL_HOME_ENV === undefined) delete process.env.SEAL_HOME_ENTERPRISES_DIR; else process.env.SEAL_HOME_ENTERPRISES_DIR = ORIGINAL_HOME_ENV; if (ORIGINAL_USER_DIR_USE_ENV === undefined) delete process.env.SEAL_USE_USER_ENTERPRISES_DIR; else process.env.SEAL_USE_USER_ENTERPRISES_DIR = ORIGINAL_USER_DIR_USE_ENV; if (ORIGINAL_USER_DIR_HOME_ENV === undefined) delete process.env.SEAL_HOME_USER_ENTERPRISES_DIR; else process.env.SEAL_HOME_USER_ENTERPRISES_DIR = ORIGINAL_USER_DIR_HOME_ENV; if (ORIGINAL_CONFIG_FILE_USE_ENV === undefined) delete process.env.SEAL_USE_CONFIG_FILE; else process.env.SEAL_USE_CONFIG_FILE = ORIGINAL_CONFIG_FILE_USE_ENV; if (ORIGINAL_CONFIG_FILE_HOME_ENV === undefined) delete process.env.SEAL_HOME_CONFIG_FILE; else process.env.SEAL_HOME_CONFIG_FILE = ORIGINAL_CONFIG_FILE_HOME_ENV; for (const dir of tempDirs.splice(0)) { rmSync(dir, { recursive: true, force: true }); } }); describe("loadCorpConfigs", () => { test("loads configs from SEAL_USE_ENTERPRISES_DIR and falls back to SEAL_HOME_ENTERPRISES_DIR", () => { const dir = makeTempDir(); writeFileSync(join(dir, "example.hose.json"), "{}"); writeFileSync(join(dir, "local.json"), JSON.stringify({ id: "direct", name: "Direct", source: { type: "seal", token: "seal-token", sealUrl: "https://direct.sealai.cc" } })); process.env.SEAL_HOME_ENTERPRISES_DIR = dir; expect(resolveEnterprisesDir()).toBe(dir); expect(loadCorpConfigs().map((corp) => corp.id)).toEqual(["direct"]); const newDir = makeTempDir(); writeFileSync(join(newDir, "local-use.json"), JSON.stringify({ id: "direct-use", name: "Direct Use", source: { type: "seal", token: "seal-token", sealUrl: "https://direct.sealai.cc" } })); process.env.SEAL_USE_ENTERPRISES_DIR = newDir; expect(resolveEnterprisesDir()).toBe(newDir); expect(loadCorpConfigs().map((corp) => corp.id)).toEqual(["direct-use"]); }); test("returns no configs when explicit env directory does not exist", () => { process.env.SEAL_USE_ENTERPRISES_DIR = join(makeTempDir(), "missing"); expect(resolveEnterprisesDir()).toBeUndefined(); expect(loadCorpConfigs()).toEqual([]); }); test("does not load current directory enterprises by default, only reading user directory", () => { const workspace = makeTempDir(); const workspaceEnterprises = join(workspace, "enterprises"); const userDir = makeTempDir(); mkdirSync(workspaceEnterprises, { recursive: true }); writeCorpConfig(join(workspaceEnterprises, "cwd-only.json"), "cwd-only", "CWD Enterprise"); writeCorpConfig(join(userDir, "user-only.json"), "user-only", "User Only"); process.chdir(workspace); process.env.SEAL_USE_USER_ENTERPRISES_DIR = userDir; // cwd enterprises/ should NOT be loaded by default expect(loadCorpConfigs().map((corp) => corp.id)).toEqual(["user-only"]); }); test("loads testEnterprisesDir from global config when specified", () => { const testDir = makeTempDir(); const userDir = makeTempDir(); writeCorpConfig(join(testDir, "test-corp.json"), "test-corp", "Test Corp"); writeCorpConfig(join(userDir, "user-corp.json"), "user-corp", "User Corp"); const configFile = join(makeTempDir(), "config.json"); process.env.SEAL_USE_CONFIG_FILE = configFile; process.env.SEAL_USE_USER_ENTERPRISES_DIR = userDir; saveGlobalConfig({ testEnterprisesDir: testDir }); const corps = loadCorpConfigs(); expect(corps.map((corp) => corp.id).sort()).toEqual(["test-corp", "user-corp"].sort()); }); test("updates the same user override that reads select", () => { delete process.env.SEAL_USE_ENTERPRISES_DIR; delete process.env.SEAL_HOME_ENTERPRISES_DIR; const testDir = makeTempDir(); const userDir = makeTempDir(); process.env.SEAL_USE_USER_ENTERPRISES_DIR = userDir; process.env.SEAL_USE_CONFIG_FILE = join(makeTempDir(), "config.json"); saveGlobalConfig({ testEnterprisesDir: testDir }); const testPath = join(testDir, "corp.json"); const userPath = join(userDir, "corp.json"); writeCorpConfig(testPath, "duplicate", "Test copy"); writeCorpConfig(userPath, "duplicate", "User copy"); expect(loadCorpConfigs()[0]?.name).toBe("User copy"); expect(findCorpConfigFile("duplicate")).toBe(userPath); updateCorpConfig("duplicate", { name: "Renamed" }); expect(loadCorpConfigs()[0]?.name).toBe("Renamed"); expect(JSON.parse(readFileSync(testPath, "utf8")).name).toBe("Test copy"); }); test("same-directory duplicates and invalid shadows use the selected valid file", () => { const dir = makeTempDir(); process.env.SEAL_USE_ENTERPRISES_DIR = dir; const first = join(dir, "a.json"); const second = join(dir, "b.json"); writeCorpConfig(first, "duplicate", "First"); writeCorpConfig(second, "duplicate", "Second"); writeFileSync(join(dir, "z-invalid.json"), JSON.stringify({ id: "duplicate" })); // Filesystem enumeration order differs across platforms; writes must follow reads. const selectedName = loadCorpConfigs()[0]?.name; expect(["First", "Second"]).toContain(selectedName ?? ""); const selected = selectedName === "First" ? first : second; const untouched = selectedName === "First" ? second : first; const untouchedName = JSON.parse(readFileSync(untouched, "utf8")).name; expect(findCorpConfigFile("duplicate")).toBe(selected); updateCorpConfig("duplicate", { name: "Updated" }); expect(loadCorpConfigs()[0]?.name).toBe("Updated"); expect(JSON.parse(readFileSync(selected, "utf8")).name).toBe("Updated"); expect(JSON.parse(readFileSync(untouched, "utf8")).name).toBe(untouchedName); }); test.skipIf(process.platform === "win32")("credential updates and overwrites tighten existing files", () => { const dir = makeTempDir(); process.env.SEAL_USE_ENTERPRISES_DIR = dir; const path = join(dir, "alpha.json"); writeCorpConfig(path, "alpha", "Alpha"); chmodSync(path, 0o644); const config = updateCorpConfig("alpha", { name: "Updated" }); expect(statSync(path).mode & 0o777).toBe(0o600); chmodSync(path, 0o644); saveCorpConfig(config, { overwrite: true }); expect(statSync(path).mode & 0o777).toBe(0o600); const globalPath = join(dir, "global-config"); process.env.SEAL_USE_CONFIG_FILE = globalPath; writeFileSync(globalPath, "{}"); chmodSync(globalPath, 0o644); saveGlobalConfig({ stateful: false }); expect(statSync(globalPath).mode & 0o777).toBe(0o600); const migratedDir = makeTempDir(); syncLegacyEnterprisesDir(migratedDir, dir); expect(statSync(join(migratedDir, "alpha.json")).mode & 0o777).toBe(0o600); }); test("defaults global config to stateless", () => { process.env.SEAL_USE_CONFIG_FILE = join(makeTempDir(), "config.json"); expect(loadGlobalConfig()).toEqual({ stateful: false, lint: { enabled: true, activeLinter: "builtin", minScore: 0 } }); }); test("saves and loads the global state mode and testEnterprisesDir", () => { const file = join(makeTempDir(), "nested", "config.json"); process.env.SEAL_USE_CONFIG_FILE = file; expect(saveGlobalConfig({ stateful: true, defaultCorpId: "corp-a", testEnterprisesDir: "/tmp/test-corps" })).toEqual({ stateful: true, defaultCorpId: "corp-a", testEnterprisesDir: "/tmp/test-corps", lint: { enabled: true, activeLinter: "builtin", minScore: 0 } }); expect(resolveGlobalConfigFile()).toBe(file); expect(loadGlobalConfig()).toEqual({ stateful: true, defaultCorpId: "corp-a", testEnterprisesDir: "/tmp/test-corps", lint: { enabled: true, activeLinter: "builtin", minScore: 0 } }); }); test("finds and updates an enterprise config file in-place", () => { const dir = makeTempDir(); process.env.SEAL_USE_ENTERPRISES_DIR = dir; writeCorpConfig(join(dir, "alpha.json"), "alpha", "Alpha Corp"); expect(findCorpConfigFile("alpha")).toBe(join(dir, "alpha.json")); expect(findCorpConfigFile("nonexistent")).toBeUndefined(); const updated = updateCorpConfig("alpha", { environment: "production", testCorpId: "alpha-test" }); expect(updated.id).toBe("alpha"); expect(updated.environment).toBe("production"); expect(updated.testCorpId).toBe("alpha-test"); // Check on-disk persistence const reloaded = loadCorpConfigs().find((c) => c.id === "alpha"); expect(reloaded?.testCorpId).toBe("alpha-test"); // Unsetting / clearing testCorpId const cleared = updateCorpConfig("alpha", { testCorpId: undefined }); expect(cleared.testCorpId).toBeUndefined(); const reloadedAfterClear = loadCorpConfigs().find((c) => c.id === "alpha"); expect(reloadedAfterClear?.testCorpId).toBeUndefined(); }); test("skips a malformed file without dropping the other enterprises in the directory", () => { const dir = makeTempDir(); process.env.SEAL_USE_ENTERPRISES_DIR = dir; writeCorpConfig(join(dir, "good.json"), "good", "Good Corp"); // A hand-edited or truncated file must not abort the whole directory load. writeFileSync(join(dir, "broken.json"), "{ not json at all"); writeFileSync(join(dir, "wrong-shape.json"), JSON.stringify({ id: "wrong-shape" })); expect(loadCorpConfigs().map((corp) => corp.id)).toEqual(["good"]); const issues = getLastCorpConfigLoadIssues(); expect(issues.map((issue) => issue.file).sort()).toEqual(["broken.json", "wrong-shape.json"]); expect(issues.map((issue) => issue.dir)).toEqual([dir, dir]); }); test("reports no issues when every file parses", () => { const dir = makeTempDir(); process.env.SEAL_USE_ENTERPRISES_DIR = dir; writeCorpConfig(join(dir, "alpha.json"), "alpha", "Alpha Corp"); expect(loadCorpConfigs()).toHaveLength(1); expect(getLastCorpConfigLoadIssues()).toEqual([]); }); test("warns about a malformed file only once per process", () => { const dir = makeTempDir(); process.env.SEAL_USE_ENTERPRISES_DIR = dir; writeFileSync(join(dir, "broken-once.json"), "{ nope"); const errors: string[] = []; const originalError = console.error; console.error = (...values: unknown[]) => { errors.push(values.map((value) => String(value)).join(" ")); }; try { loadCorpConfigs(); loadCorpConfigs(); loadCorpConfigs(); } finally { console.error = originalError; } const skipWarnings = errors.filter((line) => line.includes("跳过")); expect(skipWarnings).toHaveLength(1); expect(skipWarnings[0]).toContain("broken-once.json"); }); }); 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(); const legacy = makeTempDir(); writeCorpConfig(join(legacy, "old-corp.json"), "old-corp", "Old Corp"); const tenDaysAgo = (Date.now() - 10 * 24 * 60 * 60 * 1000) / 1000; utimesSync(join(legacy, "old-corp.json"), tenDaysAgo, tenDaysAgo); utimesSync(legacy, tenDaysAgo, tenDaysAgo); const result = syncLegacyEnterprisesDir(primary, legacy); expect(result.copied).toEqual(["old-corp.json"]); expect(result.deletedLegacyDir).toBe(true); expect(existsSync(join(primary, "old-corp.json"))).toBe(true); expect(existsSync(legacy)).toBe(false); }); test("preserves legacy directory when modified within 7 days", () => { const primary = makeTempDir(); const legacy = makeTempDir(); writeCorpConfig(join(legacy, "recent-corp.json"), "recent-corp", "Recent Corp"); const result = syncLegacyEnterprisesDir(primary, legacy); expect(result.copied).toEqual(["recent-corp.json"]); expect(result.deletedLegacyDir).toBe(false); expect(existsSync(join(primary, "recent-corp.json"))).toBe(true); expect(existsSync(legacy)).toBe(true); }); }); function makeTempDir(): string { const dir = mkdtempSync(join(tmpdir(), "seal-home-loader-")); mkdirSync(dir, { recursive: true }); tempDirs.push(dir); return dir; } function writeCorpConfig(path: string, id: string, name: string) { writeFileSync(path, JSON.stringify({ id, name, source: { type: "seal", token: "seal-token", sealUrl: `https://${id}.sealai.cc` } })); }