feat: 支持 macOS 设备 GUID 管理与修正 Linux global 路径 (#2099)
* feat(webui): 支持 macOS 设备 GUID 管理与修正 Linux global 路径
Linux 的 global 目录直接位于数据根目录下(不再经过 nt_qq), 与 macOS 对齐;
新增 getGlobalDataPath 统一推导, 修正 Registry20/machine-info 在 Linux 下指向错误目录。
macOS 设备 GUID 实现(逆向自 wrapper.node, 对齐 qq_guid_tool):
- guid = MD5(machine_id[8] || sn)
- machineid-info 使用 QQ 私有 TEA 容器(16 轮, 大端), 密钥为 IOPlatformUUID 前 16 字节
- machine_id 优先读 machineid-info, 失败回退主网卡 MAC + 0000
- sn 优先 /dev/disk0 序列号, 回退 IOPlatformSerialNumber
- 新增 GetMacGUIDInfo / GetMacHardwareInfo / SetMacMachineId /
GetMacInfoBackups / CreateMacInfoBackup / RestoreMacInfoBackup / ResetMacDeviceID
- 前端 GUID 面板支持 macOS: 显示硬件信息, 编辑 machine_id 并实时预览 GUID, 备份/恢复/删除
* fix(webui): 加固 GUID 管理并补充 Linux global 路径迁移
按评审意见处理:
- Linux 迁移: 仅当 <dataPath>/global 不存在且 <dataPath>/nt_qq/global 存在时
搬运旧目录, 新目录已存在则保持原样; 逻辑抽到 global-migrate.ts 便于测试
- macOS 主网卡 MAC: 优先 en0, 再回退父级 IOEthernetController 上的
IOMACAddress, 整条链路判空容错
- 恢复接口防目录穿越: 备份名必须命中白名单且匹配 .bak.<时间戳> 格式,
写入前校验内容合法性 (Registry20 / machine-info / TEA 容器)
- SN 留空语义统一为"沿用当前生效值", 前后端预览与落库一致
- 前端保存按钮 dirty 判定纳入 SN
- 备份命名加毫秒时间戳与随机后缀, COPYFILE_EXCL 落盘, 杜绝同秒覆盖
- 硬件查询改为异步 execFile 并加进程内缓存, 不再阻塞事件循环
测试: 新增 Linux 迁移 5 例与备份命名/穿越/内容校验用例,
全量 27 文件 256 例通过; tsc --noEmit 与 eslint 通过。
This commit is contained in:
1 parent
6797143b04
commit
7471e3ecd6
11 files changed
+1534
-47
No files matched your search
@@ -41,6 +41,7 @@ import { createOfflineRecovery } from '@/napcat-core/helper/offline-recovery';
|
||||
import { QQBasicInfoWrapper } from '@/napcat-core/helper/qq-basic-info';
|
||||
import { statusHelperSubscription } from '@/napcat-core/helper/status';
|
||||
import { applyPendingUpdates } from '@/napcat-webui-backend/src/api/UpdateNapCat';
|
||||
import { migrateLegacyGlobalPath } from './global-migrate';
|
||||
import { connectToNamedPipe } from './pipe';
|
||||
|
||||
// NapCat Shell App ES 入口文件
|
||||
@@ -64,7 +65,10 @@ function getDataPaths (wrapper: WrapperNodeApi): [string, string] {
|
||||
dataPath = path.resolve(os.homedir(), './.config/QQ');
|
||||
fs.mkdirSync(dataPath, { recursive: true });
|
||||
}
|
||||
const dataPathGlobal = path.resolve(dataPath, './nt_qq/global');
|
||||
// Linux: global 直接位于数据目录下; Windows: global 位于 nt_qq 子目录下
|
||||
const dataPathGlobal = os.platform() === 'linux'
|
||||
? path.resolve(dataPath, './global')
|
||||
: path.resolve(dataPath, './nt_qq/global');
|
||||
return [dataPath, dataPathGlobal];
|
||||
}
|
||||
|
||||
@@ -714,6 +718,7 @@ export async function NCoreInitShell () {
|
||||
}
|
||||
}
|
||||
const [dataPath, dataPathGlobal] = getDataPaths(wrapper);
|
||||
migrateLegacyGlobalPath(dataPath, dataPathGlobal, logger);
|
||||
WebUiDataRuntime.setQQDataPath(dataPath);
|
||||
const systemPlatform = getPlatformType();
|
||||
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import os from 'node:os';
|
||||
|
||||
export interface MigrationLogger {
|
||||
log: (message: string) => void;
|
||||
logError: (message: string, error?: unknown) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* 旧版 NapCat 在 Linux 上把 global 目录放在 `<dataPath>/nt_qq/global`,
|
||||
* 新版对齐 QQ 官方 Linux 客户端改为 `<dataPath>/global`。
|
||||
*
|
||||
* 仅当新目录不存在、且旧目录存在时搬运一次:
|
||||
* - 服务器仅跑 NapCat 的用户通常只有 `nt_qq/`, 迁移后即可复用原有登录凭据,
|
||||
* 避免重新扫码以及出现两套 login.db / 两个 GUID;
|
||||
* - 若 `QQ/global` 已存在(例如用户同时装了自用 QQ),则保持原样, 不覆盖也不改动,
|
||||
* 避免覆盖两份不同的设备身份, 同时天然保证重复启动时不会二次迁移;
|
||||
* - 两者都不存在时什么都不做, QQ 会在新路径自行重建。
|
||||
*
|
||||
* @param platform 目标平台, 便于测试注入
|
||||
* @returns 是否执行了迁移
|
||||
*/
|
||||
export function migrateLegacyGlobalPath (
|
||||
dataPath: string,
|
||||
dataPathGlobal: string,
|
||||
logger: MigrationLogger,
|
||||
platform: NodeJS.Platform = os.platform()
|
||||
): boolean {
|
||||
if (platform !== 'linux') return false;
|
||||
const legacyGlobalPath = path.resolve(dataPath, './nt_qq/global');
|
||||
if (legacyGlobalPath === dataPathGlobal) return false;
|
||||
// 新目录已存在: 不覆盖、不合并
|
||||
if (fs.existsSync(dataPathGlobal)) return false;
|
||||
// 没有旧数据: QQ 启动时会自行重建
|
||||
if (!fs.existsSync(legacyGlobalPath)) return false;
|
||||
|
||||
try {
|
||||
fs.mkdirSync(path.dirname(dataPathGlobal), { recursive: true });
|
||||
try {
|
||||
fs.renameSync(legacyGlobalPath, dataPathGlobal);
|
||||
} catch {
|
||||
// 跨文件系统时 rename 会失败, 退化为递归复制后删除旧目录
|
||||
fs.cpSync(legacyGlobalPath, dataPathGlobal, { recursive: true });
|
||||
fs.rmSync(legacyGlobalPath, { recursive: true, force: true });
|
||||
}
|
||||
logger.log(`[NapCat] [Core] 已迁移 Linux global 目录: ${legacyGlobalPath} -> ${dataPathGlobal}`);
|
||||
return true;
|
||||
} catch (e) {
|
||||
logger.logError('[NapCat] [Core] 迁移 Linux global 目录失败, 将在新路径重建设备信息:', e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { migrateLegacyGlobalPath } from '@/napcat-shell/global-migrate';
|
||||
|
||||
const noopLogger = { log: () => {}, logError: () => {} };
|
||||
|
||||
function withTempDir (fn: (dir: string) => void): void {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'napcat-migrate-test-'));
|
||||
try {
|
||||
fn(dir);
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
describe('Linux legacy global migration', () => {
|
||||
it('moves nt_qq/global to global when the new path is absent', () => {
|
||||
withTempDir((dir) => {
|
||||
const legacy = path.join(dir, 'nt_qq', 'global');
|
||||
fs.mkdirSync(path.join(legacy, 'nt_data', 'msf'), { recursive: true });
|
||||
fs.writeFileSync(path.join(legacy, 'nt_data', 'msf', 'machine-info'), Buffer.from('legacy-creds'));
|
||||
const target = path.join(dir, 'global');
|
||||
|
||||
expect(migrateLegacyGlobalPath(dir, target, noopLogger, 'linux')).toBe(true);
|
||||
expect(fs.existsSync(legacy)).toBe(false);
|
||||
expect(fs.readFileSync(path.join(target, 'nt_data', 'msf', 'machine-info')).toString())
|
||||
.toBe('legacy-creds');
|
||||
});
|
||||
});
|
||||
|
||||
it('does nothing when the new global path already exists (keeps both intact)', () => {
|
||||
withTempDir((dir) => {
|
||||
const legacy = path.join(dir, 'nt_qq', 'global');
|
||||
const target = path.join(dir, 'global');
|
||||
fs.mkdirSync(legacy, { recursive: true });
|
||||
fs.mkdirSync(target, { recursive: true });
|
||||
fs.writeFileSync(path.join(legacy, 'marker'), Buffer.from('legacy'));
|
||||
fs.writeFileSync(path.join(target, 'marker'), Buffer.from('new'));
|
||||
|
||||
expect(migrateLegacyGlobalPath(dir, target, noopLogger, 'linux')).toBe(false);
|
||||
expect(fs.readFileSync(path.join(legacy, 'marker')).toString()).toBe('legacy');
|
||||
expect(fs.readFileSync(path.join(target, 'marker')).toString()).toBe('new');
|
||||
});
|
||||
});
|
||||
|
||||
it('does nothing when neither path exists', () => {
|
||||
withTempDir((dir) => {
|
||||
expect(migrateLegacyGlobalPath(dir, path.join(dir, 'global'), noopLogger, 'linux')).toBe(false);
|
||||
expect(fs.existsSync(path.join(dir, 'global'))).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
it('is idempotent across repeated startups', () => {
|
||||
withTempDir((dir) => {
|
||||
const legacy = path.join(dir, 'nt_qq', 'global');
|
||||
fs.mkdirSync(legacy, { recursive: true });
|
||||
fs.writeFileSync(path.join(legacy, 'login.db'), Buffer.from('creds'));
|
||||
const target = path.join(dir, 'global');
|
||||
|
||||
expect(migrateLegacyGlobalPath(dir, target, noopLogger, 'linux')).toBe(true);
|
||||
expect(migrateLegacyGlobalPath(dir, target, noopLogger, 'linux')).toBe(false);
|
||||
expect(fs.readFileSync(path.join(target, 'login.db')).toString()).toBe('creds');
|
||||
});
|
||||
});
|
||||
|
||||
it('never touches non-Linux platforms', () => {
|
||||
withTempDir((dir) => {
|
||||
const legacy = path.join(dir, 'nt_qq', 'global');
|
||||
fs.mkdirSync(legacy, { recursive: true });
|
||||
expect(migrateLegacyGlobalPath(dir, path.join(dir, 'global'), noopLogger, 'win32')).toBe(false);
|
||||
expect(fs.existsSync(legacy)).toBe(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,220 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import {
|
||||
teaEncryptBlock,
|
||||
teaDecryptBlock,
|
||||
containerEncrypt,
|
||||
containerDecrypt,
|
||||
MacMachineInfoUtils,
|
||||
MachineInfoUtils,
|
||||
Registry20Utils,
|
||||
resolveBackupPath,
|
||||
} from '@/napcat-webui-backend/src/utils/guid';
|
||||
|
||||
// 参考实现: qq_guid_tool/macos (逆向自 macOS wrapper.node)
|
||||
// 所有期望值均由该 Python 实现生成, 用于确保 TS 复刻逐字节一致。
|
||||
|
||||
const KEY = Buffer.from('000102030405060708090a0b0c0d0e0f', 'hex');
|
||||
|
||||
function prefixRng (n: number): Buffer {
|
||||
return Buffer.from(Array.from({ length: n }, (_, i) => i));
|
||||
}
|
||||
|
||||
function teaEncryptBlockG (block: Buffer, key = KEY): Buffer {
|
||||
return teaEncryptBlock(block, key);
|
||||
}
|
||||
|
||||
function teaDecryptBlockG (block: Buffer, key = KEY): Buffer {
|
||||
return teaDecryptBlock(block, key);
|
||||
}
|
||||
|
||||
describe('macOS TEA block', () => {
|
||||
it('encrypts blocks identical to the python reference', () => {
|
||||
expect(teaEncryptBlockG(Buffer.from('0001020304050607', 'hex')).toString('hex'))
|
||||
.toBe('6328a50896bde3c8');
|
||||
expect(teaEncryptBlockG(Buffer.from('ffffffffffffffff', 'hex')).toString('hex'))
|
||||
.toBe('c79e81a2904419de');
|
||||
expect(teaEncryptBlockG(Buffer.from('0011223344556677', 'hex')).toString('hex'))
|
||||
.toBe('205f515574f0821c');
|
||||
});
|
||||
|
||||
it('decrypts the reference ciphertext', () => {
|
||||
expect(teaDecryptBlockG(Buffer.from('6328a50896bde3c8', 'hex')).toString('hex'))
|
||||
.toBe('0001020304050607');
|
||||
});
|
||||
|
||||
it('round-trips blocks', () => {
|
||||
const block = Buffer.from('a1b2c3d4e5f60718', 'hex');
|
||||
expect(teaDecryptBlockG(teaEncryptBlockG(block)).equals(block)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('macOS TEA container', () => {
|
||||
it('matches the reference for "hello world" with a deterministic rng', () => {
|
||||
const blob = containerEncrypt(Buffer.from('hello world'), KEY, prefixRng);
|
||||
expect(blob.toString('hex'))
|
||||
.toBe('5e56df427ca3a4f56dfc8cbbd3438a437050558841226bb4');
|
||||
expect(containerDecrypt(blob, KEY)!.toString('hex')).toBe('68656c6c6f20776f726c64');
|
||||
});
|
||||
|
||||
it('matches the reference for an empty payload', () => {
|
||||
const blob = containerEncrypt(Buffer.alloc(0), KEY, prefixRng);
|
||||
expect(blob.toString('hex')).toBe('b00e46ba3e788626272ec631c28ab195');
|
||||
expect(containerDecrypt(blob, KEY)!.length).toBe(0);
|
||||
});
|
||||
|
||||
it('matches the reference for a 200 byte payload', () => {
|
||||
const payload = Buffer.from(Array.from({ length: 200 }, (_, i) => i));
|
||||
const blob = containerEncrypt(payload, KEY, prefixRng);
|
||||
const expected = 'b00e46ba3e788626bea151d61ae65f4ee433279c69c420d5e86f2e9d9844f335' +
|
||||
'fc3387a05609b7b3b294a99f8d5eb630e205a6b2d2778c01c2c860fc9b5cbcdaf07aacdece0b3a3' +
|
||||
'760245fae521f96422044562bc913ce1ac90456d810a981430ed54f7cec55207b85d6b5d991b1aa0f' +
|
||||
'4b033f9f8d2d86a06577c621d197a15c4c416efa3860f47b25bf71d8cfb6a08a6b3b158e1df47f950' +
|
||||
'911ab355be47101f37f989b0fe0c8afc432891f761aeadc29a78eabfc8a0bbef190028f85357cbf' +
|
||||
'489bb0c4a7353967dddb0254fa85f82122d4a003637bdc35';
|
||||
expect(blob.toString('hex')).toBe(expected);
|
||||
expect(containerDecrypt(blob, KEY)!.equals(payload)).toBe(true);
|
||||
});
|
||||
|
||||
it('rejects a wrong key', () => {
|
||||
const blob = containerEncrypt(Buffer.from('hello world'), KEY, prefixRng);
|
||||
expect(containerDecrypt(blob, Buffer.alloc(16))).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('macOS machineid-info', () => {
|
||||
// 真实样本: 取自 macOS 14.8.9 (x86_64 VM, IOPlatformUUID 全零),
|
||||
// 源文件 ~/Library/Containers/com.tencent.qq/Data/.../global/nt_data/msf/machineid-info
|
||||
const REAL_CIPHER = '062c59f4bd7972c3baeab0dd857d9482d57ecafe96b7ec4d566e416871d7e829' +
|
||||
'0d117016cd94f644ea968bc641bae40d';
|
||||
const REAL_PLAIN = '00000008525400c91827000000000014514d303030323120202020202020202020202020';
|
||||
const REAL_KEY_UUID = '00000000-0000-0000-0000-000000000000';
|
||||
|
||||
it('decrypts a real QQ-generated machineid-info identically to the python reference', () => {
|
||||
const key = MacMachineInfoUtils.keyFromUuid(REAL_KEY_UUID);
|
||||
const plain = containerDecrypt(Buffer.from(REAL_CIPHER, 'hex'), key);
|
||||
expect(plain).not.toBeNull();
|
||||
expect(plain!.toString('hex')).toBe(REAL_PLAIN);
|
||||
const parsed = MacMachineInfoUtils.parseMachineIdInfo(plain!);
|
||||
expect(parsed.machineId.toString('hex')).toBe('525400c918270000');
|
||||
expect(parsed.sn).toBe('QM00021 ');
|
||||
expect(MacMachineInfoUtils.computeGuid(parsed.machineId, parsed.sn).toString('hex'))
|
||||
.toBe('110cac8ab81e1b7dca6e3f48b1127d92');
|
||||
});
|
||||
|
||||
it('re-encrypts the real payload to a byte-identical container', () => {
|
||||
// 期望容器由参考 python 实现以相同 rng 生成
|
||||
const key = MacMachineInfoUtils.keyFromUuid(REAL_KEY_UUID);
|
||||
const plain = MacMachineInfoUtils.buildMachineIdInfo(
|
||||
Buffer.from('525400c918270000', 'hex'), 'QM00021 ');
|
||||
expect(plain.toString('hex')).toBe(REAL_PLAIN);
|
||||
const blob = containerEncrypt(plain, key, prefixRng);
|
||||
expect(blob.toString('hex'))
|
||||
.toBe('b73dfc91350349448b9ca9a255de7bffd75a548719ab4fa6311a439386fed1c29fbf7a40d0b77b1c7699d27d11545ca7');
|
||||
});
|
||||
|
||||
it('builds and parses fields like the reference', () => {
|
||||
const plain = MacMachineInfoUtils.buildMachineIdInfo(
|
||||
Buffer.from('aabbccddeeff0011', 'hex'), 'C02TEST');
|
||||
expect(plain.toString('hex')).toBe('00000008aabbccddeeff00110000000743303254455354');
|
||||
const parsed = MacMachineInfoUtils.parseMachineIdInfo(plain);
|
||||
expect(parsed.machineId.toString('hex')).toBe('aabbccddeeff0011');
|
||||
expect(parsed.sn).toBe('C02TEST');
|
||||
});
|
||||
|
||||
it('computes the reference guid', () => {
|
||||
const guid = MacMachineInfoUtils.computeGuid(Buffer.from('aabbccddeeff0011', 'hex'), 'C02TEST');
|
||||
expect(guid.toString('hex')).toBe('99902c9e4658f3495eac9932da8de575');
|
||||
});
|
||||
|
||||
it('computes the MAC fallback guid', () => {
|
||||
const guid = MacMachineInfoUtils.computeGuid(
|
||||
Buffer.concat([Buffer.from('aabbccddeeff', 'hex'), Buffer.from([0, 0])]), 'C02TEST');
|
||||
expect(guid.toString('hex')).toBe('90daceec0ac283834cd1dba777e9d54a');
|
||||
});
|
||||
|
||||
it('derives the TEA key from IOPlatformUUID', () => {
|
||||
expect(MacMachineInfoUtils.keyFromUuid('0F1E2D3C-4B5A-6978-8E9F-A0B1C2D3E4F5').toString('hex'))
|
||||
.toBe('30463145324433432d344235412d3639');
|
||||
});
|
||||
|
||||
it('round-trips a container encrypt/decrypt', () => {
|
||||
const key = MacMachineInfoUtils.keyFromUuid('0F1E2D3C-4B5A-6978-8E9F-A0B1C2D3E4F5');
|
||||
const plain = MacMachineInfoUtils.buildMachineIdInfo(Buffer.from('0011223344556677', 'hex'), 'SN123456');
|
||||
const blob = containerEncrypt(plain, key);
|
||||
const back = containerDecrypt(blob, key);
|
||||
expect(back!.equals(plain)).toBe(true);
|
||||
const parsed = MacMachineInfoUtils.parseMachineIdInfo(back!);
|
||||
expect(parsed.machineId.toString('hex')).toBe('0011223344556677');
|
||||
expect(parsed.sn).toBe('SN123456');
|
||||
});
|
||||
});
|
||||
|
||||
function withTempDir (fn: (dir: string) => void): void {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'napcat-guid-test-'));
|
||||
try {
|
||||
fn(dir);
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
describe('backup naming', () => {
|
||||
it('does not overwrite when creating backups in quick succession', () => {
|
||||
withTempDir((dir) => {
|
||||
const target = path.join(dir, 'machineid-info');
|
||||
fs.writeFileSync(target, Buffer.from('payload'));
|
||||
const first = MacMachineInfoUtils.backup(target);
|
||||
const second = MacMachineInfoUtils.backup(target);
|
||||
const third = MachineInfoUtils.backup(target);
|
||||
expect(new Set([first, second, third]).size).toBe(3);
|
||||
for (const backup of [first, second, third]) {
|
||||
expect(fs.existsSync(backup)).toBe(true);
|
||||
}
|
||||
expect(MacMachineInfoUtils.getBackups(target)).toHaveLength(3);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('restore path validation', () => {
|
||||
it('accepts legacy and new backup names present in the whitelist', () => {
|
||||
withTempDir((dir) => {
|
||||
const target = path.join(dir, 'Registry20');
|
||||
fs.writeFileSync(target, Buffer.from('x'));
|
||||
fs.writeFileSync(`${target}.bak.20251009123456`, Buffer.from('legacy'));
|
||||
const created = Registry20Utils.backup(target);
|
||||
const list = Registry20Utils.getBackups(target);
|
||||
expect(resolveBackupPath(target, path.basename(`${target}.bak.20251009123456`), list))
|
||||
.toBe(`${target}.bak.20251009123456`);
|
||||
expect(resolveBackupPath(target, path.basename(created), list)).toBe(created);
|
||||
});
|
||||
});
|
||||
|
||||
it('rejects directory traversal and unknown backup names', () => {
|
||||
withTempDir((dir) => {
|
||||
const target = path.join(dir, 'machine-info');
|
||||
fs.writeFileSync(target, Buffer.from('x'));
|
||||
const list = MachineInfoUtils.getBackups(target);
|
||||
expect(() => resolveBackupPath(target, '../../../non-backup.txt', list)).toThrow();
|
||||
expect(() => resolveBackupPath(target, '../machine-info.bak.20251009123456', list)).toThrow();
|
||||
expect(() => resolveBackupPath(target, 'machine-info.bak.20251009123456', list)).toThrow();
|
||||
expect(() => resolveBackupPath(target, '/etc/passwd', list)).toThrow();
|
||||
expect(() => resolveBackupPath(target, 'other.bak.20251009123456', list)).toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
it('refuses to restore a backup whose content is not a valid device file', () => {
|
||||
withTempDir((dir) => {
|
||||
const target = path.join(dir, 'machine-info');
|
||||
fs.writeFileSync(target, Buffer.from('x'));
|
||||
const evil = `${target}.bak.20251009123456`;
|
||||
fs.writeFileSync(evil, Buffer.from('not-a-machine-info'));
|
||||
|
||||
expect(() => MachineInfoUtils.restore(target, path.basename(evil))).toThrow();
|
||||
// 原始文件未被破坏
|
||||
expect(fs.readFileSync(target).toString()).toBe('x');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -14,6 +14,8 @@ export default defineConfig({
|
||||
'@/napcat-common': resolve(__dirname, '../napcat-common'),
|
||||
'@/napcat-core': resolve(__dirname, '../napcat-core'),
|
||||
'@/napcat-onebot': resolve(__dirname, '../napcat-onebot'),
|
||||
'@/napcat-shell': resolve(__dirname, '../napcat-shell'),
|
||||
'@/napcat-webui-backend': resolve(__dirname, '../napcat-webui-backend'),
|
||||
'napcat-protobuf': resolve(__dirname, '../napcat-protobuf/NapProto.ts'),
|
||||
},
|
||||
},
|
||||
|
||||
@@ -5,7 +5,18 @@ import { WebUiDataRuntime } from '@/napcat-webui-backend/src/helper/Data';
|
||||
import { WebUiConfig } from '@/napcat-webui-backend/index';
|
||||
import { isEmpty } from '@/napcat-webui-backend/src/utils/check';
|
||||
import { sendError, sendSuccess } from '@/napcat-webui-backend/src/utils/response';
|
||||
import { Registry20Utils, MachineInfoUtils } from '@/napcat-webui-backend/src/utils/guid';
|
||||
import {
|
||||
Registry20Utils,
|
||||
MachineInfoUtils,
|
||||
getGlobalDataPath,
|
||||
MacMachineInfoUtils,
|
||||
computeMacGuidInfo,
|
||||
getMacPlatformUuid,
|
||||
getMacSn,
|
||||
getMacSerialNumber,
|
||||
getMacDiskSerial,
|
||||
getMacPrimaryMac,
|
||||
} from '@/napcat-webui-backend/src/utils/guid';
|
||||
import os from 'node:os';
|
||||
|
||||
// oidb 新设备验证请求辅助函数
|
||||
@@ -39,8 +50,8 @@ function oidbRequest (uid: string, body: Record<string, unknown>): Promise<Recor
|
||||
});
|
||||
}
|
||||
|
||||
// 获取 Registry20 路径的辅助函数
|
||||
const getRegistryPath = () => {
|
||||
// 获取 QQ 数据根目录 (dataPath)
|
||||
const getQQDataPath = (): string => {
|
||||
// 优先从 WebUiDataRuntime 获取早期设置的 dataPath
|
||||
let dataPath = WebUiDataRuntime.getQQDataPath();
|
||||
if (!dataPath) {
|
||||
@@ -51,20 +62,17 @@ const getRegistryPath = () => {
|
||||
if (!dataPath) {
|
||||
throw new Error('QQ data path not available yet');
|
||||
}
|
||||
return Registry20Utils.getRegistryPath(dataPath);
|
||||
return dataPath;
|
||||
};
|
||||
|
||||
// 获取 Registry20 路径的辅助函数
|
||||
const getRegistryPath = () => {
|
||||
return Registry20Utils.getRegistryPath(getQQDataPath());
|
||||
};
|
||||
|
||||
// 获取 machine-info 路径的辅助函数 (Linux)
|
||||
const getMachineInfoPath = () => {
|
||||
let dataPath = WebUiDataRuntime.getQQDataPath();
|
||||
if (!dataPath) {
|
||||
const oneBotContext = WebUiDataRuntime.getOneBotContext();
|
||||
dataPath = oneBotContext?.core?.dataPath;
|
||||
}
|
||||
if (!dataPath) {
|
||||
throw new Error('QQ data path not available yet');
|
||||
}
|
||||
return MachineInfoUtils.getMachineInfoPath(dataPath);
|
||||
return MachineInfoUtils.getMachineInfoPath(getQQDataPath());
|
||||
};
|
||||
|
||||
// 获取QQ登录二维码
|
||||
@@ -515,6 +523,132 @@ export const QQResetLinuxDeviceIDHandler: RequestHandler = async (_, res) => {
|
||||
}
|
||||
};
|
||||
|
||||
// ============================================================
|
||||
// macOS GUID 管理 (machineid-info / TEA)
|
||||
// ============================================================
|
||||
|
||||
// macOS: 当前生效的 GUID 与来源信息
|
||||
export const QQGetMacGUIDInfoHandler: RequestHandler = async (_, res) => {
|
||||
try {
|
||||
const dataPathGlobal = getGlobalDataPath(getQQDataPath());
|
||||
const info = await computeMacGuidInfo(dataPathGlobal);
|
||||
return sendSuccess(res, info);
|
||||
} catch (e) {
|
||||
return sendError(res, `Failed to get macOS GUID: ${(e as Error).message}`);
|
||||
}
|
||||
};
|
||||
|
||||
// macOS: 本机硬件信息 (UUID / SN / 主网卡 MAC)
|
||||
export const QQGetMacHardwareInfoHandler: RequestHandler = async (_, res) => {
|
||||
try {
|
||||
const [mac, platformUuid, serialNumber, diskSerial] = await Promise.all([
|
||||
getMacPrimaryMac(),
|
||||
getMacPlatformUuid(),
|
||||
getMacSerialNumber(),
|
||||
getMacDiskSerial(),
|
||||
]);
|
||||
return sendSuccess(res, {
|
||||
platformUuid: platformUuid ?? '',
|
||||
serialNumber: serialNumber ?? '',
|
||||
diskSerial: diskSerial ?? '',
|
||||
mac: mac ? mac.toString('hex') : '',
|
||||
});
|
||||
} catch (e) {
|
||||
return sendError(res, `Failed to get macOS hardware info: ${(e as Error).message}`);
|
||||
}
|
||||
};
|
||||
|
||||
// macOS: 修改 machine_id (写入 TEA 加密的 machineid-info)
|
||||
export const QQSetMacMachineIdHandler: RequestHandler = async (req, res) => {
|
||||
const { machineId, sn } = req.body;
|
||||
if (!machineId || typeof machineId !== 'string' || !/^[0-9a-fA-F]{16}$/.test(machineId)) {
|
||||
return sendError(res, 'Invalid machine_id, must be 16 hex characters');
|
||||
}
|
||||
try {
|
||||
const dataPathGlobal = getGlobalDataPath(getQQDataPath());
|
||||
const uuid = await getMacPlatformUuid();
|
||||
if (!uuid) {
|
||||
return sendError(res, 'IOPlatformUUID not available, cannot derive TEA key');
|
||||
}
|
||||
const key = MacMachineInfoUtils.keyFromUuid(uuid);
|
||||
const machineIdInfoPath = MacMachineInfoUtils.getMachineIdInfoPath(dataPathGlobal);
|
||||
// SN 留空 = 沿用当前生效值: 优先 machineid-info 内已有 SN, 其次本机硬件 SN
|
||||
let snValue: string;
|
||||
if (typeof sn === 'string' && sn.length > 0) {
|
||||
snValue = sn;
|
||||
} else {
|
||||
const existing = MacMachineInfoUtils.readMachineIdInfo(machineIdInfoPath, key);
|
||||
snValue = existing?.sn || (await getMacSn());
|
||||
}
|
||||
// 自动备份
|
||||
try {
|
||||
MacMachineInfoUtils.backup(machineIdInfoPath);
|
||||
} catch { }
|
||||
MacMachineInfoUtils.writeMachineIdInfo(machineIdInfoPath, Buffer.from(machineId, 'hex'), snValue, key);
|
||||
const guid = MacMachineInfoUtils.computeGuid(Buffer.from(machineId, 'hex'), snValue);
|
||||
return sendSuccess(res, {
|
||||
message: 'machine_id set successfully',
|
||||
guid: guid.toString('hex'),
|
||||
guidUuid: MacMachineInfoUtils.guidToUuidStyle(guid),
|
||||
});
|
||||
} catch (e) {
|
||||
return sendError(res, `Failed to set machine_id: ${(e as Error).message}`);
|
||||
}
|
||||
};
|
||||
|
||||
// macOS: machineid-info 备份列表
|
||||
export const QQGetMacInfoBackupsHandler: RequestHandler = async (_, res) => {
|
||||
try {
|
||||
const dataPathGlobal = getGlobalDataPath(getQQDataPath());
|
||||
const backups = MacMachineInfoUtils.getBackups(MacMachineInfoUtils.getMachineIdInfoPath(dataPathGlobal));
|
||||
return sendSuccess(res, backups);
|
||||
} catch (e) {
|
||||
return sendError(res, `Failed to get backups: ${(e as Error).message}`);
|
||||
}
|
||||
};
|
||||
|
||||
// macOS: 创建 machineid-info 备份
|
||||
export const QQCreateMacInfoBackupHandler: RequestHandler = async (_, res) => {
|
||||
try {
|
||||
const dataPathGlobal = getGlobalDataPath(getQQDataPath());
|
||||
const backupPath = MacMachineInfoUtils.backup(MacMachineInfoUtils.getMachineIdInfoPath(dataPathGlobal));
|
||||
return sendSuccess(res, { message: 'Backup created', path: backupPath });
|
||||
} catch (e) {
|
||||
return sendError(res, `Failed to backup: ${(e as Error).message}`);
|
||||
}
|
||||
};
|
||||
|
||||
// macOS: 恢复 machineid-info 备份
|
||||
export const QQRestoreMacInfoBackupHandler: RequestHandler = async (req, res) => {
|
||||
const { backupName } = req.body;
|
||||
if (!backupName) {
|
||||
return sendError(res, 'Backup name is required');
|
||||
}
|
||||
try {
|
||||
const dataPathGlobal = getGlobalDataPath(getQQDataPath());
|
||||
MacMachineInfoUtils.restore(MacMachineInfoUtils.getMachineIdInfoPath(dataPathGlobal), backupName);
|
||||
return sendSuccess(res, { message: 'Restored successfully' });
|
||||
} catch (e) {
|
||||
return sendError(res, `Failed to restore: ${(e as Error).message}`);
|
||||
}
|
||||
};
|
||||
|
||||
// macOS: 重置设备信息 (删除 machineid-info, 回退到 MAC)
|
||||
export const QQResetMacDeviceIDHandler: RequestHandler = async (_, res) => {
|
||||
try {
|
||||
const dataPathGlobal = getGlobalDataPath(getQQDataPath());
|
||||
const machineIdInfoPath = MacMachineInfoUtils.getMachineIdInfoPath(dataPathGlobal);
|
||||
// 自动备份
|
||||
try {
|
||||
MacMachineInfoUtils.backup(machineIdInfoPath);
|
||||
} catch { }
|
||||
MacMachineInfoUtils.delete(machineIdInfoPath);
|
||||
return sendSuccess(res, { message: 'Device ID reset successfully (machineid-info deleted)' });
|
||||
} catch (e) {
|
||||
return sendError(res, `Failed to reset Device ID: ${(e as Error).message}`);
|
||||
}
|
||||
};
|
||||
|
||||
// ============================================================
|
||||
// OIDB 新设备 QR 验证
|
||||
// ============================================================
|
||||
|
||||
@@ -31,6 +31,13 @@ import {
|
||||
QQCreateLinuxMachineInfoBackupHandler,
|
||||
QQRestoreLinuxMachineInfoBackupHandler,
|
||||
QQResetLinuxDeviceIDHandler,
|
||||
QQGetMacGUIDInfoHandler,
|
||||
QQGetMacHardwareInfoHandler,
|
||||
QQSetMacMachineIdHandler,
|
||||
QQGetMacInfoBackupsHandler,
|
||||
QQCreateMacInfoBackupHandler,
|
||||
QQRestoreMacInfoBackupHandler,
|
||||
QQResetMacDeviceIDHandler,
|
||||
} from '@/napcat-webui-backend/src/api/QQLogin';
|
||||
|
||||
const router: Router = Router();
|
||||
@@ -99,4 +106,22 @@ router.post('/RestoreLinuxMachineInfoBackup', QQRestoreLinuxMachineInfoBackupHan
|
||||
// router:重置Linux设备信息
|
||||
router.post('/ResetLinuxDeviceID', QQResetLinuxDeviceIDHandler);
|
||||
|
||||
// ============================================================
|
||||
// macOS GUID 管理
|
||||
// ============================================================
|
||||
// router:获取macOS设备GUID信息
|
||||
router.post('/GetMacGUIDInfo', QQGetMacGUIDInfoHandler);
|
||||
// router:获取macOS硬件信息
|
||||
router.post('/GetMacHardwareInfo', QQGetMacHardwareInfoHandler);
|
||||
// router:设置macOS machine_id
|
||||
router.post('/SetMacMachineId', QQSetMacMachineIdHandler);
|
||||
// router:获取macOS machineid-info备份列表
|
||||
router.post('/GetMacInfoBackups', QQGetMacInfoBackupsHandler);
|
||||
// router:创建macOS machineid-info备份
|
||||
router.post('/CreateMacInfoBackup', QQCreateMacInfoBackupHandler);
|
||||
// router:恢复macOS machineid-info备份
|
||||
router.post('/RestoreMacInfoBackup', QQRestoreMacInfoBackupHandler);
|
||||
// router:重置macOS设备信息
|
||||
router.post('/ResetMacDeviceID', QQResetMacDeviceIDHandler);
|
||||
|
||||
export { router as QQLoginRouter };
|
||||
@@ -2,11 +2,105 @@ import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import os from 'node:os';
|
||||
import crypto from 'node:crypto';
|
||||
import { execFile } from 'node:child_process';
|
||||
import { protectData, unprotectData } from 'napcat-dpapi';
|
||||
|
||||
const GUID_HEADER = Buffer.from([0x00, 0x00, 0x00, 0x14]);
|
||||
const XOR_KEY = 0x10;
|
||||
|
||||
/** 备份文件统一后缀,形如 `<原文件名>.bak.20251010031234567-1a2b3c4d` */
|
||||
const BACKUP_SUFFIX = '.bak.';
|
||||
/** 兼容历史命名(秒级、无随机后缀)以及新命名(毫秒级+随机后缀) */
|
||||
const BACKUP_SUFFIX_PATTERN = /^\.bak\.\d{8,20}(?:-[0-9a-f]{1,32})?$/i;
|
||||
|
||||
/**
|
||||
* 由 QQ 数据根目录推导 global 目录。
|
||||
* Windows: <dataPath>/nt_qq/global
|
||||
* Linux : <dataPath>/global
|
||||
* macOS : <dataPath>/global
|
||||
*/
|
||||
export function getGlobalDataPath (dataPath: string): string {
|
||||
if (os.platform() === 'win32') {
|
||||
return path.join(dataPath, 'nt_qq', 'global');
|
||||
}
|
||||
return path.join(dataPath, 'global');
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成毫秒级(UTC)时间戳,避免同一秒内的连续备份互相覆盖。
|
||||
*/
|
||||
function backupTimestamp (): string {
|
||||
const now = new Date();
|
||||
const pad = (value: number, width = 2) => String(value).padStart(width, '0');
|
||||
return [
|
||||
now.getUTCFullYear(),
|
||||
pad(now.getUTCMonth() + 1),
|
||||
pad(now.getUTCDate()),
|
||||
pad(now.getUTCHours()),
|
||||
pad(now.getUTCMinutes()),
|
||||
pad(now.getUTCSeconds()),
|
||||
pad(now.getUTCMilliseconds(), 3),
|
||||
].join('');
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建备份文件。使用 `COPYFILE_EXCL` 落盘,杜绝同秒/连击时的无感知覆盖。
|
||||
*/
|
||||
function createBackupFile (filePath: string, missingMessage: string): string {
|
||||
if (!fs.existsSync(filePath)) {
|
||||
throw new Error(missingMessage);
|
||||
}
|
||||
const timestamp = backupTimestamp();
|
||||
for (let attempt = 0; attempt < 8; attempt++) {
|
||||
const randomSuffix = crypto.randomBytes(4).toString('hex');
|
||||
const backupPath = `${filePath}${BACKUP_SUFFIX}${timestamp}-${randomSuffix}`;
|
||||
try {
|
||||
fs.copyFileSync(filePath, backupPath, fs.constants.COPYFILE_EXCL);
|
||||
return backupPath;
|
||||
} catch (e) {
|
||||
// 仅在同名冲突时重试,其余错误(权限/磁盘等)直接抛出
|
||||
if ((e as NodeJS.ErrnoException).code !== 'EEXIST') throw e;
|
||||
}
|
||||
}
|
||||
throw new Error('Failed to create backup: too many name collisions');
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验并解析备份文件名,返回可安全读取的绝对路径。
|
||||
*
|
||||
* 安全约束(防止目录穿越与任意文件覆盖):
|
||||
* - 必须是纯文件名,不能包含路径分隔符或 `..`;
|
||||
* - 必须匹配 `<原文件名>.bak.<时间戳>[-随机后缀]`;
|
||||
* - 必须存在于调用方提供的备份白名单中(来自 `readdirSync`)。
|
||||
*/
|
||||
export function resolveBackupPath (filePath: string, backupFileName: string, backupList: string[]): string {
|
||||
if (typeof backupFileName !== 'string' || backupFileName.length === 0) {
|
||||
throw new Error('Backup name is required');
|
||||
}
|
||||
if (
|
||||
backupFileName !== path.basename(backupFileName) ||
|
||||
backupFileName.includes('/') ||
|
||||
backupFileName.includes('\\') ||
|
||||
backupFileName.includes('..')
|
||||
) {
|
||||
throw new Error('Invalid backup name');
|
||||
}
|
||||
|
||||
const baseName = path.basename(filePath);
|
||||
if (!backupFileName.startsWith(baseName)) {
|
||||
throw new Error('Invalid backup name');
|
||||
}
|
||||
const suffix = backupFileName.slice(baseName.length);
|
||||
if (!BACKUP_SUFFIX_PATTERN.test(suffix)) {
|
||||
throw new Error('Invalid backup name');
|
||||
}
|
||||
if (!backupList.includes(backupFileName)) {
|
||||
throw new Error('Backup file not found');
|
||||
}
|
||||
|
||||
return path.join(path.dirname(filePath), backupFileName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Unprotects data using Windows DPAPI via napcat-dpapi.
|
||||
*/
|
||||
@@ -25,7 +119,7 @@ function dpapiProtectAndWrite (filePath: string, data: Buffer): void {
|
||||
|
||||
export class Registry20Utils {
|
||||
static getRegistryPath (dataPath: string): string {
|
||||
return path.join(dataPath, 'nt_qq', 'global', 'nt_data', 'msf', 'Registry20');
|
||||
return path.join(getGlobalDataPath(dataPath), 'nt_data', 'msf', 'Registry20');
|
||||
}
|
||||
|
||||
static readGuid (registryPath: string): string {
|
||||
@@ -91,20 +185,14 @@ export class Registry20Utils {
|
||||
}
|
||||
|
||||
static backup (registryPath: string): string {
|
||||
if (!fs.existsSync(registryPath)) {
|
||||
throw new Error('Registry20 does not exist');
|
||||
}
|
||||
const timestamp = new Date().toISOString().replace(/[-:T.]/g, '').slice(0, 14);
|
||||
const backupPath = `${registryPath}.bak.${timestamp}`;
|
||||
fs.copyFileSync(registryPath, backupPath);
|
||||
return backupPath;
|
||||
return createBackupFile(registryPath, 'Registry20 does not exist');
|
||||
}
|
||||
|
||||
static restore (registryPath: string, backupFileName: string): void {
|
||||
const dir = path.dirname(registryPath);
|
||||
const backupPath = path.join(dir, backupFileName);
|
||||
if (!fs.existsSync(backupPath)) {
|
||||
throw new Error('Backup file not found');
|
||||
const backupPath = resolveBackupPath(registryPath, backupFileName, Registry20Utils.getBackups(registryPath));
|
||||
// 内容校验: DPAPI 密文不可能为空
|
||||
if (fs.statSync(backupPath).size === 0) {
|
||||
throw new Error('Invalid backup content');
|
||||
}
|
||||
fs.copyFileSync(backupPath, registryPath);
|
||||
}
|
||||
@@ -147,7 +235,7 @@ export class MachineInfoUtils {
|
||||
* 获取 machine-info 文件路径
|
||||
*/
|
||||
static getMachineInfoPath (dataPath: string): string {
|
||||
return path.join(dataPath, 'nt_qq', 'global', 'nt_data', 'msf', 'machine-info');
|
||||
return path.join(getGlobalDataPath(dataPath), 'nt_data', 'msf', 'machine-info');
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -243,24 +331,20 @@ export class MachineInfoUtils {
|
||||
* 创建备份
|
||||
*/
|
||||
static backup (machineInfoPath: string): string {
|
||||
if (!fs.existsSync(machineInfoPath)) {
|
||||
throw new Error('machine-info file does not exist');
|
||||
}
|
||||
const timestamp = new Date().toISOString().replace(/[-:T.]/g, '').slice(0, 14);
|
||||
const backupPath = `${machineInfoPath}.bak.${timestamp}`;
|
||||
fs.copyFileSync(machineInfoPath, backupPath);
|
||||
return backupPath;
|
||||
return createBackupFile(machineInfoPath, 'machine-info file does not exist');
|
||||
}
|
||||
|
||||
/**
|
||||
* 恢复备份
|
||||
*/
|
||||
static restore (machineInfoPath: string, backupFileName: string): void {
|
||||
const dir = path.dirname(machineInfoPath);
|
||||
const backupPath = path.join(dir, backupFileName);
|
||||
if (!fs.existsSync(backupPath)) {
|
||||
throw new Error('Backup file not found');
|
||||
}
|
||||
const backupPath = resolveBackupPath(
|
||||
machineInfoPath,
|
||||
backupFileName,
|
||||
MachineInfoUtils.getBackups(machineInfoPath)
|
||||
);
|
||||
// 内容校验: 必须符合 machine-info 的 be32 长度 + ROT13 结构
|
||||
MachineInfoUtils.readMac(backupPath);
|
||||
fs.copyFileSync(backupPath, machineInfoPath);
|
||||
}
|
||||
|
||||
@@ -273,3 +357,506 @@ export class MachineInfoUtils {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// macOS TEA 容器 / machineid-info 工具类
|
||||
// ============================================================
|
||||
|
||||
const TEA_DELTA = 0x9E3779B9;
|
||||
|
||||
function teaKeyWords (key: Buffer): [number, number, number, number] {
|
||||
const padded = Buffer.concat([key, Buffer.alloc(Math.max(0, 16 - key.length))]).subarray(0, 16);
|
||||
return [
|
||||
padded.readUInt32BE(0),
|
||||
padded.readUInt32BE(4),
|
||||
padded.readUInt32BE(8),
|
||||
padded.readUInt32BE(12),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 单块 TEA 加密 (16 轮, delta 0x9E3779B9, 密钥与数据均按大端处理)
|
||||
* 逆向自 macOS wrapper.node sub_4127C1C
|
||||
*/
|
||||
export function teaEncryptBlock (block: Buffer, key: Buffer): Buffer {
|
||||
if (block.length !== 8) {
|
||||
throw new Error('TEA block must be 8 bytes');
|
||||
}
|
||||
let v0 = block.readUInt32BE(0);
|
||||
let v1 = block.readUInt32BE(4);
|
||||
const [k0, k1, k2, k3] = teaKeyWords(key);
|
||||
let sum = TEA_DELTA;
|
||||
for (let i = 0; i < 16; i++) {
|
||||
v0 = (v0 + ((((v1 << 4) + k0) ^ (v1 + sum) ^ ((v1 >>> 5) + k1)) >>> 0)) >>> 0;
|
||||
v1 = (v1 + ((((v0 << 4) + k2) ^ (v0 + sum) ^ ((v0 >>> 5) + k3)) >>> 0)) >>> 0;
|
||||
sum = (sum + TEA_DELTA) >>> 0;
|
||||
}
|
||||
const out = Buffer.alloc(8);
|
||||
out.writeUInt32BE(v0, 0);
|
||||
out.writeUInt32BE(v1, 4);
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* 单块 TEA 解密 -> sub_4127CE5
|
||||
*/
|
||||
export function teaDecryptBlock (block: Buffer, key: Buffer): Buffer {
|
||||
if (block.length !== 8) {
|
||||
throw new Error('TEA block must be 8 bytes');
|
||||
}
|
||||
let v0 = block.readUInt32BE(0);
|
||||
let v1 = block.readUInt32BE(4);
|
||||
const [k0, k1, k2, k3] = teaKeyWords(key);
|
||||
let sum = (TEA_DELTA * 16) >>> 0;
|
||||
for (let i = 0; i < 16; i++) {
|
||||
v1 = (v1 - ((((v0 << 4) + k2) ^ (v0 + sum) ^ ((v0 >>> 5) + k3)) >>> 0)) >>> 0;
|
||||
v0 = (v0 - ((((v1 << 4) + k0) ^ (v1 + sum) ^ ((v1 >>> 5) + k1)) >>> 0)) >>> 0;
|
||||
sum = (sum - TEA_DELTA) >>> 0;
|
||||
}
|
||||
const out = Buffer.alloc(8);
|
||||
out.writeUInt32BE(v0, 0);
|
||||
out.writeUInt32BE(v1, 4);
|
||||
return out;
|
||||
}
|
||||
|
||||
function xor8 (a: Buffer, b: Buffer): Buffer {
|
||||
const out = Buffer.alloc(8);
|
||||
for (let i = 0; i < 8; i++) out[i] = a[i]! ^ b[i]!;
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* QQ 加密容器封装 -> sub_414B658
|
||||
* P_i = X_i XOR C_(i-1)
|
||||
* C_i = E(P_i) XOR P_(i-1)
|
||||
* X = [head][v8 random][2 random] + payload + 00*7
|
||||
*/
|
||||
export function containerEncrypt (payload: Buffer, key: Buffer, rng: (n: number) => Buffer = crypto.randomBytes): Buffer {
|
||||
const n = payload.length;
|
||||
// 注意: Python 的 % 结果非负, JS 对负数会返回负数, 这里手动取模
|
||||
const v8 = ((8 - ((n + 10) % 8)) % 8);
|
||||
const head = Buffer.from([(rng(1)[0]! & 0xF8) | v8]);
|
||||
const stream = Buffer.concat([head, rng(v8), rng(2), payload, Buffer.alloc(7)]);
|
||||
const out = Buffer.alloc(stream.length);
|
||||
let pPrev: Buffer = Buffer.alloc(8);
|
||||
let cPrev: Buffer = Buffer.alloc(8);
|
||||
for (let i = 0; i < stream.length; i += 8) {
|
||||
const xI = stream.subarray(i, i + 8);
|
||||
const pI = xor8(xI, cPrev);
|
||||
const cI = xor8(teaEncryptBlock(pI, key), pPrev);
|
||||
cI.copy(out, i);
|
||||
pPrev = pI;
|
||||
cPrev = cI;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* QQ 加密容器解封 -> sub_4128416, 失败返回 null
|
||||
*/
|
||||
export function containerDecrypt (data: Buffer, key: Buffer, checkTail = true): Buffer | null {
|
||||
if (data.length < 16 || data.length % 8 !== 0) return null;
|
||||
const stream = Buffer.alloc(data.length);
|
||||
let pPrev: Buffer = Buffer.alloc(8);
|
||||
let cPrev: Buffer = Buffer.alloc(8);
|
||||
for (let i = 0; i < data.length; i += 8) {
|
||||
const cI = data.subarray(i, i + 8);
|
||||
const pI = i === 0 ? teaDecryptBlock(cI, key) : teaDecryptBlock(xor8(pPrev, cI), key);
|
||||
xor8(pI, cPrev).copy(stream, i);
|
||||
pPrev = pI;
|
||||
cPrev = cI;
|
||||
}
|
||||
const v8 = stream[0]! & 0x07;
|
||||
const n = data.length - v8 - 10;
|
||||
if (n < 0) return null;
|
||||
const start = v8 + 3;
|
||||
const payload = stream.subarray(start, start + n);
|
||||
const tail = stream.subarray(start + n);
|
||||
if (checkTail && tail.some((b) => b !== 0)) return null;
|
||||
return Buffer.from(payload);
|
||||
}
|
||||
|
||||
function buildFields (...chunks: Buffer[]): Buffer {
|
||||
const parts: Buffer[] = [];
|
||||
for (const chunk of chunks) {
|
||||
const len = Buffer.alloc(4);
|
||||
len.writeUInt32BE(chunk.length, 0);
|
||||
parts.push(len, chunk);
|
||||
}
|
||||
return Buffer.concat(parts);
|
||||
}
|
||||
|
||||
function parseFields (plain: Buffer): Buffer[] {
|
||||
const fields: Buffer[] = [];
|
||||
let off = 0;
|
||||
while (off + 4 <= plain.length) {
|
||||
const len = plain.readUInt32BE(off);
|
||||
off += 4;
|
||||
if (off + len > plain.length) {
|
||||
fields.push(plain.subarray(off));
|
||||
break;
|
||||
}
|
||||
fields.push(plain.subarray(off, off + len));
|
||||
off += len;
|
||||
}
|
||||
return fields;
|
||||
}
|
||||
|
||||
export interface MacMachineInfo {
|
||||
machineId: Buffer;
|
||||
sn: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* macOS machine-info 工具类
|
||||
*
|
||||
* 文件位置 (相对 QQ global 目录):
|
||||
* nt_data/msf/machineid-info —— TEA 容器, 明文 = be32(8)+machine_id[8] + be32(len)+sn
|
||||
* nt_data/msf/machine-info —— 明文 be32(8) + [MAC(6) + 00 00]
|
||||
* nt_data/msf/machine-guid —— 明文 16 字节 guid
|
||||
*/
|
||||
export class MacMachineInfoUtils {
|
||||
static getMsfDir (dataPathGlobal: string): string {
|
||||
return path.join(dataPathGlobal, 'nt_data', 'msf');
|
||||
}
|
||||
|
||||
static getMachineIdInfoPath (dataPathGlobal: string): string {
|
||||
return path.join(MacMachineInfoUtils.getMsfDir(dataPathGlobal), 'machineid-info');
|
||||
}
|
||||
|
||||
static getMachineInfoPath (dataPathGlobal: string): string {
|
||||
return path.join(MacMachineInfoUtils.getMsfDir(dataPathGlobal), 'machine-info');
|
||||
}
|
||||
|
||||
static getMachineGuidPath (dataPathGlobal: string): string {
|
||||
return path.join(MacMachineInfoUtils.getMsfDir(dataPathGlobal), 'machine-guid');
|
||||
}
|
||||
|
||||
/**
|
||||
* TEA 密钥 = IOPlatformUUID 字符串前 16 字节 (不足补 0)
|
||||
*/
|
||||
static keyFromUuid (uuid: string): Buffer {
|
||||
return Buffer.concat([Buffer.from(uuid, 'utf8').subarray(0, 16), Buffer.alloc(16)]).subarray(0, 16);
|
||||
}
|
||||
|
||||
static guidToUuidStyle (guid: Buffer, upper = true): string {
|
||||
const s = guid.toString('hex');
|
||||
const out = `${s.slice(0, 8)}-${s.slice(8, 12)}-${s.slice(12, 16)}-${s.slice(16, 20)}-${s.slice(20, 32)}`;
|
||||
return upper ? out.toUpperCase() : out;
|
||||
}
|
||||
|
||||
static buildMachineIdInfo (machineId: Buffer, sn: string): Buffer {
|
||||
if (machineId.length !== 8) {
|
||||
throw new Error('machine_id must be 8 bytes');
|
||||
}
|
||||
return buildFields(machineId, Buffer.from(sn, 'utf8'));
|
||||
}
|
||||
|
||||
static parseMachineIdInfo (plain: Buffer): MacMachineInfo {
|
||||
const fields = parseFields(plain);
|
||||
const machineId = fields[0]?.subarray(0, 8) ?? Buffer.alloc(0);
|
||||
const sn = fields[1] ? fields[1].toString('utf8') : '';
|
||||
return { machineId: Buffer.from(machineId), sn };
|
||||
}
|
||||
|
||||
/**
|
||||
* guid = MD5(machine_id[8] || sn) -> sub_414E158
|
||||
*/
|
||||
static computeGuid (machineId: Buffer, sn: string): Buffer {
|
||||
const md5 = crypto.createHash('md5');
|
||||
md5.update(machineId.subarray(0, 8));
|
||||
md5.update(sn, 'utf8');
|
||||
return md5.digest();
|
||||
}
|
||||
|
||||
static readMachineIdInfo (filePath: string, key: Buffer, checkTail = true): MacMachineInfo | null {
|
||||
if (!fs.existsSync(filePath)) return null;
|
||||
const plain = containerDecrypt(fs.readFileSync(filePath), key, checkTail);
|
||||
if (!plain) return null;
|
||||
return MacMachineInfoUtils.parseMachineIdInfo(plain);
|
||||
}
|
||||
|
||||
static writeMachineIdInfo (filePath: string, machineId: Buffer, sn: string, key: Buffer): void {
|
||||
const plain = MacMachineInfoUtils.buildMachineIdInfo(machineId, sn);
|
||||
const encrypted = containerEncrypt(plain, key);
|
||||
const dir = path.dirname(filePath);
|
||||
if (!fs.existsSync(dir)) {
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
}
|
||||
fs.writeFileSync(filePath, encrypted);
|
||||
}
|
||||
|
||||
/**
|
||||
* machine-info 是明文 be32(8) + 8 字节 (MAC(6) + 00 00)
|
||||
*/
|
||||
static readMachineId (filePath: string): Buffer | null {
|
||||
if (!fs.existsSync(filePath)) return null;
|
||||
const data = fs.readFileSync(filePath);
|
||||
if (data.length < 4) return null;
|
||||
const len = data.readUInt32BE(0);
|
||||
if (len < 8 || data.length < 4 + len) return null;
|
||||
return Buffer.from(data.subarray(4, 4 + 8));
|
||||
}
|
||||
|
||||
static readMachineGuid (filePath: string): Buffer | null {
|
||||
if (!fs.existsSync(filePath)) return null;
|
||||
const data = fs.readFileSync(filePath);
|
||||
if (data.length < 16) return null;
|
||||
return Buffer.from(data.subarray(0, 16));
|
||||
}
|
||||
|
||||
static getBackups (filePath: string): string[] {
|
||||
const dir = path.dirname(filePath);
|
||||
const baseName = path.basename(filePath);
|
||||
if (!fs.existsSync(dir)) return [];
|
||||
|
||||
return fs.readdirSync(dir)
|
||||
.filter(f => f.startsWith(`${baseName}.bak.`))
|
||||
.sort()
|
||||
.reverse();
|
||||
}
|
||||
|
||||
static backup (filePath: string): string {
|
||||
return createBackupFile(filePath, 'machineid-info file does not exist');
|
||||
}
|
||||
|
||||
static restore (filePath: string, backupFileName: string): void {
|
||||
const backupPath = resolveBackupPath(filePath, backupFileName, MacMachineInfoUtils.getBackups(filePath));
|
||||
// 内容校验: TEA 容器按 8 字节分组, 至少 16 字节
|
||||
const size = fs.statSync(backupPath).size;
|
||||
if (size < 16 || size % 8 !== 0) {
|
||||
throw new Error('Invalid backup content');
|
||||
}
|
||||
fs.copyFileSync(backupPath, filePath);
|
||||
}
|
||||
|
||||
static delete (filePath: string): void {
|
||||
if (fs.existsSync(filePath)) {
|
||||
fs.unlinkSync(filePath);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// macOS 本机硬件读取 (与 wrapper.node 的行为保持一致)
|
||||
// ============================================================
|
||||
|
||||
interface HardwareCacheEntry<T> {
|
||||
promise: Promise<T>;
|
||||
}
|
||||
|
||||
const hardwareCache = new Map<string, HardwareCacheEntry<unknown>>();
|
||||
|
||||
/**
|
||||
* 进程内硬件信息缓存。硬件标识在进程生命周期内不会变化,
|
||||
* 缓存 `Promise` 可避免并发请求重复拉起 `ioreg`/`diskutil`。
|
||||
*/
|
||||
function cachedHardware<T> (key: string, factory: () => Promise<T>): Promise<T> {
|
||||
const existing = hardwareCache.get(key);
|
||||
if (existing) return existing.promise as Promise<T>;
|
||||
const entry: HardwareCacheEntry<T> = { promise: factory() };
|
||||
hardwareCache.set(key, entry as HardwareCacheEntry<unknown>);
|
||||
return entry.promise;
|
||||
}
|
||||
|
||||
function runCommand (file: string, args: string[]): Promise<string | null> {
|
||||
return new Promise((resolve) => {
|
||||
execFile(file, args, { timeout: 10000, encoding: 'utf8', maxBuffer: 4 * 1024 * 1024 }, (error, stdout) => {
|
||||
if (error) {
|
||||
resolve(null);
|
||||
return;
|
||||
}
|
||||
resolve(stdout);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 从 `ioreg` 输出中解析 `"property" = <value>`。
|
||||
*/
|
||||
function parseIoregProperty (out: string, property: string): string | null {
|
||||
for (const line of out.split('\n')) {
|
||||
if (line.includes(`"${property}"`) && line.includes('=')) {
|
||||
const raw = line.split('=').slice(1).join('=').trim();
|
||||
return raw.replace(/^"|"$/g, '');
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 运行 `ioreg -rd1 -c <className>` 并缓存结果。
|
||||
*/
|
||||
function ioregClassOutput (className: string): Promise<string | null> {
|
||||
return cachedHardware(`ioreg:${className}`, () => runCommand('ioreg', ['-rd1', '-c', className]));
|
||||
}
|
||||
|
||||
/**
|
||||
* TEA 密钥来源: IOPlatformUUID
|
||||
*/
|
||||
export function getMacPlatformUuid (): Promise<string | null> {
|
||||
return cachedHardware('mac:platformUuid', async () => {
|
||||
const out = await ioregClassOutput('IOPlatformExpertDevice');
|
||||
return out ? parseIoregProperty(out, 'IOPlatformUUID') : null;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 序列号回退: IOPlatformSerialNumber
|
||||
*/
|
||||
export function getMacSerialNumber (): Promise<string | null> {
|
||||
return cachedHardware('mac:serialNumber', async () => {
|
||||
const out = await ioregClassOutput('IOPlatformExpertDevice');
|
||||
return out ? parseIoregProperty(out, 'IOPlatformSerialNumber') : null;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 优先 /dev/disk0 的序列号 (对应 wrapper.node sub_414CD1C)
|
||||
*/
|
||||
export function getMacDiskSerial (): Promise<string | null> {
|
||||
return cachedHardware('mac:diskSerial', async () => {
|
||||
const out = await runCommand('diskutil', ['info', '/dev/disk0']);
|
||||
if (!out) return null;
|
||||
for (const line of out.split('\n')) {
|
||||
if (line.includes('Serial Number') || line.includes('设备序列号')) {
|
||||
return line.split(':').slice(1).join(':').trim();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* macOS 序列号: 优先 /dev/disk0, 失败回退 IOPlatformSerialNumber
|
||||
*/
|
||||
export async function getMacSn (): Promise<string> {
|
||||
return (await getMacDiskSerial()) ?? (await getMacSerialNumber()) ?? '';
|
||||
}
|
||||
|
||||
/**
|
||||
* 从 ioreg 节点行中提取 `"IOMACAddress" = <...>` 的 6 字节 MAC。
|
||||
*/
|
||||
function parseIomacAddress (line: string): Buffer | null {
|
||||
const blob = line.split('=').slice(1).join('=');
|
||||
const hex = (blob.match(/[0-9a-fA-F]{2}/g) ?? []).join('');
|
||||
if (hex.length >= 12) {
|
||||
return Buffer.from(hex.slice(0, 12), 'hex');
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** 按 `+-o ` 节点行切分 ioreg 输出。 */
|
||||
function splitIoregNodes (out: string): string[] {
|
||||
const nodes: string[] = [];
|
||||
let current: string[] = [];
|
||||
for (const line of out.split('\n')) {
|
||||
if (line.includes('+-o ')) {
|
||||
if (current.length > 0) nodes.push(current.join('\n'));
|
||||
current = [line];
|
||||
} else if (current.length > 0) {
|
||||
current.push(line);
|
||||
}
|
||||
}
|
||||
if (current.length > 0) nodes.push(current.join('\n'));
|
||||
return nodes;
|
||||
}
|
||||
|
||||
/** 从节点文本中取 IOMACAddress。 */
|
||||
function nodeMac (node: string): Buffer | null {
|
||||
const line = node.split('\n').find((l) => l.includes('"IOMACAddress"'));
|
||||
return line ? parseIomacAddress(line) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 主网卡 MAC。
|
||||
*
|
||||
* wrapper.node 取的是 IOEthernetInterface 上(或其父控制器上)的 IOMACAddress。
|
||||
* 真实 ioreg 层级里 IOMACAddress 通常挂在父级控制器(如 en0 对应的
|
||||
* IOEthernetController)上,且同一层级下可能有多个接口,因此这里:
|
||||
* 1. 优先匹配 BSD Name 为 en0 的接口;
|
||||
* 2. 其次匹配第一个 USB/以太网控制器上的接口;
|
||||
* 3. 若接口自身没有该属性,则回到 `ioreg -c IOEthernetInterface` 的整个子树中查找,
|
||||
* 兼容 IOMACAddress 挂在父级控制器的情况。
|
||||
*/
|
||||
export function getMacPrimaryMac (): Promise<Buffer | null> {
|
||||
return cachedHardware('mac:primaryMac', async () => {
|
||||
const ifOut = await ioregClassOutput('IOEthernetInterface');
|
||||
const nodes = ifOut ? splitIoregNodes(ifOut) : [];
|
||||
const en0 = nodes.find((node) => node.includes('"BSD Name" = "en0"'));
|
||||
|
||||
// 1. en0 接口自身的 IOMACAddress
|
||||
if (en0) {
|
||||
const mac = nodeMac(en0);
|
||||
if (mac) return mac;
|
||||
}
|
||||
|
||||
// 2. 父级以太网控制器上的 IOMACAddress(真实机器上多数情况下挂在这里)
|
||||
const controllerOut = await ioregClassOutput('IOEthernetController');
|
||||
if (controllerOut) {
|
||||
for (const node of splitIoregNodes(controllerOut)) {
|
||||
const mac = nodeMac(node);
|
||||
if (mac) return mac;
|
||||
}
|
||||
}
|
||||
|
||||
// 3. 任意 IOEthernetInterface 自身的 IOMACAddress
|
||||
for (const node of nodes) {
|
||||
const mac = nodeMac(node);
|
||||
if (mac) return mac;
|
||||
}
|
||||
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
export interface MacGuidInfo {
|
||||
guid: string;
|
||||
guidUuid: string;
|
||||
machineId: string;
|
||||
sn: string;
|
||||
mac: string;
|
||||
platformUuid: string;
|
||||
source: 'machineid-info' | 'mac-fallback';
|
||||
}
|
||||
|
||||
/**
|
||||
* 主流程 (对应 wrapper.node GetMachineGuid4MacOS):
|
||||
* guid = MD5(machine_id[8] || sn)
|
||||
* machine_id 优先从 machineid-info (TEA) 读取, 否则回退成 MAC + 00 00
|
||||
*/
|
||||
export async function computeMacGuidInfo (dataPathGlobal: string, uuidOverride?: string, snOverride?: string): Promise<MacGuidInfo> {
|
||||
const platformUuid = uuidOverride ?? (await getMacPlatformUuid()) ?? '';
|
||||
const key = MacMachineInfoUtils.keyFromUuid(platformUuid);
|
||||
const sn = snOverride ?? (await getMacSn());
|
||||
const machineIdInfoPath = MacMachineInfoUtils.getMachineIdInfoPath(dataPathGlobal);
|
||||
const primaryMac = await getMacPrimaryMac();
|
||||
|
||||
let machineId: Buffer | null = null;
|
||||
let source: MacGuidInfo['source'] = 'machineid-info';
|
||||
let snValue = sn;
|
||||
|
||||
const fromFile = MacMachineInfoUtils.readMachineIdInfo(machineIdInfoPath, key);
|
||||
if (fromFile && fromFile.machineId.length === 8) {
|
||||
machineId = fromFile.machineId;
|
||||
if (!snOverride && fromFile.sn) snValue = fromFile.sn;
|
||||
} else {
|
||||
const mac = primaryMac;
|
||||
if (!mac) {
|
||||
throw new Error('Unable to determine machine_id (no machineid-info and no MAC)');
|
||||
}
|
||||
machineId = Buffer.concat([mac, Buffer.from([0, 0])]);
|
||||
source = 'mac-fallback';
|
||||
}
|
||||
|
||||
const guid = MacMachineInfoUtils.computeGuid(machineId, snValue);
|
||||
return {
|
||||
guid: guid.toString('hex'),
|
||||
guidUuid: MacMachineInfoUtils.guidToUuidStyle(guid),
|
||||
machineId: machineId.toString('hex'),
|
||||
sn: snValue,
|
||||
mac: primaryMac?.toString('hex') ?? '',
|
||||
platformUuid,
|
||||
source,
|
||||
};
|
||||
}
|
||||
@@ -8,6 +8,8 @@ import { useEffect, useState, useCallback, useMemo } from 'react';
|
||||
import toast from 'react-hot-toast';
|
||||
import { MdContentCopy, MdDelete, MdRefresh, MdSave, MdRestorePage, MdBackup } from 'react-icons/md';
|
||||
import MD5 from 'crypto-js/md5';
|
||||
import Hex from 'crypto-js/enc-hex';
|
||||
import Utf8 from 'crypto-js/enc-utf8';
|
||||
|
||||
import QQManager from '@/controllers/qq_manager';
|
||||
import useDialog from '@/hooks/use-dialog';
|
||||
@@ -40,6 +42,16 @@ const GUIDManager: React.FC<GUIDManagerProps> = ({ showRestart = true, compact =
|
||||
const [machineId, setMachineId] = useState<string>('');
|
||||
const [linuxBackups, setLinuxBackups] = useState<string[]>([]);
|
||||
|
||||
// macOS 状态
|
||||
const [macGuid, setMacGuid] = useState<string>('');
|
||||
const [macSource, setMacSource] = useState<string>('');
|
||||
const [macInfo, setMacInfo] = useState<{ machineId: string; sn: string; mac: string; platformUuid: string; }>({
|
||||
machineId: '', sn: '', mac: '', platformUuid: '',
|
||||
});
|
||||
const [inputMachineId, setInputMachineId] = useState<string>('');
|
||||
const [inputSn, setInputSn] = useState<string>('');
|
||||
const [macBackups, setMacBackups] = useState<string[]>([]);
|
||||
|
||||
// 通用状态
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [saving, setSaving] = useState(false);
|
||||
@@ -47,6 +59,7 @@ const GUIDManager: React.FC<GUIDManagerProps> = ({ showRestart = true, compact =
|
||||
|
||||
const isValidGUID = (guid: string) => /^[0-9a-fA-F]{32}$/.test(guid);
|
||||
const isValidMAC = (mac: string) => /^[0-9a-fA-F]{2}(-[0-9a-fA-F]{2}){5}$/.test(mac.trim().toLowerCase());
|
||||
const isValidMachineId = (id: string) => /^[0-9a-fA-F]{16}$/.test(id.trim());
|
||||
|
||||
// 前端实时计算 Linux GUID = MD5(machine-id + MAC)
|
||||
const computedLinuxGUID = useMemo(() => {
|
||||
@@ -62,6 +75,28 @@ const GUIDManager: React.FC<GUIDManagerProps> = ({ showRestart = true, compact =
|
||||
return MD5(machineId + currentMAC).toString();
|
||||
}, [isLinux, machineId, currentMAC]);
|
||||
|
||||
// macOS: GUID = MD5(machine_id[8 字节] || sn)
|
||||
const macGuidOf = useCallback((machineIdHex: string, sn: string) => {
|
||||
if (!isValidMachineId(machineIdHex)) return '';
|
||||
const mid = Hex.parse(machineIdHex.trim().toLowerCase());
|
||||
return MD5(mid.concat(Utf8.parse(sn))).toString();
|
||||
}, []);
|
||||
|
||||
// macOS: SN 留空 = 沿用当前生效值 (与后端一致)
|
||||
const effectiveMacSn = inputSn === '' ? macInfo.sn : inputSn;
|
||||
|
||||
// macOS: 实时预览 (基于输入的 machine_id / 有效 SN)
|
||||
const computedMacGUID = useMemo(() => {
|
||||
if (!isMac) return '';
|
||||
if (!isValidMachineId(inputMachineId)) return '';
|
||||
return macGuidOf(inputMachineId, effectiveMacSn);
|
||||
}, [isMac, inputMachineId, effectiveMacSn, macGuidOf]);
|
||||
|
||||
// macOS: machine_id 或 SN 任一与当前值不同即视为可保存
|
||||
const macDirty = isValidMachineId(inputMachineId) && (
|
||||
inputMachineId.trim().toLowerCase() !== macInfo.machineId || effectiveMacSn !== macInfo.sn
|
||||
);
|
||||
|
||||
// 检测平台
|
||||
const fetchPlatform = useCallback(async () => {
|
||||
try {
|
||||
@@ -131,6 +166,40 @@ const GUIDManager: React.FC<GUIDManagerProps> = ({ showRestart = true, compact =
|
||||
}
|
||||
}, []);
|
||||
|
||||
// macOS: 获取 GUID 信息 + 硬件信息
|
||||
const fetchMacInfo = useCallback(async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const info = await QQManager.getMacGUIDInfo();
|
||||
setMacGuid(info.guid);
|
||||
setMacSource(info.source);
|
||||
setMacInfo({
|
||||
machineId: info.machineId,
|
||||
sn: info.sn,
|
||||
mac: info.mac,
|
||||
platformUuid: info.platformUuid,
|
||||
});
|
||||
setInputMachineId(info.machineId);
|
||||
setInputSn(info.sn);
|
||||
} catch (error) {
|
||||
const msg = (error as Error).message;
|
||||
setMacGuid('');
|
||||
toast.error(`获取 GUID 失败: ${msg}`);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
// macOS: 获取备份
|
||||
const fetchMacBackups = useCallback(async () => {
|
||||
try {
|
||||
const data = await QQManager.getMacInfoBackups();
|
||||
setMacBackups(data);
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
fetchPlatform();
|
||||
}, [fetchPlatform]);
|
||||
@@ -140,11 +209,14 @@ const GUIDManager: React.FC<GUIDManagerProps> = ({ showRestart = true, compact =
|
||||
if (isWindows) {
|
||||
fetchGUID();
|
||||
fetchBackups();
|
||||
} else if (isMac) {
|
||||
fetchMacInfo();
|
||||
fetchMacBackups();
|
||||
} else {
|
||||
fetchLinuxInfo();
|
||||
fetchLinuxBackups();
|
||||
}
|
||||
}, [platformDetected, isWindows, fetchGUID, fetchBackups, fetchLinuxInfo, fetchLinuxBackups]);
|
||||
}, [platformDetected, isWindows, isMac, fetchGUID, fetchBackups, fetchLinuxInfo, fetchLinuxBackups, fetchMacInfo, fetchMacBackups]);
|
||||
|
||||
// ========== Windows 操作 ==========
|
||||
|
||||
@@ -310,6 +382,86 @@ const GUIDManager: React.FC<GUIDManagerProps> = ({ showRestart = true, compact =
|
||||
|
||||
// ========== 重启 ==========
|
||||
|
||||
// ========== macOS 操作 ==========
|
||||
|
||||
const handleMacSave = async () => {
|
||||
const mid = inputMachineId.trim().toLowerCase();
|
||||
if (!isValidMachineId(mid)) {
|
||||
toast.error('machine_id 格式无效,需要 16 位十六进制字符');
|
||||
return;
|
||||
}
|
||||
setSaving(true);
|
||||
try {
|
||||
await QQManager.setMacMachineId(mid, inputSn);
|
||||
toast.success('machine_id 已设置,重启后生效');
|
||||
await fetchMacInfo();
|
||||
await fetchMacBackups();
|
||||
} catch (error) {
|
||||
const msg = (error as Error).message;
|
||||
toast.error(`设置 machine_id 失败: ${msg}`);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleMacCopy = (text: string, label: string) => {
|
||||
if (text) {
|
||||
navigator.clipboard.writeText(text);
|
||||
toast.success(`${label} 已复制到剪贴板`);
|
||||
}
|
||||
};
|
||||
|
||||
const handleMacDelete = () => {
|
||||
dialog.confirm({
|
||||
title: '确认删除',
|
||||
content: '删除 machineid-info 后,QQ 将回退到基于网卡 MAC 的设备标识。确定要删除吗?',
|
||||
confirmText: '删除',
|
||||
cancelText: '取消',
|
||||
onConfirm: async () => {
|
||||
try {
|
||||
await QQManager.resetMacDeviceID();
|
||||
toast.success('已删除,重启后生效');
|
||||
await fetchMacInfo();
|
||||
await fetchMacBackups();
|
||||
} catch (error) {
|
||||
const msg = (error as Error).message;
|
||||
toast.error(`删除失败: ${msg}`);
|
||||
}
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
const handleMacBackup = async () => {
|
||||
try {
|
||||
await QQManager.createMacInfoBackup();
|
||||
toast.success('备份已创建');
|
||||
await fetchMacBackups();
|
||||
} catch (error) {
|
||||
const msg = (error as Error).message;
|
||||
toast.error(`备份失败: ${msg}`);
|
||||
}
|
||||
};
|
||||
|
||||
const handleMacRestore = (backupName: string) => {
|
||||
dialog.confirm({
|
||||
title: '确认恢复',
|
||||
content: `确定要从备份 "${backupName}" 恢复吗?当前的 machineid-info 将被覆盖。`,
|
||||
confirmText: '恢复',
|
||||
cancelText: '取消',
|
||||
onConfirm: async () => {
|
||||
try {
|
||||
await QQManager.restoreMacInfoBackup(backupName);
|
||||
toast.success('已恢复,重启后生效');
|
||||
await fetchMacInfo();
|
||||
await fetchMacBackups();
|
||||
} catch (error) {
|
||||
const msg = (error as Error).message;
|
||||
toast.error(`恢复失败: ${msg}`);
|
||||
}
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
const handleRestart = () => {
|
||||
dialog.confirm({
|
||||
title: '确认重启',
|
||||
@@ -339,18 +491,200 @@ const GUIDManager: React.FC<GUIDManagerProps> = ({ showRestart = true, compact =
|
||||
);
|
||||
}
|
||||
|
||||
// ========== macOS 不支持 ==========
|
||||
// ========== macOS 渲染 ==========
|
||||
if (isMac) {
|
||||
return (
|
||||
<div className={`flex flex-col gap-${compact ? '3' : '4'}`}>
|
||||
<div className='flex flex-col items-center justify-center py-8 gap-2'>
|
||||
<Chip variant='flat' color='warning' className='text-xs'>
|
||||
macOS 平台暂不支持 GUID 管理
|
||||
</Chip>
|
||||
{/* 当前设备 GUID */}
|
||||
<div className='flex flex-col gap-2'>
|
||||
<div className='text-sm font-medium text-default-700'>当前设备 GUID</div>
|
||||
<div className='flex items-center gap-2'>
|
||||
{macGuid
|
||||
? (
|
||||
<Chip variant='flat' color='primary' className='font-mono text-xs max-w-full'>
|
||||
{macGuid}
|
||||
</Chip>
|
||||
)
|
||||
: (
|
||||
<Chip variant='flat' color='warning' className='text-xs'>
|
||||
未设置 / 不存在
|
||||
</Chip>
|
||||
)}
|
||||
{macGuid && (
|
||||
<Button
|
||||
isIconOnly
|
||||
size='sm'
|
||||
variant='light'
|
||||
onPress={() => handleMacCopy(macGuid, 'GUID')}
|
||||
aria-label='复制GUID'
|
||||
>
|
||||
<MdContentCopy size={16} />
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
isIconOnly
|
||||
size='sm'
|
||||
variant='light'
|
||||
onPress={fetchMacInfo}
|
||||
aria-label='刷新'
|
||||
>
|
||||
<MdRefresh size={16} />
|
||||
</Button>
|
||||
</div>
|
||||
<div className='text-xs text-default-400'>
|
||||
该功能仅适用于 Windows 和 Linux 平台
|
||||
GUID = MD5(machine_id + SN),machine_id 来自 TEA 加密的 machineid-info
|
||||
{macSource === 'mac-fallback' && '(当前走网卡 MAC 回退)'}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Divider />
|
||||
|
||||
{/* 硬件信息 */}
|
||||
<div className='flex flex-col gap-1'>
|
||||
<div className='text-sm font-medium text-default-700'>IOPlatformUUID(TEA 密钥来源)</div>
|
||||
<Chip variant='flat' color='default' className='font-mono text-xs max-w-full'>
|
||||
{macInfo.platformUuid || '未知'}
|
||||
</Chip>
|
||||
<div className='text-xs text-default-400'>不可修改,密钥为其前 16 字节</div>
|
||||
</div>
|
||||
|
||||
<div className='flex flex-col gap-1'>
|
||||
<div className='text-sm font-medium text-default-700'>序列号(SN)</div>
|
||||
<Chip variant='flat' color='default' className='font-mono text-xs max-w-full'>
|
||||
{macInfo.sn || '未知'}
|
||||
</Chip>
|
||||
</div>
|
||||
|
||||
<div className='flex flex-col gap-1'>
|
||||
<div className='text-sm font-medium text-default-700'>主网卡 MAC</div>
|
||||
<Chip variant='flat' color='secondary' className='font-mono text-xs max-w-full'>
|
||||
{macInfo.mac || '未知'}
|
||||
</Chip>
|
||||
</div>
|
||||
|
||||
<Divider />
|
||||
|
||||
{/* 编辑 machine_id */}
|
||||
<div className='flex flex-col gap-2'>
|
||||
<div className='text-sm font-medium text-default-700'>设置 Machine ID</div>
|
||||
<Input
|
||||
size='sm'
|
||||
variant='bordered'
|
||||
placeholder='16 位十六进制 machine_id'
|
||||
value={inputMachineId}
|
||||
onValueChange={setInputMachineId}
|
||||
isInvalid={inputMachineId.length > 0 && !isValidMachineId(inputMachineId)}
|
||||
errorMessage={inputMachineId.length > 0 && !isValidMachineId(inputMachineId) ? '需要 16 位十六进制字符' : undefined}
|
||||
classNames={{ input: 'font-mono text-sm' }}
|
||||
maxLength={16}
|
||||
/>
|
||||
<Input
|
||||
size='sm'
|
||||
variant='bordered'
|
||||
placeholder='序列号 SN(留空使用当前值)'
|
||||
value={inputSn}
|
||||
onValueChange={setInputSn}
|
||||
classNames={{ input: 'font-mono text-sm' }}
|
||||
/>
|
||||
|
||||
{/* 实时 GUID 预览 */}
|
||||
{isValidMachineId(inputMachineId) && (
|
||||
<div className='flex flex-col gap-1 p-2 rounded-lg bg-default-100'>
|
||||
<div className='text-xs font-medium text-default-500'>预览 GUID</div>
|
||||
<div className='font-mono text-xs text-primary break-all'>
|
||||
{computedMacGUID}
|
||||
</div>
|
||||
{computedMacGUID !== macGuid && (
|
||||
<div className='text-xs text-warning-500'>
|
||||
与当前 GUID 不同,保存后重启生效
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className='flex items-center gap-2'>
|
||||
<Button
|
||||
size='sm'
|
||||
color='primary'
|
||||
variant='flat'
|
||||
isLoading={saving}
|
||||
isDisabled={!macDirty}
|
||||
onPress={handleMacSave}
|
||||
startContent={<MdSave size={16} />}
|
||||
>
|
||||
保存 Machine ID
|
||||
</Button>
|
||||
<Button
|
||||
size='sm'
|
||||
color='danger'
|
||||
variant='flat'
|
||||
isDisabled={!macGuid}
|
||||
onPress={handleMacDelete}
|
||||
startContent={<MdDelete size={16} />}
|
||||
>
|
||||
删除
|
||||
</Button>
|
||||
<Button
|
||||
size='sm'
|
||||
color='secondary'
|
||||
variant='flat'
|
||||
onPress={handleMacBackup}
|
||||
startContent={<MdBackup size={16} />}
|
||||
>
|
||||
手动备份
|
||||
</Button>
|
||||
</div>
|
||||
<div className='text-xs text-default-400'>
|
||||
修改 machine_id 后 GUID 将变化,需重启 NapCat 才能生效,操作前会自动备份
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 备份恢复 */}
|
||||
{macBackups.length > 0 && (
|
||||
<>
|
||||
<Divider />
|
||||
<div className='flex flex-col gap-2'>
|
||||
<div className='text-sm font-medium text-default-700'>
|
||||
备份列表
|
||||
<span className='text-xs text-default-400 ml-2'>(点击恢复)</span>
|
||||
</div>
|
||||
<div className='max-h-[160px] overflow-y-auto rounded-lg border border-default-200'>
|
||||
<Listbox
|
||||
aria-label='备份列表'
|
||||
selectionMode='none'
|
||||
onAction={(key) => handleMacRestore(key as string)}
|
||||
>
|
||||
{macBackups.map((name) => (
|
||||
<ListboxItem
|
||||
key={name}
|
||||
startContent={<MdRestorePage size={16} className='text-default-400' />}
|
||||
className='font-mono text-xs'
|
||||
>
|
||||
{name}
|
||||
</ListboxItem>
|
||||
))}
|
||||
</Listbox>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* 重启 */}
|
||||
{showRestart && (
|
||||
<>
|
||||
<Divider />
|
||||
<Button
|
||||
size='sm'
|
||||
color='warning'
|
||||
variant='flat'
|
||||
isLoading={restarting}
|
||||
onPress={handleRestart}
|
||||
startContent={<MdRefresh size={16} />}
|
||||
>
|
||||
重启 NapCat
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -271,6 +271,57 @@ export default class QQManager {
|
||||
await serverRequest.post<ServerResponse<null>>('/QQLogin/ResetLinuxDeviceID');
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// macOS GUID 管理
|
||||
// ============================================================
|
||||
|
||||
public static async getMacGUIDInfo () {
|
||||
const data = await serverRequest.post<ServerResponse<{
|
||||
guid: string;
|
||||
guidUuid: string;
|
||||
machineId: string;
|
||||
sn: string;
|
||||
mac: string;
|
||||
platformUuid: string;
|
||||
source: 'machineid-info' | 'mac-fallback';
|
||||
}>>('/QQLogin/GetMacGUIDInfo');
|
||||
return data.data.data;
|
||||
}
|
||||
|
||||
public static async getMacHardwareInfo () {
|
||||
const data = await serverRequest.post<ServerResponse<{
|
||||
platformUuid: string;
|
||||
serialNumber: string;
|
||||
diskSerial: string;
|
||||
mac: string;
|
||||
}>>('/QQLogin/GetMacHardwareInfo');
|
||||
return data.data.data;
|
||||
}
|
||||
|
||||
public static async setMacMachineId (machineId: string, sn?: string) {
|
||||
const data = await serverRequest.post<ServerResponse<{ guid: string; guidUuid: string; }>>(
|
||||
'/QQLogin/SetMacMachineId', { machineId, sn });
|
||||
return data.data.data;
|
||||
}
|
||||
|
||||
public static async getMacInfoBackups () {
|
||||
const data = await serverRequest.post<ServerResponse<string[]>>('/QQLogin/GetMacInfoBackups');
|
||||
return data.data.data;
|
||||
}
|
||||
|
||||
public static async createMacInfoBackup () {
|
||||
const data = await serverRequest.post<ServerResponse<{ path: string; }>>('/QQLogin/CreateMacInfoBackup');
|
||||
return data.data.data;
|
||||
}
|
||||
|
||||
public static async restoreMacInfoBackup (backupName: string) {
|
||||
await serverRequest.post<ServerResponse<null>>('/QQLogin/RestoreMacInfoBackup', { backupName });
|
||||
}
|
||||
|
||||
public static async resetMacDeviceID () {
|
||||
await serverRequest.post<ServerResponse<null>>('/QQLogin/ResetMacDeviceID');
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// NapCat 配置管理
|
||||
// ============================================================
|
||||
|
||||
@@ -221,7 +221,7 @@ const LoginConfigCard = () => {
|
||||
<div className='flex-shrink-0 w-full mt-4'>
|
||||
<div className='mb-3 text-sm text-default-600'>设备 GUID 管理</div>
|
||||
<div className='text-xs text-default-400 mb-3'>
|
||||
GUID 是设备登录唯一识别码,存储在 Registry20 文件中。修改后需重启生效。
|
||||
GUID 是设备登录唯一识别码,Windows 存于 Registry20、Linux 存于 machine-info、macOS 存于 machineid-info。修改后需重启生效。
|
||||
</div>
|
||||
<GUIDManager showRestart={false} />
|
||||
</div>
|
||||
|
||||
Reference in new issue
Block a user