// 插件配置明文迁移:把历史遗留的 password 字段从明文就地转为密文。 // 幂等:已加密(enc:v1: 前缀)的跳过;无 password 字段的插件不碰;单条失败只告警不阻断启动。 // 触发时机:应用初始化(插件同步之前也能跑——迁移只依赖本地 plugin.json 的 schema)。 "use strict"; const fs = require("fs"); const path = require("path"); const config = require("./config"); const registry = require("./registry"); const localCrypto = require("./local-crypto"); const { makeLogger } = require("./logger"); const logger = makeLogger("config-migrate"); // 按插件取 password 字段名;插件元数据不可读时返回空(不迁移,避免误伤) function keysFor(pluginId) { return registry.passwordKeysOf(pluginId); } // 单配置 JSON:%LOCALAPPDATA%\37duAutomation\plugin_configs\.json function migrateJsonFiles() { const dir = config.PLUGIN_CONFIG_DIR; if (!fs.existsSync(dir)) return 0; let n = 0; for (const f of fs.readdirSync(dir)) { if (!f.endsWith(".json")) continue; const pluginId = f.slice(0, -5); const keys = keysFor(pluginId); if (!keys.length) continue; const p = path.join(dir, f); try { const data = JSON.parse(fs.readFileSync(p, "utf-8")); if (!data || typeof data !== "object" || Array.isArray(data)) continue; const need = keys.some( (k) => typeof data[k] === "string" && data[k] && !localCrypto.isEncrypted(data[k]) ); if (!need) continue; const stored = localCrypto.encryptFields(data, keys); const tmp = p + ".tmp"; fs.writeFileSync(tmp, JSON.stringify(stored, null, 2), "utf-8"); fs.renameSync(tmp, p); // 原子替换:中途断电不会留下半截文件 n++; } catch (e) { logger.warning(`插件配置迁移跳过 ${f}:${e.message}`); } } return n; } function migrateAll() { const jsonN = migrateJsonFiles(); let dbN = 0; try { dbN = require("./plugin-configs").migrate(keysFor); } catch (e) { logger.warning(`SQLite 配置迁移失败(跳过):${e.message}`); } if (jsonN || dbN) { logger.info(`插件配置明文迁移完成:JSON ${jsonN} 个 / 方案库 ${dbN} 条`); } return { jsonN, dbN }; } module.exports = { migrateAll, migrateJsonFiles };