Files
37duAutomation/desktop/electron-shell/electron/local-crypto.js
T
puddy 9db8c74b7f feat(shell): 插件密码加密、失败熔断与客户端自动更新(v1.11.3)
- 插件配置中 format=password 字段改为 AES-256-GCM 密文落盘(本机密钥,历史明文自动迁移)
- 同一插件连续失败 3 次自动禁用(仅统计进程启动后失败),升级自动解除
- 检测到新版本后台下载,空闲窗口提前提示并自动重启升级,设置页可配安全窗口
2026-11-26 09:28:18 +08:00

120 lines
4.1 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.
// 本机敏感字段加解密:AES-256-GCM,密钥落 APP_DATA/secrets/.key(0600)。
// 用途:插件配置里的密码字段(plugin.json 声明 format=password)由明文改为密文落盘。
// 边界:只保护 %LOCALAPPDATA% 下壳子自己管的配置;插件自己写的 cookie/profile 不在此范围。
// 兼容:非 enc:v1: 前缀一律按明文处理——升级后的旧配置读取不受影响,下次保存自动转密文。
"use strict";
const fs = require("fs");
const path = require("path");
const crypto = require("crypto");
const config = require("./config");
const { makeLogger } = require("./logger");
const logger = makeLogger("local-crypto");
const DIR = path.join(config.APP_DATA, "secrets");
const KEY_FILE = path.join(DIR, ".key");
const PREFIX = "enc:v1:";
let _key = null;
// 密钥首次使用时生成;读坏/长度不对则重建(重建后旧密文解不开,会按原值返回,不抛错)
function loadKey() {
if (_key) return _key;
try {
if (fs.existsSync(KEY_FILE)) {
const k = fs.readFileSync(KEY_FILE);
if (k.length === 32) {
_key = k;
return _key;
}
logger.warning(`密钥长度异常(${k.length}),重新生成`);
}
const key = crypto.randomBytes(32);
fs.mkdirSync(DIR, { recursive: true });
fs.writeFileSync(KEY_FILE, key, { mode: 0o600 });
_key = key;
return _key;
} catch (e) {
logger.warning(`密钥初始化失败(本次进程内临时密钥): ${e.message}`);
_key = crypto.randomBytes(32);
return _key;
}
}
function isEncrypted(v) {
return typeof v === "string" && v.startsWith(PREFIX);
}
// 返回 enc:v1:<iv>:<tag>:<data>(各段 base64);空串不加密,原样返回
function encryptText(plain) {
const text = String(plain == null ? "" : plain);
if (!text) return text;
try {
const key = loadKey();
const iv = crypto.randomBytes(12);
const cipher = crypto.createCipheriv("aes-256-gcm", key, iv);
const data = Buffer.concat([cipher.update(Buffer.from(text, "utf-8")), cipher.final()]);
const tag = cipher.getAuthTag();
return PREFIX + [iv.toString("base64"), tag.toString("base64"), data.toString("base64")].join(":");
} catch (e) {
logger.warning(`加密失败(保持明文): ${e.message}`);
return text;
}
}
// 密文解密;非密文(旧明文)原样返回;解不开也原样返回,避免把配置读成空导致平台锁号
function decryptText(value) {
if (!isEncrypted(value)) return value;
try {
const parts = value.slice(PREFIX.length).split(":");
if (parts.length !== 3) return value;
const [ivB64, tagB64, dataB64] = parts;
const key = loadKey();
const decipher = crypto.createDecipheriv("aes-256-gcm", key, Buffer.from(ivB64, "base64"));
decipher.setAuthTag(Buffer.from(tagB64, "base64"));
return Buffer.concat([decipher.update(Buffer.from(dataB64, "base64")), decipher.final()]).toString("utf-8");
} catch (e) {
logger.warning(`密文解密失败(保留原值,请重新填写密码): ${e.message}`);
return value;
}
}
// 从 registry 的 fields 数组提取密码字段名(registry.fieldsFromSchema 已把 format=password 转成 type=password)
function passwordKeys(fields) {
if (!Array.isArray(fields)) return [];
return fields.filter((f) => f && f.type === "password").map((f) => f.key).filter(Boolean);
}
// 浅拷贝并加密指定 key 的字符串值;其余字段原样保留
function encryptFields(obj, keys) {
if (!obj || typeof obj !== "object" || Array.isArray(obj)) return obj;
const out = { ...obj };
for (const k of keys || []) {
const v = out[k];
if (typeof v === "string" && v && !isEncrypted(v)) out[k] = encryptText(v);
}
return out;
}
// 浅拷贝并解密所有密文值(不依赖 schema,认前缀即可)
function decryptFields(obj) {
if (!obj || typeof obj !== "object" || Array.isArray(obj)) return obj;
const out = { ...obj };
for (const k of Object.keys(out)) {
if (isEncrypted(out[k])) out[k] = decryptText(out[k]);
}
return out;
}
module.exports = {
DIR,
KEY_FILE,
isEncrypted,
encryptText,
decryptText,
passwordKeys,
encryptFields,
decryptFields,
};