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
+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 };