diff --git a/packages/bridge/src/hook-manager.ts b/packages/bridge/src/hook-manager.ts index 1d9e07a7..98ea0d8e 100644 --- a/packages/bridge/src/hook-manager.ts +++ b/packages/bridge/src/hook-manager.ts @@ -129,13 +129,7 @@ export class HookManager { this.injector = deps.injector ?? { inject: injectHookProcess, - unload: (pid, handle) => { - if (!handle) { - return; - } - - unloadHookProcess(pid, handle); - }, + unload: unloadHookProcess, }; this.makeClient = deps.makeClient ?? ((pid: number) => new QqHookClient(pid)); this.detectAccounts = deps.detectAccounts ?? detectAccountLoginsForPids; diff --git a/packages/bridge/src/hook-session.ts b/packages/bridge/src/hook-session.ts index a20f90a4..115a308c 100644 --- a/packages/bridge/src/hook-session.ts +++ b/packages/bridge/src/hook-session.ts @@ -10,7 +10,7 @@ import type { PacketSink } from '@snowluma/common/protocol-types'; import { isRealUin } from '@snowluma/common/uin'; import { EventEmitter } from 'events'; import { HookPacketClient } from './hook-packet-client'; -import type { HookInjectResult } from './injector'; +import type { HookInjectResult, ManualMapHandle } from './injector'; import { detectUinForPid } from './qq-account'; import type { QqHookClient, QqHookLoginState, QqHookPacket } from './qq-hook-client'; import { statusFor } from './hook-status'; @@ -33,8 +33,8 @@ const RECEIVE_STALE_CONFIRM_MS = 15_000; export type HookSessionDeps = { injector: { - inject: (pid: number) => HookInjectResult | Promise; - unload: (pid: number, handle: HookInjectResult['handle']) => void; + inject: (pid: number) => Promise; + unload: (pid: number, handle: ManualMapHandle) => Promise; }; makeClient: (pid: number) => QqHookClient; /** Account QQ's local data reports as signed in on `pid`, or null. Drives the @@ -440,7 +440,7 @@ export class HookSession extends EventEmitter { const handle = this.injectResult?.handle; if (this.injected && handle) { - this.injector.unload(this.pid, handle); + await this.injector.unload(this.pid, handle); this.log.info('SnowLuma unloaded from PID=%d', this.pid); } diff --git a/packages/bridge/src/injector.ts b/packages/bridge/src/injector.ts index 224c2d5e..6f7772a3 100644 --- a/packages/bridge/src/injector.ts +++ b/packages/bridge/src/injector.ts @@ -11,11 +11,11 @@ export interface ManualMapHandle { } interface NativeHookAddon { - getRuntimeIntegrity?(): unknown; + getRuntimeIntegrityAsync(): Promise; getAllMainProcessAsync(): Promise; - probeDbLock?(dbPath: string): { pid: number; name: string }[]; - loadModuleManual(pid: number, dylibPath: string): ManualMapHandle | Promise; - unloadModuleManual(pid: number, handle: ManualMapHandle): void; + getFileHoldersAsync(path: string): Promise<{ pid: number; name: string }[]>; + loadModuleManualAsync(pid: number, dylibPath: string): Promise; + unloadModuleManualAsync(pid: number, handle: ManualMapHandle): Promise; } export interface HookProcessBaseInfo { @@ -26,7 +26,7 @@ export interface HookProcessBaseInfo { export interface HookInjectResult { method: 'loadModuleManual'; - handle?: ManualMapHandle; + handle: ManualMapHandle; } let nativeAddon: NativeHookAddon | null = null; @@ -123,15 +123,15 @@ export async function injectHookProcess(pid: number): Promise throw new Error(`No hook ${injectableExt} found for ${process.platform}-${process.arch}`); } - return { method: 'loadModuleManual', handle: await addon.loadModuleManual(pid, dllPath) }; + return { method: 'loadModuleManual', handle: await addon.loadModuleManualAsync(pid, dllPath) }; } -export function unloadHookProcess(pid: number, handle: ManualMapHandle): void { +export async function unloadHookProcess(pid: number, handle: ManualMapHandle): Promise { const addon = getNativeHookAddon(); if (!addon) { throw new Error(getNativeHookLoadError() ?? 'hook native addon is not available'); } - addon.unloadModuleManual(pid, handle); + await addon.unloadModuleManualAsync(pid, handle); } diff --git a/packages/bridge/src/qq-account/db-lock.ts b/packages/bridge/src/qq-account/database-holders.ts similarity index 60% rename from packages/bridge/src/qq-account/db-lock.ts rename to packages/bridge/src/qq-account/database-holders.ts index 089d10be..4f882dbc 100644 --- a/packages/bridge/src/qq-account/db-lock.ts +++ b/packages/bridge/src/qq-account/database-holders.ts @@ -1,28 +1,27 @@ -import fs from 'node:fs'; +import fs from 'node:fs/promises'; import { getNativeHookAddon } from '../injector'; -export interface DbLockHolder { +export interface DatabaseHolder { pid: number; - name: string; } -export function probeDbLock(dbPath: string): DbLockHolder[] { +export async function getDatabaseHolders(dbPath: string): Promise { if (process.platform === 'win32') { - return probeWindowsHolders(dbPath); + return getWindowsHolders(dbPath); } - return process.platform === 'linux' ? probeLinuxLocks(dbPath) : []; + return process.platform === 'linux' ? getLinuxHolders(dbPath) : []; } -function probeWindowsHolders(dbPath: string): DbLockHolder[] { +async function getWindowsHolders(dbPath: string): Promise { const addon = getNativeHookAddon(); - if (!addon?.probeDbLock) { - throw new Error('Windows account detection requires a hook addon with probeDbLock'); + if (!addon?.getFileHoldersAsync) { + throw new Error('Windows account detection requires a hook addon with getFileHoldersAsync'); } - const holders = addon.probeDbLock(dbPath); + const holders = await addon.getFileHoldersAsync(dbPath); if ( !Array.isArray(holders) || @@ -50,16 +49,22 @@ export function isQqProcessName(name: string): boolean { } /** Match POSIX locks by device and inode; the table does not contain file paths. */ -function probeLinuxLocks(dbPath: string): DbLockHolder[] { - const stat = fs.statSync(dbPath, { throwIfNoEntry: false }); +async function getLinuxHolders(dbPath: string): Promise { + const stat = await fs.stat(dbPath).catch((error: NodeJS.ErrnoException) => { + if (error.code === 'ENOENT') { + return null; + } + + throw error; + }); if (!stat) { return []; } const key = deviceInodeKey(stat.dev, stat.ino); - const table = fs.readFileSync('/proc/locks', 'utf8'); - const holders: DbLockHolder[] = []; + const table = await fs.readFile('/proc/locks', 'utf8'); + const holders: DatabaseHolder[] = []; const seen = new Set(); for (const line of table.split('\n')) { @@ -77,7 +82,7 @@ function probeLinuxLocks(dbPath: string): DbLockHolder[] { } seen.add(pid); - holders.push({ pid, name: readProcessName(pid) }); + holders.push({ pid, name: await readProcessName(pid) }); } return holders; @@ -89,10 +94,14 @@ function deviceInodeKey(device: number, inode: number): string { return `${major.toString(16).padStart(2, '0')}:${minor.toString(16).padStart(2, '0')}:${inode}`; } -function readProcessName(pid: number): string { +async function readProcessName(pid: number): Promise { try { - return fs.readFileSync(`/proc/${pid}/comm`, 'utf8').trim(); - } catch { - return ''; + return (await fs.readFile(`/proc/${pid}/comm`, 'utf8')).trim(); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === 'ENOENT') { + return ''; + } + + throw error; } } diff --git a/packages/bridge/src/qq-account/detect.ts b/packages/bridge/src/qq-account/detect.ts index cf98ef26..8e179676 100644 --- a/packages/bridge/src/qq-account/detect.ts +++ b/packages/bridge/src/qq-account/detect.ts @@ -1,5 +1,5 @@ import { createLogger } from '@snowluma/common/logger'; -import { isQqProcessName, probeDbLock } from './db-lock'; +import { isQqProcessName, getDatabaseHolders } from './database-holders'; import { readLocalAccounts, type LocalAccount } from './login-db'; import { loginDbPaths, ntMsgDbPath, qqDataRoots, qqDataRootsForPid } from './paths'; @@ -39,8 +39,8 @@ export async function detectAccountLogins( } for (const account of report.accounts) { - const holder = probeDbLock(ntMsgDbPath(root, account)).find((candidate) => - isQqProcessName(candidate.name), + const holder = (await getDatabaseHolders(ntMsgDbPath(root, account))).find( + (candidate) => isQqProcessName(candidate.name), ); states.push({ ...account, pid: holder?.pid ?? null }); } diff --git a/packages/bridge/src/qq-account/index.ts b/packages/bridge/src/qq-account/index.ts index 496d70c8..1cebb8df 100644 --- a/packages/bridge/src/qq-account/index.ts +++ b/packages/bridge/src/qq-account/index.ts @@ -1,4 +1,4 @@ -export { isQqProcessName, probeDbLock, type DbLockHolder } from './db-lock'; +export { isQqProcessName, getDatabaseHolders, type DatabaseHolder } from './database-holders'; export { detectAccountLogins, detectAccountLoginsForPids, diff --git a/packages/bridge/src/runtime-integrity.ts b/packages/bridge/src/runtime-integrity.ts index bc114498..99df5905 100644 --- a/packages/bridge/src/runtime-integrity.ts +++ b/packages/bridge/src/runtime-integrity.ts @@ -76,18 +76,18 @@ function isNativeRuntimeIntegrity(value: unknown): value is NativeRuntimeIntegri ); } -let cached: RuntimeIntegrity | undefined; +let cached: Promise | undefined; /** One startup snapshot, shared by the startup log and the WebUI warning. */ -export function getRuntimeIntegrity(): RuntimeIntegrity { +export function getRuntimeIntegrity(): Promise { + return (cached ??= readRuntimeIntegrity()); +} + +async function readRuntimeIntegrity(): Promise { if (process.platform !== 'win32') { return { status: 'unsupported' }; } - if (cached) { - return cached; - } - try { const addon = getNativeHookAddon(); @@ -95,17 +95,17 @@ export function getRuntimeIntegrity(): RuntimeIntegrity { throw new Error(getNativeHookLoadError() ?? '原生组件不可用'); } - if (typeof addon.getRuntimeIntegrity !== 'function') { + if (typeof addon.getRuntimeIntegrityAsync !== 'function') { throw new Error('当前原生组件不支持完整性诊断,请更新原生组件'); } - const result = addon.getRuntimeIntegrity(); + const result = await addon.getRuntimeIntegrityAsync(); if (!isNativeRuntimeIntegrity(result)) { throw new Error('原生完整性诊断返回了无效数据'); } - cached = { + return { status: 'available', pid: result.pid, executablePath: result.executablePath, @@ -113,11 +113,9 @@ export function getRuntimeIntegrity(): RuntimeIntegrity { file: result.file, }; } catch (error) { - cached = { + return { status: 'unavailable', error: error instanceof Error ? error.message : String(error), }; } - - return cached; } diff --git a/packages/bridge/tests/hook-manager-state-notify.test.ts b/packages/bridge/tests/hook-manager-state-notify.test.ts index 5821751f..8549917b 100644 --- a/packages/bridge/tests/hook-manager-state-notify.test.ts +++ b/packages/bridge/tests/hook-manager-state-notify.test.ts @@ -68,8 +68,11 @@ function makeManager( bridgeManager, pipeWatcher, injector: { - inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })), - unload: vi.fn(), + inject: vi.fn(async () => ({ + method: 'loadModuleManual' as const, + handle: DUMMY_HANDLE, + })), + unload: vi.fn(async () => {}), }, makeClient: clientFactory, listProcesses: async () => pids.map((pid) => ({ pid, name: 'qq', path: '' })), @@ -174,11 +177,11 @@ describe('HookManager.onSessionsChanged', () => { } as unknown as BridgeManagerSink, pipeWatcher, injector: { - inject: vi.fn(() => ({ + inject: vi.fn(async () => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE, })), - unload: vi.fn(), + unload: vi.fn(async () => {}), }, makeClient: vi.fn(() => { const c = new EventEmitter() as any; diff --git a/packages/bridge/tests/hook-manager.test.ts b/packages/bridge/tests/hook-manager.test.ts index 94ee6739..83d2d585 100644 --- a/packages/bridge/tests/hook-manager.test.ts +++ b/packages/bridge/tests/hook-manager.test.ts @@ -29,19 +29,19 @@ function makeManager(opts: { autoLoadOnDiscovery?: boolean; processes?: number[]; onSessionsChanged?: () => void; - inject?: (pid: number) => HookInjectResult | Promise; + inject?: (pid: number) => Promise; detectAccounts?: (pids: readonly number[]) => Promise; }) { let pids = opts.processes ?? []; const live = new Set(); const inject = vi.fn( opts.inject ?? - (() => ({ + (async () => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE, })), ); - const unload = vi.fn(); + const unload = vi.fn(async () => {}); const pipeWatcher = new PipeWatcher({ listProcesses: async () => pids.map((pid) => ({ pid, name: 'qq', path: '' })), listLivePipes: async () => new Set(live), diff --git a/packages/bridge/tests/hook-reconnect-no-login-e2e.test.ts b/packages/bridge/tests/hook-reconnect-no-login-e2e.test.ts index ec604288..5b60c1d6 100644 --- a/packages/bridge/tests/hook-reconnect-no-login-e2e.test.ts +++ b/packages/bridge/tests/hook-reconnect-no-login-e2e.test.ts @@ -58,11 +58,11 @@ describe('HookManager — Docker reconnect-without-login leak guard', () => { bridgeManager, pipeWatcher, injector: { - inject: vi.fn(() => ({ + inject: vi.fn(async () => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE, })), - unload: vi.fn(), + unload: vi.fn(async () => {}), }, makeClient: () => { const c = new FakeClient(); diff --git a/packages/bridge/tests/hook-reconnect-no-login.test.ts b/packages/bridge/tests/hook-reconnect-no-login.test.ts index 382f87f0..a0efe88b 100644 --- a/packages/bridge/tests/hook-reconnect-no-login.test.ts +++ b/packages/bridge/tests/hook-reconnect-no-login.test.ts @@ -59,11 +59,11 @@ describe('HookSession — pipe reconnect with QQ never logging in', () => { const session = new HookSession(61, { detectLoginUin: async () => null, injector: { - inject: vi.fn(() => ({ + inject: vi.fn(async () => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE, })), - unload: vi.fn(), + unload: vi.fn(async () => {}), }, makeClient: () => { const c = new FakeClient(); @@ -103,11 +103,11 @@ describe('HookSession — pipe reconnect with QQ never logging in', () => { const session = new HookSession(61, { detectLoginUin: async () => null, injector: { - inject: vi.fn(() => ({ + inject: vi.fn(async () => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE, })), - unload: vi.fn(), + unload: vi.fn(async () => {}), }, makeClient: () => { const c = new FakeClient(); diff --git a/packages/bridge/tests/hook-session.test.ts b/packages/bridge/tests/hook-session.test.ts index 1cbca2eb..5e9417e1 100644 --- a/packages/bridge/tests/hook-session.test.ts +++ b/packages/bridge/tests/hook-session.test.ts @@ -112,8 +112,8 @@ function makeSession( let pipeLive = opts.pipeLive ?? false; const clients: FakeClient[] = []; const injector = { - inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })), - unload: vi.fn(), + inject: vi.fn(async () => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })), + unload: vi.fn(async () => {}), }; // Default detection exposes no account so the reconcile safety net is inert // unless a test opts into a known one. @@ -200,10 +200,10 @@ describe('HookSession — runtime TRACE', () => { try { const injector = { - inject: vi.fn(() => { + inject: vi.fn(async () => { throw new Error('fixture inject failure'); }), - unload: vi.fn(), + unload: vi.fn(async () => {}), }; const failedLoad = new HookSession(7103, { injector, @@ -248,11 +248,11 @@ describe('HookSession — runtime TRACE', () => { const clients: FakeClient[] = []; const session = new HookSession(7108, { injector: { - inject: () => { + inject: async () => { pipeLive = true; throw new Error('component loading failed [COMPONENT_LOAD_FAILED]'); }, - unload: () => undefined, + unload: async () => undefined, }, makeClient: () => { const client = new FakeClient(); @@ -451,8 +451,8 @@ describe('HookSession — load', () => { }, ); const injector = { - inject: vi.fn(() => loading), - unload: vi.fn(), + inject: vi.fn(async () => loading), + unload: vi.fn(async () => {}), }; const session = new HookSession(1234, { injector, @@ -474,10 +474,10 @@ describe('HookSession — load', () => { it('inject failure → status error, error message captured', async () => { const injector = { - inject: vi.fn(() => { + inject: vi.fn(async () => { throw new Error('inject boom'); }), - unload: vi.fn(), + unload: vi.fn(async () => {}), }; const session = new HookSession(1234, { injector, @@ -498,7 +498,7 @@ describe('HookSession — load', () => { method: 'loadModuleManual' as const, handle: DUMMY_HANDLE, }), - unload: vi.fn(), + unload: vi.fn(async () => {}), }; const session = new HookSession(1234, { injector, @@ -678,11 +678,11 @@ describe('HookSession — unload', () => { const session = new HookSession(pid, { injector: { - inject: vi.fn(() => ({ + inject: vi.fn(async () => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE, })), - unload: vi.fn(), + unload: vi.fn(async () => {}), }, makeClient: () => new FakeClient() as unknown as QqHookClient, pipeWatcher: { isPipeLive: () => pipeLive, tickNow }, @@ -699,6 +699,48 @@ describe('HookSession — unload', () => { }); describe('HookSession — serialization', () => { + it('waits for native unload before starting a queued load', async () => { + const ctx = makeSession(); + await ctx.session.load(); + let finish!: () => void; + ctx.injector.unload.mockReturnValueOnce( + new Promise((resolve) => { + finish = resolve; + }), + ); + + const unloading = ctx.session.unload(); + const loading = ctx.session.load(); + await flush(); + expect(ctx.injector.unload).toHaveBeenCalledOnce(); + expect(ctx.injector.inject).toHaveBeenCalledTimes(1); + expect(ctx.session.toInfo().injected).toBe(true); + + finish(); + await unloading; + await loading; + expect(ctx.injector.inject).toHaveBeenCalledTimes(2); + ctx.session.dispose(); + }); + + it('retains the handle when native unload rejects so it can be retried', async () => { + const ctx = makeSession(); + await ctx.session.load(); + ctx.injector.unload.mockRejectedValueOnce(new Error('unload rejected')); + + await expect(ctx.session.unload()).resolves.toMatchObject({ + status: 'error', + error: 'unload rejected', + injected: true, + }); + await expect(ctx.session.unload()).resolves.toMatchObject({ + status: 'available', + injected: false, + }); + expect(ctx.injector.unload).toHaveBeenNthCalledWith(2, ctx.session.pid, DUMMY_HANDLE); + ctx.session.dispose(); + }); + it('user mashing load → unload → load runs in order, end state consistent', async () => { const ctx = makeSession({ pipeLive: false }); @@ -864,10 +906,10 @@ describe('HookSession — pipe-down must not clobber a settled error', () => { it('onPipeDown after a failed load leaves the error status intact', async () => { const injector = { - inject: vi.fn(() => { + inject: vi.fn(async () => { throw new Error('inject boom'); }), - unload: vi.fn(), + unload: vi.fn(async () => {}), }; const session = new HookSession(1234, { injector, diff --git a/packages/bridge/tests/injector.test.ts b/packages/bridge/tests/injector.test.ts index 0efd463f..fc560360 100644 --- a/packages/bridge/tests/injector.test.ts +++ b/packages/bridge/tests/injector.test.ts @@ -62,14 +62,16 @@ function allowExisting(paths: readonly string[]): void { function fakeAddon( overrides: { getAllMainProcessAsync?: number[]; - loadModuleManual?: (pid: number, dylibPath: string) => unknown; - unloadModuleManual?: (pid: number, handle: typeof HANDLE) => void; + loadModuleManualAsync?: (pid: number, dylibPath: string) => Promise; + unloadModuleManualAsync?: (pid: number, handle: typeof HANDLE) => Promise; } = {}, ) { return { getAllMainProcessAsync: vi.fn(async () => overrides.getAllMainProcessAsync ?? []), - loadModuleManual: vi.fn(overrides.loadModuleManual ?? (() => HANDLE)), - unloadModuleManual: vi.fn(overrides.unloadModuleManual ?? (() => undefined)), + loadModuleManualAsync: vi.fn(overrides.loadModuleManualAsync ?? (async () => HANDLE)), + unloadModuleManualAsync: vi.fn( + overrides.unloadModuleManualAsync ?? (async () => undefined), + ), }; } @@ -335,13 +337,13 @@ describe('injectHookProcess', () => { await expect(injectHookProcess(4242)).rejects.toThrow('No hook so found for linux-x64'); }); - it('awaits a thenable loadModuleManual handle', async () => { + it('awaits native asynchronous injection', async () => { setPlatform('linux', 'x64'); const nodePath = nativeCandidate('snowluma-linux-x64.node', 0); const soPath = nativeCandidate('snowluma-linux-x64.so', 0); allowExisting([nodePath, soPath]); const addon = fakeAddon({ - loadModuleManual: () => Promise.resolve(HANDLE), + loadModuleManualAsync: () => Promise.resolve(HANDLE), }); installDlopen(addon); @@ -350,24 +352,8 @@ describe('injectHookProcess', () => { method: 'loadModuleManual', handle: HANDLE, }); - expect(addon.loadModuleManual).toHaveBeenCalledTimes(1); - expect(addon.loadModuleManual).toHaveBeenCalledWith(4242, soPath); - }); - - it('accepts a synchronous loadModuleManual return value', async () => { - setPlatform('darwin', 'arm64'); - const nodePath = nativeCandidate('snowluma-darwin-arm64.node', 1); - const soPath = nativeCandidate('snowluma-darwin-arm64.so', 1); - allowExisting([nodePath, soPath]); - const addon = fakeAddon({ loadModuleManual: () => HANDLE }); - installDlopen(addon); - - const { injectHookProcess } = await loadInjector(); - await expect(injectHookProcess(77)).resolves.toEqual({ - method: 'loadModuleManual', - handle: HANDLE, - }); - expect(addon.loadModuleManual).toHaveBeenCalledWith(77, soPath); + expect(addon.loadModuleManualAsync).toHaveBeenCalledTimes(1); + expect(addon.loadModuleManualAsync).toHaveBeenCalledWith(4242, soPath); }); it('injects snowluma-win32-x64.dll on win32 x64', async () => { @@ -375,7 +361,7 @@ describe('injectHookProcess', () => { const nodePath = nativeCandidate('snowluma-win32-x64.node', 0); const dllPath = nativeCandidate('snowluma-win32-x64.dll', 0); allowExisting([nodePath, dllPath]); - const addon = fakeAddon({ loadModuleManual: () => HANDLE }); + const addon = fakeAddon({ loadModuleManualAsync: async () => HANDLE }); installDlopen(addon); const { injectHookProcess } = await loadInjector(); @@ -383,7 +369,7 @@ describe('injectHookProcess', () => { method: 'loadModuleManual', handle: HANDLE, }); - expect(addon.loadModuleManual).toHaveBeenCalledWith(5150, dllPath); + expect(addon.loadModuleManualAsync).toHaveBeenCalledWith(5150, dllPath); }); it('propagates a rejected loadModuleManual', async () => { @@ -394,7 +380,7 @@ describe('injectHookProcess', () => { ]); installDlopen( fakeAddon({ - loadModuleManual: () => Promise.reject(new Error('map failed')), + loadModuleManualAsync: () => Promise.reject(new Error('map failed')), }), ); @@ -404,10 +390,24 @@ describe('injectHookProcess', () => { }); describe('unloadHookProcess', () => { + it('propagates native unload rejection', async () => { + setPlatform('linux', 'x64'); + allowExisting([nativeCandidate('snowluma-linux-x64.node', 0)]); + installDlopen( + fakeAddon({ + unloadModuleManualAsync: async () => { + throw new Error('unload failed'); + }, + }), + ); + const { unloadHookProcess } = await loadInjector(); + await expect(unloadHookProcess(4242, HANDLE)).rejects.toThrow('unload failed'); + }); + it('throws the missing-addon load error', async () => { setPlatform('linux', 'x64'); const { unloadHookProcess } = await loadInjector(); - expect(() => unloadHookProcess(4242, HANDLE)).toThrow( + await expect(unloadHookProcess(4242, HANDLE)).rejects.toThrow( 'No hook native addon found for linux-x64', ); }); @@ -419,8 +419,8 @@ describe('unloadHookProcess', () => { installDlopen(addon); const { unloadHookProcess } = await loadInjector(); - expect(unloadHookProcess(4242, HANDLE)).toBeUndefined(); - expect(addon.unloadModuleManual).toHaveBeenCalledTimes(1); - expect(addon.unloadModuleManual).toHaveBeenCalledWith(4242, HANDLE); + await expect(unloadHookProcess(4242, HANDLE)).resolves.toBeUndefined(); + expect(addon.unloadModuleManualAsync).toHaveBeenCalledTimes(1); + expect(addon.unloadModuleManualAsync).toHaveBeenCalledWith(4242, HANDLE); }); }); diff --git a/packages/bridge/tests/qq-account-db-lock.test.ts b/packages/bridge/tests/qq-account-database-holders.test.ts similarity index 63% rename from packages/bridge/tests/qq-account-db-lock.test.ts rename to packages/bridge/tests/qq-account-database-holders.test.ts index 042aa221..3a6a401d 100644 --- a/packages/bridge/tests/qq-account-db-lock.test.ts +++ b/packages/bridge/tests/qq-account-database-holders.test.ts @@ -3,7 +3,7 @@ import { mkdtemp, rm } from 'node:fs/promises'; import os from 'node:os'; import path from 'node:path'; import { SqliteDatabase } from '@snowluma/sqlite'; -import { isQqProcessName, probeDbLock } from '../src/qq-account/db-lock'; +import { isQqProcessName, getDatabaseHolders } from '../src/qq-account/database-holders'; const native = vi.hoisted(() => ({ addon: vi.fn<() => unknown>(() => null) })); @@ -12,13 +12,13 @@ vi.mock('../src/injector', () => ({ getNativeHookAddon: native.addon })); const IS_LINUX = process.platform === 'linux'; const ORIGINAL_PLATFORM = process.platform; -/** Run `probeDbLock` as if the host were Windows, with a stubbed addon. */ -function asWindows(addon: unknown, run: () => T): T { +/** Run `getDatabaseHolders` as if the host were Windows, with a stubbed addon. */ +async function asWindows(addon: unknown, run: () => Promise): Promise { Object.defineProperty(process, 'platform', { value: 'win32', configurable: true }); native.addon.mockReturnValue(addon); try { - return run(); + return await run(); } finally { Object.defineProperty(process, 'platform', { value: ORIGINAL_PLATFORM, @@ -33,9 +33,9 @@ afterEach(() => { }); describe('database holder probe', () => { - it.runIf(IS_LINUX)('reports nothing for a file that is not there', () => { + it.runIf(IS_LINUX)('reports nothing for a file that is not there', async () => { const missing = path.join(os.tmpdir(), `snowluma-absent-${process.pid}.db`); - expect(probeDbLock(missing)).toEqual([]); + expect(await getDatabaseHolders(missing)).toEqual([]); }); it.runIf(IS_LINUX)('finds the process holding a database', async () => { @@ -51,7 +51,7 @@ describe('database holder probe', () => { await db.exec('CREATE TABLE t(value TEXT)'); await db.exec('BEGIN IMMEDIATE'); - const holders = probeDbLock(file); + const holders = await getDatabaseHolders(file); const self = holders.find((holder) => holder.pid === process.pid); expect(self).toBeDefined(); // The holder is named from /proc//comm, and that name is what @@ -60,7 +60,9 @@ describe('database holder probe', () => { expect(isQqProcessName(self!.name)).toBe(false); await db.exec('ROLLBACK'); - expect(probeDbLock(file).some((holder) => holder.pid === process.pid)).toBe(false); + expect( + (await getDatabaseHolders(file)).some((holder) => holder.pid === process.pid), + ).toBe(false); } finally { await db.close(); await rm(directory, { recursive: true, force: true }); @@ -69,15 +71,28 @@ describe('database holder probe', () => { }); describe('Windows holder probe', () => { - it('reports the holders the addon lists', () => { - const holders = asWindows( + it('propagates rejected native queries instead of treating them as no login', async () => { + await expect( + asWindows( + { + getFileHoldersAsync: async () => { + throw new Error('RmGetList failed: 5'); + }, + }, + () => getDatabaseHolders('C:\\nt_msg.db'), + ), + ).rejects.toThrow('RmGetList failed: 5'); + }); + + it('reports the holders the addon lists', async () => { + const holders = await asWindows( { - probeDbLock: () => [ + getFileHoldersAsync: async () => [ { pid: 4242, name: 'QQ.exe' }, { pid: 7, name: 'weq' }, ], }, - () => probeDbLock('C:\\Tencent Files\\10001\\nt_qq\\nt_db\\nt_msg.db'), + () => getDatabaseHolders('C:\\Tencent Files\\10001\\nt_qq\\nt_db\\nt_msg.db'), ); expect(holders).toEqual([ @@ -88,22 +103,26 @@ describe('Windows holder probe', () => { it.each([[{ pid: 0, name: 'QQ' }], [{ pid: 9 }], [null], 'not-an-array'])( 'reports malformed native results: %j', - (result) => { - expect(() => - asWindows({ probeDbLock: () => result }, () => probeDbLock('C:\\nt_msg.db')), - ).toThrow('Invalid database holders'); + async (result) => { + await expect( + asWindows({ getFileHoldersAsync: async () => result }, () => + getDatabaseHolders('C:\\nt_msg.db'), + ), + ).rejects.toThrow('Invalid database holders'); }, ); - it('accepts an empty holder list', () => { - expect(asWindows({ probeDbLock: () => [] }, () => probeDbLock('C:\\nt_msg.db'))).toEqual( - [], - ); + it('accepts an empty holder list', async () => { + expect( + await asWindows({ getFileHoldersAsync: async () => [] }, () => + getDatabaseHolders('C:\\nt_msg.db'), + ), + ).toEqual([]); }); - it.each([null, {}])('reports an unavailable native probe: %j', (addon) => { - expect(() => asWindows(addon, () => probeDbLock('C:\\nt_msg.db'))).toThrow( - 'requires a hook addon with probeDbLock', + it.each([null, {}])('reports an unavailable native probe: %j', async (addon) => { + await expect(asWindows(addon, () => getDatabaseHolders('C:\\nt_msg.db'))).rejects.toThrow( + 'requires a hook addon with getFileHoldersAsync', ); }); }); diff --git a/packages/bridge/tests/qq-account-detect.test.ts b/packages/bridge/tests/qq-account-detect.test.ts index cb61b620..8518c5d3 100644 --- a/packages/bridge/tests/qq-account-detect.test.ts +++ b/packages/bridge/tests/qq-account-detect.test.ts @@ -7,15 +7,15 @@ import { getLogLevel, setLogLevel, subscribeLogs, type LogEntry } from '@snowlum const mocks = vi.hoisted(() => ({ readLocalAccounts: vi.fn(), - probeDbLock: vi.fn(), + getDatabaseHolders: vi.fn(), })); // The account list and the holder probe are covered on their own; this file is // about how the two are joined. vi.mock('../src/qq-account/login-db', () => ({ readLocalAccounts: mocks.readLocalAccounts })); -vi.mock('../src/qq-account/db-lock', async (importOriginal) => ({ - ...(await importOriginal()), - probeDbLock: mocks.probeDbLock, +vi.mock('../src/qq-account/database-holders', async (importOriginal) => ({ + ...(await importOriginal()), + getDatabaseHolders: mocks.getDatabaseHolders, })); import { detectAccountLogins, detectAccountLoginsForPids } from '../src/qq-account/detect'; @@ -29,7 +29,7 @@ const children: Array> = []; afterEach(async () => { mocks.readLocalAccounts.mockReset(); - mocks.probeDbLock.mockReset(); + mocks.getDatabaseHolders.mockReset(); for (const child of children.splice(0)) { child.kill(); @@ -77,7 +77,7 @@ describe('local account detection', () => { it('labels each account with the process holding its database', async () => { const root = await makeRoot(); mocks.readLocalAccounts.mockResolvedValue({ accounts: [ALICE, BOB], failures: [] }); - mocks.probeDbLock.mockImplementation((dbPath: string) => { + mocks.getDatabaseHolders.mockImplementation(async (dbPath: string) => { if (dbPath === ntMsgDbPath(root, ALICE)) { return [{ pid: 4242, name: 'qq' }]; } @@ -98,7 +98,7 @@ describe('local account detection', () => { mocks.readLocalAccounts.mockImplementation(async (root: string) => root === own ? { accounts: [ALICE], failures: [] } : { accounts: [BOB], failures: [] }, ); - mocks.probeDbLock.mockImplementation((dbPath: string) => + mocks.getDatabaseHolders.mockImplementation(async (dbPath: string) => dbPath === ntMsgDbPath(extra, BOB) ? [{ pid: 5151, name: 'qq' }] : [], ); @@ -109,7 +109,7 @@ describe('local account detection', () => { // An account held under an instance's own HOME is still labelled, which // is what a single-root lookup cannot do. - expect(mocks.probeDbLock).toHaveBeenCalledWith(ntMsgDbPath(extra, BOB)); + expect(mocks.getDatabaseHolders).toHaveBeenCalledWith(ntMsgDbPath(extra, BOB)); }); it('keeps account records with the same uin scoped to their own root', async () => { @@ -120,7 +120,7 @@ describe('local account detection', () => { ? { accounts: [ALICE], failures: [] } : { accounts: [{ ...ALICE, nickname: 'Stale' }], failures: [] }, ); - mocks.probeDbLock.mockImplementation((file: string) => + mocks.getDatabaseHolders.mockImplementation(async (file: string) => file === ntMsgDbPath(second, ALICE) ? [{ pid: 5151, name: 'qq' }] : [], ); @@ -152,7 +152,7 @@ describe('local account detection', () => { }, ], }); - mocks.probeDbLock.mockReturnValue([]); + mocks.getDatabaseHolders.mockResolvedValue([]); // An unreadable login.db must not look like "no accounts": an // operator reading the log has to see why nothing was reported. @@ -176,7 +176,7 @@ describe.runIf(process.platform === 'linux')('per-process data roots', () => { const home = await makeRoot(); const pid = await spawnWithHome(home); mocks.readLocalAccounts.mockResolvedValue({ accounts: [], failures: [] }); - mocks.probeDbLock.mockReturnValue([]); + mocks.getDatabaseHolders.mockResolvedValue([]); await detectAccountLoginsForPids([pid]); @@ -188,7 +188,7 @@ describe.runIf(process.platform === 'linux')('per-process data roots', () => { const home = await makeRoot(); const pids = [await spawnWithHome(home), await spawnWithHome(home)]; mocks.readLocalAccounts.mockResolvedValue({ accounts: [], failures: [] }); - mocks.probeDbLock.mockReturnValue([]); + mocks.getDatabaseHolders.mockResolvedValue([]); await detectAccountLoginsForPids(pids); @@ -200,7 +200,7 @@ describe.runIf(process.platform === 'linux')('per-process data roots', () => { const configHome = await makeRoot(); const pid = await spawnWithHome(home, { XDG_CONFIG_HOME: configHome }); mocks.readLocalAccounts.mockResolvedValue({ accounts: [], failures: [] }); - mocks.probeDbLock.mockReturnValue([]); + mocks.getDatabaseHolders.mockResolvedValue([]); await detectAccountLoginsForPids([pid]); @@ -213,7 +213,7 @@ describe.runIf(process.platform === 'linux')('per-process data roots', () => { const second = await makeRoot(); const pids = [await spawnWithHome(first), await spawnWithHome(second)]; mocks.readLocalAccounts.mockResolvedValue({ accounts: [], failures: [] }); - mocks.probeDbLock.mockReturnValue([]); + mocks.getDatabaseHolders.mockResolvedValue([]); await detectAccountLoginsForPids(pids); @@ -225,7 +225,7 @@ describe.runIf(process.platform === 'linux')('per-process data roots', () => { const home = await makeRoot(); const pid = await spawnWithHome(home); mocks.readLocalAccounts.mockResolvedValue({ accounts: [], failures: [] }); - mocks.probeDbLock.mockReturnValue([]); + mocks.getDatabaseHolders.mockResolvedValue([]); // The child exits, so its environment is no longer readable. await new Promise((resolve) => { diff --git a/packages/bridge/tests/runtime-integrity.test.ts b/packages/bridge/tests/runtime-integrity.test.ts index 124c896f..6e1f2a0d 100644 --- a/packages/bridge/tests/runtime-integrity.test.ts +++ b/packages/bridge/tests/runtime-integrity.test.ts @@ -56,20 +56,22 @@ describe('runtime integrity diagnostics', () => { }); it('keeps one startup snapshot for logging and all WebUI polls', async () => { - const read = vi.fn().mockReturnValue(sample()); - native.load.mockReturnValue({ getRuntimeIntegrity: read }); + const read = vi.fn().mockResolvedValue(sample()); + native.load.mockReturnValue({ getRuntimeIntegrityAsync: read }); const { getRuntimeIntegrity } = await import('../src/runtime-integrity'); - const first = getRuntimeIntegrity(); + const pending = getRuntimeIntegrity(); + expect(getRuntimeIntegrity()).toBe(pending); + const first = await pending; expect(first).toMatchObject({ status: 'available', process: { rid: 8192 }, file: { label: null }, }); - read.mockReturnValue({ + read.mockResolvedValue({ ...sample(), file: { status: 'ok', label: { rid: 4096, inherited: true, policy: 1 } }, }); - expect(getRuntimeIntegrity()).toBe(first); + expect(await getRuntimeIntegrity()).toBe(first); expect(read).toHaveBeenCalledTimes(1); }); @@ -77,13 +79,13 @@ describe('runtime integrity diagnostics', () => { 'retains %s query errors and the other successful result', async (field) => { native.load.mockReturnValue({ - getRuntimeIntegrity: () => ({ + getRuntimeIntegrityAsync: async () => ({ ...sample(), [field]: { status: 'error', operation: 'Win32Query', code: 5 }, }), }); const { getRuntimeIntegrity } = await import('../src/runtime-integrity'); - expect(getRuntimeIntegrity()).toMatchObject({ + expect(await getRuntimeIntegrity()).toMatchObject({ status: 'available', [field]: { status: 'error', operation: 'Win32Query', code: 5 }, }); @@ -93,7 +95,7 @@ describe('runtime integrity diagnostics', () => { it('reports old addons as unavailable rather than Medium', async () => { native.load.mockReturnValue({}); const { getRuntimeIntegrity } = await import('../src/runtime-integrity'); - expect(getRuntimeIntegrity()).toMatchObject({ + expect(await getRuntimeIntegrity()).toMatchObject({ status: 'unavailable', error: expect.stringContaining('不支持'), }); @@ -103,7 +105,7 @@ describe('runtime integrity diagnostics', () => { native.load.mockReturnValue(null); native.error.mockReturnValue('dlopen failed: incompatible binary'); const { getRuntimeIntegrity } = await import('../src/runtime-integrity'); - expect(getRuntimeIntegrity()).toMatchObject({ + expect(await getRuntimeIntegrity()).toMatchObject({ status: 'unavailable', error: 'dlopen failed: incompatible binary', }); @@ -115,28 +117,26 @@ describe('runtime integrity diagnostics', () => { { ...sample(), process: { status: 'ok', rid: -1 } }, { ...sample(), file: { status: 'ok', label: { rid: 4096, inherited: 'yes', policy: 1 } } }, ])('rejects malformed or wrong-process native results', async (result) => { - native.load.mockReturnValue({ getRuntimeIntegrity: () => result }); + native.load.mockReturnValue({ getRuntimeIntegrityAsync: async () => result }); const { getRuntimeIntegrity } = await import('../src/runtime-integrity'); - expect(getRuntimeIntegrity()).toMatchObject({ + expect(await getRuntimeIntegrity()).toMatchObject({ status: 'unavailable', error: expect.stringContaining('无效数据'), }); }); - it('preserves thrown errors without repeatedly probing on WebUI polls', async () => { + it('preserves rejected errors without repeatedly probing on WebUI polls', async () => { const read = vi .fn() - .mockImplementationOnce(() => { - throw new Error('allocation failed'); - }) - .mockReturnValue(sample()); - native.load.mockReturnValue({ getRuntimeIntegrity: read }); + .mockRejectedValueOnce(new Error('allocation failed')) + .mockResolvedValue(sample()); + native.load.mockReturnValue({ getRuntimeIntegrityAsync: read }); const { getRuntimeIntegrity } = await import('../src/runtime-integrity'); - expect(getRuntimeIntegrity()).toMatchObject({ + expect(await getRuntimeIntegrity()).toMatchObject({ status: 'unavailable', error: 'allocation failed', }); - expect(getRuntimeIntegrity()).toMatchObject({ + expect(await getRuntimeIntegrity()).toMatchObject({ status: 'unavailable', error: 'allocation failed', }); @@ -146,7 +146,7 @@ describe('runtime integrity diagnostics', () => { it('does not load the addon on non-Windows hosts', async () => { Object.defineProperty(process, 'platform', { value: 'linux', configurable: true }); const { getRuntimeIntegrity } = await import('../src/runtime-integrity'); - expect(getRuntimeIntegrity()).toEqual({ status: 'unsupported' }); + expect(await getRuntimeIntegrity()).toEqual({ status: 'unsupported' }); expect(native.load).not.toHaveBeenCalled(); }); }); diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 6a58b7a6..327e1166 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -59,7 +59,7 @@ async function main() { perUinEnabled: runtimeConfig.logPerUin ?? DEFAULT_LOG_PER_UIN, }); log.info('SnowLuma starting'); - logRuntimeIntegrity(getRuntimeIntegrity()); + logRuntimeIntegrity(await getRuntimeIntegrity()); const stopNativeStageSync = startNativeStageSync({ version: APP_VERSION, dataDir: 'data', diff --git a/packages/core/src/webui/server.ts b/packages/core/src/webui/server.ts index 87c70caa..534455c8 100644 --- a/packages/core/src/webui/server.ts +++ b/packages/core/src/webui/server.ts @@ -1364,7 +1364,7 @@ export async function initWebUI( return usage; } - app.get('/api/system', (c) => { + app.get('/api/system', async (c) => { const cpus = os.cpus(); const usage = sampleCpuLoad(); const totalMem = os.totalmem(); @@ -1397,7 +1397,7 @@ export async function initWebUI( }, runtime: { pid: process.pid, - lowIntegrity: hasLowProcessIntegrity(getRuntimeIntegrity()), + lowIntegrity: hasLowProcessIntegrity(await getRuntimeIntegrity()), rss: runtimeMemory.rss, heapTotal: runtimeMemory.heapTotal, heapUsed: runtimeMemory.heapUsed, diff --git a/packages/runtime/native/snowluma-linux-arm64.node b/packages/runtime/native/snowluma-linux-arm64.node index b210f306..d0f38f9a 100644 Binary files a/packages/runtime/native/snowluma-linux-arm64.node and b/packages/runtime/native/snowluma-linux-arm64.node differ diff --git a/packages/runtime/native/snowluma-linux-arm64.so b/packages/runtime/native/snowluma-linux-arm64.so index e035d4ce..678e5eec 100644 Binary files a/packages/runtime/native/snowluma-linux-arm64.so and b/packages/runtime/native/snowluma-linux-arm64.so differ diff --git a/packages/runtime/native/snowluma-linux-x64.node b/packages/runtime/native/snowluma-linux-x64.node index ca6cb401..5ccbc2e8 100644 Binary files a/packages/runtime/native/snowluma-linux-x64.node and b/packages/runtime/native/snowluma-linux-x64.node differ diff --git a/packages/runtime/native/snowluma-linux-x64.so b/packages/runtime/native/snowluma-linux-x64.so index 1dcbc579..00d711f0 100644 Binary files a/packages/runtime/native/snowluma-linux-x64.so and b/packages/runtime/native/snowluma-linux-x64.so differ diff --git a/packages/runtime/native/snowluma-win32-x64.node b/packages/runtime/native/snowluma-win32-x64.node index c7285959..01344948 100644 Binary files a/packages/runtime/native/snowluma-win32-x64.node and b/packages/runtime/native/snowluma-win32-x64.node differ diff --git a/packages/webui/README.md b/packages/webui/README.md index ad75b649..8a70568d 100644 --- a/packages/webui/README.md +++ b/packages/webui/README.md @@ -50,9 +50,8 @@ prove that QQ is signed out, and local detection alone never marks a bridge onli The manual login probe and `/api/processes/:pid/probe-login` endpoint are removed. Linux resolves data roots from each QQ process's `XDG_CONFIG_HOME` or `HOME`. -Windows requires a hook addon with `probeDbLock`; the currently bundled addon does -not provide it, so pre-injection account detection is unavailable there. A missing -interface is logged. Hook login events continue to report the online account. +Windows uses the bundled addon’s `getFileHoldersAsync` to find the process holding +each account database. Query failures are reported instead of treated as no login. ## Account notification templates