diff --git a/packages/napcat-core/apis/database.ts b/packages/napcat-core/apis/database.ts new file mode 100644 index 000000000..b6a4ad446 --- /dev/null +++ b/packages/napcat-core/apis/database.ts @@ -0,0 +1,104 @@ +import path from 'node:path'; +import { InstanceContext, NapCatCore } from '@/napcat-core/index'; +import { + checkSqliteAvailable, + readSingleDatabase, + scanAllDatabases, + formatScanResults, + decryptDatabaseFile, + type DatabaseScanResult, + type DatabaseReadOptions, + type TableInfo, +} from 'napcat-database'; + +export class NTQQDatabaseApi { + context: InstanceContext; + core: NapCatCore; + + constructor (context: InstanceContext, core: NapCatCore) { + this.context = context; + this.core = core; + } + + /** node:sqlite 是否可用 */ + async isSqliteAvailable (): Promise { + return checkSqliteAvailable(); + } + + /** 获取当前账号的 nt_db 目录 */ + getNtDbDir (): string { + return path.resolve(this.core.dataPath, this.core.selfInfo.uin, 'nt_qq', 'nt_db'); + } + + /** + * 获取解密缓存目录 + * 默认: /db_/ + * 可通过 customDir 完全自定义 + */ + getDefaultCacheDir (customDir?: string): string { + if (customDir) return customDir; + return path.resolve(this.core.NapCatDataPath, `db_${this.core.selfInfo.uin}`); + } + + /** 当前是否已获取到数据库 passphrase */ + hasPassphrase (): boolean { + return !!this.core.dbPassphrase; + } + + /** 获取 passphrase Buffer,未获取时返回 null */ + getPassphraseBuffer (): Buffer | null { + return this.core.dbPassphrase ? Buffer.from(this.core.dbPassphrase) : null; + } + + /** + * 读取单个加密数据库 + * @param dbName 数据库文件名 (如 'nt_msg.db'),或完整路径 + * @param cacheDir 自定义缓存目录,默认 db_ + * @param options 其他选项 + */ + readDatabase (dbName: string, cacheDir?: string, options?: Omit): DatabaseScanResult | null { + const passphrase = this.getPassphraseBuffer(); + if (!passphrase) return null; + + // 判断是文件名还是完整路径 + const dbPath = path.isAbsolute(dbName) ? dbName : path.resolve(this.getNtDbDir(), dbName); + const resolvedCacheDir = this.getDefaultCacheDir(cacheDir); + + return readSingleDatabase(dbPath, passphrase, { cacheDir: resolvedCacheDir, ...options }); + } + + /** + * 扫描所有加密数据库 + * @param cacheDir 自定义缓存目录,默认 db_ + * @param options 其他选项 + */ + scanDatabases (cacheDir?: string, options?: Omit): DatabaseScanResult[] { + const passphrase = this.getPassphraseBuffer(); + if (!passphrase) return []; + + const resolvedCacheDir = this.getDefaultCacheDir(cacheDir); + return scanAllDatabases(this.getNtDbDir(), passphrase, { cacheDir: resolvedCacheDir, ...options }); + } + + /** + * 仅解密数据库文件(不读取表信息,不需要 node:sqlite) + * @param dbName 数据库文件名或完整路径 + * @param outputPath 输出路径,默认保存到 db_/ + */ + decryptDatabase (dbName: string, outputPath?: string): string | null { + const passphrase = this.getPassphraseBuffer(); + if (!passphrase) return null; + + const dbPath = path.isAbsolute(dbName) ? dbName : path.resolve(this.getNtDbDir(), dbName); + const outPath = outputPath ?? path.resolve(this.getDefaultCacheDir(), path.basename(dbName)); + + return decryptDatabaseFile(dbPath, passphrase, outPath); + } + + /** 格式化扫描结果为可读字符串 */ + formatResults (results: DatabaseScanResult[]): string { + return formatScanResults(results); + } +} + +export type { DatabaseScanResult, DatabaseReadOptions, TableInfo }; diff --git a/packages/napcat-core/apis/index.ts b/packages/napcat-core/apis/index.ts index 9659883f5..8dba6ac37 100644 --- a/packages/napcat-core/apis/index.ts +++ b/packages/napcat-core/apis/index.ts @@ -9,3 +9,4 @@ export * from './packet'; export * from './file'; export * from './online'; export * from './flash'; +export * from './database'; diff --git a/packages/napcat-core/index.ts b/packages/napcat-core/index.ts index 58fa83e51..1e10a651f 100644 --- a/packages/napcat-core/index.ts +++ b/packages/napcat-core/index.ts @@ -8,6 +8,7 @@ import { NTQQWebApi, NTQQFlashApi, NTQQOnlineApi, + NTQQDatabaseApi, } from '@/napcat-core/apis'; import { NTQQCollectionApi } from '@/napcat-core/apis/collection'; import { @@ -118,6 +119,8 @@ export class NapCatCore { selfInfo: SelfInfo; util: NodeQQNTWrapperUtil; configLoader: NapCatConfigLoader; + /** 数据库 passphrase,由 OidbSvcTrpcTcp.0xcde_2 包获取 */ + dbPassphrase: string | undefined; // 通过构造器递过去的 runtime info 应该尽量少 constructor (context: InstanceContext, selfInfo: SelfInfo) { @@ -148,6 +151,7 @@ export class NapCatCore { GroupApi: new NTQQGroupApi(this.context, this), FlashApi: new NTQQFlashApi(this.context, this), OnlineApi: new NTQQOnlineApi(this.context, this), + DatabaseApi: new NTQQDatabaseApi(this.context, this), }; container.bind(NapCatCore).toConstantValue(this); container.bind(TypedEventEmitter).toConstantValue(this.event); @@ -330,4 +334,5 @@ export interface StableNTApiWrapper { GroupApi: NTQQGroupApi; FlashApi: NTQQFlashApi, OnlineApi: NTQQOnlineApi, + DatabaseApi: NTQQDatabaseApi, } diff --git a/packages/napcat-core/package.json b/packages/napcat-core/package.json index cde9d75af..92031d5b1 100644 --- a/packages/napcat-core/package.json +++ b/packages/napcat-core/package.json @@ -1,38 +1,39 @@ { - "name": "napcat-core", - "version": "0.0.1", - "private": true, - "type": "module", - "main": "index.ts", - "scripts": { - "typecheck": "tsc --noEmit --skipLibCheck -p tsconfig.json" + "name": "napcat-core", + "version": "0.0.1", + "private": true, + "type": "module", + "main": "index.ts", + "scripts": { + "typecheck": "tsc --noEmit --skipLibCheck -p tsconfig.json" + }, + "exports": { + ".": { + "import": "./index.ts" }, - "exports": { - ".": { - "import": "./index.ts" - }, - "./*": { - "import": "./*" - } - }, - "dependencies": { - "winston": "^3.17.0", - "json5": "^2.2.3", - "inversify": "^7.10.4", - "reflect-metadata": "^0.2.2", - "@protobuf-ts/runtime": "^2.11.1", - "ajv": "^8.13.0", - "@sinclair/typebox": "^0.34.38", - "file-type": "^21.0.0", - "compressing": "^1.10.1", - "napcat-image-size": "workspace:*", - "napcat-common": "workspace:*", - "napcat-protobuf": "workspace:*" - }, - "devDependencies": { - "@types/node": "^22.0.1" - }, - "engines": { - "node": ">=18.0.0" + "./*": { + "import": "./*" } + }, + "dependencies": { + "winston": "^3.17.0", + "json5": "^2.2.3", + "inversify": "^7.10.4", + "reflect-metadata": "^0.2.2", + "@protobuf-ts/runtime": "^2.11.1", + "ajv": "^8.13.0", + "@sinclair/typebox": "^0.34.38", + "file-type": "^21.0.0", + "compressing": "^1.10.1", + "napcat-image-size": "workspace:*", + "napcat-common": "workspace:*", + "napcat-database": "workspace:*", + "napcat-protobuf": "workspace:*" + }, + "devDependencies": { + "@types/node": "^22.0.1" + }, + "engines": { + "node": ">=18.0.0" + } } \ No newline at end of file diff --git a/packages/napcat-core/packet/transformer/proto/index.ts b/packages/napcat-core/packet/transformer/proto/index.ts index 59cf0b592..8582f6645 100644 --- a/packages/napcat-core/packet/transformer/proto/index.ts +++ b/packages/napcat-core/packet/transformer/proto/index.ts @@ -25,6 +25,7 @@ export * from './oidb/Oidb.0x929'; export * from './oidb/Oidb.0xE37_1200'; export * from './oidb/Oidb.0xE37_1700'; export * from './oidb/Oidb.0XE37_800'; +export * from './oidb/Oidb.0xCDE_2'; export * from './oidb/Oidb.0xEB7'; export * from './oidb/Oidb.0xED3_1'; export * from './oidb/Oidb.0XFE1_2'; diff --git a/packages/napcat-core/packet/transformer/proto/oidb/Oidb.0xCDE_2.ts b/packages/napcat-core/packet/transformer/proto/oidb/Oidb.0xCDE_2.ts new file mode 100644 index 000000000..c9aecdbd4 --- /dev/null +++ b/packages/napcat-core/packet/transformer/proto/oidb/Oidb.0xCDE_2.ts @@ -0,0 +1,11 @@ +import { ProtoField, ScalarType } from 'napcat-protobuf'; + +// OidbSvcTrpcTcp.0xcde_2 响应体 +// body.field2.field1 为目标字符串值 +export const OidbSvcTrpcTcp0XCDE_2RespBodyInner = { + value: ProtoField(1, ScalarType.STRING), +}; + +export const OidbSvcTrpcTcp0XCDE_2RespBody = { + inner: ProtoField(2, () => OidbSvcTrpcTcp0XCDE_2RespBodyInner), +}; diff --git a/packages/napcat-database/package.json b/packages/napcat-database/package.json new file mode 100644 index 000000000..67f1688dd --- /dev/null +++ b/packages/napcat-database/package.json @@ -0,0 +1,25 @@ +{ + "name": "napcat-database", + "version": "0.0.1", + "private": true, + "type": "module", + "main": "src/index.ts", + "scripts": { + "typecheck": "tsc --noEmit --skipLibCheck -p tsconfig.json" + }, + "exports": { + ".": { + "import": "./src/index.ts" + }, + "./src/*": { + "import": "./src/*" + } + }, + "dependencies": {}, + "devDependencies": { + "@types/node": "^22.0.1" + }, + "engines": { + "node": ">=18.0.0" + } +} \ No newline at end of file diff --git a/packages/napcat-database/src/constants.ts b/packages/napcat-database/src/constants.ts new file mode 100644 index 000000000..dab20903c --- /dev/null +++ b/packages/napcat-database/src/constants.ts @@ -0,0 +1,35 @@ +/** 文件头部扩展区大小 */ +export const EXT_HEADER_SIZE = 1024; + +/** SQLCipher 页大小 */ +export const PAGE_SIZE = 4096; + +/** PBKDF2 salt 长度 */ +export const SALT_SIZE = 16; + +/** AES-256 密钥长度 */ +export const KEY_SIZE = 32; + +/** AES-CBC IV 长度 */ +export const IV_SIZE = 16; + +/** HMAC-SHA1 长度 */ +export const HMAC_SIZE = 20; + +/** 每页保留区大小: IV(16) + HMAC_SHA1(20) + pad(12) = 48 */ +export const RESERVE_SIZE = 48; + +/** PBKDF2 主密钥迭代次数 */ +export const KDF_ITERATIONS = 4000; + +/** PBKDF2 HMAC 密钥迭代次数 */ +export const FAST_ITERATIONS = 2; + +/** HMAC salt XOR 掩码 */ +export const HMAC_MASK = 0x3a; + +/** SQLite 加密文件头 */ +export const SQLITE_HEADER = Buffer.from('SQLite header 3\0'); + +/** SQLite 明文文件头 */ +export const SQLITE_FORMAT = Buffer.from('SQLite format 3\0'); diff --git a/packages/napcat-database/src/crypto.ts b/packages/napcat-database/src/crypto.ts new file mode 100644 index 000000000..1d9c2457f --- /dev/null +++ b/packages/napcat-database/src/crypto.ts @@ -0,0 +1,29 @@ +/** + * 密钥派生 + * enc_key = PBKDF2_HMAC_SHA512(passphrase, salt, 4000, 32) + * hmac_key = PBKDF2_HMAC_SHA512(enc_key, salt ^ 0x3a, 2, 32) + */ + +import { pbkdf2Sync } from 'node:crypto'; +import { + KEY_SIZE, + KDF_ITERATIONS, + FAST_ITERATIONS, + HMAC_MASK, +} from './constants'; + +export interface DerivedKeys { + encKey: Buffer; + hmacKey: Buffer; +} +export function deriveKeys (passphrase: Buffer, salt: Buffer): DerivedKeys { + const encKey = pbkdf2Sync(passphrase, salt, KDF_ITERATIONS, KEY_SIZE, 'sha512'); + + const hmacSalt = Buffer.alloc(salt.length); + for (let i = 0; i < salt.length; i++) { + hmacSalt[i] = salt[i]! ^ HMAC_MASK; + } + const hmacKey = pbkdf2Sync(encKey, hmacSalt, FAST_ITERATIONS, KEY_SIZE, 'sha512'); + + return { encKey, hmacKey }; +} diff --git a/packages/napcat-database/src/decrypt.ts b/packages/napcat-database/src/decrypt.ts new file mode 100644 index 000000000..ad717d3be --- /dev/null +++ b/packages/napcat-database/src/decrypt.ts @@ -0,0 +1,107 @@ +import { createDecipheriv } from 'node:crypto'; +import fs from 'node:fs'; +import { + EXT_HEADER_SIZE, + PAGE_SIZE, + SALT_SIZE, + IV_SIZE, + RESERVE_SIZE, + SQLITE_HEADER, + SQLITE_FORMAT, +} from './constants'; +import { deriveKeys } from './crypto'; + +/** + * 解密单个 SQLCipher 页面 + * @param pageData 原始页数据 (4096 字节) + * @param encKey AES-256 密钥 + * @param skipSalt 页 1 需跳过前 16 字节 salt + */ +function decryptPage (pageData: Buffer, encKey: Buffer, skipSalt: number = 0): Buffer { + const data = pageData.subarray(skipSalt); + const contentLen = data.length - RESERVE_SIZE; + const encrypted = data.subarray(0, contentLen); + const iv = data.subarray(contentLen, contentLen + IV_SIZE); + + const decipher = createDecipheriv('aes-256-cbc', encKey, iv); + decipher.setAutoPadding(false); + return Buffer.concat([decipher.update(encrypted), decipher.final()]); +} + +/** + * 检查文件是否为 NTQQ 加密数据库 + */ +export function isEncryptedNTDB (fileData: Buffer): boolean { + if (fileData.length < EXT_HEADER_SIZE + PAGE_SIZE) return false; + return fileData.subarray(0, 16).equals(SQLITE_HEADER); +} + +/** + * 将加密的 NTQQ 数据库解密为标准 SQLite 数据库 + * @param fileData 完整的加密数据库文件内容 + * @param passphrase 服务端返回的密钥口令 + * @returns 解密后的 SQLite 数据库 Buffer,失败返回 null + */ +export function decryptDatabase (fileData: Buffer, passphrase: Buffer): Buffer | null { + if (!isEncryptedNTDB(fileData)) return null; + + const scData = fileData.subarray(EXT_HEADER_SIZE); + const totalPages = Math.floor(scData.length / PAGE_SIZE); + if (totalPages === 0) return null; + + const salt = scData.subarray(0, SALT_SIZE); + const { encKey } = deriveKeys(passphrase, salt); + + const output = Buffer.alloc(totalPages * PAGE_SIZE); + let offset = 0; + + for (let pgno = 1; pgno <= totalPages; pgno++) { + const pageOffset = (pgno - 1) * PAGE_SIZE; + const rawPage = scData.subarray(pageOffset, pageOffset + PAGE_SIZE); + const skip = pgno === 1 ? SALT_SIZE : 0; + const decrypted = decryptPage(rawPage, encKey, skip); + + if (pgno === 1) { + // 重建 Page 1: SQLite 标准文件头 + 解密内容 + SQLITE_FORMAT.copy(output, 0); + decrypted.copy(output, 16); + // 修正 page_size 字段 (offset 16-17, big-endian) + output.writeUInt16BE(PAGE_SIZE, 16); + // 清零 reserved space 标志 (offset 20) + output[20] = 0; + offset = PAGE_SIZE; + } else { + decrypted.copy(output, offset); + offset += PAGE_SIZE; + } + } + + return output; +} + +/** + * 解密数据库文件并写入输出路径 + * @param inputPath 加密数据库路径 + * @param passphrase 密钥口令 + * @param outputPath 输出路径 (默认: 原路径加 _decrypted 后缀) + * @returns 输出路径,失败返回 null + */ +export function decryptDatabaseFile ( + inputPath: string, + passphrase: Buffer, + outputPath?: string +): string | null { + const fileData = fs.readFileSync(inputPath); + const result = decryptDatabase(fileData, passphrase); + if (!result) return null; + + if (!outputPath) { + const dotIdx = inputPath.lastIndexOf('.'); + outputPath = dotIdx > 0 + ? inputPath.substring(0, dotIdx) + '_decrypted' + inputPath.substring(dotIdx) + : inputPath + '_decrypted'; + } + + fs.writeFileSync(outputPath, result); + return outputPath; +} diff --git a/packages/napcat-database/src/index.ts b/packages/napcat-database/src/index.ts new file mode 100644 index 000000000..9140e7b5f --- /dev/null +++ b/packages/napcat-database/src/index.ts @@ -0,0 +1,26 @@ +export { deriveKeys, type DerivedKeys } from './crypto'; +export { decryptDatabase, decryptDatabaseFile, isEncryptedNTDB } from './decrypt'; +export { + checkSqliteAvailable, + listTablesFromBuffer, + listTablesFromFile, + readSingleDatabase, + scanAllDatabases, + formatScanResults, + type TableInfo, + type ColumnInfo, + type DatabaseScanResult, + type DatabaseReadOptions, +} from './reader'; +export { + EXT_HEADER_SIZE, + PAGE_SIZE, + SALT_SIZE, + KEY_SIZE, + IV_SIZE, + HMAC_SIZE, + RESERVE_SIZE, + KDF_ITERATIONS, + FAST_ITERATIONS, + HMAC_MASK, +} from './constants'; diff --git a/packages/napcat-database/src/reader.ts b/packages/napcat-database/src/reader.ts new file mode 100644 index 000000000..44a89c7f5 --- /dev/null +++ b/packages/napcat-database/src/reader.ts @@ -0,0 +1,267 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import os from 'node:os'; +import { decryptDatabase, decryptDatabaseFile, isEncryptedNTDB } from './decrypt'; + +type DatabaseSyncType = import('node:sqlite').DatabaseSync; +type DatabaseSyncCtor = new (path: string, options?: { readOnly?: boolean; }) => DatabaseSyncType; + +let _DatabaseSync: DatabaseSyncCtor | null = null; +let _sqliteChecked = false; + + +async function loadSqlite (): Promise { + if (_sqliteChecked) return _DatabaseSync; + _sqliteChecked = true; + try { + const mod = await import('node:sqlite'); + _DatabaseSync = mod.DatabaseSync as unknown as DatabaseSyncCtor; + return _DatabaseSync; + } catch { + _DatabaseSync = null; + return null; + } +} + +function getDatabaseSync (): DatabaseSyncCtor { + if (!_DatabaseSync) { + throw new Error( + 'node:sqlite 不可用。请使用 Node.js 22+ 并添加 --experimental-sqlite 标志,' + + '或调用 checkSqliteAvailable() 检查可用性。' + ); + } + return _DatabaseSync; +} + +export async function checkSqliteAvailable (): Promise { + const ctor = await loadSqlite(); + return ctor !== null; +} + +/** 单个数据库表信息 */ +export interface TableInfo { + name: string; + type: string; // 'table' | 'view' | ... + rowCount: number; + columns: ColumnInfo[]; +} + +/** 列信息 */ +export interface ColumnInfo { + cid: number; + name: string; + type: string; + notnull: boolean; + pk: boolean; +} + +/** 单个数据库扫描结果 */ +export interface DatabaseScanResult { + /** 数据库文件名 */ + filename: string; + /** 原始加密文件路径 */ + sourcePath: string; + /** 解密后缓存文件路径 (仅当指定了 cacheDir 时) */ + cachePath?: string; + success: boolean; + error?: string; + tables: TableInfo[]; +} + +/** 扫描/读取选项 */ +export interface DatabaseReadOptions { + /** 解密后数据库缓存目录,不设置则使用临时文件 */ + cacheDir?: string; + /** 是否跳过已存在的缓存文件 (默认 true) */ + skipExistingCache?: boolean; +} + +/** + * 从 DatabaseSync 对象提取表信息 + */ +function extractTablesInfo (db: DatabaseSyncType): TableInfo[] { + const tables: TableInfo[] = []; + + const masterRows = db.prepare( + "SELECT name, type FROM sqlite_master WHERE type IN ('table', 'view') ORDER BY name" + ).all() as { name: string; type: string; }[]; + + for (const { name: tableName, type: tableType } of masterRows) { + // 获取列信息 + const columns: ColumnInfo[] = []; + try { + const cols = db.prepare(`PRAGMA table_info([${tableName}])`).all() as { + cid: number; name: string; type: string; notnull: number; pk: number; + }[]; + for (const col of cols) { + columns.push({ + cid: col.cid, + name: col.name, + type: col.type, + notnull: col.notnull === 1, + pk: col.pk === 1, + }); + } + } catch { + // PRAGMA 可能对某些表失败 + } + + // 获取行数 + let rowCount = 0; + try { + const cnt = db.prepare(`SELECT count(*) as cnt FROM [${tableName}]`).get() as { cnt: number; } | undefined; + rowCount = cnt?.cnt ?? 0; + } catch { + rowCount = -1; + } + + tables.push({ + name: tableName, + type: tableType, + rowCount, + columns, + }); + } + + return tables; +} + +/** + * 打开一个解密后的 SQLite 文件,列出所有表和列信息 + */ +export function listTablesFromFile (filePath: string): TableInfo[] { + const DB = getDatabaseSync(); + const db = new DB(filePath, { readOnly: true }); + try { + return extractTablesInfo(db); + } finally { + db.close(); + } +} + + +export function listTablesFromBuffer (data: Buffer): TableInfo[] { + const tmpPath = path.join(os.tmpdir(), `napcat_db_${Date.now()}_${Math.random().toString(36).slice(2)}.db`); + try { + fs.writeFileSync(tmpPath, data); + return listTablesFromFile(tmpPath); + } finally { + try { fs.unlinkSync(tmpPath); } catch { /* ignore */ } + } +} + +/** + * 解密并读取单个数据库文件 + * + * @param dbPath 加密数据库文件路径 + * @param passphrase 密钥口令 + * @param options 可选配置 (缓存目录等) + * @returns 数据库扫描结果 + */ +export function readSingleDatabase ( + dbPath: string, + passphrase: Buffer, + options?: DatabaseReadOptions +): DatabaseScanResult { + const filename = path.basename(dbPath); + const result: DatabaseScanResult = { + filename, + sourcePath: dbPath, + success: false, + tables: [], + }; + + try { + // 如果指定了缓存目录,且缓存文件已存在,直接读取 + if (options?.cacheDir) { + const cachedPath = path.join(options.cacheDir, filename); + result.cachePath = cachedPath; + + if (options?.skipExistingCache !== false && fs.existsSync(cachedPath)) { + result.tables = listTablesFromFile(cachedPath); + result.success = true; + return result; + } + } + + const fileData = fs.readFileSync(dbPath); + if (!isEncryptedNTDB(fileData)) { + result.error = 'Not an encrypted NTQQ database'; + return result; + } + + // 有缓存目录: 解密写入文件再读取 + if (options?.cacheDir) { + fs.mkdirSync(options.cacheDir, { recursive: true }); + const outPath = decryptDatabaseFile(dbPath, passphrase, result.cachePath); + if (!outPath) { + result.error = 'Decryption failed'; + return result; + } + result.cachePath = outPath; + result.tables = listTablesFromFile(outPath); + } else { + // 无缓存目录: 解密到内存再用临时文件读取 + const decryptedBuf = decryptDatabase(fileData, passphrase); + if (!decryptedBuf) { + result.error = 'Decryption returned null'; + return result; + } + result.tables = listTablesFromBuffer(decryptedBuf); + } + + result.success = true; + } catch (e) { + result.error = e instanceof Error ? e.message : String(e); + } + + return result; +} + +export function scanAllDatabases ( + dbDir: string, + passphrase: Buffer, + options?: DatabaseReadOptions +): DatabaseScanResult[] { + const results: DatabaseScanResult[] = []; + + if (!fs.existsSync(dbDir)) return results; + + const files = fs.readdirSync(dbDir).filter(f => f.endsWith('.db')).sort(); + + for (const filename of files) { + const filePath = path.join(dbDir, filename); + const result = readSingleDatabase(filePath, passphrase, options); + results.push(result); + } + + return results; +} + +/** + * 格式化扫描结果为可读字符串 + */ +export function formatScanResults (results: DatabaseScanResult[]): string { + const lines: string[] = []; + let totalTables = 0; + let successCount = 0; + + for (const db of results) { + if (db.success) { + successCount++; + const cacheNote = db.cachePath ? ` → ${db.cachePath}` : ''; + lines.push(`=== ${db.filename} (${db.tables.length} tables)${cacheNote} ===`); + for (const table of db.tables) { + totalTables++; + const colList = table.columns.map(c => `${c.name}:${c.type || '?'}`).join(', '); + lines.push(` ${table.name}: ${table.rowCount} rows [${colList}]`); + } + } else { + lines.push(`=== ${db.filename}: SKIP (${db.error}) ===`); + } + lines.push(''); + } + + lines.push(`Summary: ${successCount}/${results.length} databases decrypted, ${totalTables} total tables`); + return lines.join('\n'); +} diff --git a/packages/napcat-database/tsconfig.json b/packages/napcat-database/tsconfig.json new file mode 100644 index 000000000..473a385a2 --- /dev/null +++ b/packages/napcat-database/tsconfig.json @@ -0,0 +1,10 @@ +{ + "extends": "../../tsconfig.base.json", + "include": [ + "src/**/*.ts" + ], + "exclude": [ + "node_modules", + "dist" + ] +} \ No newline at end of file diff --git a/packages/napcat-framework/napcat.ts b/packages/napcat-framework/napcat.ts index ecd0ae6bd..8ad3e67c2 100644 --- a/packages/napcat-framework/napcat.ts +++ b/packages/napcat-framework/napcat.ts @@ -1,3 +1,4 @@ +import path from 'node:path'; import { NapCatPathWrapper } from 'napcat-common/src/path'; import { InitWebUi, WebUiConfig, webUiRuntimePort } from 'napcat-webui-backend/index'; import { NapCatAdapterManager } from 'napcat-adapter'; @@ -12,6 +13,8 @@ import { proxiedListenerOf } from '@/napcat-core/helper/proxy-handler'; import { statusHelperSubscription } from '@/napcat-core/helper/status'; import { applyPendingUpdates } from '@/napcat-webui-backend/src/api/UpdateNapCat'; import { WebUiDataRuntime } from '@/napcat-webui-backend/src/helper/Data'; +import { NapProtoMsg } from 'napcat-protobuf'; +import { OidbSvcTrpcTcpBase, OidbSvcTrpcTcp0XCDE_2RespBody } from '@/napcat-core/packet/transformer/proto'; // Framework ES入口文件 export async function getWebUiUrl () { @@ -61,6 +64,25 @@ export async function NCoreInitFramework ( await nativePacketHandler.init(basicInfoWrapper.getFullQQVersion(), napcatConfig.o3HookMode === 1 ? true : false); // 在 init 之后注册监听器 + // 登录前监听 OidbSvcTrpcTcp.0xcde_2 数据包,获取数据库 passphrase + let dbPassphrase: string | undefined; + nativePacketHandler.onCmd('OidbSvcTrpcTcp.0xcde_2', ({ type, hex_data }) => { + if (type !== 1) return; // 仅处理接收方向 + try { + const raw = Buffer.from(hex_data, 'hex'); + const base = new NapProtoMsg(OidbSvcTrpcTcpBase).decode(raw); + if (base.body && base.body.length > 0) { + const body = new NapProtoMsg(OidbSvcTrpcTcp0XCDE_2RespBody).decode(base.body); + if (body.inner?.value) { + dbPassphrase = body.inner.value; + logger.log('[NapCat] 已启用数据库辅助支持能力'); + } + } + } catch (e) { + logger.logError('[NapCat] [0xCDE_2] 解析失败:', e); + } + }); + // 初始化 FFmpeg 服务 await FFmpegService.init(pathWrapper.binaryPath, logger); // 直到登录成功后,执行下一步 @@ -89,12 +111,34 @@ export async function NCoreInitFramework ( // await sleep(2500); // 初始化 NapCatFramework const loaderObject = new NapCatFramework(wrapper, session, logger, selfInfo, basicInfoWrapper, pathWrapper, nativePacketHandler, napi2nativeLoader); + // 将捕获的 passphrase 设置到 core 上,供 DatabaseApi 使用 + if (dbPassphrase) { + loaderObject.core.dbPassphrase = dbPassphrase; + } await loaderObject.core.initCore(); // 启动WebUi WebUiDataRuntime.setWorkingEnv(NapCatCoreWorkingEnv.Framework); WebUiDataRuntime.setQQDataPath(loaderObject.core.dataPath); InitWebUi(logger, pathWrapper, logSubscription, statusHelperSubscription).then().catch(e => logger.logError(e)); + + // // [测试代码 - 已禁用] 使用捕获的 passphrase 读取 nt_msg.db 的表信息 + // if (dbPassphrase) { + // const sqliteOk = await checkSqliteAvailable(); + // if (!sqliteOk) { + // logger.logWarn('[NapCat] [Database] node:sqlite 不可用'); + // } else { + // const ntDbDir = path.resolve(loaderObject.core.dataPath, selfInfo.uin, 'nt_qq', 'nt_db'); + // const ntMsgDbPath = path.resolve(ntDbDir, 'nt_msg.db'); + // try { + // const result = loaderObject.core.apis.DatabaseApi.readDatabase('nt_msg.db'); + // if (result) logger.log('[NapCat] [Database] \n' + loaderObject.core.apis.DatabaseApi.formatResults([result])); + // } catch (e) { + // logger.logError('[NapCat] [Database] 读取失败:', e); + // } + // } + // } + // 使用 NapCatAdapterManager 统一管理协议适配器 const adapterManager = new NapCatAdapterManager(loaderObject.core, loaderObject.context, pathWrapper); await adapterManager.initAdapters(); diff --git a/packages/napcat-framework/package.json b/packages/napcat-framework/package.json index 38c51c8c0..cce00c5f4 100644 --- a/packages/napcat-framework/package.json +++ b/packages/napcat-framework/package.json @@ -19,6 +19,8 @@ "dependencies": { "napcat-core": "workspace:*", "napcat-common": "workspace:*", + "napcat-database": "workspace:*", + "napcat-protobuf": "workspace:*", "napcat-adapter": "workspace:*", "napcat-webui-backend": "workspace:*", "napcat-vite": "workspace:*", diff --git a/packages/napcat-framework/vite.config.ts b/packages/napcat-framework/vite.config.ts index f1544925a..5b6238dc8 100644 --- a/packages/napcat-framework/vite.config.ts +++ b/packages/napcat-framework/vite.config.ts @@ -11,7 +11,7 @@ const external = [ 'ws', 'express', ]; -const nodeModules = [...builtinModules, builtinModules.map((m) => `node:${m}`)].flat(); +const nodeModules = [...builtinModules, builtinModules.map((m) => `node:${m}`), 'node:sqlite'].flat(); const FrameworkBaseConfigPlugin: PluginOption[] = [ autoIncludeTSPlugin({ entries: [ diff --git a/packages/napcat-shell/base.ts b/packages/napcat-shell/base.ts index e8909d5ea..dd53ed621 100644 --- a/packages/napcat-shell/base.ts +++ b/packages/napcat-shell/base.ts @@ -32,6 +32,8 @@ import { sleep } from 'napcat-common/src/helper'; import { FFmpegService } from '@/napcat-core/helper/ffmpeg/ffmpeg'; import { NativePacketHandler } from 'napcat-core/packet/handler/client'; import { Napi2NativeLoader } from 'napcat-core/packet/handler/napi2nativeLoader'; +import { NapProtoMsg } from 'napcat-protobuf'; +import { OidbSvcTrpcTcpBase, OidbSvcTrpcTcp0XCDE_2RespBody } from '@/napcat-core/packet/transformer/proto'; import { loadNapcatConfig } from '@/napcat-core/helper/config'; import { logSubscription, LogWrapper } from '@/napcat-core/helper/log'; import { proxiedListenerOf } from '@/napcat-core/helper/proxy-handler'; @@ -597,6 +599,26 @@ export async function NCoreInitShell () { // wrapper.node 加载后再初始化 hook,按 schema 读取配置 const napcatConfig = loadNapcatConfig(pathWrapper.configPath); await nativePacketHandler.init(basicInfoWrapper.getFullQQVersion(), napcatConfig.o3HookMode === 1 ? true : false); + + // 登录前监听 OidbSvcTrpcTcp.0xcde_2 数据包,获取数据库 passphrase + let dbPassphrase: string | undefined; + nativePacketHandler.onCmd('OidbSvcTrpcTcp.0xcde_2', ({ type, hex_data }) => { + if (type !== 1) return; // 仅处理接收方向 + try { + const raw = Buffer.from(hex_data, 'hex'); + const base = new NapProtoMsg(OidbSvcTrpcTcpBase).decode(raw); + if (base.body && base.body.length > 0) { + const body = new NapProtoMsg(OidbSvcTrpcTcp0XCDE_2RespBody).decode(base.body); + if (body.inner?.value) { + dbPassphrase = body.inner.value; + logger.log('[NapCat] 已启用数据库辅助支持能力'); + } + } + } catch (e) { + logger.logError('[NapCat] [0xCDE_2] 解析失败:', e); + } + }); + if (process.env['NAPCAT_ENABLE_VERBOSE_LOG'] === '1') { napi2nativeLoader.nativeExports.setVerbose?.(true); } @@ -694,7 +716,25 @@ export async function NCoreInitShell () { logger.logDebug('本账号数据/缓存目录:', accountDataPath); - await new NapCatShell( + // // [测试代码 - 已禁用] 使用捕获的 passphrase 读取 nt_msg.db 的表信息 + // if (dbPassphrase) { + // const sqliteOk = await checkSqliteAvailable(); + // if (!sqliteOk) { + // logger.logWarn('[NapCat] [Database] node:sqlite 不可用,跳过数据库读取'); + // } else { + // const ntDbDir = path.resolve(dataPath, selfInfo.uin, 'nt_qq', 'nt_db'); + // const dbCacheDir = path.resolve(accountDataPath, 'decrypted_db'); + // const ntMsgDbPath = path.resolve(ntDbDir, 'nt_msg.db'); + // try { + // const result = readSingleDatabase(ntMsgDbPath, Buffer.from(dbPassphrase), { cacheDir: dbCacheDir }); + // logger.log('[NapCat] [Database] 读取完成:\n' + formatScanResults([result])); + // } catch (e) { + // logger.logError('[NapCat] [Database] 读取失败:', e); + // } + // } + // } + + const shell = new NapCatShell( wrapper, session, logger, @@ -703,7 +743,12 @@ export async function NCoreInitShell () { pathWrapper, nativePacketHandler, napi2nativeLoader - ).InitNapCat(); + ); + // 将捕获的 passphrase 设置到 core 上,供 DatabaseApi 使用 + if (dbPassphrase) { + shell.core.dbPassphrase = dbPassphrase; + } + await shell.InitNapCat(); } export class NapCatShell { diff --git a/packages/napcat-shell/package.json b/packages/napcat-shell/package.json index 5a30079ac..1c3fff949 100644 --- a/packages/napcat-shell/package.json +++ b/packages/napcat-shell/package.json @@ -22,7 +22,9 @@ "napcat-common": "workspace:*", "napcat-adapter": "workspace:*", "napcat-webui-backend": "workspace:*", - "napcat-qrcode": "workspace:*" + "napcat-qrcode": "workspace:*", + "napcat-protobuf": "workspace:*", + "napcat-database": "workspace:*" }, "devDependencies": { "json5": "^2.2.3", diff --git a/packages/napcat-shell/vite.config.ts b/packages/napcat-shell/vite.config.ts index d0e801f8a..4686d584b 100644 --- a/packages/napcat-shell/vite.config.ts +++ b/packages/napcat-shell/vite.config.ts @@ -14,7 +14,7 @@ const external = [ 'electron' ]; -const nodeModules = [...builtinModules, builtinModules.map((m) => `node:${m}`)].flat(); +const nodeModules = [...builtinModules, builtinModules.map((m) => `node:${m}`), 'node:sqlite'].flat(); const ShellBaseConfigPlugin: PluginOption[] = [ react({ tsDecorators: true }), autoIncludeTSPlugin({ diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 886d9dad7..c46a258ae 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -101,6 +101,9 @@ importers: napcat-common: specifier: workspace:* version: link:../napcat-common + napcat-database: + specifier: workspace:* + version: link:../napcat-database napcat-image-size: specifier: workspace:* version: link:../napcat-image-size @@ -118,6 +121,12 @@ importers: specifier: ^22.0.1 version: 22.19.1 + packages/napcat-database: + devDependencies: + '@types/node': + specifier: ^22.0.1 + version: 22.19.1 + packages/napcat-develop: dependencies: fs-extra: @@ -148,6 +157,12 @@ importers: napcat-core: specifier: workspace:* version: link:../napcat-core + napcat-database: + specifier: workspace:* + version: link:../napcat-database + napcat-protobuf: + specifier: workspace:* + version: link:../napcat-protobuf napcat-qrcode: specifier: workspace:* version: link:../napcat-qrcode @@ -347,6 +362,12 @@ importers: napcat-core: specifier: workspace:* version: link:../napcat-core + napcat-database: + specifier: workspace:* + version: link:../napcat-database + napcat-protobuf: + specifier: workspace:* + version: link:../napcat-protobuf napcat-qrcode: specifier: workspace:* version: link:../napcat-qrcode