From 0ddf21a2f52e1cc06113aa718c8840cfaf69e246 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=89=8B=E7=93=9C=E4=B8=80=E5=8D=81=E9=9B=AA?= Date: Wed, 4 Mar 2026 11:02:21 +0800 Subject: [PATCH] Add DatabaseHandle and DB utilities, integrate API Introduce a DatabaseHandle wrapper and helper functions for opening and decrypting NTQQ SQLite DBs (openDatabase, decryptAndOpen) in napcat-database; expose them from the package index. Add typed query/execute helpers and SQLInputValue typing. Extend NTQQDatabaseApi in napcat-core to provide high-level methods (openDecryptedDb, openDatabase, query, queryOne, execute) and export DatabaseHandle. Replace disabled inline test blocks with runtime DatabaseApi usage in napcat-framework and napcat-shell to test/read nt_msg.db via the new API. Misc: small cleanup of imports and comments. --- packages/napcat-core/apis/database.ts | 101 +++++++++++++++- packages/napcat-database/src/index.ts | 3 + packages/napcat-database/src/reader.ts | 160 +++++++++++++++++++++++++ packages/napcat-framework/napcat.ts | 32 +++-- packages/napcat-shell/base.ts | 35 +++--- 5 files changed, 294 insertions(+), 37 deletions(-) diff --git a/packages/napcat-core/apis/database.ts b/packages/napcat-core/apis/database.ts index b6a4ad446..c5dbad18a 100644 --- a/packages/napcat-core/apis/database.ts +++ b/packages/napcat-core/apis/database.ts @@ -2,6 +2,9 @@ import path from 'node:path'; import { InstanceContext, NapCatCore } from '@/napcat-core/index'; import { checkSqliteAvailable, + DatabaseHandle, + openDatabase, + decryptAndOpen, readSingleDatabase, scanAllDatabases, formatScanResults, @@ -11,6 +14,8 @@ import { type TableInfo, } from 'napcat-database'; +type SQLInputValue = import('node:sqlite').SQLInputValue; + export class NTQQDatabaseApi { context: InstanceContext; core: NapCatCore; @@ -50,8 +55,100 @@ export class NTQQDatabaseApi { return this.core.dbPassphrase ? Buffer.from(this.core.dbPassphrase) : null; } + // ======================== SQLite 数据库操作 ======================== + /** - * 读取单个加密数据库 + * 打开一个已解密的 SQLite 数据库文件 + * @param filePath 解密后 .db 文件路径 + * @param readOnly 是否只读 (默认 true) + * @returns DatabaseHandle 实例,使用完毕后需调用 .close() + */ + openDecryptedDb (filePath: string, readOnly = true): DatabaseHandle { + return openDatabase(filePath, readOnly); + } + + /** + * 解密并打开一个 NTQQ 加密数据库 + * @param dbName 数据库文件名 (如 'nt_msg.db') 或完整路径 + * @param readOnly 是否只读 (默认 true) + * @param cacheDir 自定义缓存目录,默认 db_ + * @returns DatabaseHandle 实例,使用完毕后需调用 .close() + */ + openDatabase (dbName: string, readOnly = true, cacheDir?: string): DatabaseHandle | 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 decryptAndOpen(dbPath, passphrase, resolvedCacheDir, readOnly); + } + + /** + * 对加密数据库执行查询并自动关闭连接 + * @param dbName 数据库文件名或完整路径 + * @param sql SQL 查询语句 + * @param params 绑定参数 + * @returns 查询结果行数组,passphrase 不可用时返回 null + */ + query> ( + dbName: string, + sql: string, + params?: SQLInputValue[] | Record + ): T[] | null { + const db = this.openDatabase(dbName); + if (!db) return null; + try { + return db.query(sql, params); + } finally { + db.close(); + } + } + + /** + * 对加密数据库执行查询,仅返回第一行 + * @param dbName 数据库文件名或完整路径 + * @param sql SQL 查询语句 + * @param params 绑定参数 + */ + queryOne> ( + dbName: string, + sql: string, + params?: SQLInputValue[] | Record + ): T | undefined | null { + const db = this.openDatabase(dbName); + if (!db) return null; + try { + return db.queryOne(sql, params); + } finally { + db.close(); + } + } + + /** + * 对加密数据库执行非查询 SQL (INSERT/UPDATE/DELETE 等) 并自动关闭 + * @param dbName 数据库文件名或完整路径 + * @param sql SQL 语句 + * @param params 绑定参数 + */ + execute ( + dbName: string, + sql: string, + params?: SQLInputValue[] | Record + ): { changes: number | bigint; lastInsertRowid: number | bigint; } | null { + const db = this.openDatabase(dbName, false); + if (!db) return null; + try { + return db.execute(sql, params); + } finally { + db.close(); + } + } + + // ======================== 批量扫描 ======================== + + /** + * 读取单个加密数据库的表信息 * @param dbName 数据库文件名 (如 'nt_msg.db'),或完整路径 * @param cacheDir 自定义缓存目录,默认 db_ * @param options 其他选项 @@ -60,7 +157,6 @@ export class NTQQDatabaseApi { const passphrase = this.getPassphraseBuffer(); if (!passphrase) return null; - // 判断是文件名还是完整路径 const dbPath = path.isAbsolute(dbName) ? dbName : path.resolve(this.getNtDbDir(), dbName); const resolvedCacheDir = this.getDefaultCacheDir(cacheDir); @@ -101,4 +197,5 @@ export class NTQQDatabaseApi { } } +export { DatabaseHandle }; export type { DatabaseScanResult, DatabaseReadOptions, TableInfo }; diff --git a/packages/napcat-database/src/index.ts b/packages/napcat-database/src/index.ts index 9140e7b5f..351e91a90 100644 --- a/packages/napcat-database/src/index.ts +++ b/packages/napcat-database/src/index.ts @@ -2,6 +2,9 @@ export { deriveKeys, type DerivedKeys } from './crypto'; export { decryptDatabase, decryptDatabaseFile, isEncryptedNTDB } from './decrypt'; export { checkSqliteAvailable, + DatabaseHandle, + openDatabase, + decryptAndOpen, listTablesFromBuffer, listTablesFromFile, readSingleDatabase, diff --git a/packages/napcat-database/src/reader.ts b/packages/napcat-database/src/reader.ts index 44a89c7f5..c55a19003 100644 --- a/packages/napcat-database/src/reader.ts +++ b/packages/napcat-database/src/reader.ts @@ -5,6 +5,7 @@ import { decryptDatabase, decryptDatabaseFile, isEncryptedNTDB } from './decrypt type DatabaseSyncType = import('node:sqlite').DatabaseSync; type DatabaseSyncCtor = new (path: string, options?: { readOnly?: boolean; }) => DatabaseSyncType; +type SQLInputValue = import('node:sqlite').SQLInputValue; let _DatabaseSync: DatabaseSyncCtor | null = null; let _sqliteChecked = false; @@ -38,6 +39,165 @@ export async function checkSqliteAvailable (): Promise { return ctor !== null; } +// ======================== 数据库连接管理 ======================== + +/** 数据库连接句柄,封装 DatabaseSync 实例 */ +export class DatabaseHandle { + private db: DatabaseSyncType; + private _closed = false; + readonly filePath: string; + readonly readOnly: boolean; + + constructor (filePath: string, readOnly = false) { + const DB = getDatabaseSync(); + this.db = new DB(filePath, { readOnly }); + this.filePath = filePath; + this.readOnly = readOnly; + } + + /** 数据库是否已关闭 */ + get closed (): boolean { + return this._closed; + } + + private ensureOpen (): void { + if (this._closed) throw new Error('数据库已关闭'); + } + + /** + * 执行 SELECT 查询,返回所有结果行 + * @param sql SQL 语句 + * @param params 绑定参数 (位置参数数组 或 命名参数对象) + */ + query> (sql: string, params?: SQLInputValue[] | Record): T[] { + this.ensureOpen(); + const stmt = this.db.prepare(sql); + if (params) { + if (Array.isArray(params)) { + return stmt.all(...params) as T[]; + } + return stmt.all(params) as T[]; + } + return stmt.all() as T[]; + } + + /** + * 执行 SELECT 查询,仅返回第一行 + * @param sql SQL 语句 + * @param params 绑定参数 + */ + queryOne> (sql: string, params?: SQLInputValue[] | Record): T | undefined { + this.ensureOpen(); + const stmt = this.db.prepare(sql); + if (params) { + if (Array.isArray(params)) { + return stmt.get(...params) as T | undefined; + } + return stmt.get(params) as T | undefined; + } + return stmt.get() as T | undefined; + } + + /** + * 执行非查询 SQL (INSERT/UPDATE/DELETE/CREATE 等) + * @param sql SQL 语句 + * @param params 绑定参数 + * @returns 受影响的行数信息 + */ + execute (sql: string, params?: SQLInputValue[] | Record): { changes: number | bigint; lastInsertRowid: number | bigint; } { + this.ensureOpen(); + const stmt = this.db.prepare(sql); + if (params) { + if (Array.isArray(params)) { + return stmt.run(...params); + } + return stmt.run(params); + } + return stmt.run(); + } + + /** 列出所有表的信息 */ + listTables (): TableInfo[] { + this.ensureOpen(); + return extractTablesInfo(this.db); + } + + /** 获取指定表的列信息 */ + getTableColumns (tableName: string): ColumnInfo[] { + this.ensureOpen(); + const cols = this.db.prepare(`PRAGMA table_info([${tableName}])`).all() as { + cid: number; name: string; type: string; notnull: number; pk: number; + }[]; + return cols.map(col => ({ + cid: col.cid, + name: col.name, + type: col.type, + notnull: col.notnull === 1, + pk: col.pk === 1, + })); + } + + /** 获取表的行数 */ + getRowCount (tableName: string): number { + this.ensureOpen(); + const cnt = this.db.prepare(`SELECT count(*) as cnt FROM [${tableName}]`).get() as { cnt: number; } | undefined; + return cnt?.cnt ?? 0; + } + + /** 关闭数据库连接 */ + close (): void { + if (!this._closed) { + this.db.close(); + this._closed = true; + } + } +} + +/** + * 打开一个已解密的 SQLite 数据库文件 + * @param filePath 解密后的 .db 文件路径 + * @param readOnly 是否以只读模式打开 (默认 true) + */ +export function openDatabase (filePath: string, readOnly = true): DatabaseHandle { + return new DatabaseHandle(filePath, readOnly); +} + +/** + * 解密并打开一个加密的 NTQQ 数据库 + * @param dbPath 加密数据库路径 + * @param passphrase 密钥口令 + * @param cacheDir 解密缓存目录 (可选) + * @param readOnly 是否只读 (默认 true) + */ +export function decryptAndOpen ( + dbPath: string, + passphrase: Buffer, + cacheDir?: string, + readOnly = true +): DatabaseHandle { + const filename = path.basename(dbPath); + + if (cacheDir) { + const cachedPath = path.join(cacheDir, filename); + // 已存在缓存直接打开 + if (fs.existsSync(cachedPath)) { + return new DatabaseHandle(cachedPath, readOnly); + } + fs.mkdirSync(cacheDir, { recursive: true }); + const outPath = decryptDatabaseFile(dbPath, passphrase, cachedPath); + if (!outPath) throw new Error(`解密失败: ${dbPath}`); + return new DatabaseHandle(outPath, readOnly); + } + + // 无缓存目录: 解密到临时文件 + const tmpPath = path.join(os.tmpdir(), `napcat_db_${Date.now()}_${Math.random().toString(36).slice(2)}.db`); + const fileData = fs.readFileSync(dbPath); + const decryptedBuf = decryptDatabase(fileData, passphrase); + if (!decryptedBuf) throw new Error(`解密失败: ${dbPath}`); + fs.writeFileSync(tmpPath, decryptedBuf); + return new DatabaseHandle(tmpPath, readOnly); +} + /** 单个数据库表信息 */ export interface TableInfo { name: string; diff --git a/packages/napcat-framework/napcat.ts b/packages/napcat-framework/napcat.ts index 8ad3e67c2..02fb16434 100644 --- a/packages/napcat-framework/napcat.ts +++ b/packages/napcat-framework/napcat.ts @@ -1,4 +1,3 @@ -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'; @@ -122,22 +121,21 @@ export async function NCoreInitFramework ( 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); - // } - // } - // } + // 测试 DatabaseApi + if (dbPassphrase) { + const dbApi = loaderObject.core.apis.DatabaseApi; + const sqliteOk = await dbApi.isSqliteAvailable(); + if (sqliteOk) { + try { + const result = dbApi.readDatabase('nt_msg.db'); + if (result) { + logger.log('[NapCat] [Database] nt_msg.db:\n' + dbApi.formatResults([result])); + } + } catch (e) { + logger.logError('[NapCat] [Database] 读取失败:', e); + } + } + } // 使用 NapCatAdapterManager 统一管理协议适配器 const adapterManager = new NapCatAdapterManager(loaderObject.core, loaderObject.context, pathWrapper); diff --git a/packages/napcat-shell/base.ts b/packages/napcat-shell/base.ts index dd53ed621..1b9eba4b0 100644 --- a/packages/napcat-shell/base.ts +++ b/packages/napcat-shell/base.ts @@ -716,24 +716,6 @@ export async function NCoreInitShell () { logger.logDebug('本账号数据/缓存目录:', accountDataPath); - // // [测试代码 - 已禁用] 使用捕获的 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, @@ -780,6 +762,23 @@ export class NapCatShell { async InitNapCat () { await this.core.initCore(); + + // 测试 DatabaseApi + if (this.core.dbPassphrase) { + const dbApi = this.core.apis.DatabaseApi; + const sqliteOk = await dbApi.isSqliteAvailable(); + if (sqliteOk) { + try { + const result = dbApi.readDatabase('nt_msg.db'); + if (result) { + this.context.logger.log('[NapCat] [Database] nt_msg.db:\n' + dbApi.formatResults([result])); + } + } catch (e) { + this.context.logger.logError('[NapCat] [Database] 读取失败:', e); + } + } + } + // 监听下线通知并同步到 WebUI this.core.event.on('KickedOffLine', (tips: string) => { WebUiDataRuntime.setQQLoginError(tips);