import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync } from "node:fs"; import { homedir } from "node:os"; import { join } from "node:path"; import { CorpConfig, CorpConfigSchema, GlobalConfig, GlobalConfigInput, GlobalConfigSchema } from "./types.js"; import { writeSecureFile } from "../util/secure-file.js"; const CONFIG_ENV = "SEAL_USE_ENTERPRISES_DIR"; const LEGACY_CONFIG_ENV = "SEAL_HOME_ENTERPRISES_DIR"; const USER_DIR_ENV = "SEAL_USE_USER_ENTERPRISES_DIR"; const LEGACY_USER_DIR_ENV = "SEAL_HOME_USER_ENTERPRISES_DIR"; const GLOBAL_CONFIG_ENV = "SEAL_USE_CONFIG_FILE"; const LEGACY_GLOBAL_CONFIG_ENV = "SEAL_HOME_CONFIG_FILE"; export const PRIMARY_USER_ENTERPRISES_DIR = join(homedir(), ".config", "seal-use", "enterprises"); export const LEGACY_USER_ENTERPRISES_DIR = join(homedir(), ".config", "seal-home", "enterprises"); const PRIMARY_GLOBAL_CONFIG_FILE = join(homedir(), ".config", "seal-use", "config.json"); const LEGACY_GLOBAL_CONFIG_FILE = join(homedir(), ".config", "seal-home", "config.json"); export function syncLegacyEnterprisesDir( primaryDir: string = PRIMARY_USER_ENTERPRISES_DIR, legacyDir: string = LEGACY_USER_ENTERPRISES_DIR ): { copied: string[]; deletedLegacyDir: boolean } { if (!existsSync(legacyDir)) { return { copied: [], deletedLegacyDir: false }; } mkdirSync(primaryDir, { recursive: true, mode: 0o700 }); const copied: string[] = []; let legacyFiles: string[] = []; try { legacyFiles = readdirSync(legacyDir).filter((file) => file.endsWith(".json")); } catch { return { copied: [], deletedLegacyDir: false }; } for (const file of legacyFiles) { const legacyPath = join(legacyDir, file); const primaryPath = join(primaryDir, file); if (!existsSync(primaryPath)) { writeSecureFile(primaryPath, readFileSync(legacyPath)); copied.push(file); } else { const legacyMtime = statSync(legacyPath).mtimeMs; const primaryMtime = statSync(primaryPath).mtimeMs; if (legacyMtime > primaryMtime) { writeSecureFile(primaryPath, readFileSync(legacyPath)); copied.push(file); } } } const SEVEN_DAYS_MS = 7 * 24 * 60 * 60 * 1000; const now = Date.now(); let hasNewerFileInLegacy = false; let hasRecentlyModifiedFile = false; for (const file of readdirSync(legacyDir)) { const legacyPath = join(legacyDir, file); const primaryPath = join(primaryDir, file); const stat = statSync(legacyPath); if (now - stat.mtimeMs < SEVEN_DAYS_MS) { hasRecentlyModifiedFile = true; } if (file.endsWith(".json") && existsSync(primaryPath)) { if (stat.mtimeMs > statSync(primaryPath).mtimeMs) { hasNewerFileInLegacy = true; } } } const dirStat = statSync(legacyDir); const dirRecentlyModified = now - dirStat.mtimeMs < SEVEN_DAYS_MS; let deletedLegacyDir = false; if (!hasNewerFileInLegacy && !hasRecentlyModifiedFile && !dirRecentlyModified) { rmSync(legacyDir, { recursive: true, force: true }); deletedLegacyDir = true; } return { copied, deletedLegacyDir }; } export type CorpConfigLoadIssue = { dir: string; file: string; reason: string }; 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 * abort the directory: the remaining enterprises stay usable and the caller * reports the bad file by name instead of failing every command with a bare * JSON parse error. */ export function getLastCorpConfigLoadIssues(): CorpConfigLoadIssue[] { return lastCorpLoadIssues; } export function loadCorpConfigs(): CorpConfig[] { return loadCorpConfigEntries().map((entry) => entry.config); } 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) .filter((item) => item.endsWith(".json")) .filter((item) => !item.startsWith("example."))) { const fullPath = join(dir, file); let corp: CorpConfig; let activeMalformed = false; try { const content = readFileSync(fullPath, "utf-8"); 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, storage: parsed.storage ?? "local" }; } 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 }); } } lastCorpLoadIssues = issues; const fresh = issues.filter((issue) => { const key = `${issue.dir}/${issue.file}`; if (warnedCorpFiles.has(key)) return false; warnedCorpFiles.add(key); return true; }); if (fresh.length) { console.error( `⚠️ 跳过 ${fresh.length} 个无法解析的企业配置: ${fresh.map((item) => `${item.dir}/${item.file}`).join(", ")}` ); 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()); } export function resolveEnterprisesDir(): string | undefined { return resolveEnterprisesDirs()[0]; } function resolveEnterprisesDirs(): string[] { const configured = (process.env[CONFIG_ENV] ?? process.env[LEGACY_CONFIG_ENV])?.trim(); if (configured) return existsSync(configured) ? [configured] : []; const configuredUserDir = (process.env[USER_DIR_ENV] ?? process.env[LEGACY_USER_DIR_ENV])?.trim(); let userDirs: string[]; if (configuredUserDir) { userDirs = existsSync(configuredUserDir) ? [configuredUserDir] : []; } else { try { syncLegacyEnterprisesDir(); } catch {} userDirs = existsSync(PRIMARY_USER_ENTERPRISES_DIR) ? [PRIMARY_USER_ENTERPRISES_DIR] : (existsSync(LEGACY_USER_ENTERPRISES_DIR) ? [LEGACY_USER_ENTERPRISES_DIR] : [PRIMARY_USER_ENTERPRISES_DIR]); } const globalConfig = loadGlobalConfig(); const testDir = globalConfig.testEnterprisesDir?.trim(); const candidates = testDir ? [testDir, ...userDirs] : userDirs; const uniqueExisting: string[] = []; for (const d of candidates) { if (existsSync(d) && !uniqueExisting.includes(d)) { uniqueExisting.push(d); } } return uniqueExisting; } export function resolveWritableEnterprisesDir(): string { const configured = (process.env[CONFIG_ENV] ?? process.env[LEGACY_CONFIG_ENV])?.trim(); if (configured) return configured; const configuredUserDir = (process.env[USER_DIR_ENV] ?? process.env[LEGACY_USER_DIR_ENV])?.trim(); if (configuredUserDir) return configuredUserDir; const testDir = loadGlobalConfig().testEnterprisesDir?.trim(); if (testDir && existsSync(testDir)) return testDir; return PRIMARY_USER_ENTERPRISES_DIR; } export function getEnterprisesDirCandidates(): string[] { const testDir = loadGlobalConfig().testEnterprisesDir?.trim(); return [ `${CONFIG_ENV}=`, ...(testDir ? [`testEnterprisesDir: ${testDir}`] : []), PRIMARY_USER_ENTERPRISES_DIR, LEGACY_USER_ENTERPRISES_DIR ]; } export function resolveGlobalConfigFile(): string { const configured = (process.env[GLOBAL_CONFIG_ENV] ?? process.env[LEGACY_GLOBAL_CONFIG_ENV])?.trim(); if (configured) return configured; if (existsSync(PRIMARY_GLOBAL_CONFIG_FILE)) return PRIMARY_GLOBAL_CONFIG_FILE; if (existsSync(LEGACY_GLOBAL_CONFIG_FILE)) return LEGACY_GLOBAL_CONFIG_FILE; return PRIMARY_GLOBAL_CONFIG_FILE; } let lastGlobalConfigIssue: { file: string; reason: string } | undefined; /** * Issue from the most recent loadGlobalConfig() call, if the configured file * existed but could not be parsed. `doctor` reads this to surface the bad file; * commands otherwise continue on defaults instead of failing outright. */ export function getLastGlobalConfigIssue(): { file: string; reason: string } | undefined { return lastGlobalConfigIssue; } export function loadGlobalConfig(): GlobalConfig { const file = resolveGlobalConfigFile(); lastGlobalConfigIssue = undefined; if (!existsSync(file)) { return GlobalConfigSchema.parse({}); } try { return GlobalConfigSchema.parse(JSON.parse(readFileSync(file, "utf-8"))); } catch (error) { // A hand-edited config.json must not brick every command: fall back to // defaults so the user can still run `seal-use config paths` / `corps list` // to find and fix the file. const reason = error instanceof Error ? error.message : String(error); lastGlobalConfigIssue = { file, reason }; console.error(`⚠️ 全局配置无法解析,已回退默认值: ${file} (${reason})`); console.error(`👉 Next action: seal-use config paths (检查配置文件)`); return GlobalConfigSchema.parse({}); } } export function saveGlobalConfig(config: GlobalConfigInput): GlobalConfig { const normalized = GlobalConfigSchema.parse(config); const configured = (process.env[GLOBAL_CONFIG_ENV] ?? process.env[LEGACY_GLOBAL_CONFIG_ENV])?.trim(); const file = configured || PRIMARY_GLOBAL_CONFIG_FILE; writeSecureFile(file, `${JSON.stringify(normalized, null, 2)}\n`); return normalized; } export function findCorpConfigFile(corpId: string): string | undefined { return loadCorpConfigEntries().find((entry) => entry.config.id === corpId)?.path; } export function updateCorpConfig(corpId: string, patch: Partial): CorpConfig { const filePath = findCorpConfigFile(corpId); if (!filePath) { throw new Error(`Enterprise config not found: ${corpId}`); } const raw = JSON.parse(readFileSync(filePath, "utf-8")); const merged = { ...raw, ...patch }; for (const key of Object.keys(patch) as Array) { if (patch[key] === undefined) { delete merged[key]; } } const validated = CorpConfigSchema.parse(merged); // 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; }