feat(shell): 插件密码加密、失败熔断与客户端自动更新(v1.11.3)

- 插件配置中 format=password 字段改为 AES-256-GCM 密文落盘(本机密钥,历史明文自动迁移)
- 同一插件连续失败 3 次自动禁用(仅统计进程启动后失败),升级自动解除
- 检测到新版本后台下载,空闲窗口提前提示并自动重启升级,设置页可配安全窗口
This commit is contained in:
2026-11-26 09:28:18 +08:00
parent 32e28d3aec
commit 9db8c74b7f
22 changed files with 792 additions and 38 deletions
+12 -1
View File
@@ -141,7 +141,7 @@ async function runUpdateRound(reason = "周期") {
_updateRunning = true;
logger.info(`${reason}自动更新检查开始:客户端 → 环境包 → SDK → 插件`);
try {
// 1) 客户端(壳子):只做版本比对,下载与重启交给用户确认
// 1) 客户端(壳子):版本比对 → 有新版自动后台下载 → 空闲窗口自动升级(见 shell-updater.startAutoApplyWatch)
try {
shellUpdater.startCheck();
} catch (e) {
@@ -243,6 +243,13 @@ async function init(options = {}) {
// 启动即检查插件更新(后台,不阻塞启动)
void autoSyncPlugins("启动");
// 插件配置安全:历史明文密码就地转密文(幂等;失败只告警,不影响启动)
try {
require("./config-migrate").migrateAll();
} catch (e) {
logger.warning(`插件配置明文迁移失败(忽略):${e.message}`);
}
// 环境包(便携 Python 运行时):启动即检查(异步不阻塞),缺失/有新版本自动下载;
// 插件执行/平台登录在环境包就绪前会报"环境包未就绪",由「本机组件」面板提供状态与手动更新
state.setBootStep("检查便携环境包");
@@ -262,6 +269,10 @@ async function init(options = {}) {
// 定时任务:加载 + 后台触发 + 云端合并恢复
tasks.init();
// 空闲窗口自动升级巡检:必须放在 tasks.init() 之后,
// 否则首次判定时定时任务清单还是空,会把"有定时任务"误判成安全窗口。
shellUpdater.startAutoApplyWatch();
// 设备上报(Chrome 环境 + 心跳;失败静默)
void reportDevice(account)
.then(() => logger.info("设备环境上报完成"))
@@ -0,0 +1,64 @@
// 插件配置明文迁移:把历史遗留的 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\<id>.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 };
@@ -0,0 +1,119 @@
// 本机敏感字段加解密:AES-256-GCM,密钥落 APP_DATA/secrets/.key(0600)。
// 用途:插件配置里的密码字段(plugin.json 声明 format=password)由明文改为密文落盘。
// 边界:只保护 %LOCALAPPDATA% 下壳子自己管的配置;插件自己写的 cookie/profile 不在此范围。
// 兼容:非 enc:v1: 前缀一律按明文处理——升级后的旧配置读取不受影响,下次保存自动转密文。
"use strict";
const fs = require("fs");
const path = require("path");
const crypto = require("crypto");
const config = require("./config");
const { makeLogger } = require("./logger");
const logger = makeLogger("local-crypto");
const DIR = path.join(config.APP_DATA, "secrets");
const KEY_FILE = path.join(DIR, ".key");
const PREFIX = "enc:v1:";
let _key = null;
// 密钥首次使用时生成;读坏/长度不对则重建(重建后旧密文解不开,会按原值返回,不抛错)
function loadKey() {
if (_key) return _key;
try {
if (fs.existsSync(KEY_FILE)) {
const k = fs.readFileSync(KEY_FILE);
if (k.length === 32) {
_key = k;
return _key;
}
logger.warning(`密钥长度异常(${k.length}),重新生成`);
}
const key = crypto.randomBytes(32);
fs.mkdirSync(DIR, { recursive: true });
fs.writeFileSync(KEY_FILE, key, { mode: 0o600 });
_key = key;
return _key;
} catch (e) {
logger.warning(`密钥初始化失败(本次进程内临时密钥): ${e.message}`);
_key = crypto.randomBytes(32);
return _key;
}
}
function isEncrypted(v) {
return typeof v === "string" && v.startsWith(PREFIX);
}
// 返回 enc:v1:<iv>:<tag>:<data>(各段 base64);空串不加密,原样返回
function encryptText(plain) {
const text = String(plain == null ? "" : plain);
if (!text) return text;
try {
const key = loadKey();
const iv = crypto.randomBytes(12);
const cipher = crypto.createCipheriv("aes-256-gcm", key, iv);
const data = Buffer.concat([cipher.update(Buffer.from(text, "utf-8")), cipher.final()]);
const tag = cipher.getAuthTag();
return PREFIX + [iv.toString("base64"), tag.toString("base64"), data.toString("base64")].join(":");
} catch (e) {
logger.warning(`加密失败(保持明文): ${e.message}`);
return text;
}
}
// 密文解密;非密文(旧明文)原样返回;解不开也原样返回,避免把配置读成空导致平台锁号
function decryptText(value) {
if (!isEncrypted(value)) return value;
try {
const parts = value.slice(PREFIX.length).split(":");
if (parts.length !== 3) return value;
const [ivB64, tagB64, dataB64] = parts;
const key = loadKey();
const decipher = crypto.createDecipheriv("aes-256-gcm", key, Buffer.from(ivB64, "base64"));
decipher.setAuthTag(Buffer.from(tagB64, "base64"));
return Buffer.concat([decipher.update(Buffer.from(dataB64, "base64")), decipher.final()]).toString("utf-8");
} catch (e) {
logger.warning(`密文解密失败(保留原值,请重新填写密码): ${e.message}`);
return value;
}
}
// 从 registry 的 fields 数组提取密码字段名(registry.fieldsFromSchema 已把 format=password 转成 type=password)
function passwordKeys(fields) {
if (!Array.isArray(fields)) return [];
return fields.filter((f) => f && f.type === "password").map((f) => f.key).filter(Boolean);
}
// 浅拷贝并加密指定 key 的字符串值;其余字段原样保留
function encryptFields(obj, keys) {
if (!obj || typeof obj !== "object" || Array.isArray(obj)) return obj;
const out = { ...obj };
for (const k of keys || []) {
const v = out[k];
if (typeof v === "string" && v && !isEncrypted(v)) out[k] = encryptText(v);
}
return out;
}
// 浅拷贝并解密所有密文值(不依赖 schema,认前缀即可)
function decryptFields(obj) {
if (!obj || typeof obj !== "object" || Array.isArray(obj)) return obj;
const out = { ...obj };
for (const k of Object.keys(out)) {
if (isEncrypted(out[k])) out[k] = decryptText(out[k]);
}
return out;
}
module.exports = {
DIR,
KEY_FILE,
isEncrypted,
encryptText,
decryptText,
passwordKeys,
encryptFields,
decryptFields,
};
+5 -1
View File
@@ -10,6 +10,7 @@ const platformAuth = require("./platform-auth");
const state = require("./state");
const envSync = require("./env-sync");
const sdkSync = require("./sdk-sync");
const pluginHealth = require("./plugin-health");
const { versionLt } = require("./crypto");
const { makeLogger } = require("./logger");
@@ -65,7 +66,10 @@ async function buildMeta(account) {
if (lic.ok) {
const allowed = new Set((lic.payload || {}).plugins.map((p) => p.pluginId));
for (const entry of registry.listLocalPlugins()) {
if (allowed.has(entry.id)) plugins.push(registry.pluginSchema(entry.id));
if (allowed.has(entry.id)) {
// 附带熔断状态:前端据此显示「连续失败 N 次 / 已自动禁用」与恢复入口
plugins.push({ ...registry.pluginSchema(entry.id), health: pluginHealth.status(entry.id) });
}
}
} else {
authExpired = true;
@@ -1,10 +1,11 @@
// 场景配置方案(多配置)· SQLite 实现:同一场景可保存多套命名参数组合,运行台/定时任务按需选用。
// 表:plugin_configs(shell.db),按账号 + 插件隔离,同名覆盖。
// 安全:password 字段一律**明文落盘**——不做任何加解密,避免换机/密钥异常导致密码解析出错、
// 平台连续密码错误锁号;旧版本 enc:v1 密文数据不兼容,密码需在界面重新保存方案。
// 安全:plugin.json 声明 format=password 的字段用 AES-256-GCM 加密落盘(见 local-crypto);
// 读取时按 enc:v1: 前缀解密,旧明文数据原样可用,下次保存自动转密文。
"use strict";
const { db } = require("./db");
const localCrypto = require("./local-crypto");
const MAX_CONFIGS_PER_PLUGIN = 10; // 单插件最多 10 套方案,防异常堆满
@@ -12,7 +13,7 @@ function rowToCfg(row) {
if (!row) return null;
let fields = {};
try { fields = JSON.parse(row.fields || "{}"); } catch (_) { fields = {}; }
return { id: String(row.id), name: row.name, fields, at: row.at || "" };
return { id: String(row.id), name: row.name, fields: localCrypto.decryptFields(fields), at: row.at || "" };
}
function listConfigs(account, pluginId) {
@@ -31,11 +32,12 @@ function getConfig(account, pluginId, cfgId) {
}
// 保存/覆盖:同名方案更新字段,否则新增;返回新/更新后的配置
// (fields 原样明文落盘,schema 参数保留仅为兼容旧调用方)
function saveConfig(account, pluginId, name, fields, schema) {
// passwordKeys = 该插件 format=password 字段名数组(由 registry.passwordKeysOf 提供)
function saveConfig(account, pluginId, name, fields, passwordKeys) {
const trimmed = String(name || "").trim().slice(0, 20);
if (!trimmed) return null;
const keep = fields || {};
const keys = Array.isArray(passwordKeys) ? passwordKeys : [];
const keep = localCrypto.encryptFields(fields || {}, keys);
const at = new Date().toLocaleString("zh-CN", { hour12: false });
const exists = db.prepare(
"SELECT id FROM plugin_configs WHERE account = ? AND plugin_id = ? AND name = ?"
@@ -65,4 +67,25 @@ function deleteConfig(account, pluginId, cfgId) {
return r.changes > 0;
}
module.exports = { MAX_CONFIGS_PER_PLUGIN, listConfigs, getConfig, saveConfig, deleteConfig };
// 历史明文迁移:把 password 字段加密回写(幂等;keysFor(pluginId) 返回该插件密码字段名)
function migrate(keysFor) {
let n = 0;
const rows = db.prepare("SELECT id, plugin_id, fields FROM plugin_configs").all();
for (const row of rows) {
let fields;
try { fields = JSON.parse(row.fields || "{}"); } catch (_) { continue; }
if (!fields || typeof fields !== "object" || Array.isArray(fields)) continue;
const keys = keysFor(row.plugin_id) || [];
if (!keys.length) continue;
const need = keys.some(
(k) => typeof fields[k] === "string" && fields[k] && !localCrypto.isEncrypted(fields[k])
);
if (!need) continue;
db.prepare("UPDATE plugin_configs SET fields = ? WHERE id = ?")
.run(JSON.stringify(localCrypto.encryptFields(fields, keys)), row.id);
n++;
}
return n;
}
module.exports = { MAX_CONFIGS_PER_PLUGIN, listConfigs, getConfig, saveConfig, deleteConfig, migrate };
@@ -0,0 +1,124 @@
// 插件健康熔断:同一插件连续失败达到阈值自动禁用,避免定时任务每天白跑、失败却无人知晓。
// 只统计"进程真正跑起来后失败"(runner.finishRun 中 status=error 且已有 started),
// 入队失败、SDK/环境未就绪、平台登录失败等前置问题不计入——那些不是插件本身的问题。
// 恢复:插件升级到新版本自动清零;或前端手动「恢复」。
"use strict";
const fs = require("fs");
const path = require("path");
const config = require("./config");
const { makeLogger } = require("./logger");
const logger = makeLogger("plugin-health");
const FILE = path.join(config.APP_DATA, "plugin_health.json");
const FAIL_THRESHOLD = 3;
let _cache = null;
function load() {
if (_cache) return _cache;
let data = {};
try {
if (fs.existsSync(FILE)) {
const d = JSON.parse(fs.readFileSync(FILE, "utf-8"));
if (d && typeof d === "object" && !Array.isArray(d)) data = d;
}
} catch (e) {
logger.warning(`插件健康记录损坏,已忽略:${FILE}`);
}
_cache = data;
return _cache;
}
function persist() {
try {
fs.mkdirSync(config.APP_DATA, { recursive: true });
const tmp = FILE + ".tmp";
fs.writeFileSync(tmp, JSON.stringify(_cache || {}, null, 2), "utf-8");
fs.renameSync(tmp, FILE); // 原子替换
} catch (e) {
logger.warning(`插件健康记录落盘失败:${e.message}`);
}
}
function entry(pluginId) {
const all = load();
return all[pluginId] || null;
}
/**
* 记录一次运行结果。
* @returns {{ tripped: boolean, fails: number }} tripped 表示本次刚好触达熔断阈值
*/
function record(pluginId, ok, error) {
if (!pluginId) return { tripped: false, fails: 0 };
const all = load();
const cur = all[pluginId] || { fails: 0, tripped: false };
if (ok) {
if (cur.fails || cur.tripped) {
all[pluginId] = { fails: 0, tripped: false, last_ok_at: new Date().toLocaleString("zh-CN", { hour12: false }) };
persist();
logger.info(`插件 ${pluginId} 执行成功,失败计数清零 / 熔断解除`);
}
return { tripped: false, fails: 0 };
}
const fails = (parseInt(cur.fails, 10) || 0) + 1;
const tripped = cur.tripped || fails >= FAIL_THRESHOLD;
all[pluginId] = {
fails,
tripped,
error: String(error || "").slice(0, 300),
last_fail_at: new Date().toLocaleString("zh-CN", { hour12: false }),
};
persist();
if (tripped && !cur.tripped) {
logger.warning(`插件 ${pluginId} 连续失败 ${fails} 次,已自动熔断(需人工恢复或升级插件)`);
return { tripped: true, fails };
}
return { tripped: false, fails };
}
function isTripped(pluginId) {
const e = entry(pluginId);
return !!(e && e.tripped);
}
function status(pluginId) {
const e = entry(pluginId);
return {
tripped: !!(e && e.tripped),
fails: (e && parseInt(e.fails, 10)) || 0,
threshold: FAIL_THRESHOLD,
error: (e && e.error) || "",
last_fail_at: (e && e.last_fail_at) || "",
};
}
function all() {
const out = {};
for (const [pid, e] of Object.entries(load())) {
if (!e) continue;
out[pid] = {
tripped: !!e.tripped,
fails: parseInt(e.fails, 10) || 0,
threshold: FAIL_THRESHOLD,
error: e.error || "",
last_fail_at: e.last_fail_at || "",
};
}
return out;
}
// 手动恢复 / 插件升级后自动调用
function reset(pluginId) {
if (!pluginId) return false;
const all = load();
if (!all[pluginId]) return false;
delete all[pluginId];
persist();
logger.info(`插件 ${pluginId} 熔断已解除(手动恢复或版本更新)`);
return true;
}
module.exports = { FAIL_THRESHOLD, record, isTripped, status, all, reset };
@@ -15,6 +15,7 @@ const { pluginRoot } = require("./registry");
const sdkResolver = require("./sdk-resolver");
const logger = makeLogger("plugin-sync");
const pluginHealth = require("./plugin-health");
const DL_TIMEOUT = 300;
const MAX_PKG_BYTES = 200 * 1024 * 1024;
@@ -252,6 +253,8 @@ function installPkg(pluginId, content) {
fs.rmSync(tmp, { recursive: true, force: true });
return false;
}
// 新版本给一次重新机会:清除该插件的失败熔断(旧版本的问题可能已修复)
try { pluginHealth.reset(pluginId); } catch (_) { /* 忽略 */ }
return true;
}
+26 -1
View File
@@ -136,4 +136,29 @@ function findByName(name) {
return find(name);
}
module.exports = { pluginRoot, listLocalPlugins, readManifest, fieldsFromSchema, pluginSchema, find };
// 按插件 id 取密码字段名(format=password)。
// 目录名与 manifest.id 可能不一致:生产机安装目录用 xq0078,仓库里是「XQ0078 中文名」。
// 先按目录名直查,失败再遍历比对 manifest.id,避免配置加密因命名差异静默失效。
function passwordKeysOf(pluginId) {
const localCrypto = require("./local-crypto"); // 延迟 require:本模块被 config 间接依赖,避免加载期环
try {
return localCrypto.passwordKeys(find(pluginId).fields);
} catch (_) { /* 目录名不等于 id:继续遍历 */ }
try {
for (const entry of listLocalPlugins()) {
const schema = pluginSchema(entry.id);
if (schema.id === pluginId) return localCrypto.passwordKeys(schema.fields);
}
} catch (_) { /* 忽略 */ }
return [];
}
module.exports = {
pluginRoot,
listLocalPlugins,
readManifest,
fieldsFromSchema,
pluginSchema,
find,
passwordKeysOf,
};
+34 -1
View File
@@ -19,6 +19,8 @@ const platformAuth = require("./platform-auth");
const platformCreds = require("./platform-creds");
const sdkResolver = require("./sdk-resolver");
const sdkSync = require("./sdk-sync");
const localCrypto = require("./local-crypto");
const pluginHealth = require("./plugin-health");
const { HUB } = require("./hub");
const { makeLogger } = require("./logger");
@@ -229,6 +231,25 @@ function finishRun(runId, plugin, status, error, summary) {
peak_mem_mb: run.peak_mem_mb || 0,
logs: Array.isArray(run.logs) ? run.logs : [],
});
// 插件健康熔断:只统计"进程真正跑起来后失败"(run.started 有值);
// 入队失败 / SDK 未就绪 / 平台登录失败等前置错误不计入,避免冤枉插件。
try {
if (status === "done") {
pluginHealth.record(plugin.id, true, "");
} else if (status === "error" && run.started) {
const h = pluginHealth.record(plugin.id, false, error);
if (h.tripped) {
notifyUser(
"插件已自动禁用",
`「${run.name || plugin.name || plugin.id}」连续失败 ${h.fails} 次,已停止自动执行;排查后可在场景页手动恢复`,
"important"
);
}
}
// cancelled(用户取消/排队超时)与 interrupted(客户端退出)不计入插件健康
} catch (e) {
logger.warning(`插件健康记录失败:${e.message}`);
}
// 日志集中回传:整次运行日志上送中心机(离线自动暂存补报;失败不阻断运行收尾)
try {
require("./log-upload").uploadRun({
@@ -291,7 +312,8 @@ function loadUiSavedFields(pluginId) {
try {
const raw = fs.readFileSync(path.join(config.PLUGIN_CONFIG_DIR, `${pluginId}.json`), "utf-8");
const v = JSON.parse(raw);
return v && typeof v === "object" && !Array.isArray(v) ? v : null;
// 密码字段以密文落盘,注入插件前先解密(旧明文数据原样透传)
return v && typeof v === "object" && !Array.isArray(v) ? localCrypto.decryptFields(v) : null;
} catch (_) {
return null; // 无保存配置/损坏:维持空 fields(插件走自身默认值)
}
@@ -323,6 +345,17 @@ function submitRun(account, plugin, fields, opts) {
(!process.env.PYTHON_EXE && !config.pythonEnvRoot() && config.IS_FROZEN)) {
throwEnvNotReady();
}
// 熔断拦截:连续失败到阈值后拒绝执行,避免定时任务每天白跑、失败却无人知晓
if (pluginHealth.isTripped(plugin.id)) {
const h = pluginHealth.status(plugin.id);
throw Object.assign(
new Error(
`插件「${plugin.name || plugin.id}」连续失败 ${h.fails} 次已自动禁用` +
`${h.error ? `(最近错误:${h.error})` : ""},请排查后在场景页点击「恢复」`
),
{ status: 409 }
);
}
let effFields = fields && typeof fields === "object" && !Array.isArray(fields) ? fields : {};
if (Object.keys(effFields).length === 0) {
const saved = loadUiSavedFields(plugin.id);
+26 -5
View File
@@ -21,6 +21,8 @@ const runHistory = require("./run-history");
const lastFields = require("./last-fields");
const notes = require("./notes");
const pluginConfigs = require("./plugin-configs");
const localCrypto = require("./local-crypto");
const pluginHealth = require("./plugin-health");
const scheduler = require("./scheduler");
const tasks = require("./tasks");
const flows = require("./flows");
@@ -308,6 +310,8 @@ function settingsSnapshot() {
settings_file: shellSettings.filePath(),
autostart: autostartEnabled(),
close_behavior: s.close_behavior,
auto_shell_update: s.auto_shell_update,
auto_update_safe_min: s.auto_update_safe_min,
run_timeout_sec: config.runTimeoutFor(null),
run_timeout_override: s.run_timeout_sec,
run_timeout_default: config.RUN_TIMEOUT,
@@ -647,6 +651,16 @@ async function route(req, res, url) {
return sendJson(res, 200, { ok: true, rollback: done });
}
// ---------- 插件失败熔断:手动恢复(升级插件也会自动清零) ----------
const healthResetMatch = p.match(/^\/api\/plugins\/([^/]+)\/health\/reset$/);
if (healthResetMatch && method === "POST") {
session.requireLogin(cookies);
const pluginId = decodeURIComponent(healthResetMatch[1]);
checkUiAllowed(pluginId);
pluginHealth.reset(pluginId);
return sendJson(res, 200, { ok: true, health: pluginHealth.status(pluginId) });
}
// ---------- 壳子更新 ----------
if (p === "/api/shell/update-status" && method === "GET") {
session.requireLogin(cookies);
@@ -729,7 +743,7 @@ async function route(req, res, url) {
session.requireLogin(cookies);
const body = await readJsonBody(req);
const patch = {};
for (const k of ["close_behavior", "run_timeout_sec", "run_max_mem_mb", "log_max_mb", "log_keep"]) {
for (const k of ["close_behavior", "auto_shell_update", "auto_update_safe_min", "run_timeout_sec", "run_max_mem_mb", "log_max_mb", "log_keep"]) {
if (Object.prototype.hasOwnProperty.call(body, k)) patch[k] = body[k];
}
let next;
@@ -1116,8 +1130,11 @@ async function route(req, res, url) {
const body = await readJsonBody(req);
if (!body.plugin_id) throw Object.assign(new Error("缺少 plugin_id"), { status: 400 });
checkUiAllowed(body.plugin_id);
const plugin = registry.find(body.plugin_id);
const cfg = pluginConfigs.saveConfig(account, body.plugin_id, body.name, body.fields, plugin.fields);
// 密码字段名由 registry 解析(兼容"目录名≠manifest.id"的历史差异),加密落盘
const cfg = pluginConfigs.saveConfig(
account, body.plugin_id, body.name, body.fields,
registry.passwordKeysOf(body.plugin_id)
);
if (!cfg) throw Object.assign(new Error("配置名称不能为空"), { status: 400 });
return sendJson(res, 200, { ok: true, config: cfg });
}
@@ -1183,7 +1200,8 @@ function readPluginConfig(pluginId) {
if (!fs.existsSync(p)) return {};
try {
const data = JSON.parse(fs.readFileSync(p, "utf-8"));
return data && typeof data === "object" && !Array.isArray(data) ? data : {};
// 密码字段解密后再给插件 UI / 执行链;旧明文数据原样透传
return data && typeof data === "object" && !Array.isArray(data) ? localCrypto.decryptFields(data) : {};
} catch (e) {
return {};
}
@@ -1192,9 +1210,12 @@ function readPluginConfig(pluginId) {
function savePluginConfig(pluginId, data) {
const p = path.join(config.PLUGIN_CONFIG_DIR, `${pluginId}.json`);
try {
// format=password 字段加密落盘;取不到插件元数据时按原样保存(不阻断)
const keys = registry.passwordKeysOf(pluginId);
const stored = localCrypto.encryptFields(data, keys);
fs.mkdirSync(config.PLUGIN_CONFIG_DIR, { recursive: true });
const tmp = p + ".tmp";
fs.writeFileSync(tmp, JSON.stringify(data, null, 2), "utf-8");
fs.writeFileSync(tmp, JSON.stringify(stored, null, 2), "utf-8");
fs.renameSync(tmp, p); // 原子替换
} catch (e) {
logger.warning(`插件 ${pluginId} 配置保存失败:${e.message}`);
+18 -1
View File
@@ -1,4 +1,4 @@
// 设置中心持久化:用户级可调项(关闭行为 / 执行超时与内存 / 日志保留)。
// 设置中心持久化:用户级可调项(关闭行为 / 执行超时与内存 / 日志保留 / 自动更新)。
// 明文 JSON:%LOCALAPPDATA%\37duAutomation\shell-settings.json(与插件配置同根,重装不丢)。
// 只做「存取 + 校验」,不碰 HTTP、不碰 Electron API(开机自启由调用方读写系统设置)。
// 取值语义:null = 跟随默认(.env / 内置常量);数字 = 用户覆盖值。
@@ -12,6 +12,8 @@ const FILE_NAME = "shell-settings.json";
// 可写入的键与合法范围(范围外一律拒绝,避免手改坏文件/前端传错把设备跑废)
const RULES = {
close_behavior: { type: "enum", values: ["tray", "quit"] },
auto_shell_update: { type: "enum", values: ["on", "off"] },
auto_update_safe_min: { type: "num", min: 1, max: 60, nullable: false, integer: true },
run_timeout_sec: { type: "num", min: 0, max: 7 * 24 * 3600, nullable: true, integer: true },
run_max_mem_mb: { type: "num", min: 0, max: 32768, nullable: true, integer: true },
log_max_mb: { type: "num", min: 1, max: 512, nullable: true, integer: true },
@@ -36,6 +38,8 @@ function filePath() {
function defaults() {
return {
close_behavior: "tray", // tray = 关闭窗口收托盘继续跑;quit = 关闭即退出程序
auto_shell_update: "on", // on = 检测到新版后台自动下载、空闲窗口自动升级重启(Windows Update 式)
auto_update_safe_min: 10,// 未来 N 分钟内有定时任务就不触发自动升级,避免任务被跳过不补跑
run_timeout_sec: null, // 空 = 用 .env 的 RUN_TIMEOUT(默认 21600 = 6 小时;0 = 不限时)
run_max_mem_mb: null, // 空 = 用 .env / 内置默认(物理内存 70%,4GB~16GB;0 = 不限)
log_max_mb: null, // 空 = 内置默认 10MB 单文件
@@ -133,6 +137,17 @@ function closeBehavior() {
return get().close_behavior || "tray";
}
/** 自动更新开关(on = 开,off = 关);默认开 */
function autoShellUpdate() {
return get().auto_shell_update !== "off";
}
/** 自动升级前需预留的安全窗口(分钟):未来这段时间有定时任务就不触发 */
function autoUpdateSafeMin() {
const n = get().auto_update_safe_min;
return Number.isFinite(n) && n > 0 ? n : 10;
}
module.exports = {
filePath,
defaults,
@@ -142,4 +157,6 @@ module.exports = {
runMaxMemMb,
logRotation,
closeBehavior,
autoShellUpdate,
autoUpdateSafeMin,
};
@@ -1,4 +1,4 @@
// 壳子(主程序)自动更新:检查 → 用户确认下载(带进度)→ 点击重启升级。
// 壳子(主程序)自动更新:检查 → 后台自动下载(可选手动)→ 空闲窗口自动重启升级(Windows Update 式)。
// 对齐 Python shell_updater.py 的状态结构与并发控制。
"use strict";
@@ -8,6 +8,7 @@ const crypto = require("crypto");
const { spawn } = require("child_process");
const cp = require("./cpclient");
const config = require("./config");
const settings = require("./settings");
const { versionLt } = require("./crypto");
const { makeLogger } = require("./logger");
@@ -15,6 +16,11 @@ const logger = makeLogger("shell-updater");
const SHELL_CACHE = path.join(config.APP_DATA, "shell");
const PERIODIC_INTERVAL = 30 * 60 * 1000;
// 自动升级尝试标记:落盘而非内存——升级会 process.exit 重启,内存变量必丢。
// 作用:同一版本自动升级后若版本号仍未变化(打包漏写 shell.version / 安装未生效),
// 冷却期内不再自动重试,避免无人值守时无限重启循环。
const AUTO_ATTEMPT_FILE = path.join(SHELL_CACHE, "auto-update-attempt.json");
const AUTO_ATTEMPT_COOLDOWN = 6 * 3600 * 1000;
// 升级等待窗口:独立 HTA(mshta.exe)进程。
// 壳子自身进程必须退出才能被 NSIS 替换文件,所以这段时间 Electron 窗口必然消失;
@@ -166,6 +172,14 @@ let _pendingVersion = "";
let _pendingNotes = "";
let _pendingPkg = ""; // 已通过 sha256 校验的缓存安装包绝对路径
// 自动更新(Windows Update 式):检测后自动后台下载,空闲窗口提前通知再重启安装。
// 倒计时期间重复 tick 不再发通知;条件被打破(任务进来/定时任务临近)则取消本次升级。
const AUTO_NOTICE_SEC = 30;
const AUTO_WATCH_MS = 60 * 1000;
const USER_IDLE_SEC = 60; // 用户 60 秒无键鼠输入才算空闲,避免正在用机器时被强拉重启
let _autoWatchTimer = null;
let _autoNoticeTimer = null;
const _STATE = {
checking: false,
check_at: 0,
@@ -319,7 +333,13 @@ async function checkUpdate() {
_STATE.dl_pct = 0;
}
const cached = await validateCache(cloud, info.sha256);
if (cached) restorePending(cloud, notes, cached);
if (cached) {
restorePending(cloud, notes, cached);
} else if (settings.autoShellUpdate()) {
// 自动更新开:缓存没有可用包才后台静默下载(不打断任务),下载完由空闲巡检择机安装。
// 必须放在作废旧包之后调用,否则旧包 downloaded 态会让 startDownload 直接早退、漏掉新版。
void startDownload().catch((e) => logger.warning(`自动下载壳子更新失败:${e.message}`));
}
} finally {
_STATE.checking = false;
_checking = false;
@@ -340,6 +360,104 @@ function startPeriodicCheck() {
}, PERIODIC_INTERVAL);
}
// ==================== 空闲窗口自动升级 ====================
// 四个条件全满足才装:包已就绪 / 无任务运行或排队 / 未来安全窗口无定时任务 / 用户键鼠空闲。
// 任一条被打破就取消本轮,下个 tick 重新判断——绝不为了升级打断正在进行的工作。
function readAutoAttempt() {
try {
const d = JSON.parse(fs.readFileSync(AUTO_ATTEMPT_FILE, "utf-8"));
return d && typeof d === "object" ? d : {};
} catch (e) {
return {};
}
}
function markAutoAttempt(version) {
try {
fs.mkdirSync(SHELL_CACHE, { recursive: true });
fs.writeFileSync(AUTO_ATTEMPT_FILE, JSON.stringify({ version, at: Date.now() }), "utf-8");
} catch (e) {
logger.warning(`写自动升级尝试标记失败:${e.message}`);
}
}
function autoIdleReady() {
if (!settings.autoShellUpdate()) return { ok: false, why: "自动更新已关闭" };
if (!localShellVersion()) return { ok: false, why: "源码开发模式" };
if (_STATE.applying || _downloading) return { ok: false, why: "升级/下载进行中" };
const st = pendingStatus();
if (!st.downloaded || !_pendingVersion) return { ok: false, why: "无已就绪升级包" };
// 防死循环:同版本自动升级后版本号仍未变化(安装未生效),冷却期内不再自动重试
const att = readAutoAttempt();
if (att.version === _pendingVersion && Date.now() - (Number(att.at) || 0) < AUTO_ATTEMPT_COOLDOWN) {
return { ok: false, why: `已自动尝试升级 v${att.version} 未生效,进入冷却(避免重复重启)` };
}
// 延迟 require:避免与 tasks / app 形成模块加载环
const scheduler = require("./scheduler");
if (scheduler.isBusy()) return { ok: false, why: "设备正在执行任务" };
const queue = require("./queue");
if (queue.busy() || queue.size() > 0) return { ok: false, why: "执行队列非空" };
const tasks = require("./tasks");
const safeMs = settings.autoUpdateSafeMin() * 60 * 1000;
if (tasks.hasRunWithin(safeMs)) return { ok: false, why: `未来 ${settings.autoUpdateSafeMin()} 分钟有定时任务` };
// 用户活跃判定:Electron 主进程可用 powerMonitor;取不到时按空闲处理(不因能力缺失卡死升级)
try {
const { powerMonitor } = require("electron");
if (powerMonitor && powerMonitor.getSystemIdleTime() < USER_IDLE_SEC) {
return { ok: false, why: "用户正在操作电脑" };
}
} catch (e) { /* 非 Electron 环境:跳过用户活跃判定 */ }
return { ok: true, version: _pendingVersion, why: "设备空闲" };
}
function startAutoApplyWatch() {
if (_autoWatchTimer) return;
_autoWatchTimer = setInterval(() => {
try { void autoApplyTick(); } catch (e) { logger.warning(`自动升级巡检异常:${e.message}`); }
}, AUTO_WATCH_MS);
if (_autoWatchTimer.unref) _autoWatchTimer.unref();
logger.info(`壳子空闲自动升级巡检已启动(每 ${AUTO_WATCH_MS / 1000}s,提前 ${AUTO_NOTICE_SEC}s 提醒)`);
}
async function autoApplyTick() {
const r = autoIdleReady();
// 倒计时中:条件被打破就立刻取消,不必等到 30 秒后复核
if (_autoNoticeTimer) {
if (!r.ok) {
logger.info(`自动升级条件中断(${r.why}),取消本轮`);
clearTimeout(_autoNoticeTimer);
_autoNoticeTimer = null;
}
return;
}
if (!r.ok) return;
logger.info(`空闲窗口满足,${AUTO_NOTICE_SEC}s 后自动升级到 ${r.version}`);
try {
require("./notify-toast").show(
"客户端即将自动更新",
`新版本 v${r.version} 已就绪,设备当前空闲,${AUTO_NOTICE_SEC} 秒后自动重启升级(${r.why || "空闲窗口"})`,
"warning"
);
} catch (e) { /* 通知失败不阻断升级 */ }
_autoNoticeTimer = setTimeout(() => {
_autoNoticeTimer = null;
// 倒计时期间可能有新任务/定时任务进来,装前再判一次
const r2 = autoIdleReady();
if (!r2.ok) {
logger.info(`自动升级装前复核未通过(${r2.why}),本轮跳过`);
return;
}
// 先落盘尝试标记:升级成功后进程直接退出,事后再写来不及
markAutoAttempt(r2.version);
try {
applyUpdate();
} catch (e) {
logger.warning(`自动升级执行失败:${e.message}`);
}
}, AUTO_NOTICE_SEC * 1000);
if (_autoNoticeTimer.unref) _autoNoticeTimer.unref();
}
async function startDownload() {
const cur = localShellVersion();
if (!cur) return;
@@ -519,6 +637,9 @@ function pendingStatus() {
new: downloaded ? _pendingVersion : "",
notes: downloaded ? _pendingNotes : "",
downloaded,
auto_update: settings.autoShellUpdate(),
auto_safe_min: settings.autoUpdateSafeMin(),
auto_notice_pending: !!_autoNoticeTimer,
available: !!_STATE.available,
latest: _STATE.latest || "",
checked_at: _STATE.check_at || 0,
@@ -675,9 +796,11 @@ function applyUpdate() {
module.exports = {
startCheck,
startPeriodicCheck,
startAutoApplyWatch,
startDownload,
pendingStatus,
applyUpdate,
cleanupStalePackages,
localShellVersion,
autoIdleReady,
};
+24
View File
@@ -269,6 +269,29 @@ function nextRunAt(s) {
return nextMatch(cron, last || new Date());
}
/** 未来 windowMs 内(含到点容差回看)是否有启用的定时任务到点;供壳子自动升级判断安全窗口 */
function hasRunWithin(windowMs) {
const now = Date.now();
// 直接从 now-容差 起算,而不是走 nextRunAt(s):后者以 last_run_at 为锚点,
// 壳子停机后重启、tick 尚未推进 last_run_at 时会算出过去的点,导致漏判下一到点。
const from = new Date(now - CATCHUP_SKIP_MS);
for (const s of _schedules) {
if (!s.enabled) continue;
let cron;
try {
cron = parseCron(s.cron || "");
// 防御:分钟级历史任务本就不会触发,不计入安全窗口
if (minGapMinutes(cron) < 60) continue;
} catch (e) {
continue;
}
const t = nextMatch(cron, from);
if (!t) continue;
if (t.getTime() - now <= windowMs) return true;
}
return false;
}
function publicView(s) {
const out = { ...s };
out.enabled = !!out.enabled;
@@ -548,6 +571,7 @@ module.exports = {
deleteSchedule,
toggleSchedule,
nextRunAt,
hasRunWithin,
watchRun,
pushBackup,
restoreFromCloud,