Files
37duAutomation/desktop/electron-shell/electron/plugin-sync.js
T
puddy dbb05e6ab3 feat(electron-shell): 启动链路修复与执行/配置收口插件侧
- 启动链路 P1-P7 修复:预算对齐、完成事件推送、端口占用提示、前端阶段文案接管
- 静态缓存按 IS_FROZEN 区分开发/打包态,bootPhaseOwned 竞态修复
- 一键执行与参数配置统一收口到插件界面,定时任务引用 config_id
- 环境包迁移到 %LOCALAPPDATA%\37duAutomation\python-env,重装零解压
- shell-updater:缓存包 sha256 校验、静默升级后自动拉起新版、自动清理旧安装包
- after-pack 钩子生成 shell.version 修复打包态版本识别
- 插件 xq0031/xq0045 迁移至 plugins/XQ0001-0100/ 号段分桶中文目录
2026-09-28 14:20:35 +08:00

391 lines
13 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 插件按账号权限自下载 + 版本更新(执行机主动拉取;下载/校验/原子安装)。
// 对齐 Python webhost plugin_sync.py:清单 diff → download-ticket → sha256 → 临时目录原子替换。
"use strict";
const fs = require("fs");
const path = require("path");
const os = require("os");
const crypto = require("crypto");
const AdmZip = require("adm-zip");
const cp = require("./cpclient");
const config = require("./config");
const { sha256Hex, versionLt } = require("./crypto");
const { makeLogger } = require("./logger");
const { pluginRoot } = require("./registry");
const logger = makeLogger("plugin-sync");
const DL_TIMEOUT = 300;
const MAX_PKG_BYTES = 200 * 1024 * 1024;
// 回滚存储:升级前把上一版整体拷贝到 APP_DATA/plugin_rollback/<id>@<version>/(只保留每插件最新一版)。
// 放 APP_DATA 而非插件根,避免污染插件目录(pruneStale 遍历/版本目录混入)与 dev 仓库。
const ROLLBACK_DIR = path.join(config.APP_DATA, "plugin_rollback");
// 升级前备份当前版本(仅已装插件),返回 "id@version";失败返回 null(不阻断升级)
function backupForRollback(pluginId) {
const target = path.join(pluginRoot(), pluginId);
const mf = path.join(target, "plugin.json");
if (!fs.existsSync(mf)) return null; // 首次安装无需备份
const ver = localVersion(pluginId) || "unknown";
try {
fs.mkdirSync(ROLLBACK_DIR, { recursive: true });
// 只保留最新一版回滚:先清掉该插件的旧备份
for (const name of fs.readdirSync(ROLLBACK_DIR)) {
if (name.startsWith(pluginId + "@")) {
fs.rmSync(path.join(ROLLBACK_DIR, name), { recursive: true, force: true });
}
}
fs.cpSync(target, path.join(ROLLBACK_DIR, `${pluginId}@${ver}`), { recursive: true });
logger.info(`插件 ${pluginId}@${ver} 已备份(可回滚)`);
return `${pluginId}@${ver}`;
} catch (e) {
logger.warning(`插件 ${pluginId} 回滚备份失败:${e.message}`);
return null;
}
}
// 某插件可回滚的版本列表(按版本降序)
function rollbackAvailable(pluginId) {
try {
if (!fs.existsSync(ROLLBACK_DIR)) return [];
return fs
.readdirSync(ROLLBACK_DIR)
.filter((n) => n.startsWith(pluginId + "@"))
.map((n) => n.slice(pluginId.length + 1))
.sort((a, b) => (versionLt(a, b) ? 1 : -1));
} catch (e) {
return [];
}
}
// 全部可回滚插件的索引(供前端展示)
function rollbackIndex() {
try {
if (!fs.existsSync(ROLLBACK_DIR)) return [];
return fs
.readdirSync(ROLLBACK_DIR)
.filter((n) => n.includes("@"))
.map((n) => {
const idx = n.lastIndexOf("@");
return { id: n.slice(0, idx), version: n.slice(idx + 1) };
});
} catch (e) {
return [];
}
}
// 回滚到备份版本(取最新备份);失败抛错
function rollbackPlugin(pluginId) {
const versions = rollbackAvailable(pluginId);
if (!versions.length) throw new Error("该插件无可用回滚版本");
const ver = versions[0];
const src = path.join(ROLLBACK_DIR, `${pluginId}@${ver}`);
const target = path.join(pluginRoot(), pluginId);
if (!fs.existsSync(src)) throw new Error("回滚备份缺失");
fs.mkdirSync(pluginRoot(), { recursive: true });
if (fs.existsSync(target)) fs.rmSync(target, { recursive: true, force: true });
fs.cpSync(src, target, { recursive: true });
logger.info(`插件 ${pluginId} 已回滚到 ${ver}`);
return `${pluginId}@${ver}`;
}
// 同步串行锁:启动后台同步 / 登录后同步 / 手动刷新共用
let _syncPromise = Promise.resolve();
function withSyncLock(fn) {
const run = _syncPromise.then(fn, fn);
// 无论成功失败都继续链,保证后续同步不被前一次卡死
_syncPromise = run.catch(() => {});
return run;
}
function localVersion(pluginId) {
const mf = path.join(pluginRoot(), pluginId, "plugin.json");
if (!fs.existsSync(mf)) return "";
try {
return String(JSON.parse(fs.readFileSync(mf, "utf-8")).version || "");
} catch (e) {
return "";
}
}
// 中心机可用插件清单(id/name/version);不可达返回 null(离线用本地)
async function cloudPluginManifest(account) {
if (!config.CONTROLPLANE_URL || !account) return null;
try {
const r = await cp.request("GET", "/api/plugins", {
headers: cp.machineHeaders(),
params: { account },
timeout: 5,
});
return r.plugins || [];
} catch (e) {
logger.warning(`拉取插件清单失败(离线用本地插件):${e.message}`);
return null;
}
}
async function dlTicket(pluginId, version, account) {
try {
return await cp.request(
"GET",
`/api/plugins/${encodeURIComponent(pluginId)}/versions/${encodeURIComponent(version)}/download-ticket`,
{ headers: cp.machineHeaders(), params: { account }, timeout: 5 }
);
} catch (e) {
logger.warning(`获取下载票据失败 ${pluginId}@${version}:${e.message}`);
return null;
}
}
async function fetchPkg(ticket) {
try {
const r = await cp.request("GET", `/api/download/${encodeURIComponent(ticket)}`, {
headers: cp.machineHeaders(),
timeout: DL_TIMEOUT,
raw: true,
});
return r.body;
} catch (e) {
logger.warning(`下载插件包失败:${e.message}`);
return null;
}
}
// 版本兼容校验:manifest 声明 minRuntimeVersion 且当前运行时不满足 → 抛错(安装前调用)
function assertRuntimeCompat(pluginId, manifest) {
const need = String((manifest && manifest.minRuntimeVersion) || "").trim();
const cur = config.runtimeVersion();
if (need && cur && versionLt(cur, need)) {
throw new Error(`插件 ${pluginId} 要求运行时 >= ${need},当前运行时 ${cur}(请先升级客户端)`);
}
}
// 解压安装:临时目录 → 校验非法路径 → 版本兼容校验 → 原子替换(升级前自动备份上一版)
function installPkg(pluginId, content) {
if (content.length > MAX_PKG_BYTES) {
logger.error(`插件包 ${pluginId} 超大小上限,拒绝安装`);
return false;
}
let zip;
try {
zip = new AdmZip(content);
} catch (e) {
logger.error(`插件包 ${pluginId} 不是合法 ZIP`);
return false;
}
const entries = zip.getEntries();
const names = entries.map((en) => en.entryName);
if (!names.includes("plugin.json")) {
logger.error(`插件包 ${pluginId} 缺 plugin.json`);
return false;
}
for (const n of names) {
if (n.startsWith("/") || n.split("/").includes("..")) {
logger.error(`插件包 ${pluginId} 含非法路径:${n}`);
return false;
}
}
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), `.pkg_${pluginId}_`));
try {
zip.extractAllTo(tmp, true /* overwrite */);
} catch (e) {
logger.error(`解压插件包 ${pluginId} 失败:${e.message}`);
fs.rmSync(tmp, { recursive: true, force: true });
return false;
}
// 版本兼容校验:新包 plugin.json 声明 minRuntimeVersion 且当前运行时不满足 → 拒绝安装(防坏包)
let mf;
try {
mf = JSON.parse(fs.readFileSync(path.join(tmp, "plugin.json"), "utf-8"));
} catch (e) {
logger.error(`插件包 ${pluginId} 的 plugin.json 解析失败:${e.message}`);
fs.rmSync(tmp, { recursive: true, force: true });
return false;
}
try {
assertRuntimeCompat(pluginId, mf);
} catch (e) {
logger.error(`插件 ${pluginId} 拒绝安装:${e.message}`);
fs.rmSync(tmp, { recursive: true, force: true });
return false;
}
const target = path.join(pluginRoot(), pluginId);
try {
fs.mkdirSync(pluginRoot(), { recursive: true });
backupForRollback(pluginId); // 升级前保留上一版(首次安装自动跳过)
if (fs.existsSync(target)) fs.rmSync(target, { recursive: true, force: true });
moveDir(tmp, target); // 跨盘兼容:同卷 rename / 跨卷复制+删除
} catch (e) {
logger.error(`安装插件 ${pluginId} 失败:${e.message}`);
fs.rmSync(tmp, { recursive: true, force: true });
return false;
}
return true;
}
// 目录移动:同卷用 rename(原子);跨卷(如 %TEMP% 在 C:、插件目录在 D:)Windows 的 rename
// 会报 EXDEV,回退为"复制+删除",避免插件安装失败。
function moveDir(src, dest) {
try {
fs.renameSync(src, dest);
} catch (e) {
if (e.code === "EXDEV") {
fs.cpSync(src, dest, { recursive: true });
fs.rmSync(src, { recursive: true, force: true });
} else {
throw e;
}
}
}
function localPluginEntries() {
const root = pluginRoot();
const out = [];
if (!fs.existsSync(root)) return out;
for (const name of fs.readdirSync(root)) {
if (name.startsWith("_") || name === "__pycache__") continue;
const full = path.join(root, name);
let stat;
try {
stat = fs.statSync(full);
} catch (e) {
continue;
}
if (stat.isDirectory() && (fs.existsSync(path.join(full, "__init__.py")) || fs.existsSync(path.join(full, "plugin.json")))) {
out.push(full);
}
}
return out;
}
// 清理中心机已删除/收回授权的本地插件(仅云端清单可达时;设备忙则整轮跳过)
function pruneStale(keepIds) {
const scheduler = require("./scheduler");
const root = pluginRoot();
if (!fs.existsSync(root) || scheduler.isBusy()) return [];
const removed = [];
for (const entry of localPluginEntries()) {
const pid = path.basename(entry);
if (keepIds.has(pid)) continue;
try {
fs.rmSync(entry, { recursive: true, force: true });
removed.push(pid);
logger.info(`插件 ${pid} 已在中心机删除/收回授权,本地目录同步移除`);
} catch (e) {
logger.warning(`清理本地插件 ${pid} 失败:${e.message}`);
}
}
return removed;
}
// 按账号权限同步插件:首次下载 + 版本更新 + 清理已删除。离线/失败静默降级。
async function syncPlugins(account) {
const result = { downloaded: [], updated: [], up_to_date: [], failed: [], removed: [] };
if (!config.CONTROLPLANE_URL || !account) return result;
const manifest = await cloudPluginManifest(account);
if (manifest === null) return result;
result.removed = pruneStale(new Set(manifest.map((p) => p.id)));
for (const p of manifest) {
const pid = p.id;
const ver = p.version || p.latest_version || "";
if (!pid || !ver) continue;
const local = localVersion(pid);
if (local === ver || (local && !versionLt(local, ver))) {
result.up_to_date.push(pid);
continue;
}
const tkt = await dlTicket(pid, ver, account);
if (!tkt) {
result.failed.push(pid);
continue;
}
const content = await fetchPkg(tkt.ticket || "");
if (!content) {
result.failed.push(pid);
continue;
}
const expect = (tkt.sha256 || "").toLowerCase();
if (expect && sha256Hex(content) !== expect) {
logger.error(`插件包 ${pid}@${ver} sha256 校验失败,拒绝安装`);
result.failed.push(pid);
continue;
}
if (installPkg(pid, content)) {
(local ? result.updated : result.downloaded).push(pid);
} else {
result.failed.push(pid);
}
}
logger.info(
`插件同步完成:下载=${result.downloaded.join(",")} 更新=${result.updated.join(",")} ` +
`最新=${result.up_to_date.join(",")} 清理=${result.removed.join(",")} 失败=${result.failed.join(",")}`
);
return result;
}
// 权限白名单:控制面拉取 + 本地缓存(fail-closed:无账号/离线无缓存 = 空集)
const ALLOW_CACHE = path.join(config.APP_DATA, "plugin_allow.json");
function saveAllowedCache(ids) {
try {
fs.mkdirSync(config.APP_DATA, { recursive: true });
fs.writeFileSync(ALLOW_CACHE, JSON.stringify([...ids].sort()), "utf-8");
} catch (e) {
logger.warning(`插件权限清单缓存写入失败: ${e.message}`);
}
}
function loadAllowedCache() {
if (!fs.existsSync(ALLOW_CACHE)) return null;
try {
const raw = JSON.parse(fs.readFileSync(ALLOW_CACHE, "utf-8"));
return new Set((raw || []).map(String));
} catch (e) {
return null;
}
}
async function resolveAllowed(account) {
if (!config.CONTROLPLANE_URL) return new Set();
if (!account) {
logger.info("未登录(无会话账号),插件零权限加载");
return new Set();
}
try {
const r = await cp.request("GET", "/api/plugins", {
headers: cp.machineHeaders(),
params: { account },
timeout: 5,
});
const allowed = new Set((r.plugins || []).map((p) => p.id));
logger.info(`控制面权限清单(${account}):${[...allowed].sort().join(",") || "(空)"}`);
saveAllowedCache(allowed);
return allowed;
} catch (e) {
const cached = loadAllowedCache();
if (cached !== null) {
logger.info(`权限清单拉取失败,用本地缓存(${account}):${e.message}`);
return cached;
}
logger.warning(`权限清单拉取失败且无缓存,插件零权限加载:${e.message}`);
return new Set();
}
}
module.exports = {
withSyncLock,
syncPlugins,
cloudPluginManifest,
localVersion,
resolveAllowed,
pluginRoot,
backupForRollback,
rollbackAvailable,
rollbackIndex,
rollbackPlugin,
installPkg,
assertRuntimeCompat,
ROLLBACK_DIR,
};