1199 lines
48 KiB
JavaScript
1199 lines
48 KiB
JavaScript
// 本地 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 queue = require("./queue");
|
||
const runHistory = require("./run-history");
|
||
const lastFields = require("./last-fields");
|
||
const notes = require("./notes");
|
||
const pluginConfigs = require("./plugin-configs");
|
||
const scheduler = require("./scheduler");
|
||
const tasks = require("./tasks");
|
||
const flows = require("./flows");
|
||
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();
|
||
}
|
||
|
||
// ==================== 离线自动登录(断网 / 服务端不可达时的 7 天离线授权入口) ====================
|
||
// 服务端探活:用 /api/me/pubkey(无鉴权)判断控制面是否可达
|
||
async function serverReachable() {
|
||
try {
|
||
await cp.request("GET", "/api/me/pubkey", { headers: cp.machineHeaders(), timeout: 4 });
|
||
return true;
|
||
} catch (e) {
|
||
return false;
|
||
}
|
||
}
|
||
|
||
// 无会话且服务端不可达时:若存在有效(未过期、验签通过)离线授权票据,为该账号建立本地会话。
|
||
// 这样断网/服务端宕机期间,授权期内的用户仍能进入工作台并运行已授权插件(最长离线 7 天)。
|
||
function tryOfflineSession(res) {
|
||
try {
|
||
const st = licensing.licenseStatus();
|
||
if (st.status === "ok" && st.payload && st.payload.userId) {
|
||
const acct = st.payload.userId;
|
||
const token = session.establishSession(acct, "");
|
||
setSessionCookie(res, token);
|
||
logger.info(`离线授权自动登录:${acct}(服务端不可达,离线模式,最长 7 天)`);
|
||
return acct;
|
||
}
|
||
} catch (e) {
|
||
/* 忽略:票据缺失/无效/过期时不自动登录 */
|
||
}
|
||
return "";
|
||
}
|
||
|
||
// ==================== 业务组装 ====================
|
||
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") {
|
||
let account = session.sessAccount(cookies);
|
||
// 无会话时先探测服务端:可达走正常登录;不可达且存在有效离线授权票据(最长 7 天)时自动登录
|
||
const reachable = account ? true : await serverReachable();
|
||
if (!account && !reachable) account = tryOfflineSession(res);
|
||
if (!account) {
|
||
return sendJson(res, 200, { account: "", is_admin: false, dept: "", nickname: "", avatar: "" });
|
||
}
|
||
if (reachable) {
|
||
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 });
|
||
// 已登录态下换号:同样受"任务执行中不可切换"约束(未登录时首次登录不受影响)
|
||
if (session.sessAccount(cookies)) assertIdleForSwitch();
|
||
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") {
|
||
// 执行/排队中不允许切账号:一次运行带着账号上下文(平台 cookie、凭据注入、上报归属),
|
||
// 半路换号会串号。必须等它跑完,或用户先在「执行队列」手动停止。
|
||
assertIdleForSwitch();
|
||
const token = cookies[session.SESSION_COOKIE] || "";
|
||
session.clearSession(token);
|
||
clearSessionCookie(res);
|
||
return sendJson(res, 200, { ok: true });
|
||
}
|
||
|
||
// 离线登录:不依赖网络,仅校验本地 7 天离线授权票据(验签 + 未过期),消费票据直接进入工作台
|
||
if (p === "/api/admin/offline-login" && method === "POST") {
|
||
if (session.sessAccount(cookies)) assertIdleForSwitch();
|
||
const st = licensing.licenseStatus();
|
||
if (st.status !== "ok" || !st.payload || !st.payload.userId) {
|
||
const reason =
|
||
st.status === "missing" ? "本机无离线授权票据,请先联网登录一次以获取 7 天离线授权"
|
||
: st.status === "expired" ? "离线授权已过期(最长离线 7 天),请联网刷新后重试"
|
||
: st.status === "invalid" ? "离线授权票据无效,请联网重新登录"
|
||
: "离线登录不可用,请联网登录";
|
||
return sendJson(res, 403, { detail: reason });
|
||
}
|
||
const acct = st.payload.userId;
|
||
const token = session.establishSession(acct, "");
|
||
setSessionCookie(res, token);
|
||
logger.info(`离线登录成功:${acct}(消费本地 7 天授权票据)`);
|
||
return sendJson(res, 200, { ok: true, account: acct, offline: 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("账号未开通或未解析到有效工号,请联系管理员。"));
|
||
// 钉钉扫码回调也是"换号"入口:执行/排队中直接拦掉,避免任务串到新账号
|
||
if (hasActiveRuns()) {
|
||
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/boot/status" && method === "GET") {
|
||
return sendJson(res, 200, state.bootStatus());
|
||
}
|
||
|
||
if (p === "/api/meta" && method === "GET") {
|
||
const account = session.sessAccount(cookies);
|
||
const data = await meta.buildMeta(account);
|
||
return sendJson(res, 200, data);
|
||
}
|
||
|
||
// ---------- 本机目录选择(插件 UI 用:原生「选择文件夹」对话框,仅返回路径) ----------
|
||
if (p === "/api/dialog/directory" && method === "POST") {
|
||
session.requireLogin(cookies);
|
||
const body = await readJsonBody(req);
|
||
const { dialog, BrowserWindow } = require("electron");
|
||
const win = BrowserWindow.getAllWindows().find((w) => !w.isDestroyed()) || null;
|
||
const opts = {
|
||
title: String(body.title || "选择文件夹"),
|
||
properties: ["openDirectory", "createDirectory"],
|
||
defaultPath: String(body.current || "") || undefined,
|
||
};
|
||
const r = win ? await dialog.showOpenDialog(win, opts) : await dialog.showOpenDialog(opts);
|
||
const picked = (r.filePaths || [])[0] || "";
|
||
return sendJson(res, 200, { ok: true, canceled: !!r.canceled || !picked, path: picked });
|
||
}
|
||
|
||
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}`);
|
||
}
|
||
// 同步完成 → 推事件,前端据此刷新插件清单(避免用户看到"空场景/请授权"旧值)
|
||
try {
|
||
HUB.publish({ t: "plugins_synced", failed: result.failed || [] });
|
||
} catch (e) { /* 忽略:推送失败不影响返回 */ }
|
||
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);
|
||
void envSync.checkAndSync(true); // 后台下载+切换,进度经 /api/env/status 轮询展示
|
||
return sendJson(res, 200, { ok: true });
|
||
}
|
||
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 noteText = String(body && body.note !== undefined && body.note !== null ? body.note : "").trim();
|
||
if (noteText) {
|
||
notes.save(account, plugin.id, noteText);
|
||
try { await notes.push(account, plugin.id, noteText); } catch (_) { /* 回传失败不阻断执行 */ }
|
||
}
|
||
// 提交即入队:返回排队位置,前端据此提示"已加入队列,第 N 位"
|
||
const r = runner.submitRun(account, plugin, body.fields || {}, {
|
||
trigger: "manual",
|
||
note: noteText || notes.get(account, plugin.id),
|
||
});
|
||
return sendJson(res, 202, {
|
||
run_id: r.run_id,
|
||
queue_position: r.queue_position,
|
||
queued: r.queue_position > 1,
|
||
});
|
||
}
|
||
|
||
// 执行队列快照(当前执行 + 等待中的任务,带位置与等待时长)
|
||
if (p === "/api/queue" && method === "GET") {
|
||
const account = session.requireLogin(cookies);
|
||
return sendJson(res, 200, queue.snapshot(account));
|
||
}
|
||
|
||
// 运行历史列表(当前账号,新的在前):右轨「最近运行」与执行台「已完成」态的数据源
|
||
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" && run.status !== "queued") {
|
||
throw Object.assign(new Error("运行已结束,无需停止"), { status: 409 });
|
||
}
|
||
const wasQueued = run.status === "queued";
|
||
if (!runner.terminateRun(runMatch[1])) {
|
||
throw Object.assign(new Error("任务刚刚结束,请刷新后再试"), { status: 409 });
|
||
}
|
||
return sendJson(res, 200, { ok: true, was_queued: wasQueued });
|
||
}
|
||
|
||
// ---------- 定时任务 ----------
|
||
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);
|
||
}
|
||
|
||
// ---------- 流程编排(DAG) ----------
|
||
if (p === "/api/flows" && method === "GET") {
|
||
const account = session.requireLogin(cookies);
|
||
return sendJson(res, 200, { flows: flows.list(account) });
|
||
}
|
||
if (p === "/api/flows" && method === "POST") {
|
||
const account = session.requireLogin(cookies);
|
||
const body = await readJsonBody(req);
|
||
let rec;
|
||
try {
|
||
rec = flows.create(account, body);
|
||
} catch (e) {
|
||
throw Object.assign(new Error(e.message), { status: 400 });
|
||
}
|
||
tasks.pushBackup(account, session.cpHeaders(cookies)); // 流程配置随定时备份一起上云
|
||
return sendJson(res, 201, rec);
|
||
}
|
||
// 运行态快照(含每个节点的状态),供流程页轮询/首屏兜底
|
||
if (p === "/api/flows/runs" && method === "GET") {
|
||
const account = session.requireLogin(cookies);
|
||
return sendJson(res, 200, { runs: flows.activeRuns(account) });
|
||
}
|
||
const flowRunGet = p.match(/^\/api\/flows\/runs\/([^/]+)$/);
|
||
if (flowRunGet && method === "GET") {
|
||
const account = session.requireLogin(cookies);
|
||
const r = flows.getRun(flowRunGet[1]);
|
||
// 同样的越权保护:别人的流程运行不对外暴露
|
||
if (!r || r.account !== account) throw Object.assign(new Error("流程运行不存在"), { status: 404 });
|
||
return sendJson(res, 200, r);
|
||
}
|
||
// 人工确认节点:流程跑到 confirm 节点会挂起,这里点「继续 / 终止」
|
||
const flowConfirm = p.match(/^\/api\/flows\/runs\/([^/]+)\/confirm$/);
|
||
if (flowConfirm && method === "POST") {
|
||
const account = session.requireLogin(cookies);
|
||
const run = flows.getRun(flowConfirm[1]);
|
||
if (!run || run.account !== account) throw Object.assign(new Error("流程运行不存在"), { status: 404 });
|
||
const body = await readJsonBody(req);
|
||
const done = flows.confirmNode(flowConfirm[1], String(body.node_id || ""), !!body.ok);
|
||
if (!done) throw Object.assign(new Error("该确认节点已超时或已被处理"), { status: 409 });
|
||
return sendJson(res, 200, { ok: true });
|
||
}
|
||
|
||
// 流程版本历史:只给摘要(时间/名称/节点数/类型分布),节点明细走回滚接口
|
||
const flowVer = p.match(/^\/api\/flows\/([^/]+)\/versions$/);
|
||
if (flowVer && method === "GET") {
|
||
const account = session.requireLogin(cookies);
|
||
try {
|
||
return sendJson(res, 200, { versions: flows.listVersions(flowVer[1], account) });
|
||
} catch (e) {
|
||
throw Object.assign(new Error(e.message), { status: e.status || 400 });
|
||
}
|
||
}
|
||
const flowRollback = p.match(/^\/api\/flows\/([^/]+)\/rollback$/);
|
||
if (flowRollback && method === "POST") {
|
||
const account = session.requireLogin(cookies);
|
||
const body = await readJsonBody(req);
|
||
try {
|
||
const rec = flows.rollback(flowRollback[1], account, String(body.vid || ""));
|
||
tasks.pushBackup(account, session.cpHeaders(cookies));
|
||
return sendJson(res, 200, rec);
|
||
} catch (e) {
|
||
throw Object.assign(new Error(e.message), { status: e.status || 400 });
|
||
}
|
||
}
|
||
|
||
const flowMatch = p.match(/^\/api\/flows\/([^/]+)(\/run)?$/);
|
||
if (flowMatch && flowMatch[2] && method === "POST") {
|
||
const account = session.requireLogin(cookies);
|
||
try {
|
||
return sendJson(res, 202, flows.run(account, flowMatch[1]));
|
||
} catch (e) {
|
||
throw Object.assign(new Error(e.message), { status: e.status || 400 });
|
||
}
|
||
}
|
||
if (flowMatch && !flowMatch[2] && method === "PUT") {
|
||
const account = session.requireLogin(cookies);
|
||
const body = await readJsonBody(req);
|
||
let rec;
|
||
try {
|
||
rec = flows.update(flowMatch[1], account, body);
|
||
} catch (e) {
|
||
throw Object.assign(new Error(e.message), { status: e.status || 400 });
|
||
}
|
||
if (!rec) throw Object.assign(new Error("流程不存在"), { status: 404 });
|
||
tasks.pushBackup(account, session.cpHeaders(cookies));
|
||
return sendJson(res, 200, rec);
|
||
}
|
||
if (flowMatch && !flowMatch[2] && method === "DELETE") {
|
||
const account = session.requireLogin(cookies);
|
||
try {
|
||
if (!flows.remove(flowMatch[1], account)) throw Object.assign(new Error("流程不存在"), { status: 404 });
|
||
} catch (e) {
|
||
throw Object.assign(new Error(e.message), { status: e.status || 400 });
|
||
}
|
||
tasks.pushBackup(account, session.cpHeaders(cookies));
|
||
return sendJson(res, 200, { ok: true });
|
||
}
|
||
|
||
// ---------- 插件配置 / 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 });
|
||
}
|
||
|
||
// ---------- 插件备注(账号 × 插件 唯一;本机缓存 + 回传中心机)----------
|
||
if (p === "/api/plugin-notes" && method === "GET") {
|
||
const account = session.requireLogin(cookies);
|
||
// 拉取中心机(跨设备一致):失败静默,直接用本机缓存
|
||
try { await notes.pull(account); } catch (_) { /* 离线继续用本机 */ }
|
||
return sendJson(res, 200, { ok: true, notes: notes.all(account) });
|
||
}
|
||
if (p === "/api/plugin-notes" && method === "POST") {
|
||
const account = session.requireLogin(cookies);
|
||
const body = await readJsonBody(req);
|
||
const pluginId = String((body && body.plugin_id) || "").trim();
|
||
if (!pluginId) throw Object.assign(new Error("缺少 plugin_id"), { status: 400 });
|
||
const note = notes.save(account, pluginId, body && body.note);
|
||
// 回传失败不阻断用户操作(本机已保存,下次拉取/执行时补报)
|
||
try { await notes.push(account, pluginId, note); } catch (_) { /* 离线:仅本机 */ }
|
||
return sendJson(res, 200, { ok: true, plugin_id: pluginId, note });
|
||
}
|
||
|
||
// ---------- 场景配置方案(多配置,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 hasActiveRuns() {
|
||
if (queue.busy() || queue.size() > 0) return true;
|
||
for (const [, r] of state.RUNS) {
|
||
if (r && (r.status === "running" || r.status === "queued")) return true;
|
||
}
|
||
return false;
|
||
}
|
||
|
||
function assertIdleForSwitch() {
|
||
if (!hasActiveRuns()) return;
|
||
const running = queue.runningItem();
|
||
const tip = running && running.name ? `「${running.name}」正在执行` : "有任务正在执行或排队";
|
||
throw Object.assign(
|
||
new Error(`${tip},请先在「执行队列」停止任务后再切换账号`),
|
||
{ status: 409 }
|
||
);
|
||
}
|
||
|
||
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);
|
||
}
|
||
|
||
// 静态资源内存缓存:首屏 index.html/js/css 每次 readFileSync 是同步 IO,会阻塞事件循环,
|
||
// 与 boot status 轮询、WS 握手抢时间(空机器 + 杀软扫描场景被放大)→ 命中缓存零 IO。
|
||
// 仅打包态启用:开发态 dist 随时重建,内存缓存会吐旧文件,必须每次读盘。
|
||
const _STATIC_CACHE = new Map();
|
||
const STATIC_CACHE_MAX = 200;
|
||
|
||
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";
|
||
if (config.IS_FROZEN) {
|
||
const cached = _STATIC_CACHE.get(target);
|
||
if (cached) {
|
||
res.writeHead(200, { "Content-Type": mediaType, "Content-Length": cached.length });
|
||
res.end(cached);
|
||
return;
|
||
}
|
||
}
|
||
const body = fs.readFileSync(target);
|
||
if (config.IS_FROZEN) {
|
||
if (_STATIC_CACHE.size >= STATIC_CACHE_MAX) _STATIC_CACHE.clear(); // 简单防无限增长
|
||
_STATIC_CACHE.set(target, body);
|
||
}
|
||
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, "&")
|
||
.replace(/</g, "<")
|
||
.replace(/>/g, ">")
|
||
.replace(/"/g, """)
|
||
.replace(/'/g, "'");
|
||
}
|
||
|
||
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}`);
|
||
}
|
||
// 端口占用时窗口还没建,直接 exit 用户只看到"闪一下就没了" → 弹窗说明后再退出
|
||
try {
|
||
const { dialog } = require("electron");
|
||
dialog.showErrorBox(
|
||
"37du 自动化工作台",
|
||
`本地服务端口 ${config.PORT} 被占用,无法启动。\n请先关闭旧客户端/底座进程后重试。\n(${e.code || e.message})`
|
||
);
|
||
} catch (_e) { /* 非 Electron 环境忽略 */ }
|
||
process.exit(1);
|
||
});
|
||
return server;
|
||
}
|
||
|
||
module.exports = { createServer, listen, parseCookies };
|