diff --git a/packages/core/tests/hook-reconnect-no-login-e2e.test.ts b/packages/core/tests/hook-reconnect-no-login-e2e.test.ts new file mode 100644 index 00000000..4c0a61f9 --- /dev/null +++ b/packages/core/tests/hook-reconnect-no-login-e2e.test.ts @@ -0,0 +1,99 @@ +// E2E for Docker "QQ never logs in + pipe keeps reconnecting" scenario. +// +// Drives the real PipeWatcher + HookManager through repeated same-PID +// pipe up/down cycles via tickNow() and asserts the BridgeManager mock +// is never touched (no login → no Bridge / OneBotInstance / Identity). + +import { describe, it, expect, vi } from 'vitest'; +import { EventEmitter } from 'events'; +import { HookManager } from '../src/hook/hook-manager'; +import { PipeWatcher } from '../src/hook/pipe-watcher'; +import type { ManualMapHandle } from '../src/hook/injector'; +import type { BridgeManager } from '../src/bridge/manager'; +import type { QqHookClient } from '../src/hook/qq-hook-client'; + +const DUMMY_HANDLE: ManualMapHandle = { base: 0n, entry: 0n, exceptionTable: 0n, size: 0 }; +const flush = () => new Promise(r => setImmediate(r)); + +class FakeClient extends EventEmitter { + isClosed = false; + isLoggedIn = false; + async connectAll(_opts: { recv: boolean }) { + if (this.isClosed) throw new Error('client is closed'); + } + getLoginState() { return { loggedIn: false, uin: '0', uinNumber: 0n }; } + close() { + if (this.isClosed) return; + this.isClosed = true; + this.emit('close'); + } +} + +describe('HookManager — Docker reconnect-without-login leak guard', () => { + it('after N pipe up/down cycles: no Bridge calls, no client accumulation', async () => { + const PID = 61; + const liveSet = new Set([PID]); + const clients: FakeClient[] = []; + + const pipeWatcher = new PipeWatcher({ + listProcesses: () => [{ pid: PID, name: 'qq', path: '' }], + listLivePipes: async () => new Set(liveSet), + intervalMs: 60_000, // manual ticks only + }); + + const bridgeManager = { + onPacket: vi.fn(), + onHookLogin: vi.fn(), + onPidDisconnected: vi.fn(), + } as unknown as BridgeManager; + + const manager = new HookManager({ + bridgeManager, + pipeWatcher, + injector: { + inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })), + unload: vi.fn(), + }, + makeClient: () => { + const c = new FakeClient(); + clients.push(c); + return c as unknown as QqHookClient; + }, + autoLoadOnDiscovery: true, + listProcesses: () => [{ pid: PID, name: 'qq', path: '' }], + }); + + // Initial discovery + first connect. + await pipeWatcher.start(); + await flush(); + await flush(); + + // Drive 50 pipe up/down cycles with the QQ process staying alive but + // the pipe (= QQ control socket) bouncing every "tick". + const CYCLES = 50; + for (let i = 0; i < CYCLES; i++) { + liveSet.delete(PID); + await pipeWatcher.tickNow(); + await flush(); + liveSet.add(PID); + await pipeWatcher.tickNow(); + await flush(); + } + + // The "QQ never logs in" hypothesis: BridgeManager should never have + // been told about a login or a disconnect. + expect(bridgeManager.onHookLogin).not.toHaveBeenCalled(); + expect(bridgeManager.onPidDisconnected).not.toHaveBeenCalled(); + expect(bridgeManager.onPacket).not.toHaveBeenCalled(); + + // Hook layer should hold at most one live client. + const alive = clients.filter(c => !c.isClosed); + expect(alive.length, `live clients after ${CYCLES} cycles: ${alive.length}`).toBeLessThanOrEqual(1); + + // Total clients minted = roughly one per up cycle. Sanity bound: + // we must have actually exercised the reconnect path. + expect(clients.length).toBeGreaterThan(1); + + manager.dispose(); + }); +}); diff --git a/packages/core/tests/hook-reconnect-no-login.test.ts b/packages/core/tests/hook-reconnect-no-login.test.ts new file mode 100644 index 00000000..a6ab3a90 --- /dev/null +++ b/packages/core/tests/hook-reconnect-no-login.test.ts @@ -0,0 +1,123 @@ +// Regression test for the Docker "QQ-never-logs-in + pipe keeps reconnecting" leak hypothesis. +// +// User-reported pattern (Docker, idle login screen): +// 02:41:23 [Hook] pipe connected: PID=61 +// 04:37:55 [Hook] pipe connected: PID=61 (same PID, ~2h later) +// 04:40:44 [Hook] pipe connected: PID=61 +// 04:43:48 [Hook] pipe connected: PID=61 → eventual OOM-kill +// +// Hypothesis (H2): every onPipeDown → onPipeUp cycle leaks the prior +// QqHookClient (listeners or socket-ref keeping it pinned in memory), +// so repeated reconnect drives unbounded growth. +// +// This test drives N up/down cycles against a HookSession with a FakeClient +// factory and asserts: +// - at most one client is alive at any point +// - every prior client's EventEmitter listener count drops to 0 after teardown + +import { describe, it, expect, vi } from 'vitest'; +import { EventEmitter } from 'events'; +import { HookSession } from '../src/hook/hook-session'; +import type { ManualMapHandle } from '../src/hook/injector'; +import type { QqHookClient } from '../src/hook/qq-hook-client'; + +const DUMMY_HANDLE: ManualMapHandle = { base: 0n, entry: 0n, exceptionTable: 0n, size: 0 }; + +class FakeClient extends EventEmitter { + isClosed = false; + isLoggedIn = false; + private loginState = { loggedIn: false, uin: '0', uinNumber: 0n }; + + async connectAll(_opts: { recv: boolean }): Promise { + if (this.isClosed) throw new Error('client is closed'); + } + getLoginState() { return { ...this.loginState }; } + close(): void { + if (this.isClosed) return; + this.isClosed = true; + this.emit('close'); + } +} + +function totalListenerCount(emitter: EventEmitter): number { + return emitter.eventNames().reduce((n, evt) => n + emitter.listenerCount(evt), 0); +} + +const flush = () => new Promise(r => setImmediate(r)); + +describe('HookSession — pipe reconnect with QQ never logging in', () => { + it('does not accumulate live FakeClient instances across N pipe up/down cycles', async () => { + let pipeLive = true; + const clients: FakeClient[] = []; + const session = new HookSession(61, { + injector: { + inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })), + unload: vi.fn(), + }, + makeClient: () => { + const c = new FakeClient(); + clients.push(c); + return c as unknown as QqHookClient; + }, + pipeWatcher: { isPipeLive: () => pipeLive }, + }); + + await session.load(); + session.onPipeUp(); + await flush(); + + const CYCLES = 50; + for (let i = 0; i < CYCLES; i++) { + pipeLive = false; + session.onPipeDown(); + await flush(); + pipeLive = true; + session.onPipeUp(); + await flush(); + } + + const alive = clients.filter(c => !c.isClosed); + expect.soft(clients.length).toBeGreaterThan(1); + expect(alive.length, `expected ≤1 live client after ${CYCLES} reconnects, got ${alive.length}`) + .toBeLessThanOrEqual(1); + }); + + it('drops all listeners from each torn-down client', async () => { + let pipeLive = true; + const clients: FakeClient[] = []; + const session = new HookSession(61, { + injector: { + inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })), + unload: vi.fn(), + }, + makeClient: () => { + const c = new FakeClient(); + clients.push(c); + return c as unknown as QqHookClient; + }, + pipeWatcher: { isPipeLive: () => pipeLive }, + }); + + await session.load(); + session.onPipeUp(); + await flush(); + + const CYCLES = 20; + for (let i = 0; i < CYCLES; i++) { + pipeLive = false; + session.onPipeDown(); + await flush(); + pipeLive = true; + session.onPipeUp(); + await flush(); + } + + // Every client except the current one should have 0 listeners attached. + // (HookSession.tearDownClient does client.removeAllListeners().) + for (let i = 0; i < clients.length - 1; i++) { + const lc = totalListenerCount(clients[i]); + expect(lc, `client #${i} of ${clients.length} still has ${lc} listeners after teardown`) + .toBe(0); + } + }); +});