Files
37duAutomation/desktop/electron-shell/electron/licensing.js
T

309 lines
9.5 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 部署端产品化能力层:离线授权/管控清单缓存、中心机公钥缓存、联网判定、验签、运行上报。
// 对齐 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,
};