本次提交包含多项功能更新: 1. 为多个插件(xq0002/0003/0004/0008/0010/0011/0020/0031_xq0032/0033/0035/0037/0045_xq0046/0047/0048)新增 UI 界面及配置支持 2. 新增运行日志集中回传功能,客户端自动上传运行日志到中心机集中存储 3. 新增插件分类字段支持,用于场景库分组管理 4. 优化 xq0034/0037/0048 等插件的功能及描述 5. 修复控制面响应兼容问题,支持新旧版本数据格式 6. 新增 xq0033 插件的状态存储模块,用于历史记录管理 7. 优化 CRM 登录窗口模式,支持全屏置顶
285 lines
10 KiB
JavaScript
285 lines
10 KiB
JavaScript
// 平台登录态(HR/OA):真实登录/登出/在线校验。
|
||
// 保持 Python 子进程执行登录(壳内置 python/webhost/backend/shared 下的
|
||
// hr_login_api、oa_login_api,纯 requests 接口登录无浏览器;自包含 vendor,
|
||
// 不依赖老 webhost 底座),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) {
|
||
// 与 Python 侧(hr_login_api 对 PLATFORM_ACCOUNT 做 strip)对齐,避免首尾空白导致目录错位
|
||
const acc = String(account || "").trim();
|
||
const base = acc ? path.join(BASE_SESSIONS_DIR, acc) : 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();
|
||
// 与 Python 侧校验超时(15s)对齐:登录刚完成时平台响应可能偏慢,过短易误判失效
|
||
const timer = setTimeout(() => ctrl.abort(), 15000);
|
||
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,
|
||
// 与 Python requests 默认一致:跟随重定向后再判定;manual 会把 302 直接误判为失效
|
||
redirect: "follow",
|
||
});
|
||
clearTimeout(timer);
|
||
const text = (await resp.text()).trim();
|
||
value = resp.status === 200 && (text.startsWith("{") || text.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_api; import json; print(json.dumps(hr_login_api.main({"force": False}), ensure_ascii=False))`
|
||
: `from webhost.backend.shared import oa_login_api; import json; print(json.dumps(oa_login_api.main(force=False), ensure_ascii=False))`;
|
||
const out = await runPython(snippet, 5 * 60 * 1000, extraEnv);
|
||
const result = extractJson(out) || {};
|
||
const ok = !!result.success;
|
||
let online = ok ? await isOnline(pid, account) : false;
|
||
if (ok && !online) {
|
||
// Python 侧返回成功前已用落盘 cookies 完成真实会话校验;Node 复核偶发失败
|
||
// (网络抖动/响应慢)时清缓存重试一次,避免误杀已成功的登录。
|
||
await new Promise((r) => setTimeout(r, 1500));
|
||
_onlineCache.delete(cacheKey);
|
||
online = await isOnline(pid, account);
|
||
}
|
||
if (ok && !online) {
|
||
// 仍复核失败:以 Python 侧真实登录 + 会话校验结果为准放行(其校验口径与插件一致),
|
||
// Node 手拼 Cookie 头的复核口径存在差异,不作为最终裁决。
|
||
logger.warning(`平台 ${pid} Node 复核未通过,但 Python 侧已登录并校验成功,按登录成功处理(账号 ${account})`);
|
||
online = true;
|
||
}
|
||
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 };
|
||
}
|
||
|
||
// 带超时的在线校验:超时先按未登录返回,校验仍在后台继续跑并回填缓存,
|
||
// 用于 meta 这类"不能为一次外网校验卡住整屏"的场景。
|
||
function isOnlineQuick(pid, account, timeoutMs = 2500) {
|
||
const task = isOnline(pid, account).catch(() => false);
|
||
return Promise.race([task, new Promise((r) => setTimeout(() => r(false), timeoutMs))]);
|
||
}
|
||
|
||
// 当前账号的平台状态(个人中心展示):在线态 + 是否已配置个人账号密码 + 已存用户名
|
||
// 两平台并行校验:串行时最坏 15s×2,并行后总耗时 ≈ 单平台最坏值。
|
||
async function status(account) {
|
||
const creds = platformCreds.get(account) || {};
|
||
return Promise.all(
|
||
Object.keys(LABELS).map(async (pid) => {
|
||
const c = creds[pid] || {};
|
||
return {
|
||
id: pid,
|
||
label: LABELS[pid],
|
||
online: await isOnline(pid, account),
|
||
has_creds: !!(c.user && c.pass),
|
||
user: c.user || "",
|
||
};
|
||
})
|
||
);
|
||
}
|
||
|
||
module.exports = {
|
||
platforms,
|
||
sessionDir,
|
||
isOnline,
|
||
isOnlineQuick,
|
||
login,
|
||
logout,
|
||
status,
|
||
BASE_SESSIONS_DIR,
|
||
};
|