feat(electron-shell): 补录壳子源码(排除运行环境与构建产物)

This commit is contained in:
2026-09-24 16:14:24 +08:00
parent 08a9b962b4
commit f3311339e5
56 changed files with 17858 additions and 0 deletions
+157
View File
@@ -0,0 +1,157 @@
// 应用组装层:启动初始化(单活复位/权限/授权/插件同步/壳子检查/定时任务/设备上报)+ 本地服务。
"use strict";
const os = require("os");
const fs = require("fs");
const path = require("path");
const crypto = require("crypto");
const config = require("./config");
const state = require("./state");
const session = require("./session");
const scheduler = require("./scheduler");
const licensing = require("./licensing");
const registry = require("./registry");
const pluginSync = require("./plugin-sync");
const tasks = require("./tasks");
const shellUpdater = require("./shell-updater");
const chromeManager = require("./chrome-manager");
const envSync = require("./env-sync");
const { makeLogger, setLogFile } = require("./logger");
const logger = makeLogger("app");
// 设备 ID:持久化 uuid(跨重启稳定,供 device/report)
function deviceId() {
const f = path.join(config.APP_DATA, "device_id");
try {
if (fs.existsSync(f)) {
const v = fs.readFileSync(f, "utf-8").trim();
if (v) return v;
}
const id = crypto.randomUUID();
fs.mkdirSync(config.APP_DATA, { recursive: true });
fs.writeFileSync(f, id, "utf-8");
return id;
} catch (e) {
return "dev-" + crypto.randomBytes(8).toString("hex");
}
}
function localIp() {
try {
const ifs = os.networkInterfaces();
for (const list of Object.values(ifs)) {
for (const it of list || []) {
if (it.family === "IPv4" && !it.internal) return it.address;
}
}
} catch (e) {
/* 忽略 */
}
return "";
}
// 设备环境上报(心跳 + Chrome 环境):Node 版新增接入(旧 Python 底座无调用方)
async function reportDevice(account) {
const chrome = await chromeManager.detectLocal();
await licensing.deviceReport(deviceId(), account, {
hostname: os.hostname(),
os: process.platform,
ip: localIp(),
chromeInstalled: chrome.installed,
chromeVersion: chrome.version,
chromeOk: chrome.installed,
});
}
async function init(options = {}) {
// 崩溃现场落盘(窗口模式无控制台时排查唯一窗口):Electron 运行时都落盘(含打包版),
// CLI 纯 Node 模式日志走 stdout 即可。不能依赖 ELECTRON_RENDERER_URL(本工程从不设置)。
// ★ 日志放数据根 %LOCALAPPDATA%\37duAutomation\logs\(打包态 SHELL_ROOT 在 app.asar 内只读,不能写)
if (process.versions && process.versions.electron) {
setLogFile(path.join(config.APP_DATA, "logs", "shell.log"));
}
scheduler.initActive();
// 账号:优先 .env,其次最近活跃本机会话
const account = config.CONTROLPLANE_ACCOUNT || session.sessActiveAccount();
if (config.CONTROLPLANE_URL) {
// 权限白名单(fail-closed)
try {
const allowed = await pluginSync.resolveAllowed(account);
state.setAllowed(allowed);
} catch (e) {
state.setAllowed(new Set());
}
// 敏感凭证中心化下发(在线拉取 RSA 解密 / 本地缓存兜底;失败不阻断启动)
try {
const creds = await require("./creds-sync").load(account);
if (creds && Object.keys(creds).length) {
config.applyCreds(creds);
logger.info(`中心机敏感凭证下发完成(${Object.keys(creds).length} 个键)`);
}
} catch (e) {
logger.warning(`加载中心机敏感凭证失败:${e.message}`);
}
// 启动同步离线授权票据
if (account) {
try {
await licensing.syncLicensing(account);
logger.info(`启动同步离线授权票据成功(账号 ${account})`);
} catch (e) {
logger.warning(`启动同步离线授权票据失败:${e.message}`);
}
}
// 启动即检查插件更新(后台,不阻塞启动)
const accts = session.accountSet();
if (accts.size > 0) {
const firstAcct = accts.values().next().value;
void pluginSync
.withSyncLock(async () => {
await pluginSync.syncPlugins(firstAcct);
const manifest = await pluginSync.cloudPluginManifest(firstAcct);
if (manifest !== null) state.setAllowed(new Set(manifest.map((p) => p.id)));
logger.info(`启动插件更新完成(账号 ${firstAcct})`);
})
.catch((e) => logger.warning(`启动插件更新失败:${e.message}`));
}
// 环境包(便携 Python 运行时):启动即检查(异步不阻塞),缺失/有新版本自动下载;
// 插件执行/平台登录在环境包就绪前会报"环境包未就绪",由设置页提供状态与手动更新
void envSync
.checkAndSync()
.then((r) => logger.info(`环境包检查:${r.ok ? `就绪 v${r.version || ""}` : `未就绪(${r.reason})`}`))
.catch((e) => logger.warning(`环境包启动检查异常:${e.message}`));
// 常驻周期检查(30 分钟,与壳子更新同频)
setInterval(() => {
void envSync.checkAndSync().catch((e) => logger.warning(`环境包周期检查异常:${e.message}`));
}, 30 * 60 * 1000);
// 壳子更新:启动检查 + 常驻周期检查
shellUpdater.startCheck();
shellUpdater.startPeriodicCheck();
// 定时任务:加载 + 后台触发 + 云端合并恢复
tasks.init();
// 设备上报(Chrome 环境 + 心跳;失败静默)
void reportDevice(account)
.then(() => logger.info("设备环境上报完成"))
.catch(() => {});
} else {
logger.info("未配置中心机地址(CONTROLPLANE_URL),进入离线本地模式");
state.setAllowed(new Set());
tasks.load();
tasks.start();
}
logger.info(`插件根目录:${registry.pluginRoot()}`);
logger.info(`数据根目录:${config.APP_DATA}`);
return { deviceId: deviceId(), account };
}
module.exports = { init, deviceId };
@@ -0,0 +1,279 @@
// 浏览器(Chrome)管理:检测本机是否已装 Chrome → 从中心机拿内网链接下载安装包 → 静默安装。
// 对齐 Python chrome_manager.py 的状态结构与流程。
"use strict";
const fs = require("fs");
const path = require("path");
const { spawn, execFile } = require("child_process");
const cp = require("./cpclient");
const config = require("./config");
const { makeLogger } = require("./logger");
const logger = makeLogger("chrome-manager");
const CHROME_CACHE = path.join(config.APP_DATA, "chrome");
let _pendingPkg = null;
const _STATE = {
installed: true,
version: "",
checking: false,
check_error: "",
cloud_available: true,
dl_status: "idle",
dl_received: 0,
dl_total: 0,
dl_pct: 0,
dl_error: "",
installing: false,
};
const VERSION_RE = /^\d+\.\d+\.\d+\.\d+$/;
// 本机检测缓存:前端轮询 status 时避免每 2s 反复 spawn reg/powershell
let _localCache = { ts: 0, value: null };
const LOCAL_CACHE_TTL = 30 * 1000;
async function detectLocal(force = false) {
const now = Date.now();
if (!force && _localCache.value && now - _localCache.ts < LOCAL_CACHE_TTL) {
return _localCache.value;
}
const exe = await findChromeExe();
let value;
if (!exe) value = { installed: false, version: "" };
else value = { installed: true, version: await readVersion(exe) };
_localCache = { ts: now, value };
return value;
}
function execFileAsync(file, args, timeout = 8000) {
return new Promise((resolve) => {
execFile(file, args, { timeout, windowsHide: true }, (err, stdout, stderr) => {
if (err) resolve({ err, stdout: stdout || "", stderr: stderr || "" });
else resolve({ err: null, stdout: stdout || "", stderr: stderr || "" });
});
});
}
// 注册表探测 Chrome.exe 路径(64/32 位)
async function findChromeExe() {
const roots = [
["HKLM", "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\chrome.exe"],
["HKLM", "SOFTWARE\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\App Paths\\chrome.exe"],
["HKCU", "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\chrome.exe"],
];
for (const [hive, key] of roots) {
const r = await execFileAsync("reg", ["query", `${hive}\\${key}`, "/ve"]);
if (!r.err) {
// 输出形如: (默认) REG_SZ C:\...\chrome.exe
const m = /REG_SZ\s+(.+)$/m.exec(r.stdout);
if (m && fs.existsSync(m[1].trim())) return m[1].trim();
}
}
// 目录扫描兜底
const dirs = [
path.join(process.env.PROGRAMFILES || "C:/Program Files", "Google", "Chrome", "Application"),
path.join(process.env["PROGRAMFILES(X86)"] || "C:/Program Files (x86)", "Google", "Chrome", "Application"),
path.join(config.APP_DATA, "..", "Google", "Chrome", "Application"),
];
for (const d of dirs) {
const p = path.join(d, "chrome.exe");
if (fs.existsSync(p)) return p;
}
return null;
}
async function readVersion(exe) {
const r = await execFileAsync(
"powershell",
["-NoProfile", "-NonInteractive", "-Command", `(Get-Item -LiteralPath '${exe}').VersionInfo.ProductVersion`],
8000
);
if (r.err) return "";
const v = r.stdout.trim();
return VERSION_RE.test(v) ? v : "";
}
async function cloudInfo() {
if (!config.CONTROLPLANE_URL) return null;
try {
const r = await cp.request("GET", "/api/file-sources/chrome", { headers: cp.machineHeaders(), timeout: 5 });
if (!r.available) {
_STATE.cloud_available = false;
return null;
}
_STATE.cloud_available = true;
return r;
} catch (e) {
logger.info(`获取浏览器云端信息失败(离线跳过):${e.message}`);
_STATE.cloud_available = false;
return null;
}
}
async function status() {
const local = await detectLocal();
if (local.installed) {
_STATE.installed = true;
_STATE.version = local.version;
_STATE.check_error = "";
} else {
_STATE.installed = false;
_STATE.version = "";
}
const pkgOk = !!_pendingPkg && fs.existsSync(_pendingPkg);
return {
installed: !!_STATE.installed,
version: _STATE.version || "",
downloaded: !!pkgOk,
cloud_available: !!_STATE.cloud_available,
error: _STATE.check_error || "",
installing: !!_STATE.installing,
dl: {
status: _STATE.dl_status || "idle",
received: _STATE.dl_received || 0,
total: _STATE.dl_total || 0,
pct: _STATE.dl_pct || 0,
error: _STATE.dl_error || "",
},
};
}
async function refresh() {
_STATE.checking = true;
try {
await detectLocal();
await cloudInfo();
} catch (e) {
logger.warning(`浏览器检测异常:${e.message}`);
} finally {
_STATE.checking = false;
}
}
let _downloading = false;
async function startDownload() {
if (_STATE.dl_status === "downloading") return;
if (_STATE.dl_status === "downloaded" && _pendingPkg && fs.existsSync(_pendingPkg)) return;
const info = await cloudInfo();
if (!info || !info.url) return;
const url = String(info.url).trim();
const expect = String(info.sha256 || "").toLowerCase();
const filename = String(info.filename || "ChromeStandaloneSetup64.exe").trim();
if (_downloading) return;
_downloading = true;
_STATE.dl_status = "downloading";
_STATE.dl_received = 0;
_STATE.dl_total = 0;
_STATE.dl_pct = 0;
_STATE.dl_error = "";
try {
await download(url, expect, filename);
} catch (e) {
logger.warning(`下载 Chrome 安装包失败:${e.message}`);
_STATE.dl_status = "failed";
_STATE.dl_error = `安装包下载失败(${e.constructor.name})`;
cleanupPart();
} finally {
_downloading = false;
}
logger.info(`开始下载 Chrome 安装包:${url}`);
}
async function download(url, expect, filename) {
const crypto = require("crypto");
const sha = crypto.createHash("sha256");
const tmp = path.join(CHROME_CACHE, `${filename}.part`);
const pkg = path.join(CHROME_CACHE, filename);
fs.mkdirSync(CHROME_CACHE, { recursive: true });
const out = fs.createWriteStream(tmp);
let received = 0;
let total = 0;
const ctrl = new AbortController();
const timer = setTimeout(() => ctrl.abort(), 600 * 1000);
const res = await fetch(url, { signal: ctrl.signal, redirect: "follow" });
if (!res.ok) throw new Error(`HTTP ${res.status}`);
total = parseInt(res.headers.get("content-length") || "0", 10);
const reader = res.body.getReader();
for (;;) {
const { done, value } = await reader.read();
if (done) break;
out.write(value);
sha.update(value);
received += value.length;
_STATE.dl_received = received;
_STATE.dl_total = total;
_STATE.dl_pct = total ? Math.floor((received * 100) / total) : 0;
}
clearTimeout(timer);
await new Promise((res2, rej2) => out.end((e) => (e ? rej2(e) : res2())));
const digest = sha.digest("hex");
if (expect && digest !== expect) {
logger.error("Chrome 安装包 sha256 校验失败");
_STATE.dl_status = "failed";
_STATE.dl_error = "安装包校验失败,请重试";
cleanupPart();
return;
}
try {
fs.renameSync(tmp, pkg);
} catch (e) {
_STATE.dl_status = "failed";
_STATE.dl_error = "安装包保存失败";
cleanupPart();
return;
}
_pendingPkg = pkg;
_STATE.dl_status = "downloaded";
_STATE.dl_pct = 100;
_STATE.dl_received = received;
_STATE.dl_total = total;
logger.info(`Chrome 安装包下载完成:${pkg}`);
}
function cleanupPart() {
try {
for (const f of fs.readdirSync(CHROME_CACHE)) {
if (f.endsWith(".part")) fs.unlinkSync(path.join(CHROME_CACHE, f));
}
} catch (e) {
/* 忽略 */
}
}
function install() {
if (!_pendingPkg || !fs.existsSync(_pendingPkg)) {
throw Object.assign(new Error("未找到已下载的 Chrome 安装包"), { status: 404 });
}
_STATE.installing = true;
logger.info(`开始静默安装 Chrome:${_pendingPkg}`);
const child = spawn(_pendingPkg, ["/silent", "/install"], {
cwd: path.dirname(_pendingPkg),
windowsHide: true,
stdio: "ignore",
detached: true,
});
child.unref();
void pollInstall();
return { ok: true, installing: true };
}
async function pollInstall() {
for (let i = 0; i < 60; i++) {
await new Promise((r) => setTimeout(r, 5000));
const local = await detectLocal();
if (local.installed) {
_STATE.installing = false;
_STATE.installed = true;
_STATE.version = local.version;
logger.info(`Chrome 安装完成:${_STATE.version}`);
return;
}
}
_STATE.installing = false;
logger.warning("等待 Chrome 安装完成超时");
}
module.exports = { status, refresh, startDownload, install, detectLocal };
+204
View File
@@ -0,0 +1,204 @@
// 37du Electron 壳:配置固化(.env 加载 + 路径 + 常量)
// 对齐 Python webhost backend/core/config.py 的语义与路径约定。
"use strict";
const fs = require("fs");
const path = require("path");
// 打包态判定:Electron 运行时 + resources 下存在 app.asar(打包版独有,dev `electron .` 无 asar)。
// 不能依赖 ELECTRON_RENDERER_URL(那是 electron-vite 等 dev-server 工具的变量,本工程从不设置)。
const IS_FROZEN =
!!process.versions &&
!!process.versions.electron &&
!!process.resourcesPath &&
!process.env.ELECTRON_RUN_AS_NODE &&
fs.existsSync(path.join(process.resourcesPath, "app.asar"));
// 本模块目录:desktop/electron-shell/electron → parents
const SHELL_ROOT = path.resolve(__dirname, "..");
// 仓库根:electron/../.. = 37duAutomation(dev 模式定位 plugins/ 与 webhost 参考实现)
const REPO_ROOT = path.resolve(SHELL_ROOT, "..", "..");
const DESKTOP_ROOT = path.resolve(SHELL_ROOT, "..");
// ==================== 轻量 .env 加载(仅本模块目录,变量已存在则不覆盖) ====================
function loadDotEnv() {
const envPath = path.join(SHELL_ROOT, ".env");
if (!fs.existsSync(envPath)) return;
try {
const text = fs.readFileSync(envPath, "utf-8");
for (const rawLine of text.split(/\r?\n/)) {
const line = rawLine.trim();
if (!line || line.startsWith("#") || !line.includes("=")) continue;
const idx = line.indexOf("=");
const key = line.slice(0, idx).trim();
const value = line.slice(idx + 1).trim();
if (key && process.env[key] === undefined) process.env[key] = value;
}
} catch (e) {
// 读取失败静默(与 Python 实现一致)
}
}
loadDotEnv();
// ==================== 基础常量 ====================
const PORT = 8799;
// 数据根目录:与影刀版 / 旧 Python 底座共享 %LOCALAPPDATA%\37duAutomation(跨端契约)
function localAppData() {
return process.env.LOCALAPPDATA || process.env.APPDATA || require("os").homedir();
}
const APP_DATA = path.join(localAppData(), "37duAutomation");
// 插件本地配置目录:per-plugin JSON 持久化
const PLUGIN_CONFIG_DIR = path.join(APP_DATA, "plugin_configs");
// 插件源码/安装根:dev = 仓库根 plugins/;打包 = exe 同级 plugins/
function pluginRoot() {
if (process.env.SHELL_PLUGIN_ROOT) return process.env.SHELL_PLUGIN_ROOT;
if (IS_FROZEN) {
return path.join(path.dirname(process.execPath), "plugins");
}
return path.join(REPO_ROOT, "plugins");
}
// 运行时版本:打包态读 exe 同级 shell.version(发版文件);开发/CLI 回退 package.json 版本。
// 插件 plugin.json 可声明 minRuntimeVersion 做版本兼容校验(不满足则拒绝安装)。
function runtimeVersion() {
try {
if (!process.env.ELECTRON_RUN_AS_NODE && process.resourcesPath) {
const vf = path.join(path.dirname(process.execPath), "shell.version");
if (fs.existsSync(vf)) {
const v = fs.readFileSync(vf, "utf-8").trim();
if (v) return v;
}
}
const pkg = JSON.parse(fs.readFileSync(path.join(SHELL_ROOT, "package.json"), "utf-8"));
return String(pkg.version || "").trim();
} catch (e) {
return "";
}
}
// ==================== 控制面配置 ====================
const CONTROLPLANE_URL = (process.env.CONTROLPLANE_URL || "").replace(/\/+$/, "");
const CONTROLPLANE_ACCOUNT = process.env.CONTROLPLANE_ACCOUNT || "";
const CONTROLPLANE_TOKEN = process.env.CONTROLPLANE_TOKEN || "";
// ==================== 插件执行子进程配置 ====================
// Python 解释器:优先 env,默认 python(PATH 中的 venv/系统 Python)
const PYTHON_EXE = process.env.PYTHON_EXE || "python";
const RUN_TIMEOUT = parseInt(process.env.RUN_TIMEOUT || "1800", 10);
const RUN_MAX_MEM_MB = parseInt(process.env.RUN_MAX_MEM_MB || "2048", 10);
// ==================== 便携 Python 环境包(python-env) ====================
// 版本化目录(python-env/<version>/)+ current.json 指向当前版本,保留上一版供回滚。
// 目录位置:打包态 = exe 同级 python-env/;开发态 = electron-shell/python-env/(可本地构建联调)。
function envRootDir() {
if (process.env.SHELL_PYTHON_ENV_ROOT) return path.resolve(process.env.SHELL_PYTHON_ENV_ROOT);
if (IS_FROZEN) return path.join(path.dirname(process.execPath), "python-env");
return path.join(SHELL_ROOT, "python-env");
}
// 当前环境包目录(current.json → 版本目录);无环境包返回 ""
function pythonEnvRoot() {
const dir = envRootDir();
try {
const raw = fs.readFileSync(path.join(dir, "current.json"), "utf-8").replace(/^\uFEFF/, "");
const cur = JSON.parse(raw);
const ver = String((cur || {}).version || "").trim();
if (ver && fs.existsSync(path.join(dir, ver, "python.exe"))) return path.join(dir, ver);
} catch (e) {
/* 尚无环境包 */
}
return "";
}
// 环境包解析的 Python 解释器:显式 PYTHON_EXE 优先,其次环境包,最后系统 python
function pythonExe() {
if (process.env.PYTHON_EXE) return process.env.PYTHON_EXE;
const envRoot = pythonEnvRoot();
if (envRoot) return path.join(envRoot, "python.exe");
return "python";
}
// 运行时根(webhost 包所在目录):环境包模式 = 环境包根;否则 = desktop/(dev,webhost 在仓库内)
function runtimeRoot() {
const envRoot = pythonEnvRoot();
if (envRoot) return envRoot;
return DESKTOP_ROOT;
}
// 插件执行入口:环境包模式 = 环境包内 plugin_runner.py;打包态 = exe 同级;dev = 仓库 webhost
function runnerScript() {
if (process.env.SHELL_RUNNER_SCRIPT) return process.env.SHELL_RUNNER_SCRIPT;
const envRoot = pythonEnvRoot();
if (envRoot) return path.join(envRoot, "webhost", "backend", "core", "plugin_runner.py");
if (IS_FROZEN) {
return path.join(path.dirname(process.execPath), "plugin_runner.py");
}
return path.join(DESKTOP_ROOT, "webhost", "backend", "core", "plugin_runner.py");
}
// Job Object 守护(环境包模式启用内存上限 + 整树托管):无环境包返回 ""
function jobGuardScript() {
const envRoot = pythonEnvRoot();
if (envRoot) return path.join(envRoot, "webhost", "backend", "core", "job_guard.py");
return "";
}
// 前端静态资源:壳自带 renderer/dist(可单独拷贝);dev 兜底复用 webhost 构建产物
function frontendDist() {
const own = path.join(SHELL_ROOT, "renderer", "dist");
if (fs.existsSync(path.join(own, "index.html"))) return own;
const legacy = path.join(DESKTOP_ROOT, "webhost", "frontend", "dist");
if (fs.existsSync(path.join(legacy, "index.html"))) return legacy;
return own;
}
// 平台登录子进程:spawn python <shared 模块>(webhost.backend.shared.hr_login/oa_login)
function sharedModule(moduleName) {
return path.join(DESKTOP_ROOT, "webhost", "backend", "shared", `${moduleName}.py`);
}
// 敏感凭证中心化下发:进程级覆盖存储(唯一来源:中心机下发 / 本地加密缓存)
const _CREDS_OVERRIDE = {};
function applyCreds(values) {
if (values && typeof values === "object") {
Object.assign(_CREDS_OVERRIDE, values);
}
}
function getCred(name) {
if (_CREDS_OVERRIDE[name] !== undefined) return _CREDS_OVERRIDE[name];
return process.env[name] !== undefined ? process.env[name] : "";
}
module.exports = {
SHELL_ROOT,
REPO_ROOT,
DESKTOP_ROOT,
PORT,
APP_DATA,
PLUGIN_CONFIG_DIR,
CONTROLPLANE_URL,
CONTROLPLANE_ACCOUNT,
CONTROLPLANE_TOKEN,
PYTHON_EXE,
RUN_TIMEOUT,
RUN_MAX_MEM_MB,
IS_FROZEN,
pluginRoot,
runnerScript,
frontendDist,
sharedModule,
runtimeVersion,
applyCreds,
getCred,
envRootDir,
pythonEnvRoot,
pythonExe,
runtimeRoot,
jobGuardScript,
};
+133
View File
@@ -0,0 +1,133 @@
// 中心机 REST 客户端:_cp_call 等价(头规则一致、超时、错误透传 detail)。
"use strict";
const { makeLogger } = require("./logger");
const config = require("./config");
const logger = makeLogger("cpclient");
class HttpError extends Error {
constructor(status, detail) {
super(typeof detail === "string" && detail ? detail : `中心机 ${status}`);
this.status = status;
this.detail = detail;
}
}
function baseUrl() {
if (!config.CONTROLPLANE_URL) {
const err = new Error("统一后端未配置(CONTROLPLANE_URL)");
err.status = 503;
throw err;
}
return config.CONTROLPLANE_URL;
}
// 机器凭证头(X-API-Token)
function machineHeaders() {
const h = {};
if (config.CONTROLPLANE_TOKEN) h["X-API-Token"] = config.CONTROLPLANE_TOKEN;
return h;
}
// params: {a: 1} → query string
function qs(params) {
if (!params) return "";
const parts = Object.entries(params)
.filter(([, v]) => v !== undefined && v !== null)
.map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`);
return parts.length ? `?${parts.join("&")}` : "";
}
async function request(method, urlPath, opts = {}) {
const { headers = {}, json, params, body, timeout = 30, raw = false } = opts;
const url = `${baseUrl()}${urlPath}${qs(params)}`;
const h = { ...headers };
let payload;
if (json !== undefined) {
h["Content-Type"] = "application/json";
payload = JSON.stringify(json);
} else if (body !== undefined) {
payload = body;
}
const ctrl = new AbortController();
const timer = setTimeout(() => ctrl.abort(), timeout * 1000);
let res;
try {
res = await fetch(url, {
method,
headers: h,
body: payload,
signal: ctrl.signal,
redirect: "follow",
});
} catch (e) {
const err = new Error(`中心机不可达: ${e.message}`);
err.status = 502;
throw err;
} finally {
clearTimeout(timer);
}
const buf = Buffer.from(await res.arrayBuffer());
if (res.status >= 400) {
let detail = buf.toString("utf-8").slice(0, 300);
try {
detail = JSON.parse(detail).detail || detail;
} catch (e) {
/* 非 JSON 错误体 */
}
throw new HttpError(res.status, detail);
}
if (raw) {
return { status: res.status, headers: res.headers, body: buf };
}
// JSON(二进制接口用 raw)
const text = buf.toString("utf-8");
try {
return JSON.parse(text);
} catch (e) {
return { detail: text.slice(0, 300) };
}
}
// 流式下载(shell/chrome 大包,带进度回调):返回 {status, sha, contentLength}
async function streamDownload(urlPath, opts = {}) {
const { headers = {}, timeout = 600, onProgress, onData } = opts;
const url = `${baseUrl()}${urlPath}`;
const ctrl = new AbortController();
const timer = setTimeout(() => ctrl.abort(), timeout * 1000);
let res;
try {
res = await fetch(url, { headers, signal: ctrl.signal, redirect: "follow" });
} catch (e) {
clearTimeout(timer);
const err = new Error(`下载失败: ${e.message}`);
err.status = 502;
throw err;
}
const crypto = require("crypto");
const sha = crypto.createHash("sha256");
const total = parseInt(res.headers.get("content-length") || "0", 10);
let received = 0;
const reader = res.body.getReader();
try {
for (;;) {
const { done, value } = await reader.read();
if (done) break;
sha.update(value);
received += value.length;
if (onData) onData(value);
if (onProgress) onProgress(received, total);
}
} catch (e) {
throw new Error(`下载中断: ${e.message}`);
} finally {
clearTimeout(timer);
}
if (res.status >= 400) {
throw new HttpError(res.status, `下载失败 HTTP ${res.status}`);
}
return { status: res.status, sha256: sha.digest("hex"), contentLength: total, received };
}
module.exports = { HttpError, request, machineHeaders, qs, streamDownload, baseUrl };
@@ -0,0 +1,119 @@
// 执行机敏感凭证下发与缓存:中心机在线拉取(RSA 解密) + 加密缓存(离线复用)。
// 对齐 Python creds_sync.py:RSA-2048 密钥对 + OAEP-SHA256 解密 + cache.json 密文缓存。
"use strict";
const fs = require("fs");
const path = require("path");
const crypto = require("crypto");
const cp = require("./cpclient");
const config = require("./config");
const session = require("./session");
const { loadOrCreateRsaKey, rsaDecrypt } = require("./crypto");
const { makeLogger } = require("./logger");
const logger = makeLogger("creds-sync");
// 与服务端 config_push._ALLOWED_KEYS 保持一致(双重保障:下发限定范围)
const ALLOWED_KEYS = new Set([
"DINGTALK_APPKEY",
"DINGTALK_APPSECRET",
"DINGTALK_AGENT_ID",
"DINGTALK_CORP_ID",
]);
const CREDS_DIR = path.join(config.APP_DATA, "creds");
const PRIV_PATH = path.join(CREDS_DIR, "id_rsa.pem");
const CACHE_FILE = path.join(CREDS_DIR, "cache.json");
let _priv = null;
function privateKey() {
if (!_priv) _priv = loadOrCreateRsaKey(PRIV_PATH);
return _priv;
}
function publicKeyPem() {
const key = privateKey();
return crypto.createPublicKey(key).export({ type: "spki", format: "pem" }).toString();
}
function decrypt(cipherB64) {
return rsaDecrypt(privateKey(), cipherB64);
}
function saveCache(encrypted) {
try {
fs.mkdirSync(CREDS_DIR, { recursive: true });
fs.writeFileSync(CACHE_FILE, JSON.stringify(encrypted), "utf-8");
} catch (e) {
logger.warning(`敏感凭证缓存写入失败: ${e.message}`);
}
}
function loadCache() {
if (!fs.existsSync(CACHE_FILE)) return {};
try {
const raw = JSON.parse(fs.readFileSync(CACHE_FILE, "utf-8"));
const out = {};
for (const [k, b64] of Object.entries(raw || {})) {
if (!ALLOWED_KEYS.has(k)) continue;
try {
out[k] = decrypt(b64);
} catch (e) {
logger.warning(`敏感凭证缓存解密失败: ${k}`);
}
}
return out;
} catch (e) {
return {};
}
}
// 中心机在线拉取并解密敏感凭证;不可用返回 null(走缓存兜底)
async function sync(account) {
if (!config.CONTROLPLANE_URL || !account || !session.cloudToken(account)) return null;
try {
const headers = {
Authorization: `Bearer ${session.cloudToken(account)}`,
};
if (config.CONTROLPLANE_TOKEN) headers["X-API-Token"] = config.CONTROLPLANE_TOKEN;
// 1. 上报本机 RSA 公钥(幂等 upsert;中心机用该公钥加密下发)
await cp.request("POST", "/api/admin/creds/register", {
headers,
json: { account, pubkey_pem: publicKeyPem() },
timeout: 10,
});
// 2. 拉取加密后的敏感凭证
const r = await cp.request("GET", "/api/admin/creds", { headers, timeout: 10 });
const encrypted = r.creds || {};
if (Object.keys(encrypted).length === 0) return {};
// 3. 本机私钥逐个解密
const out = {};
for (const [k, b64] of Object.entries(encrypted)) {
if (!ALLOWED_KEYS.has(k)) continue;
try {
out[k] = decrypt(b64);
} catch (e) {
logger.warning(`敏感凭证解密失败: ${k}`);
}
}
// 4. 密文原样落盘缓存(离线复用)
saveCache(encrypted);
return out;
} catch (e) {
logger.warning(`中心机敏感凭证拉取失败(用本地缓存): ${e.message}`);
return null;
}
}
async function load(account = "") {
account = account || config.CONTROLPLANE_ACCOUNT;
if (!account) account = session.sessActiveAccount();
const synced = await sync(account);
if (synced !== null) return synced;
const cached = loadCache();
if (Object.keys(cached).length) logger.info("使用本地敏感凭证缓存(中心机不可达或无云令牌)");
return cached;
}
module.exports = { load, sync, publicKeyPem, decrypt, ALLOWED_KEYS, PRIV_PATH };
+120
View File
@@ -0,0 +1,120 @@
// 密码学与通用工具:Ed25519 验签 / RSA-OAEP 解密 / sha256 / base64url / 版本比较。
"use strict";
const crypto = require("crypto");
const fs = require("fs");
const path = require("path");
// ==================== base64url(无填充解码,对齐 Python urlsafe_b64decode) ====================
function b64urlDecode(s) {
// JS 中 -len % 4 为负数(Python 为正补数),显式换算补位数
const pad = (4 - (s.length % 4)) % 4;
return Buffer.from(s + "=".repeat(pad), "base64url");
}
// ==================== Ed25519 票据验签 ====================
// 票据格式:base64url(canonical_json).base64url(64B 签名);验签返回 payload 对象。
function verifyBlob(blob, publicKeyPem) {
if (typeof blob !== "string" || !blob.includes(".")) throw new Error("bad blob");
const idx = blob.lastIndexOf(".");
const b64 = blob.slice(0, idx);
const sig64 = blob.slice(idx + 1);
const canon = b64urlDecode(b64);
const sig = b64urlDecode(sig64);
if (sig.length !== 64) throw new Error("bad signature len");
const key = crypto.createPublicKey(publicKeyPem);
const ok = crypto.verify(null, canon, key, sig);
if (!ok) throw new Error("signature verification failed");
return JSON.parse(canon.toString("utf-8"));
}
// ==================== RSA-2048 密钥对(creds 下发) ====================
// 私钥 PKCS8 PEM 落盘 %LOCALAPPDATA%\37duAutomation\creds\id_rsa.pem;公钥上报中心机。
function loadOrCreateRsaKey(privPath) {
if (fs.existsSync(privPath)) {
try {
const pem = fs.readFileSync(privPath, "utf-8");
return crypto.createPrivateKey(pem);
} catch (e) {
// 损坏则重新生成
}
}
const { privateKey, publicKey } = crypto.generateKeyPairSync("rsa", {
modulusLength: 2048,
publicExponent: 0x10001,
publicKeyEncoding: { type: "spki", format: "pem" },
privateKeyEncoding: { type: "pkcs8", format: "pem" },
});
fs.mkdirSync(path.dirname(privPath), { recursive: true });
fs.writeFileSync(privPath, privateKey, { encoding: "utf-8", mode: 0o600 });
return privateKey;
}
// OAEP-SHA256 解密 base64 密文 → 明文(与服务端 rsa_encrypt 对称)
function rsaDecrypt(privateKey, cipherB64) {
const ct = Buffer.from(cipherB64, "base64");
const pt = crypto.privateDecrypt(
{ key: privateKey, padding: crypto.constants.RSA_PKCS1_OAEP_PADDING, oaepHash: "sha256" },
ct
);
return pt.toString("utf-8");
}
// ==================== 通用工具 ====================
function sha256Hex(data) {
return crypto.createHash("sha256").update(data).digest("hex");
}
// 版本比较:数字段按 int,非数字段按 str 小写(对齐 Python licensing._version_lt)
function versionKey(s) {
return String(s)
.split(".")
.map((x) => (/^\d+$/.test(x) ? [1, parseInt(x, 10)] : [0, x.toLowerCase()]));
}
function versionLt(a, b) {
const ka = versionKey(a);
const kb = versionKey(b);
for (let i = 0; i < Math.max(ka.length, kb.length); i++) {
const x = ka[i] || [0, ""];
const y = kb[i] || [0, ""];
if (x[0] !== y[0]) return x[0] < y[0];
if (x[0] === 1) {
if (x[1] !== y[1]) return x[1] < y[1];
} else if (x[1] !== y[1]) return x[1] < y[1];
}
return false;
}
function deadlinePassed(deadline) {
if (!deadline) return false;
const t = Date.parse(String(deadline).replace("Z", "+00:00"));
if (Number.isNaN(t)) return false;
return Date.now() > t;
}
function nowStr() {
const d = new Date();
const p = (n) => String(n).padStart(2, "0");
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`;
}
function newId() {
return Date.now().toString(16) + crypto.randomBytes(4).toString("hex");
}
function sleep(ms) {
return new Promise((r) => setTimeout(r, ms));
}
module.exports = {
b64urlDecode,
verifyBlob,
loadOrCreateRsaKey,
rsaDecrypt,
sha256Hex,
versionLt,
deadlinePassed,
nowStr,
newId,
sleep,
};
+42
View File
@@ -0,0 +1,42 @@
// 壳子本地 SQLite(better-sqlite3):替代散落 JSON 承载新增数据。
// 数据库:%LOCALAPPDATA%\37duAutomation\shell.db
// 说明:
// - 既有 JSON(license/active/schedules/run_history/creds 等)是和老客户端(Python webhost)
// 共享的契约文件,保持原样不动;**新增数据一律入 SQLite**,避免再堆 JSON。
// - better-sqlite3 为原生模块:CLI 模式用系统 Node 的二进制;打包(electron-builder)时
// 自动 rebuild 为 Electron ABI,产物无需额外处理。
"use strict";
const path = require("path");
const Database = require("better-sqlite3");
const config = require("./config");
const { makeLogger } = require("./logger");
const logger = makeLogger("db");
const DB_PATH = path.join(config.APP_DATA, "shell.db");
// 打开即建库建表(幂等);WAL 提升并发读性能,写仍同步
const db = new Database(DB_PATH);
db.pragma("journal_mode = WAL");
function migrate() {
db.exec(`
-- 场景配置方案(多配置):同一场景多套命名参数,运行台/定时任务按需选用
CREATE TABLE IF NOT EXISTS plugin_configs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
account TEXT NOT NULL,
plugin_id TEXT NOT NULL,
name TEXT NOT NULL,
fields TEXT NOT NULL DEFAULT '{}',
at TEXT NOT NULL DEFAULT '',
UNIQUE(account, plugin_id, name)
);
CREATE INDEX IF NOT EXISTS idx_pcfg_owner ON plugin_configs(account, plugin_id);
`);
logger.info(`SQLite 就绪:${DB_PATH}`);
}
migrate();
module.exports = { db, DB_PATH };
@@ -0,0 +1,170 @@
// Electron 壳:窗口 / 托盘 / 单实例 / 自启。渲染层加载本地 8799 兼容层(复用 webhost 前端)。
"use strict";
const fs = require("fs");
const { app, BrowserWindow, Tray, Menu, nativeImage, dialog, screen } = require("electron");
const path = require("path");
const config = require("./config");
const { makeLogger } = require("./logger");
const logger = makeLogger("electron-main");
// 移除 Electron 默认英文菜单栏(File Edit View Window Help):成品客户端菜单由页面自绘
Menu.setApplicationMenu(null);
const PORT = config.PORT;
const URL = `http://127.0.0.1:${PORT}`;
// 窗口状态持久化:记住位置/尺寸,重启还原(防显示器变更后窗口跑到屏幕外)
const WINDOW_STATE_FILE = path.join(config.APP_DATA, "window-state.json");
function loadWindowState() {
try {
if (!fs.existsSync(WINDOW_STATE_FILE)) return null;
const s = JSON.parse(fs.readFileSync(WINDOW_STATE_FILE, "utf-8"));
if (!s || typeof s !== "object") return null;
const w = Math.max(1000, Math.min(4000, Number(s.width) || 1200));
const h = Math.max(660, Math.min(4000, Number(s.height) || 780));
const x = Number(s.x);
const y = Number(s.y);
if (
!Number.isFinite(x) ||
!Number.isFinite(y) ||
!screen.getAllDisplays().some((d) => {
const a = d.workArea;
return x < a.x + a.width && x + w > a.x && y < a.y + a.height && y + h > a.y;
})
) {
return { width: w, height: h }; // 位置失效:只恢复尺寸
}
return { width: w, height: h, x, y };
} catch (e) {
return null;
}
}
function saveWindowState(win) {
try {
const b = win.getBounds();
fs.mkdirSync(config.APP_DATA, { recursive: true });
fs.writeFileSync(WINDOW_STATE_FILE, JSON.stringify(b), "utf-8");
} catch (e) {
/* 忽略:状态保存失败不影响运行 */
}
}
let mainWindow = null;
let tray = null;
let server = null;
// 单实例锁:重复启动聚焦已有窗口
if (!app.requestSingleInstanceLock()) {
app.quit();
} else {
app.on("second-instance", () => {
if (mainWindow) {
if (mainWindow.isMinimized()) mainWindow.restore();
mainWindow.focus();
}
});
app.setAppUserModelId("37du.Host");
function createWindow() {
const st = loadWindowState() || {};
mainWindow = new BrowserWindow({
width: st.width || 1200,
height: st.height || 780,
x: st.x,
y: st.y,
minWidth: 1000,
minHeight: 660,
backgroundColor: "#eef2f9",
title: "37du 自动化工作台",
icon: trayIconImage(),
webPreferences: {
contextIsolation: true,
nodeIntegration: false,
sandbox: true,
preload: path.join(__dirname, "preload.js"),
},
});
mainWindow.loadURL(URL);
// 关闭时保存窗口状态;resize/move 防抖保存(异常退出也不丢太多)
let stateTimer = null;
const save = () => {
if (stateTimer) clearTimeout(stateTimer);
stateTimer = setTimeout(() => {
if (mainWindow && !mainWindow.isDestroyed()) saveWindowState(mainWindow);
}, 400);
if (stateTimer.unref) stateTimer.unref();
};
mainWindow.on("resize", save);
mainWindow.on("move", save);
mainWindow.on("close", () => {
if (mainWindow && !mainWindow.isDestroyed()) saveWindowState(mainWindow);
});
mainWindow.on("closed", () => {
mainWindow = null;
});
}
function trayIconImage() {
// 16x16 蓝色圆点占位图标(正式打包时替换为 tools/icon.ico 生成的 png)
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16"><rect width="16" height="16" rx="4" fill="#3b6cf6"/><text x="8" y="12" font-size="10" text-anchor="middle" fill="#fff" font-family="sans-serif">37</text></svg>`;
return nativeImage.createFromDataURL(`data:image/svg+xml;base64,${Buffer.from(svg).toString("base64")}`);
}
function createTray() {
tray = new Tray(trayIconImage());
const ctx = Menu.buildFromTemplate([
{ label: "打开工作台", click: () => createWindow() },
{ type: "separator" },
{
label: "开机自启",
type: "checkbox",
checked: app.getLoginItemSettings().openAtLogin,
click: (item) => {
app.setLoginItemSettings({ openAtLogin: item.checked });
},
},
{ type: "separator" },
{ label: "退出", click: () => app.quit() },
]);
tray.setToolTip("37du 自动化工作台");
tray.setContextMenu(ctx);
tray.on("click", () => {
if (!mainWindow) createWindow();
else mainWindow.show();
});
}
app.whenReady().then(async () => {
try {
const { init } = require("./app");
const { listen } = require("./server");
await init();
server = listen(() => {
createWindow();
createTray();
logger.info("Electron 壳就绪");
});
} catch (e) {
logger.error(`启动失败:${e.stack || e}`);
dialog.showErrorBox("37du 自动化工作台", `启动失败:${e.message}`);
app.quit();
}
});
app.on("window-all-closed", () => {
app.quit(); // Windows:关闭窗口即退出(服务随主进程结束)
});
app.on("before-quit", () => {
try {
if (server) server.close();
} catch (e) {
/* 忽略 */
}
});
}
+277
View File
@@ -0,0 +1,277 @@
// 环境包同步(python-env):检查中心机 /api/file-sources/python-env → 下载 → sha256 →
// 解压到 python-env/<version>/ → 更新 current.json → 清理(保留上一版供回滚)。
// 与插件/壳子更新同一套"版本单点 + 校验 + 原子切换"模式;中心机无需改接口(category 为
// 任意字符串,`agent_cli file push --category python-env` 即可发布)。
"use strict";
const fs = require("fs");
const path = require("path");
const crypto = require("crypto");
const AdmZip = require("adm-zip");
const cp = require("./cpclient");
const config = require("./config");
const { versionLt } = require("./crypto");
const { makeLogger } = require("./logger");
const logger = makeLogger("env-sync");
const _STATE = {
installed: false,
version: "",
dir: "",
cloud_available: false,
cloud_version: "",
dl_status: "idle", // idle | downloading | downloaded | failed
dl_received: 0,
dl_total: 0,
dl_pct: 0,
dl_error: "",
checking: false,
};
function envDir() {
return config.envRootDir();
}
// 当前环境包版本(读 current.json;兼容 UTF-8 BOM)
function readCurrent() {
try {
const raw = fs.readFileSync(path.join(envDir(), "current.json"), "utf-8").replace(/^\uFEFF/, "");
const cur = JSON.parse(raw);
return String((cur || {}).version || "").trim();
} catch (e) {
return "";
}
}
// 中心机登记的云端环境包信息
async function cloudInfo() {
if (!config.CONTROLPLANE_URL) return null;
try {
const r = await cp.request("GET", "/api/file-sources/python-env", {
headers: cp.machineHeaders(),
timeout: 8,
});
_STATE.cloud_available = !!(r && r.available);
_STATE.cloud_version = r && r.available ? String(r.version || "") : "";
return r && r.available ? r : null;
} catch (e) {
logger.warning(`获取环境包云端信息失败(离线跳过):${e.message}`);
_STATE.cloud_available = false;
_STATE.cloud_version = "";
return null;
}
}
// 状态(每次从磁盘实时计算安装态;云端信息来自最近一次 cloudInfo)
function status() {
const ver = readCurrent();
const dir = ver ? path.join(envDir(), ver) : "";
const installed = !!dir && fs.existsSync(path.join(dir, "python.exe"));
return {
installed,
version: installed ? ver : "",
dir: installed ? dir : "",
cloud_available: !!_STATE.cloud_available,
cloud_version: _STATE.cloud_version || "",
checking: !!_STATE.checking,
dl: {
status: _STATE.dl_status || "idle",
received: _STATE.dl_received || 0,
total: _STATE.dl_total || 0,
pct: _STATE.dl_pct || 0,
error: _STATE.dl_error || "",
},
};
}
// 刷新状态(供启动后/同步后调用,等价于 status())
function refreshStatus() {
return status();
}
function resetDl() {
_STATE.dl_status = "idle";
_STATE.dl_received = 0;
_STATE.dl_total = 0;
_STATE.dl_pct = 0;
_STATE.dl_error = "";
}
// 下载 zip 到缓存目录(.part → sha256 → rename),返回落盘路径
async function downloadZip(info) {
const url = String(info.url || "").trim();
if (!url) throw new Error("环境包下载地址为空");
const expect = String(info.sha256 || "").toLowerCase();
const filename = String(info.filename || `python-env-${info.version}.zip`).trim();
const cache = path.join(envDir(), "_cache");
fs.mkdirSync(cache, { recursive: true });
const part = path.join(cache, `${filename}.part`);
const zip = path.join(cache, filename);
const sha = crypto.createHash("sha256");
const ctrl = new AbortController();
const timer = setTimeout(() => ctrl.abort(), 900 * 1000); // 大包 15 分钟上限
const res = await fetch(url, { signal: ctrl.signal, redirect: "follow" });
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const total = parseInt(res.headers.get("content-length") || "0", 10);
const out = fs.createWriteStream(part);
let received = 0;
try {
const reader = res.body.getReader();
for (;;) {
const { done, value } = await reader.read();
if (done) break;
out.write(value);
sha.update(value);
received += value.length;
_STATE.dl_received = received;
_STATE.dl_total = total;
_STATE.dl_pct = total ? Math.floor((received * 100) / total) : 0;
}
await new Promise((resolve, reject) => out.end((e) => (e ? reject(e) : resolve())));
} finally {
clearTimeout(timer);
}
const digest = sha.digest("hex");
if (expect && digest !== expect) {
try { fs.unlinkSync(part); } catch (e) { /* 忽略 */ }
throw new Error("环境包 sha256 校验失败");
}
try {
fs.renameSync(part, zip);
} catch (e) {
try { fs.unlinkSync(part); } catch (e2) { /* 忽略 */ }
throw new Error("环境包保存失败");
}
return zip;
}
// 解压 zip → python-env/<version>/,防路径穿越;返回版本目录
async function extractZip(zip, version) {
const target = path.join(envDir(), version);
const tmp = path.join(envDir(), `.${version}.tmp`);
const rm = (p) => {
try { fs.rmSync(p, { recursive: true, force: true }); } catch (e) { /* 忽略 */ }
};
// 清理可能的残留临时目录
rm(tmp);
rm(target);
fs.mkdirSync(tmp, { recursive: true });
const az = new AdmZip(zip);
const entries = az.getEntries();
for (const en of entries) {
const name = en.entryName.replace(/\\/g, "/");
if (name.startsWith("/") || name.split("/").includes("..")) {
throw new Error(`环境包含非法路径: ${name}`);
}
}
az.extractAllTo(tmp, true);
// 冒烟校验:必须含 python.exe + webhost/backend/core/plugin_runner.py
if (!fs.existsSync(path.join(tmp, "python.exe"))) throw new Error("环境包缺少 python.exe");
if (!fs.existsSync(path.join(tmp, "webhost", "backend", "core", "plugin_runner.py"))) {
throw new Error("环境包缺少 plugin_runner.py");
}
// 原子切换(带重试:杀软可能短暂占用新解压文件导致 rename EPERM)
let lastErr = null;
for (let i = 0; i < 3; i++) {
try {
fs.renameSync(tmp, target);
return target;
} catch (e) {
lastErr = e;
await new Promise((r) => setTimeout(r, 500 * (i + 1)));
}
}
throw lastErr || new Error("环境包切换失败");
}
// 切换当前版本 + 清理旧版本(保留上一版供回滚)
function switchCurrent(version) {
const cur = readCurrent();
fs.mkdirSync(envDir(), { recursive: true });
fs.writeFileSync(
path.join(envDir(), "current.json"),
JSON.stringify({ version, updated_at: new Date().toISOString() }, null, 2),
"utf-8"
);
// 清理:保留当前 + 上一版;其余删除(异常残留目录也清)
const keep = new Set([version, cur].filter(Boolean));
try {
for (const name of fs.readdirSync(envDir())) {
if (name === "current.json" || name === "_cache") continue;
if (keep.has(name)) continue;
const p = path.join(envDir(), name);
try { fs.rmSync(p, { recursive: true, force: true }); } catch (e) { /* 忽略 */ }
}
} catch (e) { /* 忽略 */ }
}
let _syncing = false;
// 手动/启动同步:有更新的环境包则下载并切换;无则保持现状
async function checkAndSync(force = false) {
if (_syncing) return { ok: false, reason: "busy" };
_syncing = true;
_STATE.checking = true;
resetDl();
try {
const info = await cloudInfo();
if (!info) return { ok: false, reason: "no-cloud" };
const cur = readCurrent();
if (!force && cur && !versionLt(cur, info.version) && fs.existsSync(path.join(envDir(), cur, "python.exe"))) {
refreshStatus();
return { ok: true, current: true, version: cur };
}
_STATE.dl_status = "downloading";
logger.info(`开始下载环境包 ${info.version}:${info.url}`);
const zip = await downloadZip(info);
_STATE.dl_status = "downloaded";
_STATE.dl_pct = 100;
const dir = await extractZip(zip, info.version);
switchCurrent(info.version);
_STATE.dl_status = "idle";
logger.info(`环境包 ${info.version} 安装完成:${dir}`);
refreshStatus();
return { ok: true, current: false, version: info.version };
} catch (e) {
logger.warning(`环境包同步失败:${e.message}`);
_STATE.dl_status = "failed";
_STATE.dl_error = e.message;
return { ok: false, reason: "error", error: e.message };
} finally {
_syncing = false;
_STATE.checking = false;
}
}
// 回滚到上一版(current.json 前一个版本目录;无则报错)
function rollback() {
const cur = readCurrent();
const versions = [];
try {
for (const name of fs.readdirSync(envDir())) {
if (name === "current.json" || name === "_cache") continue;
if (fs.existsSync(path.join(envDir(), name, "python.exe"))) versions.push(name);
}
} catch (e) { /* 忽略 */ }
const target = versions
.filter((v) => v !== cur)
.sort((a, b) => (versionLt(a, b) ? 1 : -1))[0];
if (!target) return { ok: false, error: "无可回滚版本" };
switchCurrent(target);
refreshStatus();
return { ok: true, version: target };
}
module.exports = {
status,
refreshStatus,
checkAndSync,
rollback,
readCurrent,
envDir,
extractZip,
switchCurrent,
};
+39
View File
@@ -0,0 +1,39 @@
// 事件枢纽:插件运行线程产生的 日志/进度/完成 事件 → WS 广播给渲染层。
// 对齐 Python webhost hub.py 语义(t/run_id/plugin_id/level/pct/ok/error)。
"use strict";
const { EventEmitter } = require("events");
class Hub extends EventEmitter {
constructor() {
super();
this._clients = new Set(); // ws 连接
}
// 由 server.js 在 WS 连接建立后注册
addClient(ws) {
this._clients.add(ws);
ws.on("close", () => this._clients.delete(ws));
ws.on("error", () => this._clients.delete(ws));
}
clientCount() {
return this._clients.size;
}
publish(event) {
this.emit("event", event);
const payload = JSON.stringify(event);
for (const ws of this._clients) {
try {
if (ws.readyState === 1 /* OPEN */) ws.send(payload);
} catch (e) {
this._clients.delete(ws);
}
}
}
}
const HUB = new Hub();
module.exports = { Hub, HUB };
@@ -0,0 +1,72 @@
// 上次执行参数(per 账号 + per 插件):供场景执行台「恢复上次参数」使用,免去每次逐项重填。
// 存储:%LOCALAPPDATA%\37duAutomation\last_run_fields.json(纯新增文件,不改既有契约)
// 安全:password 类型字段一律不落盘(插件 fields 可含密码),只保存非敏感项。
"use strict";
const fs = require("fs");
const path = require("path");
const config = require("./config");
const { makeLogger } = require("./logger");
const logger = makeLogger("last-fields");
const STORE_PATH = path.join(config.APP_DATA, "last_run_fields.json");
const MAX_FIELDS = 40; // 单插件最多记 40 项,防异常插件撑爆文件
function loadAll() {
if (!fs.existsSync(STORE_PATH)) return {};
try {
const d = JSON.parse(fs.readFileSync(STORE_PATH, "utf-8"));
return d && typeof d === "object" && !Array.isArray(d) ? d : {};
} catch (e) {
logger.warning(`上次参数读取失败:${e.message}`);
return {};
}
}
function saveAll(data) {
try {
fs.mkdirSync(config.APP_DATA, { recursive: true });
const tmp = STORE_PATH + ".tmp";
fs.writeFileSync(tmp, JSON.stringify(data, null, 2), "utf-8");
fs.renameSync(tmp, STORE_PATH); // 原子替换
} catch (e) {
logger.warning(`上次参数写入失败:${e.message}`);
}
}
// 保存一次执行的参数快照;schema = 插件的 fields 元数据(用于剔除 password 等敏感项)
function remember(account, pluginId, fields, schema) {
if (!account || !pluginId || !fields || typeof fields !== "object") return;
const secret = new Set(
(Array.isArray(schema) ? schema : [])
.filter((f) => f && f.type === "password")
.map((f) => f.key)
);
const keep = {};
for (const [k, v] of Object.entries(fields)) {
if (secret.has(k)) continue;
if (Object.keys(keep).length >= MAX_FIELDS) break;
keep[k] = v;
}
const all = loadAll();
if (!all[account] || typeof all[account] !== "object") all[account] = {};
all[account][pluginId] = {
fields: keep,
at: new Date().toLocaleString("zh-CN", { hour12: false }),
};
saveAll(all);
}
// 读取上次参数;无记录返回 { fields: {}, at: "" }
function recall(account, pluginId) {
const all = loadAll();
const rec = (all[account] || {})[pluginId] || null;
if (!rec || typeof rec !== "object") return { fields: {}, at: "" };
return {
fields: rec.fields && typeof rec.fields === "object" ? rec.fields : {},
at: rec.at || "",
};
}
module.exports = { STORE_PATH, MAX_FIELDS, remember, recall };
@@ -0,0 +1,308 @@
// 部署端产品化能力层:离线授权/管控清单缓存、中心机公钥缓存、联网判定、验签、运行上报。
// 对齐 Python webhost licensing.py 的路径与语义(跨端共享 %LOCALAPPDATA%\37duAutomation)。
"use strict";
const fs = require("fs");
const path = require("path");
const config = require("./config");
const { verifyBlob, sha256Hex, versionLt, deadlinePassed, nowStr } = require("./crypto");
const cp = require("./cpclient");
const { makeLogger } = require("./logger");
const logger = makeLogger("licensing");
const KEYS_DIR = path.join(config.APP_DATA, "keys");
const licensePath = path.join(config.APP_DATA, "license.json");
const controlPath = path.join(config.APP_DATA, "control.json");
const reportsPath = path.join(config.APP_DATA, "offline_reports.jsonl");
const ONLINE_TTL = 180 * 1000;
let _lastSync = 0;
const _CONTROLPLANE_URL = config.CONTROLPLANE_URL;
function touchSync() {
_lastSync = Date.now();
}
function isOnline() {
return Date.now() - _lastSync <= ONLINE_TTL;
}
// ==================== 公钥缓存与验签 ====================
function pubPemPath() {
return path.join(KEYS_DIR, "pub.pem");
}
function cachePublicKey(pemText) {
pemText = (pemText || "").trim();
if (!pemText) return;
fs.mkdirSync(KEYS_DIR, { recursive: true });
fs.writeFileSync(pubPemPath(), pemText, "ascii");
touchSync();
}
function loadPublicKey() {
try {
return fs.readFileSync(pubPemPath(), "utf-8");
} catch (e) {
return null;
}
}
function verifyLicense() {
if (!fs.existsSync(licensePath)) throw new Error("无本地授权票据(license.json)");
const pub = loadPublicKey();
if (!pub) throw new Error("缺少中心机公钥,无法验签授权票据");
const data = JSON.parse(fs.readFileSync(licensePath, "utf-8"));
return verifyBlob(data.ticket, pub);
}
function emptyControl() {
return { revokedPlugins: [], disabledPlugins: [], forcedUpdates: [] };
}
function verifyControl() {
if (!fs.existsSync(controlPath)) return emptyControl();
const pub = loadPublicKey();
if (!pub) return emptyControl();
try {
const data = JSON.parse(fs.readFileSync(controlPath, "utf-8"));
const payload = verifyBlob(data.ticket, pub);
return payload && typeof payload === "object" ? payload : {};
} catch (e) {
return emptyControl();
}
}
// ==================== 授权周期(离线最多 7 天) ====================
function licenseStatus() {
if (!fs.existsSync(licensePath)) return { status: "missing", payload: null };
let lic;
try {
lic = verifyLicense();
} catch (e) {
return { status: "invalid", payload: null };
}
const exp = lic.expiresAt;
if (!exp || Date.now() > parseInt(exp, 10) * 1000) {
return { status: "expired", payload: lic };
}
return { status: "ok", payload: lic };
}
// 授权票据概要:供状态栏 / 授权票据卡展示"剩余 N 天"(expiresAt 为 epoch 秒,中心机签发)
function licenseInfo() {
const st = licenseStatus();
const exp = st.payload && st.payload.expiresAt ? parseInt(st.payload.expiresAt, 10) : 0;
return {
status: st.status, // missing | invalid | expired | ok
expire_ts: exp,
expire_at: exp ? new Date(exp * 1000).toLocaleString("zh-CN", { hour12: false }) : "",
days_left: exp ? Math.ceil((exp * 1000 - Date.now()) / 86400000) : null,
};
}
function ensureLicense(account) {
const st = licenseStatus();
if (st.status === "ok" && (st.payload || {}).userId === account) {
return Promise.resolve({ ok: true, payload: st.payload });
}
return syncLicensing(account)
.catch((e) => {
logger.warning(`授权票据联网刷新失败(离线或控制面不可达):${e.message}`);
})
.then(() => {
const st2 = licenseStatus();
return {
ok: st2.status === "ok" && (st2.payload || {}).userId === account,
payload: st2.payload,
};
});
}
// ==================== 缓存写读 ====================
function saveLicense(ticketJson) {
const text = typeof ticketJson === "object"
? JSON.stringify(ticketJson)
: JSON.stringify({ ticket: ticketJson });
fs.mkdirSync(config.APP_DATA, { recursive: true });
fs.writeFileSync(licensePath, text, "utf-8");
touchSync();
}
function saveControl(ticketJson) {
const text = typeof ticketJson === "object"
? JSON.stringify(ticketJson)
: JSON.stringify({ ticket: ticketJson });
fs.mkdirSync(config.APP_DATA, { recursive: true });
fs.writeFileSync(controlPath, text, "utf-8");
touchSync();
}
// ==================== 启动前校验链 ====================
function installedVersion(pluginId) {
try {
const act = fs.readFileSync(path.join(config.APP_DATA, "active.json"), "utf-8");
const d = JSON.parse(act);
return d.pluginId === pluginId ? d.version || "" : "";
} catch (e) {
return "";
}
}
async function runCheckAllowed(pluginId, account, online) {
const lic = await ensureLicense(account);
if (!lic.ok) return "授权已过期(最长离线 7 天),请联网刷新后重试";
const control = verifyControl();
if ((control.revokedPlugins || []).includes(pluginId)) return "插件已被下架(revoked),禁止运行";
if ((control.disabledPlugins || []).includes(pluginId)) return "插件已被禁用(disabled),禁止运行";
const licPlugins = {};
for (const p of (lic.payload || {}).plugins || []) licPlugins[p.pluginId] = p;
const grant = licPlugins[pluginId];
if (!grant) return `账号 ${account} 无插件「${pluginId}」的授权`;
if (!grant.canRun) return `账号 ${account} 无「${pluginId}」的运行授权`;
if (online) {
const forced = (control.forcedUpdates || []).find((f) => f.pluginId === pluginId);
if (forced) {
const minVer = forced.minVersion || "";
const deadline = forced.deadline || "";
if (minVer && deadline && deadlinePassed(deadline)) {
const installed = installedVersion(pluginId);
if (installed && versionLt(installed, minVer)) {
return `插件需强制升级到 v${minVer} 以上(deadline 已过),当前 v${installed} 已禁止启动,请先更新`;
}
}
}
}
return null;
}
// ==================== 联网同步(公钥 + 授权票据 + 管控清单,逐资源容错) ====================
async function syncLicensing(account) {
if (!config.CONTROLPLANE_URL || !account) return;
const headers = cp.machineHeaders();
let gotAny = false;
try {
const r = await cp.request("GET", "/api/me/pubkey", { headers, timeout: 5 });
cachePublicKey(r.pub || "");
gotAny = true;
} catch (e) {
logger.warning(`中心机公钥拉取失败:${e.message}`);
}
try {
const r = await cp.request("GET", "/api/me/license", { headers, params: { account }, timeout: 5 });
saveLicense(r);
gotAny = true;
} catch (e) {
logger.warning(`离线授权票据拉取失败:${e.message}`);
}
try {
const r = await cp.request("GET", "/api/me/control-list", { headers, timeout: 5 });
saveControl(r);
gotAny = true;
} catch (e) {
logger.warning(`管控清单拉取失败:${e.message}`);
}
if (gotAny) await flushOfflineReports();
}
// ==================== 运行上报 ====================
async function report(account, deviceId, pluginId, version, status, msg = "", durationSec = 0) {
const rec = {
account, device_id: deviceId, plugin_id: pluginId, version,
status, msg, duration_sec: parseInt(durationSec, 10) || 0,
at: nowStr(),
};
if (!_CONTROLPLANE_URL) return;
try {
await pushReport(rec);
touchSync();
return;
} catch (e) {
// 离线:暂存待补报
}
try {
fs.mkdirSync(config.APP_DATA, { recursive: true });
fs.appendFileSync(reportsPath, JSON.stringify(rec) + "\n", "utf-8");
} catch (e) {
/* 忽略 */
}
}
async function pushReport(rec) {
const headers = cp.machineHeaders();
await cp.request("POST", "/api/runtime/report", { headers, json: rec, timeout: 5 });
}
// 重连后补报此前暂存的离线记录;返回补报条数
async function flushOfflineReports() {
if (!fs.existsSync(reportsPath)) return 0;
let sent = 0;
const pending = [];
const lines = fs.readFileSync(reportsPath, "utf-8").split(/\r?\n/).filter((l) => l.trim());
for (const ln of lines) {
try {
const rec = JSON.parse(ln);
await pushReport(rec);
sent++;
} catch (e) {
pending.push(ln);
}
}
try {
if (pending.length === 0) fs.unlinkSync(reportsPath);
else fs.writeFileSync(reportsPath, pending.join("\n") + "\n", "utf-8");
} catch (e) {
/* 忽略 */
}
return sent;
}
// 设备上报(心跳 + Chrome 环境):int 0/1 语义
async function deviceReport(deviceId, account, info) {
if (!_CONTROLPLANE_URL) return false;
const payload = {
device_id: deviceId,
account: account || "",
hostname: (info && info.hostname) || "",
os: (info && info.os) || "windows",
ip: (info && info.ip) || "",
chrome_installed: (info && info.chromeInstalled) ? 1 : 0,
chrome_version: (info && info.chromeVersion) || "",
chrome_ok: (info && info.chromeOk) ? 1 : 0,
status: 1,
};
try {
await cp.request("POST", "/api/device/report", { headers: cp.machineHeaders(), json: payload, timeout: 5 });
touchSync();
return true;
} catch (e) {
logger.warning(`设备上报失败:${e.message}`);
return false;
}
}
module.exports = {
KEYS_DIR,
licensePath,
controlPath,
reportsPath,
touchSync,
isOnline,
cachePublicKey,
verifyLicense,
verifyControl,
licenseStatus,
licenseInfo,
ensureLicense,
saveLicense,
saveControl,
runCheckAllowed,
syncLicensing,
report,
flushOfflineReports,
deviceReport,
sha256Hex,
};
+68
View File
@@ -0,0 +1,68 @@
// 日志:INFO 屏蔽大体积 JSON 调试日志;DEBUG 模式开启完整输出(AGENTS.md 规范)。
"use strict";
const fs = require("fs");
const path = require("path");
const LEVELS = { DEBUG: 10, INFO: 20, WARNING: 30, ERROR: 40 };
const DEBUG = process.env.DEBUG === "1" || process.env.DEBUG === "true";
const MAX_LOG_BYTES = 10 * 1024 * 1024; // 单文件 10MB,超出轮转(保留 3 份)
let _file = null; // { fd 简化:按行 append 即可 }
function setLogFile(filePath) {
_file = filePath;
try {
fs.mkdirSync(path.dirname(filePath), { recursive: true });
} catch (e) {
_file = null;
}
}
// 按大小轮转:shell.log → shell.log.1 → .2 → .3(丢弃最旧)
function rotateIfNeeded() {
if (!_file) return;
try {
const st = fs.statSync(_file);
if (st.size < MAX_LOG_BYTES) return;
for (let i = 2; i >= 1; i--) {
const a = `${_file}.${i}`;
const b = `${_file}.${i + 1}`;
if (fs.existsSync(a)) fs.renameSync(a, b);
}
if (fs.existsSync(_file)) fs.renameSync(_file, `${_file}.1`);
} catch (e) {
/* 轮转失败忽略 */
}
}
function ts() {
const d = new Date();
const p = (n) => String(n).padStart(2, "0");
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`;
}
function write(level, name, msg) {
if (LEVELS[level] < LEVELS[DEBUG ? "DEBUG" : "INFO"]) return;
const line = `${ts()} ${level.padEnd(7)} ${name} ${msg}`;
console.log(line);
if (_file) {
try {
rotateIfNeeded();
fs.appendFileSync(_file, line + "\n", "utf-8");
} catch (e) {
/* 落盘失败静默 */
}
}
}
function makeLogger(name) {
return {
debug: (msg) => write("DEBUG", name, msg),
info: (msg) => write("INFO", name, msg),
warning: (msg) => write("WARNING", name, msg),
error: (msg) => write("ERROR", name, msg),
};
}
module.exports = { makeLogger, setLogFile, isDebug: DEBUG };
+22
View File
@@ -0,0 +1,22 @@
// 入口:CLI 模式(node electron/main.js --cli,无 Electron)或 Electron 模式(electron .)。
"use strict";
const isCli = process.argv.includes("--cli") || !process.versions || !process.versions.electron;
if (isCli) {
const { init } = require("./app");
const { listen } = require("./server");
const { makeLogger } = require("./logger");
const logger = makeLogger("main");
(async () => {
await init();
listen();
logger.info("CLI 模式运行中(Ctrl+C 退出)。Electron 窗口模式:npm run electron");
})().catch((e) => {
logger.error(`启动失败:${e.stack || e}`);
process.exit(1);
});
} else {
require("./electron-main");
}
+72
View File
@@ -0,0 +1,72 @@
// 宿主插件元数据 / 平台权限解析(/api/meta 聚合)。
// 对齐 Python core/meta.py:插件可见性 = 本地授权票据快照;平台白名单来自中心机。
"use strict";
const cp = require("./cpclient");
const config = require("./config");
const licensing = require("./licensing");
const registry = require("./registry");
const platformAuth = require("./platform-auth");
const state = require("./state");
const envSync = require("./env-sync");
const { makeLogger } = require("./logger");
const logger = makeLogger("meta");
// 调中心机获取账号可登录平台白名单;控制面不可达返回 null(调用方决定拒绝)
async function accountAllowedPlatforms(account) {
if (!config.CONTROLPLANE_URL) return null;
try {
const r = await cp.request("GET", "/api/platforms/allowed", {
headers: cp.machineHeaders(),
params: { account },
timeout: 5,
});
return new Set(r.allowed || []);
} catch (e) {
return null;
}
}
// /api/meta 聚合响应
async function buildMeta(account) {
let authExpired = false;
let plugins = [];
if (account) {
const lic = await licensing.ensureLicense(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));
}
} else {
authExpired = true;
}
}
const allowedPlats = account ? await accountAllowedPlatforms(account) : null;
const platforms = [];
for (const [pid, m] of Object.entries(state.PLATFORMS)) {
platforms.push({
id: pid,
label: m.label,
online: await platformAuth.isOnline(pid, account), // 按当前账号的会话校验
allowed: allowedPlats === null ? true : allowedPlats.has(pid),
});
}
return {
appName: "37du 自动化工作台",
dingtalkScan: !!config.CONTROLPLANE_URL,
authExpired,
// 授权票据概要:常驻态进状态栏 / 票据卡(剩余天数),异常态才升级为横幅
license: licensing.licenseInfo(),
platforms,
plugins,
// 环境包(便携 Python 运行时)概要:设置页/状态栏展示,空 = 未安装
env: {
version: envSync.readCurrent() || "",
installed: !!envSync.readCurrent(),
},
};
}
module.exports = { buildMeta, accountAllowedPlatforms };
@@ -0,0 +1,249 @@
// 平台登录态(HR/OA):真实登录/登出/在线校验。
// 保持 Python 子进程执行登录自动化(shared/hr_login、oa_login,DrissionPage 滑块),
// Node 壳只负责拉起子进程与解析结果。
// ★ 按账号隔离:每个登录账号拥有独立的会话目录(.sessions/<账号>/)与独立 HR/OA 账号密码,
// 子进程通过 PLATFORM_ACCOUNT 环境变量 + hr_login_username/password 注入各自身份。
"use strict";
const fs = require("fs");
const path = require("path");
const { spawn } = require("child_process");
const config = require("./config");
const platformCreds = require("./platform-creds");
const { makeLogger } = require("./logger");
const logger = makeLogger("platform-auth");
const LABELS = { hr: "HR 系统", oa: "OA 系统" };
const COOKIE_FILES = {
hr: "hr_cookies.json",
oa: "oa_cookies.json",
};
const BASE_SESSIONS_DIR = path.join(config.APP_DATA, ".sessions");
const _onlineCache = new Map(); // `${account}:${pid}` -> {ts, value}
const ONLINE_CACHE_TTL = 15 * 1000;
function platforms() {
return Object.keys(LABELS).map((pid) => ({ id: pid, label: LABELS[pid] }));
}
// 账号隔离的会话目录;无账号时回退共享目录(兼容旧数据)
function sessionDir(account) {
const base = account ? path.join(BASE_SESSIONS_DIR, String(account)) : BASE_SESSIONS_DIR;
try {
fs.mkdirSync(base, { recursive: true });
} catch (e) {
/* 忽略 */
}
return base;
}
// spawn python 子进程执行 snippet,返回 stdout 最后一行 JSON(或文本)
function runPython(snippet, timeoutMs = 120000, extraEnv = {}) {
return new Promise((resolve, reject) => {
const args = ["-c", snippet];
const child = spawn(config.pythonExe(), args, {
// webhost 包解析:环境包模式 cwd=环境包根(webhost/ 在其中);dev = desktop/(仓库内 webhost)
cwd: config.runtimeRoot(),
windowsHide: true,
env: { ...process.env, PYTHONIOENCODING: "utf-8", PYTHONUTF8: "1", ...extraEnv },
stdio: ["ignore", "pipe", "pipe"],
});
let out = "";
let err = "";
const timer = setTimeout(() => {
try {
treeKill(child.pid);
} catch (e) {
/* 忽略 */
}
reject(new Error("平台登录子进程超时"));
}, timeoutMs);
child.stdout.on("data", (d) => (out += d.toString("utf-8")));
child.stderr.on("data", (d) => (err += d.toString("utf-8")));
child.on("error", (e) => {
clearTimeout(timer);
reject(new Error(`拉起 Python 子进程失败: ${e.message}`));
});
child.on("close", (code) => {
clearTimeout(timer);
if (code !== 0) {
reject(new Error(`平台子进程退出(${code}): ${err.slice(0, 300)}`));
return;
}
resolve(out.trim());
});
});
}
function treeKill(pid) {
try {
if (process.platform === "win32") {
const killer = spawn("taskkill", ["/pid", String(pid), "/T", "/F"], {
windowsHide: true,
stdio: "ignore",
detached: true,
});
killer.unref();
} else {
try {
process.kill(-pid, "SIGKILL");
} catch (e) {
process.kill(pid, "SIGKILL");
}
}
} catch (e) {
/* 忽略 */
}
}
function extractJson(out) {
// 兼容模块 print("最终结果:", dict) 与纯 JSON 输出:取最后一个 JSON 对象
const lines = out.split(/\r?\n/).filter((l) => l.trim());
for (let i = lines.length - 1; i >= 0; i--) {
const line = lines[i];
const idx = line.indexOf("{");
if (idx >= 0) {
try {
return JSON.parse(line.slice(idx));
} catch (e) {
/* 继续找 */
}
}
}
return null;
}
// 真实校验平台登录态(发起轻量 API 校验,非内存假状态);结果短缓存避免频繁请求平台。
const VALIDATE = {
hr: {
url: "https://hr.37du.co/RedseaPlatform/PtUsers.mc?method=getCurUserInfo",
method: "POST",
},
oa: {
url: "https://oa.37du.co/sys/notify/sys_notify_todo/sysNotifyTodo.do?method=sumTodoCount",
method: "GET",
},
};
function loadCookies(pid, account) {
const file = path.join(sessionDir(account), COOKIE_FILES[pid]);
if (!fs.existsSync(file)) return [];
try {
const raw = JSON.parse(fs.readFileSync(file, "utf-8"));
return Array.isArray(raw) ? raw : [];
} catch (e) {
return [];
}
}
async function isOnline(pid, account) {
const cacheKey = `${account || ""}:${pid}`;
const cached = _onlineCache.get(cacheKey);
if (cached && Date.now() - cached.ts < ONLINE_CACHE_TTL) return cached.value;
let value = false;
const def = VALIDATE[pid];
if (!def) return false;
try {
const cookies = loadCookies(pid, account);
if (cookies.length === 0) {
value = false;
} else {
const pairs = [];
for (const c of cookies) {
if (c && c.name && c.value && (!c.domain || String(c.domain).includes("37du.co"))) {
pairs.push(`${c.name}=${c.value}`);
}
}
const ctrl = new AbortController();
const timer = setTimeout(() => ctrl.abort(), 8000);
const resp = await fetch(def.url, {
method: def.method,
headers: {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/120.0.0.0 Safari/537.36",
"Content-Type": "application/x-www-form-urlencoded",
...(pairs.length ? { Cookie: pairs.join("; ") } : {}),
},
body: def.method === "POST" ? "" : undefined,
signal: ctrl.signal,
redirect: "manual",
});
clearTimeout(timer);
const text = await resp.text();
value = resp.status === 200 && text.trim().startsWith("{") || text.trim().startsWith("[");
}
} catch (e) {
logger.warning(`平台 ${pid} 在线校验失败:${e.message}`);
value = false;
}
_onlineCache.set(cacheKey, { ts: Date.now(), value });
return value;
}
// 真实登录:cookies 有效则复用(不弹浏览器),失效则浏览器自动化登录。
// account:当前登录账号;其个人 HR/OA 账号密码通过环境变量注入登录子进程。
async function login(pid, account) {
if (!LABELS[pid]) throw Object.assign(new Error(`未知平台: ${pid}`), { status: 404 });
const cacheKey = `${account || ""}:${pid}`;
_onlineCache.delete(cacheKey);
const extraEnv = { PLATFORM_ACCOUNT: account || "" };
const credEnv = platformCreds.envFor(account, pid);
if (credEnv) {
Object.assign(extraEnv, credEnv);
logger.info(`平台 ${pid} 使用账号「${credEnv[`${pid}_login_username`]}」登录(账号 ${account})`);
} else {
logger.warning(`平台 ${pid} 登录:账号 ${account} 未配置个人平台账号密码,将回退共享配置`);
}
try {
const snippet =
pid === "hr"
? `from webhost.backend.shared import hr_login; import json; print(json.dumps(hr_login.main({"force": False}), ensure_ascii=False))`
: `from webhost.backend.shared import oa_login; import json; print(json.dumps(oa_login.main(force=False), ensure_ascii=False))`;
const out = await runPython(snippet, 5 * 60 * 1000, extraEnv);
const result = extractJson(out) || {};
const ok = !!result.success;
const online = ok ? await isOnline(pid, account) : false;
return {
id: pid,
label: LABELS[pid],
online,
message: result.message || (ok ? "登录成功" : "登录失败"),
};
} catch (e) {
logger.error(`平台 ${pid} 登录失败(账号 ${account}):${e.message}`);
return { id: pid, label: LABELS[pid], online: false, message: `登录过程异常:${e.message}` };
}
}
// 登出平台:删除该账号的 cookies 文件,使该账号的平台登录态失效。
function logout(pid, account) {
if (!LABELS[pid]) throw Object.assign(new Error(`未知平台: ${pid}`), { status: 404 });
_onlineCache.delete(`${account || ""}:${pid}`);
const file = path.join(sessionDir(account), COOKIE_FILES[pid]);
try {
if (fs.existsSync(file)) fs.unlinkSync(file);
} catch (e) {
logger.warning(`清除平台 ${pid} cookies 失败(账号 ${account}):${e.message}`);
}
return { id: pid, label: LABELS[pid], online: false };
}
// 当前账号的平台状态(个人中心展示):在线态 + 是否已配置个人账号密码 + 已存用户名
async function status(account) {
const creds = platformCreds.get(account) || {};
const out = [];
for (const pid of Object.keys(LABELS)) {
const c = creds[pid] || {};
out.push({
id: pid,
label: LABELS[pid],
online: await isOnline(pid, account),
has_creds: !!(c.user && c.pass),
user: c.user || "",
});
}
return out;
}
module.exports = { platforms, sessionDir, isOnline, login, logout, status, BASE_SESSIONS_DIR };
@@ -0,0 +1,111 @@
// 平台账号凭据(HR/OA)按账号本机加密保存:AES-256-GCM,随机密钥落盘。
// 每人在壳里「个人中心→平台账号」填写自己的 HR/OA 账号密码;
// 登录时注入 Python 登录模块环境变量(hr_login_username / hr_login_password 等)。
"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("platform-creds");
const DIR = path.join(config.APP_DATA, "platform-creds");
const KEY_FILE = path.join(DIR, ".key");
const DATA_FILE = path.join(DIR, "creds.json");
// 密文结构:{iv, tag, data}(base64)
function loadKey() {
try {
if (fs.existsSync(KEY_FILE)) return fs.readFileSync(KEY_FILE);
const key = crypto.randomBytes(32);
fs.mkdirSync(DIR, { recursive: true });
fs.writeFileSync(KEY_FILE, key, { mode: 0o600 });
return key;
} catch (e) {
logger.warning(`平台账号凭据密钥初始化失败: ${e.message}`);
return crypto.randomBytes(32); // 进程内可用;重启后不可解(仅兜底,几乎不会走到)
}
}
function encrypt(obj) {
const key = loadKey();
const iv = crypto.randomBytes(12);
const cipher = crypto.createCipheriv("aes-256-gcm", key, iv);
const data = Buffer.from(JSON.stringify(obj), "utf-8");
const enc = Buffer.concat([cipher.update(data), cipher.final()]);
const tag = cipher.getAuthTag();
return { iv: iv.toString("base64"), tag: tag.toString("base64"), data: enc.toString("base64") };
}
function decrypt(payload) {
const key = loadKey();
const iv = Buffer.from(payload.iv, "base64");
const tag = Buffer.from(payload.tag, "base64");
const data = Buffer.from(payload.data, "base64");
const decipher = crypto.createDecipheriv("aes-256-gcm", key, iv);
decipher.setAuthTag(tag);
return JSON.parse(Buffer.concat([decipher.update(data), decipher.final()]).toString("utf-8"));
}
function loadAll() {
if (!fs.existsSync(DATA_FILE)) return {};
try {
return decrypt(JSON.parse(fs.readFileSync(DATA_FILE, "utf-8")));
} catch (e) {
logger.warning(`平台账号凭据读取失败: ${e.message}`);
return {};
}
}
function saveAll(all) {
try {
fs.mkdirSync(DIR, { recursive: true });
fs.writeFileSync(DATA_FILE, JSON.stringify(encrypt(all)), "utf-8");
} catch (e) {
logger.warning(`平台账号凭据保存失败: ${e.message}`);
}
}
// account → {hr: {user, pass}, oa: {user, pass}}
function get(account) {
if (!account) return null;
return loadAll()[account] || null;
}
// 保存当前账号某平台的凭据;pass 为空串表示保留原密码(仅更新用户名/不清除)
function upsert(account, pid, creds) {
if (!account) throw new Error("缺少账号");
if (!creds) return false;
const all = loadAll();
const entry = all[account] || {};
const cur = entry[pid] || {};
const user = typeof creds.user === "string" ? creds.user.trim() : "";
let pass = typeof creds.pass === "string" ? creds.pass : "";
if (user === "" && pass === "") {
// 清空该平台凭据
delete entry[pid];
} else {
if (user === "") user = cur.user || ""; // 未填用户名:沿用
if (pass === "") pass = cur.pass || ""; // 未填密码:沿用
entry[pid] = { user, pass };
}
all[account] = entry;
saveAll(all);
return true;
}
// 供登录注入环境变量:{hr_login_username, hr_login_password};未配置返回 null
function envFor(account, pid) {
const c = get(account);
if (!c) return null;
const p = c[pid];
if (!p || !p.user) return null;
return {
[`${pid}_login_username`]: p.user,
[`${pid}_login_password`]: p.pass || "",
};
}
module.exports = { get, upsert, envFor, DIR };
@@ -0,0 +1,73 @@
// 场景配置方案(多配置)· SQLite 实现:同一场景可保存多套命名参数组合,运行台/定时任务按需选用。
// 表:plugin_configs(shell.db),按账号 + 插件隔离,同名覆盖。
// 安全:password 类型字段一律不落盘(与 last-fields.js 一致,仅保存非敏感项)。
"use strict";
const { db } = require("./db");
const MAX_CONFIGS_PER_PLUGIN = 10; // 单插件最多 10 套方案,防异常堆满
// 过滤敏感字段:schema = 插件的 fields 元数据,password 类型不入库
function sanitize(fields, schema) {
const secret = new Set(
(Array.isArray(schema) ? schema : [])
.filter((f) => f && f.type === "password")
.map((f) => f.key)
);
const out = {};
for (const [k, v] of Object.entries(fields || {})) {
if (secret.has(k)) continue;
out[k] = v;
}
return out;
}
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 || "" };
}
function listConfigs(account, pluginId) {
const rows = db.prepare(
"SELECT id, name, fields, at FROM plugin_configs WHERE account = ? AND plugin_id = ? ORDER BY id"
).all(account, pluginId);
return rows.map(rowToCfg);
}
// 保存/覆盖:同名方案更新字段,否则新增;返回新/更新后的配置
function saveConfig(account, pluginId, name, fields, schema) {
const trimmed = String(name || "").trim().slice(0, 20);
if (!trimmed) return null;
const keep = sanitize(fields, schema);
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 = ?"
).get(account, pluginId, trimmed);
if (exists) {
db.prepare(
"UPDATE plugin_configs SET fields = ?, at = ? WHERE id = ?"
).run(JSON.stringify(keep), at, exists.id);
return rowToCfg(db.prepare("SELECT id, name, fields, at FROM plugin_configs WHERE id = ?").get(exists.id));
}
const count = db.prepare(
"SELECT COUNT(*) AS n FROM plugin_configs WHERE account = ? AND plugin_id = ?"
).get(account, pluginId);
if (count.n >= MAX_CONFIGS_PER_PLUGIN) {
throw Object.assign(new Error(`每个场景最多保存 ${MAX_CONFIGS_PER_PLUGIN} 套配置`), { status: 400 });
}
const r = db.prepare(
"INSERT INTO plugin_configs (account, plugin_id, name, fields, at) VALUES (?, ?, ?, ?, ?)"
).run(account, pluginId, trimmed, JSON.stringify(keep), at);
return rowToCfg(db.prepare("SELECT id, name, fields, at FROM plugin_configs WHERE id = ?").get(r.lastInsertRowid));
}
function deleteConfig(account, pluginId, cfgId) {
const r = db.prepare(
"DELETE FROM plugin_configs WHERE account = ? AND plugin_id = ? AND id = ?"
).run(account, pluginId, cfgId);
return r.changes > 0;
}
module.exports = { MAX_CONFIGS_PER_PLUGIN, listConfigs, saveConfig, deleteConfig };
@@ -0,0 +1,375 @@
// 插件按账号权限自下载 + 版本更新(执行机主动拉取;下载/校验/原子安装)。
// 对齐 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 });
fs.renameSync(tmp, target);
} catch (e) {
logger.error(`安装插件 ${pluginId} 失败:${e.message}`);
fs.rmSync(tmp, { recursive: true, force: true });
return false;
}
return true;
}
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,
};
@@ -0,0 +1,14 @@
// preload:contextBridge 白名单 IPC(渲染层主通道走 HTTP 兼容层,此处仅暴露只读环境信息)。
"use strict";
const { contextBridge } = require("electron");
contextBridge.exposeInMainWorld("dshShell", {
platform: process.platform,
versions: {
electron: process.versions.electron,
node: process.versions.node,
chrome: process.versions.chrome,
},
// 渲染层可通过 window.open 打开中心机控制面(外部 URL 需在渲染层显式触发)
});
+119
View File
@@ -0,0 +1,119 @@
// 插件注册表:读取 plugins/<id>/plugin.json 元数据(manifest 驱动,与 Python meta.py 语义一致)。
"use strict";
const fs = require("fs");
const path = require("path");
const config = require("./config");
const { makeLogger } = require("./logger");
const logger = makeLogger("registry");
function pluginRoot() {
return config.pluginRoot();
}
// 本地已落盘插件条目(目录包含 __init__.py 或 plugin.json,后者兜底下载中断的残缺目录)
function listLocalPlugins() {
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()) {
if (fs.existsSync(path.join(full, "__init__.py")) || fs.existsSync(path.join(full, "plugin.json"))) {
out.push({ id: name, dir: full });
}
}
}
return out;
}
// 读取插件 manifest;缺文件/解析失败返回 null(不阻断)
function readManifest(pluginId) {
const mf = path.join(pluginRoot(), pluginId, "plugin.json");
if (!fs.existsSync(mf)) return null;
try {
const data = JSON.parse(fs.readFileSync(mf, "utf-8"));
return data && typeof data === "object" ? data : null;
} catch (e) {
logger.warning(`插件 ${pluginId} plugin.json 解析失败:${e.message}`);
return null;
}
}
// JSON-Schema(object.properties) → 前端表单 [{key,label,type,default,options,description}]
function fieldsFromSchema(schema) {
if (!schema || schema.type !== "object" || !schema.properties) return null;
const out = [];
for (const [key, prop] of Object.entries(schema.properties)) {
const item = { key, label: prop.title || key, default: prop.default ?? "" };
const t = prop.type || "string";
if (t === "integer" || t === "number") item.type = "int";
else if (t === "string" && Array.isArray(prop.enum)) {
item.type = "select";
item.options = prop.enum;
} else if (t === "string" && prop.format === "password") item.type = "password";
else if (t === "array") {
item.type = "multiselect";
if (prop.items && Array.isArray(prop.items.enum)) item.options = prop.items.enum;
} else item.type = "text";
if (prop.description) item.description = prop.description;
out.push(item);
}
return out;
}
// 组装插件元数据(manifest 驱动,与 Python meta._plugin_schema 一致)
function pluginSchema(pluginId) {
const manifest = readManifest(pluginId);
const base = {
id: pluginId,
name: pluginId,
version: "0",
description: "",
uses_month: false,
ui: false,
capabilities: [],
permissions: {},
fields: [],
};
if (!manifest) return base;
const fields = fieldsFromSchema(manifest.fields);
return {
id: manifest.id || pluginId,
name: manifest.name || pluginId,
version: manifest.version || "0",
description: manifest.description || "",
uses_month: !!manifest.uses_month,
ui: !!manifest.ui,
platform: manifest.platform || "", // hr / oa / ""(前端平台徽章 + 运行并发闸按(账号,平台)隔离)
min_runtime_version: manifest.minRuntimeVersion || "", // 版本兼容校验声明(安装时强校验,此处透传前端展示)
capabilities: manifest.capabilities || [],
permissions: manifest.permissions || {},
fields: fields || [],
};
}
function find(pluginId) {
const dir = path.join(pluginRoot(), pluginId);
if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory()) throw new Error(`插件不存在: ${pluginId}`);
const manifest = readManifest(pluginId);
if (!manifest && !fs.existsSync(path.join(dir, "__init__.py"))) {
throw new Error(`插件不存在: ${pluginId}`);
}
return { id: pluginId, dir, manifest, ...pluginSchema(pluginId) };
}
function findByName(name) {
// 供 /api/runs 以插件名查找(与 PLUGINS.find 语义对齐)
return find(name);
}
module.exports = { pluginRoot, listLocalPlugins, readManifest, fieldsFromSchema, pluginSchema, find };
@@ -0,0 +1,205 @@
// 运行历史(壳子本地持久化):每次运行的结论 + 该次运行的日志,供「最近运行 / 点击回放」使用。
// 存储:%LOCALAPPDATA%\37duAutomation\
// run_history.jsonl 索引(只存结论,一行一次运行,无日志)
// run_history/<run_id>.jsonl 该次运行的日志(一行一条)
// 分离存储的原因:列表接口只读索引(几百行、恒定体积),详情才读单个日志文件,
// 避免"列表要解析所有历史日志"这种随使用时长线性劣化的写法。
// 职责划分:state.RUNS 内存态只服务"正在跑的那一次";本模块服务"跑过的那些次"。
"use strict";
const fs = require("fs");
const path = require("path");
const config = require("./config");
const { makeLogger } = require("./logger");
const logger = makeLogger("run-history");
const HISTORY_PATH = path.join(config.APP_DATA, "run_history.jsonl");
const RUNS_DIR = path.join(config.APP_DATA, "run_history");
// 上限:历史是"回顾"用的,不追求全量归档
const MAX_RECORDS = 300; // 裁剪目标:每次裁剪后保留最近 300 次运行(实际条数在 300 ~ 350 之间浮动)
const PRUNE_SLACK = 50; // 超出裁剪目标这么多条才做一次整体裁剪(避免每次运行都重写整个索引)
const MAX_LOGS_PER_RUN = 400; // 单次运行最多保留 400 条日志
const MAX_MSG_LEN = 1000; // 单条日志最大长度(防插件打印大体积 JSON 灌爆历史)
const MAX_LOG_BYTES_PER_RUN = 32 * 1024; // 单次运行日志总量上限,超出即停止记录(软截断)
// run_id 形如 32 位 hex;做白名单校验,杜绝路径穿越
function safeRunId(runId) {
const s = String(runId || "");
return /^[A-Za-z0-9_-]{8,64}$/.test(s) ? s : "";
}
function logFilePath(runId) {
const id = safeRunId(runId);
return id ? path.join(RUNS_DIR, `${id}.jsonl`) : "";
}
// 截断超长日志(对齐"正常 INFO 级别屏蔽大体积 JSON"的日志规范精神)
function clip(msg) {
const s = String(msg === undefined || msg === null ? "" : msg);
return s.length > MAX_MSG_LEN ? s.slice(0, MAX_MSG_LEN) + "…(已截断)" : s;
}
// 逐行读取 JSONL;单行损坏(例如写入中断)只跳过该行,不拖垮整个文件
function readLines(file) {
if (!file || !fs.existsSync(file)) return [];
let text;
try {
text = fs.readFileSync(file, "utf-8");
} catch (e) {
logger.warning(`运行历史读取失败(${path.basename(file)}):${e.message}`);
return [];
}
const out = [];
for (const line of text.split(/\r?\n/)) {
const s = line.trim();
if (!s) continue;
try {
out.push(JSON.parse(s));
} catch (e) {
/* 跳过损坏行 */
}
}
return out;
}
// 原子整体替换(临时文件 + rename),避免写一半留下半行
function writeLines(file, records) {
try {
fs.mkdirSync(path.dirname(file), { recursive: true });
const tmp = file + ".tmp";
const body = records.length ? records.map((r) => JSON.stringify(r)).join("\n") + "\n" : "";
fs.writeFileSync(tmp, body, "utf-8");
fs.renameSync(tmp, file);
} catch (e) {
logger.warning(`运行历史写入失败(${path.basename(file)}):${e.message}`);
}
}
function readIndex() {
return readLines(HISTORY_PATH).filter((r) => r && typeof r === "object" && r.run_id);
}
// 写单次运行的日志文件(受条数与总字节双上限约束)
function writeRunLogs(runId, logs) {
const file = logFilePath(runId);
if (!file || !Array.isArray(logs) || !logs.length) return;
const kept = [];
let bytes = 0;
for (const l of logs.slice(-MAX_LOGS_PER_RUN)) {
const rec = {
t: l && l.t ? String(l.t) : "",
level: (l && l.level) || "INFO",
msg: clip(l && l.msg),
};
bytes += rec.msg.length + 32;
if (bytes > MAX_LOG_BYTES_PER_RUN) {
kept.push({ t: "", level: "WARN", msg: "(日志过长,后续内容已省略,完整日志请查看运行日志面板)" });
break;
}
kept.push(rec);
}
writeLines(file, kept);
}
// 索引条数缓存:本模块是索引的唯一写入方,可安全缓存,避免每次追加都整文件读取
let _count = -1;
function indexCount() {
if (_count < 0) _count = readIndex().length;
return _count;
}
// 裁剪索引到上限,并清理不再被引用的日志文件(避免目录无限膨胀)
function prune() {
const all = readIndex();
_count = all.length;
if (all.length <= MAX_RECORDS) return;
const kept = all.slice(-MAX_RECORDS);
writeLines(HISTORY_PATH, kept);
_count = kept.length;
const alive = new Set(kept.map((r) => safeRunId(r.run_id)).filter(Boolean));
let removed = 0;
try {
for (const name of fs.readdirSync(RUNS_DIR)) {
const id = name.replace(/\.jsonl$/, "");
if (!name.endsWith(".jsonl") || alive.has(id)) continue;
fs.unlinkSync(path.join(RUNS_DIR, name));
removed++;
}
} catch (e) {
/* 目录不存在或个别文件被占用:忽略,不影响主流程 */
}
if (removed) logger.info(`运行历史已裁剪至最近 ${MAX_RECORDS} 次,清理日志文件 ${removed} 个`);
}
// 追加一次已结束的运行(结论进索引,日志单独落文件)
function append(rec) {
if (!rec || !safeRunId(rec.run_id)) return;
writeRunLogs(rec.run_id, rec.logs);
const briefRec = { ...rec };
delete briefRec.logs;
try {
fs.mkdirSync(config.APP_DATA, { recursive: true });
fs.appendFileSync(HISTORY_PATH, JSON.stringify(briefRec) + "\n", "utf-8");
} catch (e) {
logger.warning(`运行历史追加失败:${e.message}`);
return;
}
_count = indexCount() + 1;
// 留出 slack 再裁剪:否则一旦到达上限,之后每次运行都会重写整个索引
if (_count > MAX_RECORDS + PRUNE_SLACK) prune();
}
// 列表视图:只给列表需要的字段(不含日志)
function brief(rec) {
return {
run_id: rec.run_id,
plugin_id: rec.plugin_id || "",
name: rec.name || rec.plugin_id || "",
version: rec.version || "",
trigger: rec.trigger || "manual",
schedule_id: rec.schedule_id || "",
status: rec.status || "",
ok: !!rec.ok,
error: rec.error || "",
started: rec.started || 0,
finished: rec.finished || 0,
duration_sec: rec.duration_sec || 0,
summary: rec.summary || "",
};
}
// 当前账号最近 limit 次运行(新的在前)
function list(account, limit) {
const n = Math.max(1, Math.min(100, parseInt(limit, 10) || 20));
const mine = readIndex().filter((r) => r.account === account);
return mine.slice(-n).reverse().map(brief);
}
// 单次运行详情(结论 + 日志);account 用于隔离,取不到返回 null
function get(runId, account) {
const id = safeRunId(runId);
if (!id) return null;
const all = readIndex();
for (let i = all.length - 1; i >= 0; i--) {
if (all[i].run_id === id && all[i].account === account) {
return { ...brief(all[i]), logs: readLines(logFilePath(id)) };
}
}
return null;
}
module.exports = {
HISTORY_PATH,
RUNS_DIR,
MAX_RECORDS,
PRUNE_SLACK,
MAX_LOGS_PER_RUN,
MAX_MSG_LEN,
MAX_LOG_BYTES_PER_RUN,
append,
list,
get,
};
+356
View File
@@ -0,0 +1,356 @@
// 插件执行核心:登记运行记录 + 进程级隔离执行插件 + 结束后上报。
// 对齐 Python runner.py 完整执行链:spawn python plugin_runner(★ 逐字节协议)
// → stdin 单行 JSON fields → stdout JSON 事件行 → 超时整树强杀(taskkill /T /F)。
"use strict";
const { spawn } = require("child_process");
const readline = require("readline");
const crypto = require("crypto");
const config = require("./config");
const state = require("./state");
const scheduler = require("./scheduler");
const licensing = require("./licensing");
const runHistory = require("./run-history");
const { HUB } = require("./hub");
const { makeLogger } = require("./logger");
const logger = makeLogger("runner");
// 手动停止登记:run_id → 停止标记
const _USER_STOPPED = new Set();
// run_id → kill 函数(执行中,供整树强杀)
const _ACTIVE = new Map();
function isUserStopped(runId) {
return _USER_STOPPED.has(runId);
}
function treeKill(pid) {
// Windows 整树强杀(含 DrissionPage 浏览器等孙进程);非 Windows 直接 kill 子进程组
try {
if (process.platform === "win32") {
const killer = spawn("taskkill", ["/pid", String(pid), "/T", "/F"], {
windowsHide: true,
stdio: "ignore",
detached: true,
});
killer.unref();
} else {
try {
process.kill(-pid, "SIGKILL");
} catch (e) {
process.kill(pid, "SIGKILL");
}
}
} catch (e) {
logger.warning(`整树强杀失败 pid=${pid}: ${e.message}`);
}
}
function terminateRun(runId) {
_USER_STOPPED.add(runId);
const kill = _ACTIVE.get(runId);
if (!kill) return false; // 尚未拉起执行子进程(排队中)或已结束
try {
kill();
} catch (e) {
/* 忽略 */
}
return true;
}
// 平台命名空间并发闸键:按(账号, 平台)隔离,保护该账号各自的平台登录态 cookies
function nsKey(account, platform) {
return `${account || "anon"}:${platform || "local"}`;
}
// 发布日志事件,并同步累积到"这一次运行"的记录里(结束后随运行历史落盘,供点击回放)
function emitLog(runId, pluginId, level, msg) {
const text = String(msg === undefined || msg === null ? "" : msg);
state.appendRunLog(runId, {
t: new Date().toLocaleTimeString("zh-CN", { hour12: false }),
level: level || "INFO",
msg: text,
});
HUB.publish({ t: "log", run_id: runId, plugin_id: pluginId, level: level || "INFO", msg: text });
}
// 结束一次运行:写终态 → 落盘运行历史 → 广播 run_done。
// 所有结束路径(队列拒绝 / 队列异常 / 子进程收尾)共用,避免漏记历史。
function finishRun(runId, plugin, status, error, summary) {
const ok = status === "done";
const finished = Date.now() / 1000;
const run = state.RUNS.get(runId) || {};
const durationSec = run.started ? Math.max(0, Math.round(finished - run.started)) : 0;
state.setRun(runId, {
status,
error: ok ? "" : error || "",
summary: summary || "",
finished,
duration_sec: durationSec,
});
runHistory.append({
run_id: runId,
account: run.account || "",
plugin_id: plugin.id,
name: run.name || plugin.name || plugin.id,
version: run.version || plugin.version || "0",
trigger: run.trigger || "manual",
schedule_id: run.schedule_id || "",
status,
ok,
error: ok ? "" : error || "",
summary: summary || "",
started: run.started || 0,
finished,
duration_sec: durationSec,
logs: Array.isArray(run.logs) ? run.logs : [],
});
HUB.publish({
t: "run_done",
run_id: runId,
plugin_id: plugin.id,
name: run.name || plugin.name || plugin.id,
trigger: run.trigger || "manual",
ok,
error: ok ? "" : error || "",
duration_sec: durationSec,
summary: summary || "",
});
}
// 提交一次插件运行(手动 POST /api/runs 与定时任务共用入口);立即返回 run_id。
// opts: { trigger: "manual" | "schedule", schedule_id } —— 用于区分"谁触发的",落进运行历史
function submitRun(account, plugin, fields, opts) {
const o = opts && typeof opts === "object" ? opts : {};
const trigger = o.trigger === "schedule" ? "schedule" : "manual";
const runId = crypto.randomBytes(16).toString("hex");
state.registerRun(runId, {
status: "running",
account,
plugin_id: plugin.id,
name: plugin.name || plugin.id,
version: plugin.version || "0",
trigger,
schedule_id: o.schedule_id || "",
started: Date.now() / 1000,
result: null,
error: null,
logs: [],
});
HUB.publish({
t: "run_start",
run_id: runId,
plugin_id: plugin.id,
name: plugin.name || plugin.id,
trigger,
at: new Date().toLocaleTimeString("zh-CN", { hour12: false }),
});
licensing.report(account, "", plugin.id, plugin.version || "0", "start");
void runQueued(plugin, fields, runId, account);
return runId;
}
async function runQueued(plugin, fields, runId, account) {
try {
// 平台命名空间并发闸:按(账号, 平台)串行(保护各账号各自的平台登录态 cookies)
if (scheduler.nsLocked(nsKey(account, plugin.platform))) {
emitLog(runId, plugin.id, "INFO", `同平台任务执行中,排队等待(命名空间 ${nsKey(account, plugin.platform)})…`);
}
await scheduler.withNsLock(nsKey(account, plugin.platform), async () => {
const startFn = async () => {
if (isUserStopped(runId)) {
// 排队期间用户已点停止:不真正拉起插件
throw new Error("用户已取消该排队任务");
}
await startChild(plugin, fields, runId, account);
return runId;
};
const r = await scheduler.requestStart(account, plugin.id, plugin.version || "0", startFn);
if (!r.ok) {
const err = isUserStopped(runId) ? "用户手动强制停止" : r.error;
if (isUserStopped(runId)) _USER_STOPPED.delete(runId);
finishRun(runId, plugin, "error", err, "");
}
});
} catch (e) {
logger.error(`运行队列异常:${e.message}`);
finishRun(runId, plugin, "error", `运行队列异常:${e.message}`, "");
}
}
// 拉起执行子进程:子进程 spawn 成功后立即 resolve(runId)(requestStart 随即标记 running);
// 执行结束(close)后异步落终态 + 上报 + 回空闲。
function startChild(plugin, fields, runId, account) {
return new Promise((resolve, reject) => {
const timeout = config.RUN_TIMEOUT;
// 执行环境解析:便携环境包(python-env)优先 → 经 job_guard(Job Object 内存上限
// + 整树托管)拉起 plugin_runner;无环境包(dev 直接 .venv)保持原直拉链路。
// 两种模式协议逐字节一致(plugin_runner stdout JSON 事件行经 stdio 原样透传)。
const python = config.pythonExe();
const envRoot = config.pythonEnvRoot();
const guard = config.jobGuardScript();
const baseArgs = ["-u", config.runnerScript(), "--plugin", plugin.id, "--run", runId];
if (state.ALLOWED !== null) {
baseArgs.push("--allowed", [...state.ALLOWED].sort().join(","));
}
let cmd;
let cwd;
if (envRoot && guard) {
// 环境包模式:python -u job_guard.py --mem <MB> --timeout <s> -- python -u plugin_runner.py ...
cmd = [
python, "-u", guard,
"--mem", String(config.RUN_MAX_MEM_MB),
"--timeout", String(timeout),
"--", python, ...baseArgs,
];
cwd = envRoot;
} else {
cmd = [python, ...baseArgs];
cwd = envRoot || config.REPO_ROOT;
}
let child;
try {
child = spawn(cmd[0], cmd.slice(1), {
cwd,
windowsHide: true,
env: {
...process.env,
PYTHONIOENCODING: "utf-8",
PYTHONUTF8: "1",
PLATFORM_ACCOUNT: account || "",
// 环境包插件加载器据此定位插件根(dev 直拉模式传了也无害)
PLUGINS_ROOT: config.pluginRoot(),
},
stdio: ["pipe", "pipe", "pipe"],
});
} catch (e) {
reject(new Error(`拉起执行子进程失败: ${e.message}`));
return;
}
let resolved = false;
const killFn = () => treeKill(child.pid);
_ACTIVE.set(runId, killFn);
const result = {};
const publish = (ev) => {
const t = ev.ev;
if (t === "log") {
emitLog(runId, plugin.id, ev.level, ev.msg);
} else if (t === "progress") {
HUB.publish({ t: "progress", run_id: runId, plugin_id: plugin.id, pct: Math.max(0, Math.min(100, parseInt(ev.pct, 10) || 0)) });
} else if (t === "result") {
Object.assign(result, ev);
}
};
const rlOut = readline.createInterface({ input: child.stdout });
rlOut.on("line", (line) => {
const s = String(line).trim();
if (!s) return;
try {
const ev = JSON.parse(s);
if (ev && typeof ev === "object" && ev.ev) publish(ev);
} catch (e) {
/* 非 JSON 行忽略 */
}
});
const rlErr = readline.createInterface({ input: child.stderr });
rlErr.on("line", (line) => {
const s = String(line).trim();
if (s) {
emitLog(runId, plugin.id, "ERROR", s);
}
});
// 写 fields(单行 JSON,UTF-8)并关闭 stdin
try {
child.stdin.write(Buffer.from(JSON.stringify(fields || {}), "utf-8"));
child.stdin.end();
} catch (e) {
/* 子进程可能已退出 */
}
let timedOut = false;
let finalized = false;
let timer = null;
const finalize = (code, spawnErr) => {
if (finalized) return;
finalized = true;
if (timer) clearTimeout(timer);
_ACTIVE.delete(runId);
const hasResult = result && Object.keys(result).length > 0;
let status;
let error;
if (hasResult) {
status = result.ok ? "done" : "error";
error = result.error || "";
} else if (spawnErr) {
status = "error";
error = spawnErr;
} else if (isUserStopped(runId)) {
status = "error";
error = "用户手动强制停止";
} else if (timedOut) {
status = "error";
error = `插件执行超时(${timeout}s)已强制终止`;
} else {
status = "error";
error = `执行进程异常退出(exit=${code})且未返回结果`;
}
state.setRun(runId, { result: hasResult ? result.result : null });
finishRun(
runId,
plugin,
status,
status === "done" ? "" : error,
hasResult ? ((result.result || {}).summary || "") : ""
);
_USER_STOPPED.delete(runId);
scheduler.markDone(plugin.id, runId); // 单活槽位回空闲并唤醒排队请求
reportRun(plugin, runId); // 运行上报(联网实时/离线暂存补报)
};
child.once("spawn", () => {
resolved = true;
timer = setTimeout(() => {
timedOut = true;
logger.warning(`插件执行超时(${timeout}s)已强制终止:${plugin.id}`);
killFn();
}, timeout * 1000);
resolve(runId);
});
child.on("error", (err) => {
if (!resolved) {
_ACTIVE.delete(runId);
reject(new Error(`拉起执行子进程失败: ${err.message}`));
return;
}
finalize(null, `执行子进程异常: ${err.message}`);
});
child.on("close", (code) => {
finalize(code, null);
});
});
}
function reportRun(plugin, runId) {
try {
const run = state.RUNS.get(runId) || {};
const account = run.account || "";
const status = run.status === "done" ? "done" : run.status === "running" ? "running" : "error";
const msg = run.error || "";
const duration = run.started ? Math.floor(Date.now() / 1000 - run.started) : 0;
licensing.report(account, "", plugin.id, run.version || "", status, msg, duration);
} catch (e) {
logger.warning(`运行上报失败:${e.message}`);
}
}
module.exports = { submitRun, terminateRun, isUserStopped };
@@ -0,0 +1,157 @@
// 设备级单活调度器:整机同一时刻只运行一个插件进程(对齐 Python scheduler.py)。
// active.json 同路径同格式(跨端共享);switching/running 均视为忙;启动失败回滚空闲。
"use strict";
const fs = require("fs");
const path = require("path");
const config = require("./config");
const { nowStr } = require("./crypto");
const { makeLogger } = require("./logger");
const logger = makeLogger("scheduler");
const ACTIVE_PATH = path.join(config.APP_DATA, "active.json");
function readActive() {
try {
if (!fs.existsSync(ACTIVE_PATH)) return {};
const d = JSON.parse(fs.readFileSync(ACTIVE_PATH, "utf-8"));
return d && typeof d === "object" ? d : {};
} catch (e) {
return {};
}
}
function isBusy() {
const s = readActive().status;
return s === "running" || s === "switching";
}
function writeActive(fields) {
const d = { ...readActive(), ...fields };
d.userId = d.userId ?? "";
d.pluginId = d.pluginId ?? "";
d.version = d.version ?? "";
d.status = d.status ?? "idle";
d.startedAt = d.startedAt ?? "";
d.runId = d.runId ?? "";
try {
fs.mkdirSync(config.APP_DATA, { recursive: true });
const tmp = ACTIVE_PATH + ".tmp";
fs.writeFileSync(tmp, JSON.stringify(d), "utf-8");
fs.renameSync(tmp, ACTIVE_PATH); // 原子写
} catch (e) {
logger.warning(`写 active.json 失败:${e.message}`);
}
}
function initActive() {
fs.mkdirSync(config.APP_DATA, { recursive: true });
if (!fs.existsSync(ACTIVE_PATH)) {
writeActive({ userId: "", pluginId: "", version: "", status: "idle", runId: "", startedAt: "" });
} else {
const s = readActive().status;
if (s === "running" || s === "switching") {
logger.warning("检测到上次异常退出残留的运行状态(running/switching),复位为空闲");
writeActive({ status: "idle", userId: "", pluginId: "", version: "", runId: "", startedAt: "" });
}
}
}
function current() {
return readActive();
}
function isActive(pluginId) {
const a = readActive();
return a.status === "running" && a.pluginId === pluginId;
}
// ==================== 设备级单活(Promise 门闩) ====================
const _waiters = [];
function _wake() {
const ws = _waiters.splice(0);
for (const r of ws) r();
}
async function waitIdle() {
while (isBusy()) {
await new Promise((resolve) => _waiters.push(resolve));
}
}
// 抢占链(原子门闩):把「检查空闲 → 写 switching → 拉起 → 写 running」这段临界区串行化,
// 保证同一时刻只有一个 requestStart 能进入启动段(不同平台命名空间并发提交时也不会双开进程)。
let _claimChain = Promise.resolve();
// 阻塞等待设备空闲后启动:startFn 负责拉起子进程并返回 run_id(不可阻塞)。
// 启动失败回滚"空闲"并唤醒等待者。
function requestStart(user, pluginId, version, startFn) {
const run = _claimChain.then(async () => {
await waitIdle();
writeActive({ status: "switching", startedAt: nowStr() });
try {
const runId = await startFn();
writeActive({ userId: user, pluginId, version, status: "running", runId, startedAt: nowStr() });
return { ok: true, run_id: runId };
} catch (e) {
writeActive({ status: "idle" });
_wake();
return { ok: false, error: `启动失败:${e.message}` };
}
});
// 无论成功失败都推进链,避免一次异常卡死后续排队请求
_claimChain = run.then(
() => {},
() => {}
);
return run;
}
// 运行结束:若 active 仍是该插件则回空闲并唤醒等待者(幂等)
function markDone(pluginId, runId) {
const a = readActive();
if (a.pluginId === pluginId && (a.runId === runId || a.status === "running")) {
writeActive({ status: "idle", userId: "", pluginId: "", version: "", runId: "", startedAt: "" });
_wake();
}
}
// ==================== 平台命名空间并发闸(同平台串行,保护共享 cookies) ====================
const _nsQueues = {};
const _nsInflight = {};
function nsLocked(platform) {
const key = (platform || "").trim() || "local";
return (_nsInflight[key] || 0) > 0;
}
async function withNsLock(platform, fn) {
const key = (platform || "").trim() || "local";
const prev = _nsQueues[key] || Promise.resolve();
const run = prev.then(async () => {
_nsInflight[key] = (_nsInflight[key] || 0) + 1;
try {
return await fn();
} finally {
_nsInflight[key] = (_nsInflight[key] || 0) - 1;
}
});
_nsQueues[key] = run.catch(() => {});
return run;
}
module.exports = {
ACTIVE_PATH,
readActive,
isBusy,
writeActive,
initActive,
current,
isActive,
requestStart,
markDone,
nsLocked,
withNsLock,
};
+923
View File
@@ -0,0 +1,923 @@
// 本地 HTTP/WS 兼容层(127.0.0.1:8799):壳 UI 本地 API 全集 + /pui 插件 UI + /ws 事件 + 静态前端。
// 路由与返回结构对齐 Python webhost backend/apis/*(渲染层主通道走 HTTP,插件 iframe 同源调用)。
"use strict";
const http = require("http");
const fs = require("fs");
const path = require("path");
const crypto = require("crypto");
const { URL } = require("url");
const { WebSocketServer } = require("ws");
const cp = require("./cpclient");
const config = require("./config");
const state = require("./state");
const session = require("./session");
const licensing = require("./licensing");
const registry = require("./registry");
const meta = require("./meta");
const runner = require("./runner");
const runHistory = require("./run-history");
const lastFields = require("./last-fields");
const pluginConfigs = require("./plugin-configs");
const scheduler = require("./scheduler");
const tasks = require("./tasks");
const platformAuth = require("./platform-auth");
const platformCreds = require("./platform-creds");
const shellUpdater = require("./shell-updater");
const chromeManager = require("./chrome-manager");
const pluginSync = require("./plugin-sync");
const envSync = require("./env-sync");
const { HUB } = require("./hub");
const { makeLogger } = require("./logger");
const logger = makeLogger("server");
const MIME = {
".html": "text/html", ".js": "application/javascript", ".mjs": "application/javascript",
".css": "text/css", ".json": "application/json", ".map": "application/json",
".svg": "image/svg+xml", ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg",
".gif": "image/gif", ".ico": "image/x-icon", ".woff": "font/woff",
".woff2": "font/woff2", ".ttf": "font/ttf", ".txt": "text/plain",
};
// ==================== 工具 ====================
function parseCookies(req) {
const out = {};
const raw = req.headers.cookie || "";
for (const part of raw.split(";")) {
const idx = part.indexOf("=");
if (idx > 0) {
const k = part.slice(0, idx).trim();
const v = part.slice(idx + 1).trim();
try {
out[k] = decodeURIComponent(v);
} catch (e) {
out[k] = v;
}
}
}
return out;
}
function readJsonBody(req, limit = 2 * 1024 * 1024) {
return new Promise((resolve, reject) => {
const chunks = [];
let size = 0;
req.on("data", (c) => {
size += c.length;
if (size > limit) {
const e = new Error("请求体过大");
e.status = 413;
reject(e);
req.destroy();
return;
}
chunks.push(c);
});
req.on("end", () => {
const buf = Buffer.concat(chunks);
if (buf.length === 0) return resolve({});
try {
resolve(JSON.parse(buf.toString("utf-8")));
} catch (e) {
const err = new Error("JSON 解析失败");
err.status = 400;
reject(err);
}
});
req.on("error", reject);
});
}
function readRawBody(req, limit = 5 * 1024 * 1024) {
return new Promise((resolve, reject) => {
const chunks = [];
let size = 0;
req.on("data", (c) => {
size += c.length;
if (size > limit) {
const e = new Error("请求体过大");
e.status = 413;
reject(e);
req.destroy();
return;
}
chunks.push(c);
});
req.on("end", () => resolve(Buffer.concat(chunks)));
req.on("error", reject);
});
}
function sendJson(res, status, obj) {
const body = JSON.stringify(obj);
res.writeHead(status, {
"Content-Type": "application/json; charset=utf-8",
"Content-Length": Buffer.byteLength(body),
});
res.end(body);
}
function sendHtml(res, status, html) {
const body = Buffer.from(html, "utf-8");
res.writeHead(status, {
"Content-Type": "text/html; charset=utf-8",
"Content-Length": body.length,
});
res.end(body);
}
function setSessionCookie(res, token) {
res.setHeader("Set-Cookie", `${session.SESSION_COOKIE}=${token}; Path=/; HttpOnly; SameSite=Lax`);
}
function clearSessionCookie(res) {
res.setHeader("Set-Cookie", `${session.SESSION_COOKIE}=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0`);
}
function handleError(res, err) {
if (err && err.status) {
sendJson(res, err.status, { detail: err.message || String(err.status) });
} else {
logger.error(`请求处理异常:${err && err.stack ? err.stack : err}`);
sendJson(res, 500, { detail: "内部错误" });
}
}
// ==================== 钉钉登录 state(防 CSRF) ====================
const _LOGIN_STATES = new Map();
const LOGIN_STATE_TTL = 5 * 60 * 1000;
function loginStateNew() {
const now = Date.now();
for (const [s, exp] of _LOGIN_STATES) {
if (exp < now) _LOGIN_STATES.delete(s);
}
const s = crypto.randomBytes(24).toString("base64url");
_LOGIN_STATES.set(s, now + LOGIN_STATE_TTL);
return s;
}
function loginStateTake(s) {
const exp = _LOGIN_STATES.get(s);
_LOGIN_STATES.delete(s);
return !!exp && exp >= Date.now();
}
// ==================== 业务组装 ====================
async function dingtalkEstablish(account, nickname, dingtalkUid, res) {
if (!account) throw Object.assign(new Error("工号不能为空"), { status: 400 });
const r = await cp.request("POST", "/api/admin/dingtalk/auth", {
headers: { ...cp.machineHeaders(), "Content-Type": "application/json" },
json: { account, nickname, dingtalk_uid: dingtalkUid },
timeout: 15,
});
const acct = r.account || account;
const token = session.establishSession(acct, null);
setSessionCookie(res, token);
if (config.CONTROLPLANE_URL) {
try {
await licensing.syncLicensing(acct);
} catch (e) {
logger.warning(`登录后同步离线授权票据失败:${e.message}`);
}
// 异步刷新敏感凭证(不阻断)
require("./creds-sync")
.load(acct)
.then((creds) => {
if (creds && Object.keys(creds).length) config.applyCreds(creds);
})
.catch(() => {});
}
return {
ok: true,
account: acct,
is_admin: !!r.is_admin,
created: !!r.created,
must_change_pwd: !!r.must_change_pwd,
};
}
// ==================== 路由表 ====================
async function route(req, res, url) {
const cookies = parseCookies(req);
const p = url.pathname;
const method = req.method;
// ---------- 静态前端 ----------
if (method === "GET" && !p.startsWith("/api") && !p.startsWith("/pui") && !p.startsWith("/auth")) {
return serveStatic(res, url);
}
// ---------- 认证 / 会话 ----------
if (p === "/api/admin/me" && method === "GET") {
const account = session.sessAccount(cookies);
if (!account) {
return sendJson(res, 200, { account: "", is_admin: false, dept: "", nickname: "", avatar: "" });
}
try {
const r = await cp.request("GET", "/api/admin/me", { headers: session.cpHeaders(cookies), timeout: 10 });
if (r.account === account) return sendJson(res, 200, r);
} catch (e) {
/* 云端不可达降级 */
}
return sendJson(res, 200, { account, is_admin: false, dept: "", nickname: "", avatar: "" });
}
if (p === "/api/admin/login" && method === "POST") {
const body = await readJsonBody(req);
const account = String(body.account || "").trim();
if (!account) throw Object.assign(new Error("账号不能为空"), { status: 400 });
const r = await cp.request("POST", "/api/admin/auth", {
headers: {
"X-Admin-User": account,
...(config.CONTROLPLANE_TOKEN ? { "X-API-Token": config.CONTROLPLANE_TOKEN } : {}),
"Content-Type": "application/json",
},
json: { account, password: body.password },
timeout: 15,
});
if (!r.ok) return sendJson(res, 200, r);
const token = session.establishSession(account, r.cloud_token || "");
setSessionCookie(res, token);
// 登录成功即后台同步:授权票据 + 插件 + 敏感凭证(失败不阻断登录)
afterLogin(account);
return sendJson(res, 200, { ...r, account });
}
if (p === "/api/admin/logout" && method === "POST") {
const token = cookies[session.SESSION_COOKIE] || "";
session.clearSession(token);
clearSessionCookie(res);
return sendJson(res, 200, { ok: true });
}
if (p === "/api/admin/password" && method === "POST") {
const body = await readJsonBody(req);
const r = await cp.request("POST", "/api/admin/password", {
headers: { ...session.cpHeaders(cookies), "Content-Type": "application/json" },
json: body,
timeout: 15,
});
return sendJson(res, 200, r);
}
if (p === "/api/admin/overview" && method === "GET") {
return sendJson(res, 200, { plugins: [], accounts: [], admins: [] });
}
// ---------- 头像 ----------
const avatarMatch = p.match(/^\/api\/avatar\/([^/]+)$/);
if (avatarMatch && method === "GET") {
if (!config.CONTROLPLANE_URL) throw Object.assign(new Error("统一后端未配置(CONTROLPLANE_URL)"), { status: 503 });
const r = await cp.request("GET", `/api/avatar/${encodeURIComponent(avatarMatch[1])}`, { timeout: 10, raw: true });
res.writeHead(200, {
"Content-Type": r.headers.get("content-type") || "application/octet-stream",
"Content-Length": r.body.length,
});
return res.end(r.body);
}
if (p === "/api/avatar" && method === "POST") {
const account = session.sessAccount(cookies);
if (!account) throw Object.assign(new Error("未登录"), { status: 401 });
if (!config.CONTROLPLANE_URL) throw Object.assign(new Error("统一后端未配置(CONTROLPLANE_URL)"), { status: 503 });
const raw = await readRawBody(req);
if (raw.length === 0) throw Object.assign(new Error("头像文件为空"), { status: 400 });
const r = await cp.request("POST", `/api/admin/avatar?account=${encodeURIComponent(account)}`, {
headers: { ...session.cpHeaders(cookies), "Content-Type": req.headers["content-type"] || "multipart/form-data" },
body: raw,
timeout: 30,
});
return sendJson(res, 200, r);
}
// ---------- 钉钉 ----------
if (p === "/api/admin/dingtalk/login" && method === "POST") {
const body = await readJsonBody(req);
const r = await dingtalkEstablish(String(body.account || "").trim(), body.nickname || "", body.dingtalk_uid || "", res);
return sendJson(res, 200, r);
}
if (p === "/api/admin/dingtalk/inline" && method === "POST") {
const body = await readJsonBody(req);
if (!String(body.code || "").trim()) throw Object.assign(new Error("缺少扫码截图码"), { status: 400 });
if (!config.CONTROLPLANE_URL) throw Object.assign(new Error("未配置中心机地址,无法扫码登录"), { status: 503 });
const info = await cp.request("POST", "/api/admin/dingtalk/sns", {
headers: { ...cp.machineHeaders(), "Content-Type": "application/json" },
json: { code: String(body.code).trim() },
timeout: 15,
});
const account = String(info.account || "").trim();
if (!account) throw Object.assign(new Error("扫码未解析到有效账号,请重新扫码"), { status: 401 });
const r = await dingtalkEstablish(account, info.nickname || "", info.unionid || "", res);
return sendJson(res, 200, r);
}
if (p === "/api/admin/dingtalk/inline_qr" && method === "GET") {
if (!config.CONTROLPLANE_URL) throw Object.assign(new Error("未配置中心机地址,无法扫码登录"), { status: 503 });
const back = `http://${url.host}/api/admin/dingtalk/cb`;
const r = await cp.request("GET", "/api/admin/dingtalk/inline_qr", {
headers: cp.machineHeaders(),
params: { back },
timeout: 15,
});
return sendJson(res, 200, r);
}
if (p === "/api/auth/dingtalk" && method === "GET") {
if (!config.CONTROLPLANE_URL) throw Object.assign(new Error("未配置中心机地址(CONTROLPLANE_URL)"), { status: 503 });
const stateParam = loginStateNew();
const redirectUri = `http://localhost:${config.PORT}/auth/done`;
const r = await cp.request("GET", "/api/dingtalk/login-url", {
headers: cp.machineHeaders(),
params: { back: redirectUri, state: stateParam },
timeout: 15,
});
return sendJson(res, 200, { url: r.url || "", state: stateParam });
}
if (p === "/auth/done" && method === "GET") {
const code = url.searchParams.get("code") || "";
const stateParam = url.searchParams.get("state") || "";
const error = url.searchParams.get("error") || "";
if (error) return sendHtml(res, 200, authDonePage("钉钉登录被取消或失败,请返回重试。"));
if (!(code && stateParam) || !loginStateTake(stateParam)) {
return sendHtml(res, 200, authDonePage("登录状态无效或已过期,请返回重新扫码。"));
}
let info;
try {
info = await cp.request("POST", "/auth/exchange", { json: { code }, timeout: 15 });
} catch (e) {
return sendHtml(res, 200, authDonePage(`登录失败:${e.message}`));
}
const account = String(info.account || "").trim();
if (!account || !info.exists) return sendHtml(res, 200, authDonePage("账号未开通或未解析到有效工号,请联系管理员。"));
const token = session.establishSession(account, info.token || "");
setSessionCookie(res, token);
if (config.CONTROLPLANE_URL) {
try {
await licensing.syncLicensing(account);
} catch (e) {
logger.warning(`登录后同步离线授权票据失败:${e.message}`);
}
}
res.writeHead(302, { Location: "/" });
return res.end();
}
if (p === "/api/admin/dingtalk/qr" && method === "GET") {
if (!config.CONTROLPLANE_URL) return sendJson(res, 200, { url: "" });
const back = `http://${url.host}/api/admin/dingtalk/cb`;
return sendJson(res, 200, {
url: `${config.CONTROLPLANE_URL}/api/admin/dingtalk/scan?${encodeURIComponent("back")}=${encodeURIComponent(back)}`,
});
}
if (p === "/api/admin/dingtalk/cb" && method === "GET") {
return sendHtml(res, 200, DINGTALK_CB_HTML);
}
// ---------- 元数据 / 插件同步 ----------
if (p === "/api/meta" && method === "GET") {
const account = session.sessAccount(cookies);
const data = await meta.buildMeta(account);
return sendJson(res, 200, data);
}
if (p === "/api/plugins/sync" && method === "POST") {
const account = session.requireLogin(cookies);
const result = await pluginSync.withSyncLock(async () => {
const r = await pluginSync.syncPlugins(account);
const manifest = await pluginSync.cloudPluginManifest(account);
if (manifest !== null) state.setAllowed(new Set(manifest.map((pl) => pl.id)));
return r;
});
try {
await licensing.syncLicensing(account);
} catch (e) {
logger.warning(`同步后刷新授权票据失败:${e.message}`);
}
return sendJson(res, 200, result);
}
// ---------- 插件回滚(升级前自动备份上一版,坏包可回退) ----------
if (p === "/api/plugins/rollback" && method === "GET") {
session.requireLogin(cookies);
return sendJson(res, 200, { items: pluginSync.rollbackIndex() });
}
const rollbackMatch = p.match(/^\/api\/plugins\/rollback\/([^/]+)$/);
if (rollbackMatch && method === "POST") {
session.requireLogin(cookies);
const pluginId = decodeURIComponent(rollbackMatch[1]);
if (scheduler.isBusy()) {
throw Object.assign(new Error("设备正在执行任务,请结束后再回滚"), { status: 409 });
}
const done = pluginSync.rollbackPlugin(pluginId);
return sendJson(res, 200, { ok: true, rollback: done });
}
// ---------- 壳子更新 ----------
if (p === "/api/shell/update-status" && method === "GET") {
session.requireLogin(cookies);
return sendJson(res, 200, shellUpdater.pendingStatus());
}
if (p === "/api/shell/check" && method === "POST") {
session.requireLogin(cookies);
shellUpdater.startCheck();
return sendJson(res, 200, { ok: true, checking: true });
}
if (p === "/api/shell/download" && method === "POST") {
session.requireLogin(cookies);
shellUpdater.startDownload();
return sendJson(res, 200, { ok: true });
}
if (p === "/api/shell/apply" && method === "POST") {
session.requireLogin(cookies);
shellUpdater.applyUpdate();
return sendJson(res, 200, { ok: true });
}
// ---------- Chrome ----------
if (p === "/api/chrome/status" && method === "GET") {
session.requireLogin(cookies);
return sendJson(res, 200, await chromeManager.status());
}
if (p === "/api/chrome/check" && method === "POST") {
session.requireLogin(cookies);
await chromeManager.refresh();
return sendJson(res, 200, { ok: true });
}
if (p === "/api/chrome/download" && method === "POST") {
session.requireLogin(cookies);
chromeManager.startDownload();
return sendJson(res, 200, { ok: true });
}
if (p === "/api/chrome/install" && method === "POST") {
session.requireLogin(cookies);
return sendJson(res, 200, chromeManager.install());
}
// ---------- 环境包(便携 Python 运行时) ----------
if (p === "/api/env/status" && method === "GET") {
session.requireLogin(cookies);
return sendJson(res, 200, envSync.status());
}
if (p === "/api/env/sync" && method === "POST") {
session.requireLogin(cookies);
const r = await envSync.checkAndSync(true);
return sendJson(res, 200, { ok: r.ok, reason: r.reason || "", version: r.version || "" });
}
if (p === "/api/env/rollback" && method === "POST") {
session.requireLogin(cookies);
return sendJson(res, 200, envSync.rollback());
}
// ---------- 平台登录(按账号隔离会话与账号密码) ----------
// 当前账号的平台状态:在线态 + 是否已配置个人 HR/OA 账号密码 + 已存用户名
if (p === "/api/platforms/status" && method === "GET") {
const account = session.requireLogin(cookies);
return sendJson(res, 200, { platforms: await platformAuth.status(account) });
}
// 保存当前账号的 HR/OA 账号密码(本机加密);pass 留空表示保留原密码
if (p === "/api/platforms/creds" && method === "PUT") {
const account = session.requireLogin(cookies);
const body = await readJsonBody(req);
const updated = [];
for (const pid of ["hr", "oa"]) {
if (body && body[pid] && (body[pid].user !== undefined || body[pid].pass !== undefined)) {
platformCreds.upsert(account, pid, body[pid]);
updated.push(pid);
}
}
logger.info(`账号 ${account} 更新平台账号密码:${updated.join(",") || "无"}`);
return sendJson(res, 200, { ok: true, updated });
}
const platLogin = p.match(/^\/api\/platforms\/([^/]+)\/(login|logout)$/);
if (platLogin && method === "POST") {
const account = session.requireLogin(cookies);
const pid = platLogin[1];
const action = platLogin[2];
if (!state.PLATFORMS[pid]) throw Object.assign(new Error("平台不存在"), { status: 404 });
if (action === "logout") {
return sendJson(res, 200, platformAuth.logout(pid, account));
}
// login:授权票据有效 + 平台白名单
const lic = await licensing.ensureLicense(account);
if (!lic.ok) throw Object.assign(new Error("授权已过期(最长离线 7 天),请联网刷新后重试"), { status: 403 });
const allowed = await meta.accountAllowedPlatforms(account);
if (allowed === null) throw Object.assign(new Error("控制面不可达,无法校验平台权限"), { status: 503 });
if (!allowed.has(pid)) throw Object.assign(new Error("无该平台访问权限,请联系管理员在控制面授权"), { status: 403 });
const r = await platformAuth.login(pid, account);
return sendJson(res, 200, r);
}
// ---------- 运行 ----------
if (p === "/api/runs" && method === "POST") {
const account = session.requireLogin(cookies);
const body = await readJsonBody(req);
let plugin;
try {
plugin = registry.find(body.plugin_id);
} catch (e) {
throw Object.assign(new Error("插件不存在"), { status: 404 });
}
const online = licensing.isOnline();
const deny = await licensing.runCheckAllowed(plugin.id, account, online);
if (deny) {
logger.info(`插件 ${plugin.id} 启动被拒(账号 ${account}):${deny}`);
throw Object.assign(new Error(deny), { status: 403 });
}
// 记住本次参数(不含 password 字段),供执行台「恢复上次参数」
lastFields.remember(account, plugin.id, body.fields || {}, plugin.fields);
const runId = runner.submitRun(account, plugin, body.fields || {}, { trigger: "manual" });
return sendJson(res, 202, { run_id: runId });
}
// 运行历史列表(当前账号,新的在前):右轨「最近运行」与执行台「已完成」态的数据源
if (p === "/api/runs" && method === "GET") {
const account = session.requireLogin(cookies);
const limit = url.searchParams.get("limit") || 20;
return sendJson(res, 200, { runs: runHistory.list(account, limit) });
}
const runMatch = p.match(/^\/api\/runs\/([^/]+)(\/stop)?$/);
if (runMatch && method === "GET") {
const account = session.requireLogin(cookies);
const run = state.RUNS.get(runMatch[1]);
if (run && run.account === account) return sendJson(res, 200, run);
// 内存态已淘汰(壳子重启 / 超过 MAX_RUNS)时回落到持久化历史,保证「点击回放」仍可用
const hist = runHistory.get(runMatch[1], account);
if (!hist) throw Object.assign(new Error("运行不存在"), { status: 404 });
return sendJson(res, 200, hist);
}
if (runMatch && runMatch[2] && method === "POST") {
const account = session.requireLogin(cookies);
const run = state.RUNS.get(runMatch[1]);
if (!run || run.account !== account) throw Object.assign(new Error("运行不存在"), { status: 404 });
if (run.status !== "running") throw Object.assign(new Error("运行已结束,无需停止"), { status: 409 });
if (!runner.terminateRun(runMatch[1])) {
throw Object.assign(new Error("任务尚未真正启动(排队中或刚结束),请稍候再试"), { status: 409 });
}
return sendJson(res, 200, { ok: true });
}
// ---------- 定时任务 ----------
if (p === "/api/schedules" && method === "GET") {
const account = session.requireLogin(cookies);
return sendJson(res, 200, { schedules: tasks.listSchedules(account) });
}
if (p === "/api/schedules" && method === "POST") {
const account = session.requireLogin(cookies);
const body = await readJsonBody(req);
if (!body.plugin_id) throw Object.assign(new Error("请选择插件"), { status: 400 });
try {
registry.find(body.plugin_id);
} catch (e) {
throw Object.assign(new Error("插件不存在"), { status: 404 });
}
let rec;
try {
rec = tasks.createSchedule(account, body);
} catch (e) {
throw Object.assign(new Error(`cron 表达式无效:${e.message}`), { status: 400 });
}
tasks.pushBackup(account, session.cpHeaders(cookies));
return sendJson(res, 201, rec);
}
const schedMatch = p.match(/^\/api\/schedules\/([^/]+)(\/toggle)?$/);
if (schedMatch && method === "PUT") {
const account = session.requireLogin(cookies);
findOwned(schedMatch[1], account);
const body = await readJsonBody(req);
if (body.plugin_id) {
try {
registry.find(body.plugin_id);
} catch (e) {
throw Object.assign(new Error("插件不存在"), { status: 404 });
}
}
let rec;
try {
rec = tasks.updateSchedule(schedMatch[1], body);
} catch (e) {
throw Object.assign(new Error(`cron 表达式无效:${e.message}`), { status: 400 });
}
if (!rec) throw Object.assign(new Error("任务不存在"), { status: 404 });
tasks.pushBackup(account, session.cpHeaders(cookies));
return sendJson(res, 200, rec);
}
if (schedMatch && !schedMatch[2] && method === "DELETE") {
const account = session.requireLogin(cookies);
findOwned(schedMatch[1], account);
if (!tasks.deleteSchedule(schedMatch[1])) throw Object.assign(new Error("任务不存在"), { status: 404 });
tasks.pushBackup(account, session.cpHeaders(cookies));
return sendJson(res, 200, { ok: true });
}
if (schedMatch && schedMatch[2] && method === "POST") {
const account = session.requireLogin(cookies);
findOwned(schedMatch[1], account);
const body = await readJsonBody(req);
const rec = tasks.toggleSchedule(schedMatch[1], !!body.enabled);
if (!rec) throw Object.assign(new Error("任务不存在"), { status: 404 });
tasks.pushBackup(account, session.cpHeaders(cookies));
return sendJson(res, 200, rec);
}
// ---------- 插件配置 / UI ----------
const cfgMatch = p.match(/^\/api\/plugin-config\/([^/]+)$/);
if (cfgMatch && method === "GET") {
session.requireLogin(cookies);
checkUiAllowed(cfgMatch[1]);
const data = readPluginConfig(cfgMatch[1]);
return sendJson(res, 200, data);
}
if (cfgMatch && method === "POST") {
session.requireLogin(cookies);
checkUiAllowed(cfgMatch[1]);
const data = await readJsonBody(req);
if (!data || typeof data !== "object" || Array.isArray(data)) {
throw Object.assign(new Error("配置体必须是 JSON 对象"), { status: 400 });
}
savePluginConfig(cfgMatch[1], data);
return sendJson(res, 200, { ok: true });
}
// 上次执行参数(执行台「恢复上次参数」):只含非敏感项,password 字段不落盘
const lastFieldsMatch = p.match(/^\/api\/plugins\/([^/]+)\/last-fields$/);
if (lastFieldsMatch && method === "GET") {
const account = session.requireLogin(cookies);
checkUiAllowed(lastFieldsMatch[1]);
const rec = lastFields.recall(account, lastFieldsMatch[1]);
return sendJson(res, 200, { fields: rec.fields, at: rec.at });
}
// ---------- 场景配置方案(多配置,SQLite 存储)----------
if (p === "/api/plugin-configs" && method === "GET") {
const account = session.requireLogin(cookies);
const pluginId = url.searchParams.get("plugin_id") || "";
if (!pluginId) throw Object.assign(new Error("缺少 plugin_id"), { status: 400 });
checkUiAllowed(pluginId);
return sendJson(res, 200, { configs: pluginConfigs.listConfigs(account, pluginId) });
}
if (p === "/api/plugin-configs" && method === "POST") {
const account = session.requireLogin(cookies);
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);
if (!cfg) throw Object.assign(new Error("配置名称不能为空"), { status: 400 });
return sendJson(res, 200, { ok: true, config: cfg });
}
const cfgDelMatch = p.match(/^\/api\/plugin-configs\/([^/]+)\/([^/]+)$/);
if (cfgDelMatch && method === "DELETE") {
const account = session.requireLogin(cookies);
const pluginId = decodeURIComponent(cfgDelMatch[1]);
const cfgId = decodeURIComponent(cfgDelMatch[2]);
checkUiAllowed(pluginId);
const ok = pluginConfigs.deleteConfig(account, pluginId, cfgId);
if (!ok) throw Object.assign(new Error("配置不存在"), { status: 404 });
return sendJson(res, 200, { ok: true });
}
const puiMatch = p.match(/^\/pui\/([^/]+)(\/.*)?$/);
if (puiMatch && method === "GET") {
session.requireLogin(cookies);
checkUiAllowed(puiMatch[1]);
return servePluginUi(res, puiMatch[1], puiMatch[2] || "");
}
sendJson(res, 404, { detail: "Not Found" });
}
function findOwned(sid, account) {
const s = tasks.getSchedule(sid);
if (!s) throw Object.assign(new Error("任务不存在"), { status: 404 });
if (s.account !== account) throw Object.assign(new Error("仅创建者可管理该任务"), { status: 403 });
}
function checkUiAllowed(pluginId) {
try {
registry.find(pluginId);
} catch (e) {
throw Object.assign(new Error("插件不存在"), { status: 404 });
}
if (state.ALLOWED !== null && !state.ALLOWED.has(pluginId)) {
throw Object.assign(new Error("插件不存在"), { status: 404 });
}
}
function readPluginConfig(pluginId) {
const p = path.join(config.PLUGIN_CONFIG_DIR, `${pluginId}.json`);
if (!fs.existsSync(p)) return {};
try {
const data = JSON.parse(fs.readFileSync(p, "utf-8"));
return data && typeof data === "object" && !Array.isArray(data) ? data : {};
} catch (e) {
return {};
}
}
function savePluginConfig(pluginId, data) {
const p = path.join(config.PLUGIN_CONFIG_DIR, `${pluginId}.json`);
try {
fs.mkdirSync(config.PLUGIN_CONFIG_DIR, { recursive: true });
const tmp = p + ".tmp";
fs.writeFileSync(tmp, JSON.stringify(data, null, 2), "utf-8");
fs.renameSync(tmp, p); // 原子替换
} catch (e) {
logger.warning(`插件 ${pluginId} 配置保存失败:${e.message}`);
throw Object.assign(new Error("配置保存失败"), { status: 500 });
}
}
function servePluginUi(res, pluginId, rel) {
const uiRoot = path.resolve(path.join(registry.pluginRoot(), pluginId, "ui"));
if (!fs.existsSync(uiRoot) || !fs.statSync(uiRoot).isDirectory()) {
throw Object.assign(new Error("该插件未提供前端界面"), { status: 404 });
}
let target;
if (!rel.trim()) target = path.join(uiRoot, "index.html");
else target = path.resolve(path.join(uiRoot, rel));
if (!target.startsWith(uiRoot + path.sep) && target !== uiRoot) {
throw Object.assign(new Error("not found"), { status: 404 });
}
if (fs.existsSync(target) && fs.statSync(target).isDirectory()) target = path.join(target, "index.html");
if (!fs.existsSync(target) || !fs.statSync(target).isFile()) {
const fallback = path.join(uiRoot, "index.html");
if (!fs.existsSync(fallback)) throw Object.assign(new Error("not found"), { status: 404 });
target = fallback;
}
const mediaType = MIME[path.extname(target).toLowerCase()] || "application/octet-stream";
const cache = path.basename(target) === "index.html" ? "no-cache" : "public, max-age=86400";
const body = fs.readFileSync(target);
// 插件 UI 内容安全策略:仅允许同源资源(内网离线部署),阻断外联脚本/图片/跳转外域
const CSP =
"default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; " +
"img-src 'self' data:; font-src 'self' data:; connect-src 'self'; base-uri 'none'; form-action 'self'";
res.writeHead(200, {
"Content-Type": mediaType,
"Cache-Control": cache,
"Content-Length": body.length,
"Content-Security-Policy": CSP,
});
res.end(body);
}
function serveStatic(res, url) {
const dist = config.frontendDist();
let rel = url.pathname === "/" ? "index.html" : url.pathname.slice(1);
let target = path.resolve(path.join(dist, rel));
if (!target.startsWith(dist + path.sep) && target !== dist) {
return sendJson(res, 404, { detail: "Not Found" });
}
if (fs.existsSync(target) && fs.statSync(target).isDirectory()) target = path.join(target, "index.html");
if (!fs.existsSync(target) || !fs.statSync(target).isFile()) {
// SPA 兜底:回 index.html(history 路由)
target = path.join(dist, "index.html");
if (!fs.existsSync(target)) return sendJson(res, 404, { detail: "Not Found" });
}
const mediaType = MIME[path.extname(target).toLowerCase()] || "application/octet-stream";
const body = fs.readFileSync(target);
res.writeHead(200, { "Content-Type": mediaType, "Content-Length": body.length });
res.end(body);
}
function escapeHtml(s) {
return String(s === undefined || s === null ? "" : s)
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;")
.replace(/'/g, "&#39;");
}
function authDonePage(text) {
return `<!doctype html><html><head><meta charset="utf-8"><title>登录</title></head>
<body style="font-family:sans-serif;text-align:center;padding:60px">
<p>${escapeHtml(text)}</p><p><a href="/">返回</a></p></body></html>`;
}
const DINGTALK_CB_HTML = `<!doctype html><html><head><meta charset="utf-8"><title>登录中</title></head>
<body style="margin:0;background:#f5f6fa;font-family:system-ui,-apple-system,sans-serif">
<div style="padding:60px 20px;text-align:center;color:#5c6470">钉钉登录中,请稍候…</div>
<script>
(async function(){
var q = new URLSearchParams(location.search);
var account = q.get('account') || '';
var nickname = q.get('nickname') || '';
if (account) {
try {
await fetch('/api/admin/dingtalk/login', {
method:'POST', headers:{'Content-Type':'application/json'},
body: JSON.stringify({ account: account, nickname: nickname })
});
} catch (e) {}
}
try { window.opener && window.opener.location.reload(); } catch (e) {}
setTimeout(function(){ try { window.close(); } catch (e) {} }, 500);
})();
</script></body></html>`;
// ==================== 登录后异步同步(不阻断登录响应) ====================
function afterLogin(account) {
if (!config.CONTROLPLANE_URL) return;
void licensing
.syncLicensing(account)
.catch((e) => logger.warning(`登录后同步离线授权票据失败:${e.message}`));
void pluginSync
.withSyncLock(async () => {
await pluginSync.syncPlugins(account);
const manifest = await pluginSync.cloudPluginManifest(account);
if (manifest !== null) state.setAllowed(new Set(manifest.map((pl) => pl.id)));
})
.catch((e) => logger.warning(`登录后插件同步失败:${e.message}`));
void require("./creds-sync")
.load(account)
.then((creds) => {
if (creds && Object.keys(creds).length) config.applyCreds(creds);
})
.catch(() => {});
}
// ==================== 服务器启动 ====================
function createServer() {
const server = http.createServer(async (req, res) => {
const url = new URL(req.url, `http://${req.headers.host || `127.0.0.1:${config.PORT}`}`);
logger.debug(`${req.method} ${url.pathname}`); // 请求级调试日志(DEBUG 模式)
try {
await route(req, res, url);
} catch (e) {
handleError(res, e);
}
});
// WS /ws:握手需有效统一账户会话
const wss = new WebSocketServer({ noServer: true });
server.on("upgrade", (req, socket, head) => {
const url = new URL(req.url, `http://127.0.0.1:${config.PORT}`);
if (url.pathname !== "/ws") {
socket.destroy();
return;
}
const cookies = parseCookies(req);
if (!session.sessAccount(cookies)) {
socket.write("HTTP/1.1 401 Unauthorized\r\n\r\n");
socket.destroy();
return;
}
wss.handleUpgrade(req, socket, head, (ws) => {
wss.emit("connection", ws, req);
});
});
wss.on("connection", (ws) => {
// 心跳标记:30s ping 一次,连续一个周期无 pong 视为僵尸连接 terminate(浏览器会自动回 pong)
ws.isAlive = true;
ws.on("pong", () => {
ws.isAlive = true;
});
HUB.addClient(ws);
});
// 心跳巡检:防 WS 连接泄漏(页面刷新残留/半开连接)
const heartbeat = setInterval(() => {
for (const ws of wss.clients) {
if (!ws.isAlive) {
ws.terminate();
continue;
}
ws.isAlive = false;
try {
ws.ping();
} catch (e) {
ws.terminate();
}
}
}, 30 * 1000);
if (heartbeat.unref) heartbeat.unref(); // 不阻碍进程退出
server.on("close", () => clearInterval(heartbeat));
return server;
}
function listen(cb) {
const server = createServer();
server.listen(config.PORT, "127.0.0.1", () => {
logger.info(`本地服务已启动:http://127.0.0.1:${config.PORT}`);
if (cb) cb(server);
});
server.on("error", (e) => {
if (e.code === "EADDRINUSE") {
logger.error(`端口 ${config.PORT} 已被占用(旧实例?),请先停止旧底座`);
} else {
logger.error(`本地服务启动失败:${e.message}`);
}
process.exit(1);
});
return server;
}
module.exports = { createServer, listen, parseCookies };
+148
View File
@@ -0,0 +1,148 @@
// 统一账户会话:cookie 会话唯一真源 + 本机会话落盘持久化 + 云端 token 缓存。
// 对齐 Python webhost session.py:cp_session cookie、7 天滑动续期、重启恢复。
"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("session");
const SESSION_COOKIE = "cp_session";
const SESS_TTL = 7 * 24 * 3600 * 1000; // ms
const _SESS = new Map(); // token -> { account, ts }
// account -> 最近云端会话 token(7 天,供 /api/plugins 等用 Bearer)
const _ACCT_CLOUD_TOKEN = new Map();
const SESS_FILE = path.join(config.SHELL_ROOT, "_cp_sessions.json");
function persist() {
const payload = {};
for (const [token, item] of _SESS) {
payload[token] = [item.account, Math.floor(item.ts / 1000), _ACCT_CLOUD_TOKEN.get(item.account) || ""];
}
try {
fs.writeFileSync(SESS_FILE, JSON.stringify(payload), "utf-8");
} catch (e) {
logger.warning(`本机会话持久化失败: ${e.message}`);
}
}
function load() {
if (!fs.existsSync(SESS_FILE)) return;
try {
const raw = JSON.parse(fs.readFileSync(SESS_FILE, "utf-8"));
const now = Date.now();
for (const [token, item] of Object.entries(raw || {})) {
try {
const [acct, ts, cloudTok] = item;
const t = parseFloat(ts) * 1000;
if (now - t <= SESS_TTL) {
_SESS.set(token, { account: acct, ts: t });
if (cloudTok) _ACCT_CLOUD_TOKEN.set(acct, cloudTok);
}
} catch (e) {
/* 跳过坏条目 */
}
}
} catch (e) {
/* 损坏则忽略 */
}
}
// cookies: {name: value};返回当前登录账号(滑动续期)
function sessAccount(cookies) {
const token = (cookies || {})[SESSION_COOKIE] || "";
if (!token) return "";
const item = _SESS.get(token);
if (!item) return "";
const now = Date.now();
if (now - item.ts > SESS_TTL) {
_SESS.delete(token);
return "";
}
item.ts = now; // 滑动续期
persist();
return item.account;
}
function requireLogin(cookies) {
const account = sessAccount(cookies);
if (!account) {
const err = new Error("未登录:请先登录统一账户");
err.status = 401;
throw err;
}
return account;
}
// 建立会话(登录成功):写入内存 + 落盘 + 返回新 token(调用方 set-cookie)
function establishSession(account, cloudToken) {
const token = crypto.randomBytes(16).toString("hex");
_SESS.set(token, { account, ts: Date.now() });
if (cloudToken) _ACCT_CLOUD_TOKEN.set(account, cloudToken);
persist();
return token;
}
function clearSession(token) {
if (token) _SESS.delete(token);
persist();
}
function sessActiveAccount() {
let best = "";
let bestTs = 0;
for (const item of _SESS.values()) {
if (item.ts > bestTs) {
bestTs = item.ts;
best = item.account;
}
}
return best;
}
function accountSet() {
return new Set([..._SESS.values()].map((i) => i.account));
}
function cloudToken(account) {
return _ACCT_CLOUD_TOKEN.get(account) || "";
}
// 到中心机调用头:Bearer 云令牌优先 + X-Admin-User 兜底 + X-API-Token
function cpHeaders(cookies) {
const h = {};
const account = sessAccount(cookies);
if (account) {
const tok = cloudToken(account);
if (tok) h["Authorization"] = `Bearer ${tok}`;
h["X-Admin-User"] = account;
}
if (config.CONTROLPLANE_TOKEN) h["X-API-Token"] = config.CONTROLPLANE_TOKEN;
return h;
}
// 启动恢复
load();
module.exports = {
SESSION_COOKIE,
SESS_FILE,
sessAccount,
requireLogin,
establishSession,
clearSession,
sessActiveAccount,
accountSet,
cloudToken,
setCloudToken: (account, tok) => {
if (tok) _ACCT_CLOUD_TOKEN.set(account, tok);
else _ACCT_CLOUD_TOKEN.delete(account);
persist();
},
cpHeaders,
};
@@ -0,0 +1,313 @@
// 壳子(主程序)自动更新:检查 → 用户确认下载(带进度)→ 点击重启升级。
// 对齐 Python shell_updater.py 的状态结构与并发控制。
"use strict";
const fs = require("fs");
const path = require("path");
const { spawn } = require("child_process");
const cp = require("./cpclient");
const config = require("./config");
const { versionLt, sha256Hex } = require("./crypto");
const { makeLogger } = require("./logger");
const logger = makeLogger("shell-updater");
const SHELL_CACHE = path.join(config.APP_DATA, "shell");
const PERIODIC_INTERVAL = 30 * 60 * 1000;
let _checking = false;
let _downloading = false;
let _pendingVersion = "";
let _pendingNotes = "";
const _STATE = {
checking: false,
check_at: 0,
latest: "",
notes: "",
available: false,
check_error: "",
dl_version: "",
dl_status: "idle", // idle | downloading | downloaded | failed
dl_received: 0,
dl_total: 0,
dl_pct: 0,
dl_error: "",
applying: false,
};
function shellVersionFile() {
// 打包运行:exe 同级 shell.version
if (process.env.ELECTRON_RUN_AS_NODE) return null;
if (process.resourcesPath) return path.join(path.dirname(process.execPath), "shell.version");
return null;
}
function localShellVersion() {
const vf = shellVersionFile();
if (!vf) return ""; // 源码/CLI 开发模式:不参与自更新
try {
return fs.existsSync(vf) ? fs.readFileSync(vf, "utf-8").trim() : "";
} catch (e) {
return "";
}
}
async function fetchCloudVersion() {
if (!localShellVersion() || !config.CONTROLPLANE_URL) {
_STATE.check_error = !localShellVersion() ? "源码开发模式,不参与自更新" : "未配置中心机地址";
return null;
}
try {
const r = await cp.request("GET", "/api/shell/version", { headers: cp.machineHeaders(), timeout: 5 });
return r;
} catch (e) {
logger.info(`检查壳子更新失败(离线跳过):${e.message}`);
_STATE.check_error = `控制面不可达(${e.constructor.name})`;
return null;
}
}
function cachedPkg(version) {
const p = path.join(SHELL_CACHE, `setup-37du-host-${version}.exe`);
return fs.existsSync(p) ? p : null;
}
function restorePending(cloud, notes) {
_pendingVersion = cloud;
_pendingNotes = notes;
_STATE.dl_version = cloud;
_STATE.dl_status = "downloaded";
_STATE.dl_pct = 100;
logger.info(`壳子新版本 ${cloud} 已在缓存中,等待用户重启更新`);
}
async function checkUpdate() {
if (_checking) return;
_checking = true;
try {
_STATE.checking = true;
const cur = localShellVersion();
const info = await fetchCloudVersion();
_STATE.check_at = Date.now();
if (!cur) {
_STATE.latest = "";
_STATE.notes = "";
_STATE.available = false;
return;
}
if (!info) {
_STATE.available = false;
return;
}
const cloud = String(info.version || "");
const notes = String(info.notes || "");
_STATE.latest = cloud;
_STATE.notes = notes;
_STATE.check_error = "";
if (!cloud || !versionLt(cur, cloud)) {
_STATE.available = false;
return;
}
_STATE.available = true;
if (cachedPkg(cloud)) restorePending(cloud, notes);
} finally {
_STATE.checking = false;
_checking = false;
}
}
function startCheck() {
void checkUpdate();
}
function startPeriodicCheck() {
setInterval(() => {
try {
void checkUpdate();
} catch (e) {
logger.warning(`周期检查壳子更新失败:${e.message}`);
}
}, PERIODIC_INTERVAL);
}
async function startDownload() {
const cur = localShellVersion();
if (!cur) return;
if (_STATE.dl_status === "downloading") return;
if (_STATE.dl_status === "downloaded" && _pendingVersion) return;
const info = await fetchCloudVersion();
if (!info) return;
const cloud = String(info.version || "");
if (!cloud || !versionLt(cur, cloud)) return;
if (cachedPkg(cloud)) {
restorePending(cloud, String(info.notes || ""));
return;
}
if (_downloading) return;
_downloading = true;
_STATE.dl_version = cloud;
_STATE.dl_status = "downloading";
_STATE.dl_received = 0;
_STATE.dl_total = 0;
_STATE.dl_pct = 0;
_STATE.dl_error = "";
try {
await download(cloud, info);
} catch (e) {
logger.warning(`下载壳子安装包失败:${e.message}`);
_STATE.dl_status = "failed";
_STATE.dl_error = `安装包下载失败(${e.constructor.name})`;
cleanupPart(cloud);
} finally {
_downloading = false;
}
logger.info(`开始下载壳子新版本 ${cloud}`);
}
async function download(cloud, info) {
const innerUrl = String(info.url || "").trim();
const tmp = path.join(SHELL_CACHE, `setup-37du-host-${cloud}.exe.part`);
const pkg = path.join(SHELL_CACHE, `setup-37du-host-${cloud}.exe`);
const expect = String(info.sha256 || "").toLowerCase();
fs.mkdirSync(SHELL_CACHE, { recursive: true });
const out = fs.createWriteStream(tmp);
const crypto = require("crypto");
const sha = crypto.createHash("sha256");
let received = 0;
let total = 0;
if (innerUrl) {
await downloadFromUrl(innerUrl, {}, out, sha, (rcv, tot) => {
received = rcv;
total = tot;
_STATE.dl_received = received;
_STATE.dl_total = total;
_STATE.dl_pct = total ? Math.floor((received * 100) / total) : 0;
});
} else {
const r = await cp.streamDownload("/api/shell/pkg", {
headers: cp.machineHeaders(),
timeout: 600,
onData: (chunk) => {
out.write(chunk);
sha.update(chunk);
},
onProgress: (rcv, tot) => {
received = rcv;
total = tot;
_STATE.dl_received = received;
_STATE.dl_total = total;
_STATE.dl_pct = total ? Math.floor((received * 100) / total) : 0;
},
});
received = r.received;
total = r.contentLength;
}
await new Promise((res, rej) => out.end((e) => (e ? rej(e) : res())));
const digest = sha.digest("hex");
if (expect && digest !== expect) {
logger.error(`壳子安装包 sha256 校验失败,放弃更新`);
_STATE.dl_status = "failed";
_STATE.dl_error = "安装包校验失败,请重试";
cleanupPart(cloud);
return;
}
try {
fs.renameSync(tmp, pkg);
} catch (e) {
_STATE.dl_status = "failed";
_STATE.dl_error = "安装包保存失败";
cleanupPart(cloud);
return;
}
_STATE.dl_status = "downloaded";
_STATE.dl_pct = 100;
_STATE.dl_received = received;
_STATE.dl_total = total;
restorePending(cloud, String(info.notes || ""));
}
async function downloadFromUrl(url, headers, out, sha, onProgress) {
const ctrl = new AbortController();
const timer = setTimeout(() => ctrl.abort(), 600 * 1000);
const res = await fetch(url, { headers, signal: ctrl.signal, redirect: "follow" });
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const total = parseInt(res.headers.get("content-length") || "0", 10);
let received = 0;
const reader = res.body.getReader();
for (;;) {
const { done, value } = await reader.read();
if (done) break;
out.write(value);
sha.update(value);
received += value.length;
onProgress(received, total);
}
clearTimeout(timer);
}
function cleanupPart(cloud) {
try {
fs.unlinkSync(path.join(SHELL_CACHE, `setup-37du-host-${cloud}.exe.part`));
} catch (e) {
/* 忽略 */
}
}
function pendingStatus() {
let cur = localShellVersion();
let downloaded = !!_pendingVersion && cachedPkg(_pendingVersion) !== null;
if (!downloaded) {
_pendingVersion = "";
_pendingNotes = "";
}
return {
current: cur,
new: downloaded ? _pendingVersion : "",
notes: downloaded ? _pendingNotes : "",
downloaded,
available: !!_STATE.available,
latest: _STATE.latest || "",
checked_at: _STATE.check_at || 0,
checking: !!_STATE.checking,
error: _STATE.check_error || "",
applying: !!_STATE.applying,
dl: {
version: _STATE.dl_version || "",
status: _STATE.dl_status || "idle",
received: _STATE.dl_received || 0,
total: _STATE.dl_total || 0,
pct: _STATE.dl_pct || 0,
error: _STATE.dl_error || "",
},
};
}
function applyUpdate() {
const version = _pendingVersion;
const pkg = cachedPkg(version);
if (!pkg) throw new Error(`未找到已下载的安装包:setup-37du-host-${version}.exe`);
_STATE.applying = true;
logger.info(`开始静默升级到 ${version}:${pkg}`);
const child = spawn(pkg, ["/VERYSILENT", "/SUPPRESSMSGBOXES", "/NORESTART"], {
cwd: path.dirname(pkg),
windowsHide: true,
stdio: "ignore",
detached: true,
});
child.unref();
// 给安装器接管进程,随后退出
setTimeout(() => {
if (typeof process.exit === "function") process.exit(0);
}, 1000);
}
module.exports = {
startCheck,
startPeriodicCheck,
startDownload,
pendingStatus,
applyUpdate,
cachedPkg,
localShellVersion,
};
+55
View File
@@ -0,0 +1,55 @@
// 运行时共享状态:可变全局唯一真源(对齐 Python webhost state.py)。
"use strict";
const PLATFORMS = {
hr: { id: "hr", label: "HR 系统" },
oa: { id: "oa", label: "OA 系统" },
};
// 运行会话:run_id -> {status, account, plugin_id, name, version, trigger, schedule_id, started, result, error, logs}
const RUNS = new Map();
const MAX_RUNS = 50;
// 单次运行内存中累积的日志上限(结束后由 run-history 落盘,此处只服务"正在跑"的实时展示与回放)
const MAX_RUN_LOGS = 800;
// 插件权限白名单(null = 全量;空集 = 零权限)。由登录/启动/同步决定。
let ALLOWED = null;
function setAllowed(v) {
ALLOWED = v === undefined ? null : v;
}
function setRun(runId, fields) {
const run = RUNS.get(runId);
if (run) Object.assign(run, fields);
}
function registerRun(runId, record) {
if (RUNS.size >= MAX_RUNS) {
const oldest = RUNS.keys().next().value;
RUNS.delete(oldest);
}
RUNS.set(runId, record);
}
// 累积"这一次运行"的日志:日志是运行的属性,跟着运行走(不再是全局单例)
function appendRunLog(runId, entry) {
const run = RUNS.get(runId);
if (!run) return;
if (!Array.isArray(run.logs)) run.logs = [];
run.logs.push(entry);
if (run.logs.length > MAX_RUN_LOGS) run.logs.splice(0, run.logs.length - MAX_RUN_LOGS);
}
module.exports = {
PLATFORMS,
RUNS,
MAX_RUNS,
MAX_RUN_LOGS,
ALLOWED,
setAllowed,
setRun,
registerRun,
appendRunLog,
};
+483
View File
@@ -0,0 +1,483 @@
// 定时任务(壳子内置定时):5 段 cron 解析 + schedules.json 存储 + 中心机备份/恢复 + 后台触发。
// 语义对齐 Python tasks.py(★ 契约:dom/dow OR 规则、0/7 周日归一、30s tick、last_run_at 记忆)。
// 差异:错过不补跑——壳子停机/离线期间到点的任务直接跳过(时间过了就过了,要补就人工运行一次);
// 触发失败(授权被拒/插件缺失/启动异常)同样跳过本次到点,等下一个 cron 点再试,不每 tick 重试。
"use strict";
const fs = require("fs");
const path = require("path");
const config = require("./config");
const cp = require("./cpclient");
const session = require("./session");
const { newId, nowStr, versionLt: _unused } = require("./crypto");
const { HUB } = require("./hub");
const { makeLogger } = require("./logger");
const logger = makeLogger("tasks");
const SCHED_FILE = path.join(config.APP_DATA, "schedules.json");
const TICK_SECS = 30;
const DENY_LOG_CD = 300;
// 到点判定容差:nxt 落在 now 前该时长内仍算"及时到点"正常触发;超过则视为错过(停机/离线期间到点),跳过。
// 正常 tick 每 30s 一轮,单轮最坏耗时(deny 检查 5s 超时 + 多任务串行)远小于 4×TICK。
const CATCHUP_SKIP_MS = TICK_SECS * 4 * 1000;
// 到点且未错过(供 tick 使用;独立成纯函数便于测试)
function isDueNow(nxt, now) {
if (!nxt) return false;
const lag = now.getTime() - nxt.getTime();
return lag >= 0 && lag <= CATCHUP_SKIP_MS;
}
// 最小触发间隔(分钟):同一小时内相邻命中点的最小间距。
// 分钟字段集合内任意相邻命中点间隔 < 60 → 存在 < 1 小时的连续触发(每分钟/每 30 分钟等),禁止。
function minGapMinutes(cron) {
const mins = [...cron.minute].sort((a, b) => a - b);
if (mins.length <= 1) return 60; // 单点(如 `0`)= 每小时一次(或更稀疏)
let gap = Infinity;
for (let i = 0; i < mins.length; i++) {
const a = mins[i];
const b = i + 1 < mins.length ? mins[i + 1] : mins[0] + 60;
gap = Math.min(gap, b - a);
}
return gap;
}
// 校验:定时任务最低支持小时级间隔,分钟级禁止(避免高频触发 + 每 tick 无效检查影响性能)
function assertHourlyMin(cron) {
if (minGapMinutes(cron) < 60) {
const err = new Error("定时任务最小间隔为 1 小时,不支持分钟级触发(每分钟/每 30 分钟等)");
err.status = 400;
throw err;
}
}
let _schedules = [];
let _started = false;
const _denyLogTs = new Map();
// ==================== 标准 5 段 cron 解析 ====================
function parseField(spec, lo, hi) {
if (spec === "*" || spec === "?") {
const s = new Set();
for (let v = lo; v <= hi; v++) s.add(v);
return s;
}
const out = new Set();
for (let part of String(spec).split(",")) {
part = part.trim();
if (!part) continue;
let step = 1;
if (part.includes("/")) {
const idx = part.indexOf("/");
const stepS = part.slice(idx + 1);
part = part.slice(0, idx);
step = parseInt(stepS, 10);
if (Number.isNaN(step) || step < 1) throw new Error(`无效步长:${stepS}`);
}
let a, b;
if (part === "*" || part === "?") {
a = lo; b = hi;
} else if (part.includes("-")) {
const idx = part.indexOf("-");
a = parseInt(part.slice(0, idx), 10);
b = parseInt(part.slice(idx + 1), 10);
} else {
a = b = parseInt(part, 10);
}
if (Number.isNaN(a) || Number.isNaN(b) || a < lo || a > hi || b < lo || b > hi || a > b) {
throw new Error(`字段越界:${part}`);
}
for (let v = a; v <= b; v += step) out.add(v);
}
if (out.size === 0) throw new Error("空字段");
return out;
}
function parseCron(expr) {
const parts = String(expr || "").trim().split(/\s+/);
if (parts.length !== 5) throw new Error("cron 需为 5 段:分 时 日 月 周");
const minute = parseField(parts[0], 0, 59);
const hour = parseField(parts[1], 0, 23);
const dom = parseField(parts[2], 1, 31);
const month = parseField(parts[3], 1, 12);
const dow = parseField(parts[4], 0, 7);
const has7 = dow.has(7);
dow.delete(7);
if (has7) dow.add(0);
return { minute, hour, dom, month, dow };
}
function cronDow(dt) {
// 标准 cron 周日编号:0=周日,1=周一 … 6=周六(与 Python 底座 _cron_dow 一致)。
// 注意:JS getDay() 本身就是该编号(周日=0),不能再做 (x+6)%7 的偏移——那会整体差一天,
// 导致「工作日 1-5」实际落在周二~周六、且 `0`/`7`(周日)错到周一。
return dt.getDay();
}
function setRange(lo, hi) {
const s = new Set();
for (let v = lo; v <= hi; v++) s.add(v);
return s;
}
function nextMatch(cron, after) {
const { minute, hour, dom, month, dow } = cron;
const domAny = dom.size === 31 && [...dom].every((v) => v >= 1 && v <= 31);
const dowAny = dow.size === 7;
let t = new Date(after);
t.setSeconds(0, 0);
t = new Date(t.getTime() + 60000); // +1 分钟
for (let i = 0; i < 10000; i++) {
if (!month.has(t.getMonth() + 1)) {
const y = t.getMonth() === 11 ? t.getFullYear() + 1 : t.getFullYear();
const m = t.getMonth() === 11 ? 0 : t.getMonth() + 1;
t = new Date(y, m, 1, 0, 0, 0, 0);
continue;
}
let dayOk;
if (!domAny && !dowAny) dayOk = dom.has(t.getDate()) || dow.has(cronDow(t));
else if (!dowAny) dayOk = dow.has(cronDow(t));
else if (!domAny) dayOk = dom.has(t.getDate());
else dayOk = true;
if (!dayOk) {
t = new Date(t.getFullYear(), t.getMonth(), t.getDate() + 1, 0, 0, 0, 0);
continue;
}
if (!hour.has(t.getHours())) {
t = new Date(t.getFullYear(), t.getMonth(), t.getDate(), t.getHours() + 1, 0, 0, 0);
continue;
}
if (!minute.has(t.getMinutes())) {
t = new Date(t.getTime() + 60000);
continue;
}
return t;
}
return null;
}
// ==================== 本地存储与 CRUD ====================
function load() {
try {
if (fs.existsSync(SCHED_FILE)) {
const data = JSON.parse(fs.readFileSync(SCHED_FILE, "utf-8"));
_schedules = ((data || {}).schedules || []).filter((s) => s && typeof s === "object");
} else {
_schedules = [];
}
} catch (e) {
logger.warning(`定时任务配置损坏,已忽略:${SCHED_FILE}`);
_schedules = [];
}
}
function persist() {
try {
fs.mkdirSync(config.APP_DATA, { recursive: true });
fs.writeFileSync(SCHED_FILE, JSON.stringify({ schedules: _schedules }, null, 2), "utf-8");
} catch (e) {
logger.warning(`定时任务配置持久化失败:${e.message}`);
}
}
function getSchedule(sid) {
for (const s of _schedules) {
if (s.id === sid) return { ...s };
}
return null;
}
function listSchedules(account) {
return _schedules.filter((s) => s.account === account).map(publicView);
}
function createSchedule(account, payload) {
const cron = (payload.cron || "").trim();
parseCron(cron); // 非法抛错
assertHourlyMin(parseCron(cron)); // 分钟级抛错
const rec = {
id: newId(),
name: (payload.name || "").trim() || "定时任务",
account,
plugin_id: payload.plugin_id || "",
fields: payload.fields || {},
cron,
enabled: !!payload.enabled,
last_run_at: "",
created_at: nowStr(),
updated_at: nowStr(),
};
_schedules.push(rec);
persist();
return { ...rec };
}
function updateSchedule(sid, payload) {
if (payload.cron) {
parseCron(payload.cron);
assertHourlyMin(parseCron(payload.cron));
}
for (const s of _schedules) {
if (s.id !== sid) continue;
if ("name" in payload) s.name = (payload.name || "").trim() || "定时任务";
if ("plugin_id" in payload) s.plugin_id = payload.plugin_id;
if ("fields" in payload) s.fields = payload.fields || {};
if (payload.cron) s.cron = payload.cron.trim();
if ("enabled" in payload) s.enabled = !!payload.enabled;
s.updated_at = nowStr();
persist();
return { ...s };
}
return null;
}
function deleteSchedule(sid) {
const idx = _schedules.findIndex((s) => s.id === sid);
if (idx < 0) return false;
_schedules.splice(idx, 1);
persist();
return true;
}
function toggleSchedule(sid, enabled) {
for (const s of _schedules) {
if (s.id !== sid) continue;
s.enabled = !!enabled;
s.updated_at = nowStr();
persist();
return { ...s };
}
return null;
}
function nextRunAt(s) {
let cron;
try {
cron = parseCron(s.cron || "");
} catch (e) {
return null;
}
let last = null;
if (s.last_run_at) {
const t = Date.parse(s.last_run_at.replace(" ", "T"));
if (!Number.isNaN(t)) last = new Date(t);
}
return nextMatch(cron, last || new Date());
}
function publicView(s) {
const out = { ...s };
out.enabled = !!out.enabled;
out.last_run_at = out.last_run_at || "";
// 上次执行结论(计划视图要显示"上次 ✓ 成功 31s";无记录时为空,前端按"从未"处理)
out.last_status = out.last_status || "";
out.last_duration = parseInt(out.last_duration, 10) || 0;
out.last_error = out.last_error || "";
const nxt = out.enabled ? nextRunAt(s) : null;
out.next_run_at = nxt ? fmt(nxt) : "";
return out;
}
function fmt(d) {
const p = (n) => String(n).padStart(2, "0");
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`;
}
function exportByAccount(account) {
return _schedules.filter((s) => s.account === account).map((s) => ({ ...s }));
}
// ==================== 后台触发 ====================
function start() {
if (_started) return;
_started = true;
setInterval(() => {
try {
void tick();
} catch (e) {
logger.warning(`定时任务检查异常:${e.message}`);
}
}, TICK_SECS * 1000);
logger.info(`定时任务后台检查已启动(每 ${TICK_SECS}s 一次)`);
}
async function tick() {
const now = new Date();
const due = [];
const changed = []; // 触发成功或错过跳过都改了 last_run_at,需落盘
for (const s of _schedules) {
if (!s.enabled) continue;
let cron;
try {
cron = parseCron(s.cron || "");
// 防御:历史遗留的分钟级任务不触发(创建/编辑已被 assertHourlyMin 拦截)
if (minGapMinutes(cron) < 60) {
logger.warning(`定时任务「${s.name}」为分钟级间隔,已禁止触发,请在计划页改为小时级或以上`);
continue;
}
} catch (e) {
continue;
}
let last = null;
if (s.last_run_at) {
const t = Date.parse(s.last_run_at.replace(" ", "T"));
if (!Number.isNaN(t)) last = new Date(t);
}
const nxt = nextMatch(cron, last || now);
if (!nxt || nxt.getTime() > now.getTime()) continue; // 未来触发点
if (!isDueNow(nxt, now)) {
// 错过:壳子停机/离线期间到点,时间过了就过了,不补跑(要补就人工运行一次)。
// last_run_at 推进到"现在",下次 tick 直接从未来点开始算。
s.last_run_at = fmt(now);
changed.push(s);
logger.info(`定时任务「${s.name}」错过触发点 ${fmt(nxt)}(停机/离线期间),跳过不补跑`);
continue;
}
due.push([s, nxt]);
}
for (const [s, nxt] of due) {
if (await fire(s)) {
s.last_run_at = fmt(nxt);
} else {
// 触发失败(授权被拒/插件缺失/启动异常):跳过本次到点,等下一个 cron 点再试,
// 避免每 30s tick 对同一任务无效重试。
s.last_run_at = fmt(now);
}
changed.push(s);
}
if (changed.length) persist();
}
async function fire(s) {
const registry = require("./registry");
const licensing = require("./licensing");
const runner = require("./runner");
let plugin;
try {
plugin = registry.find(s.plugin_id || "");
} catch (e) {
logger.warning(`定时任务「${s.name}」的插件 ${s.plugin_id} 不存在,跳过触发`);
return false;
}
const account = s.account || "";
const deny = await licensing.runCheckAllowed(plugin.id, account, licensing.isOnline());
if (deny) {
const ts = Date.now();
const lastLog = _denyLogTs.get(s.id);
_denyLogTs.set(s.id, ts);
if (lastLog === undefined || ts - lastLog >= DENY_LOG_CD * 1000) {
logger.warning(`定时任务「${s.name}」触发被拒(账号 ${account}):${deny}`);
}
return false;
}
try {
const runId = runner.submitRun(account, plugin, s.fields || {}, {
trigger: "schedule",
schedule_id: s.id,
});
watchRun(s.id, runId);
logger.info(`定时任务触发:「${s.name}」(插件 ${plugin.id},账号 ${account})`);
return true;
} catch (e) {
logger.error(`定时任务「${s.name}」启动失败:${e.message}`);
return false;
}
}
// 定时触发的运行结束后,把结论回写到该任务上(计划视图展示"上次 ✓ 成功 31s")
function watchRun(scheduleId, runId) {
let timer = null;
const onEvent = (ev) => {
if (!ev || ev.t !== "run_done" || ev.run_id !== runId) return;
HUB.removeListener("event", onEvent);
if (timer) clearTimeout(timer);
const target = _schedules.find((x) => x.id === scheduleId);
if (!target) return; // 任务已被删除
target.last_status = ev.ok ? "ok" : "error";
target.last_duration = parseInt(ev.duration_sec, 10) || 0;
target.last_error = ev.ok ? "" : ev.error || "";
persist();
};
HUB.on("event", onEvent);
// 兜底:进程异常或事件丢失时不让监听器长期驻留(执行超时上限 + 2 分钟宽限)
timer = setTimeout(() => HUB.removeListener("event", onEvent), (config.RUN_TIMEOUT + 120) * 1000);
if (timer.unref) timer.unref();
}
// ==================== 中心机备份(防丢失) ====================
function pushBackup(account, headers) {
if (!config.CONTROLPLANE_URL || !account) return;
const payload = { data: { schedules: exportByAccount(account) } };
cp.request("POST", "/api/schedules/backup", {
headers: { ...(headers || {}), "Content-Type": "application/json" },
json: payload,
timeout: 10,
})
.then(() => logger.info(`定时任务备份成功(账号 ${account})`))
.catch((e) => logger.warning(`定时任务备份失败(账号 ${account}):${e.message}`));
}
function restoreFromCloud() {
if (!config.CONTROLPLANE_URL) return;
const account = session.sessActiveAccount();
if (!account) return;
const headers = { "X-Admin-User": account };
if (config.CONTROLPLANE_TOKEN) headers["X-API-Token"] = config.CONTROLPLANE_TOKEN;
const tok = session.cloudToken(account);
if (tok) headers["Authorization"] = `Bearer ${tok}`;
cp.request("GET", "/api/schedules/backup", { headers, timeout: 5 })
.then((r) => {
const remote = ((r.data || {}).schedules) || [];
const localIds = new Set(_schedules.map((s) => s.id));
let added = 0;
for (const s of remote) {
if (!s || typeof s !== "object" || localIds.has(s.id) || s.account !== account) continue;
try {
parseCron(s.cron || "");
assertHourlyMin(parseCron(s.cron || "")); // 分钟级历史任务不恢复
} catch (e) {
continue;
}
_schedules.push(s);
localIds.add(s.id);
added++;
}
if (added) {
persist();
logger.info(`定时任务云端恢复 ${added} 条(账号 ${account})`);
}
})
.catch((e) => logger.warning(`定时任务云端恢复失败(跳过):${e.message}`));
}
function init() {
load();
start();
restoreFromCloud();
}
module.exports = {
parseCron,
parseField,
nextMatch,
cronDow,
isDueNow,
minGapMinutes,
assertHourlyMin,
CATCHUP_SKIP_MS,
load,
persist,
getSchedule,
listSchedules,
createSchedule,
updateSchedule,
deleteSchedule,
toggleSchedule,
nextRunAt,
watchRun,
pushBackup,
restoreFromCloud,
init,
SCHED_FILE,
};