123 lines
5.1 KiB
JavaScript
123 lines
5.1 KiB
JavaScript
// 场景配置方案(多配置)· SQLite 实现:同一场景可保存多套命名参数组合,运行台/定时任务按需选用。
|
||
// 表:plugin_configs(shell.db),按账号 + 插件隔离,同名覆盖。
|
||
// 安全:password 类型字段 AES-256-GCM 加密落盘(本机 MachineGuid 派生密钥,换机密文失效),
|
||
// 每套方案可绑定不同账号密码,定时任务到点直接用方案字段执行。
|
||
"use strict";
|
||
|
||
const crypto = require("crypto");
|
||
const { execSync } = require("child_process");
|
||
const { db } = require("./db");
|
||
|
||
const MAX_CONFIGS_PER_PLUGIN = 10; // 单插件最多 10 套方案,防异常堆满
|
||
const ENC_PREFIX = "enc:v1:"; // 密文字段标记(iv12 + ct + tag16 → base64)
|
||
|
||
// ---- 本机绑定加解密(MachineGuid 派生密钥,进程内缓存)----
|
||
let _key = null;
|
||
function secretKey() {
|
||
if (_key) return _key;
|
||
let guid = "";
|
||
try {
|
||
const out = execSync('reg query "HKLM\\SOFTWARE\\Microsoft\\Cryptography" /v MachineGuid', { encoding: "utf8" });
|
||
guid = (/MachineGuid\s+REG_SZ\s+(\S+)/.exec(out) || [])[1] || "";
|
||
} catch (_) { /* 读不到时密钥退化为纯盐(仅本机临时可用) */ }
|
||
_key = crypto.createHash("sha256").update(`37du-plugin-cfg:${guid}`).digest();
|
||
return _key;
|
||
}
|
||
|
||
function encVal(v) {
|
||
if (typeof v !== "string" || !v || v.startsWith(ENC_PREFIX)) return v;
|
||
const iv = crypto.randomBytes(12);
|
||
const c = crypto.createCipheriv("aes-256-gcm", secretKey(), iv);
|
||
const ct = Buffer.concat([c.update(v, "utf8"), c.final(), c.getAuthTag()]);
|
||
return ENC_PREFIX + Buffer.concat([iv, ct]).toString("base64");
|
||
}
|
||
|
||
function decVal(v) {
|
||
if (typeof v !== "string" || !v.startsWith(ENC_PREFIX)) return v;
|
||
try {
|
||
const buf = Buffer.from(v.slice(ENC_PREFIX.length), "base64");
|
||
const iv = buf.subarray(0, 12);
|
||
const tag = buf.subarray(buf.length - 16);
|
||
const ct = buf.subarray(12, buf.length - 16);
|
||
const d = crypto.createDecipheriv("aes-256-gcm", secretKey(), iv);
|
||
d.setAuthTag(tag);
|
||
return Buffer.concat([d.update(ct), d.final()]).toString("utf8");
|
||
} catch (_) {
|
||
return ""; // 换机/密文损坏:解不出当空值,避免把密文当密码用
|
||
}
|
||
}
|
||
|
||
// password 类型字段加密落盘(已加密值幂等跳过);schema = 插件的 fields 元数据
|
||
function encryptSecrets(fields, schema) {
|
||
const secret = new Set(
|
||
(Array.isArray(schema) ? schema : [])
|
||
.filter((f) => f && f.type === "password")
|
||
.map((f) => f.key)
|
||
);
|
||
const out = {};
|
||
for (const [k, v] of Object.entries(fields || {})) {
|
||
out[k] = secret.has(k) ? encVal(v) : v;
|
||
}
|
||
return out;
|
||
}
|
||
|
||
function rowToCfg(row) {
|
||
if (!row) return null;
|
||
let raw = {};
|
||
try { raw = JSON.parse(row.fields || "{}"); } catch (_) { raw = {}; }
|
||
const fields = {};
|
||
for (const [k, v] of Object.entries(raw)) fields[k] = decVal(v); // 按 enc 前缀解密
|
||
return { id: String(row.id), name: row.name, fields, at: row.at || "" };
|
||
}
|
||
|
||
function listConfigs(account, pluginId) {
|
||
const rows = db.prepare(
|
||
"SELECT id, name, fields, at FROM plugin_configs WHERE account = ? AND plugin_id = ? ORDER BY id"
|
||
).all(account, pluginId);
|
||
return rows.map(rowToCfg);
|
||
}
|
||
|
||
// 按 id 取单个方案(定时任务到点解析参数用;方案已删除返回 null)
|
||
function getConfig(account, pluginId, cfgId) {
|
||
const row = db.prepare(
|
||
"SELECT id, name, fields, at FROM plugin_configs WHERE account = ? AND plugin_id = ? AND id = ?"
|
||
).get(account, pluginId, String(cfgId || ""));
|
||
return rowToCfg(row);
|
||
}
|
||
|
||
// 保存/覆盖:同名方案更新字段,否则新增;返回新/更新后的配置
|
||
function saveConfig(account, pluginId, name, fields, schema) {
|
||
const trimmed = String(name || "").trim().slice(0, 20);
|
||
if (!trimmed) return null;
|
||
const keep = encryptSecrets(fields, schema);
|
||
const at = new Date().toLocaleString("zh-CN", { hour12: false });
|
||
const exists = db.prepare(
|
||
"SELECT id FROM plugin_configs WHERE account = ? AND plugin_id = ? AND name = ?"
|
||
).get(account, pluginId, trimmed);
|
||
if (exists) {
|
||
db.prepare(
|
||
"UPDATE plugin_configs SET fields = ?, at = ? WHERE id = ?"
|
||
).run(JSON.stringify(keep), at, exists.id);
|
||
return rowToCfg(db.prepare("SELECT id, name, fields, at FROM plugin_configs WHERE id = ?").get(exists.id));
|
||
}
|
||
const count = db.prepare(
|
||
"SELECT COUNT(*) AS n FROM plugin_configs WHERE account = ? AND plugin_id = ?"
|
||
).get(account, pluginId);
|
||
if (count.n >= MAX_CONFIGS_PER_PLUGIN) {
|
||
throw Object.assign(new Error(`每个场景最多保存 ${MAX_CONFIGS_PER_PLUGIN} 套配置`), { status: 400 });
|
||
}
|
||
const r = db.prepare(
|
||
"INSERT INTO plugin_configs (account, plugin_id, name, fields, at) VALUES (?, ?, ?, ?, ?)"
|
||
).run(account, pluginId, trimmed, JSON.stringify(keep), at);
|
||
return rowToCfg(db.prepare("SELECT id, name, fields, at FROM plugin_configs WHERE id = ?").get(r.lastInsertRowid));
|
||
}
|
||
|
||
function deleteConfig(account, pluginId, cfgId) {
|
||
const r = db.prepare(
|
||
"DELETE FROM plugin_configs WHERE account = ? AND plugin_id = ? AND id = ?"
|
||
).run(account, pluginId, cfgId);
|
||
return r.changes > 0;
|
||
}
|
||
|
||
module.exports = { MAX_CONFIGS_PER_PLUGIN, listConfigs, getConfig, saveConfig, deleteConfig };
|