fix(bridge): self-heal login detection when the hook misses the edge

Docker SnowLuma could hang forever at "等待登录" after QQ had already
logged in. Root cause: login detection is edge-triggered — it only learns
the state from a loginState frame the native hook PUSHES when it observes
the login transition. `getLoginState()` is a cached value read once at
connect; after that the session waits passively. Desktop attaches the
hook before the user logs in, so it catches the edge. In Docker, QQ
auto-logs-in from a persisted session — fast on startup — so the
transition lands before the recv pipe is connected (frames aren't
replayed) or via a silent restore path the hook doesn't intercept. The
edge is missed and the cached state stays not-logged-in.

Fix: while connected but not logged in, actively re-probe QQ's own
ptlogin/deeplink ports via probeQqLoginInfo (level-triggered, pipe-
independent — the same call the workaround used) and synthesize the login
once it reports a real uin. Immediate probe on connect + a 3s interval;
stopped on login / teardown / dispose, with an in-flight guard so a slow
port scan can't stack concurrent probes. Idempotent with the pushed-frame
path. 7 tests cover detect-via-probe, the later-interval case, the
not-logged-in / non-real-uin / throwing-probe guards, no double-emit, and
no concurrent stacking. probeLogin is injectable for tests.
This commit is contained in:
DrSmoothl committed 2026-06-30 23:29:51 +08:00
1 parent 397087dc74
commit c90a3954e4
2 files changed
+215 -2

No files matched your search

+76 -2
View File
@@ -4,15 +4,25 @@ import { EventEmitter } from 'events';
import { HookPacketClient } from './hook-packet-client';
import type { HookInjectResult } from './injector';
import type { QqHookClient, QqHookLoginState, QqHookPacket } from './qq-hook-client';
import { probeQqLoginInfo, type QqPortLoginInfo } from './qq-port-probe';
import { statusFor } from './hook-status';
import type { HookProcessInfo, HookProcessStatus } from './types';
/** How often to actively re-probe QQ's login state while connected but not yet
* logged in — the safety net for a login the native hook never pushed (Docker
* auto-login races/bypasses the pushed loginState frame). */
const LOGIN_RECONCILE_INTERVAL_MS = 3000;
export type HookSessionDeps = {
injector: {
inject: (pid: number) => HookInjectResult;
unload: (pid: number, handle: HookInjectResult['handle']) => void;
};
makeClient: (pid: number) => QqHookClient;
/** Active, pipe-independent login probe (reads QQ's ptlogin/deeplink ports).
* Drives the login-reconcile safety net; injectable for tests. Defaults to
* `probeQqLoginInfo`. */
probeLogin?: (pid: number) => Promise<QqPortLoginInfo | null>;
/** Sync fast-path check used by load() to skip re-injection when a
* prior SnowLuma run left a working pipe behind. `tickNow` forces a
* fresh poll — used after unload to dodge the up-to-1500ms cache
@@ -50,6 +60,7 @@ export class HookSession extends EventEmitter {
private readonly injector: HookSessionDeps['injector'];
private readonly makeClient: HookSessionDeps['makeClient'];
private readonly probeLogin: (pid: number) => Promise<QqPortLoginInfo | null>;
private readonly pipeWatcher: HookSessionDeps['pipeWatcher'];
private readonly onPacket: PacketSink | null;
private readonly log: Logger;
@@ -70,12 +81,15 @@ export class HookSession extends EventEmitter {
private bound = false;
private opChain: Promise<unknown> = Promise.resolve();
private disposed = false;
private loginProbeTimer: ReturnType<typeof setInterval> | null = null;
private probing = false;
constructor(pid: number, deps: HookSessionDeps) {
super();
this.pid = pid;
this.injector = deps.injector;
this.makeClient = deps.makeClient;
this.probeLogin = deps.probeLogin ?? probeQqLoginInfo;
this.pipeWatcher = deps.pipeWatcher;
this.onPacket = deps.onPacket ?? null;
this.log = deps.log ?? createLogger('HookSession');
@@ -347,8 +361,15 @@ export class HookSession extends EventEmitter {
// handleLoginState owns the connected+loggedIn → 'online' (+ login
// emit) transition; defer to it so the status is set once. Otherwise
// we're connected-but-not-logged-in → 'loaded'.
if (loginState.loggedIn) this.handleLoginState(loginState);
else this.applyStatus();
if (loginState.loggedIn) {
this.handleLoginState(loginState);
} else {
this.applyStatus();
// The native hook only PUSHES a loginState frame on the login edge;
// if QQ logged in before/around connect (Docker auto-login) that edge
// is missed and we'd wait forever. Actively re-probe until logged in.
this.startLoginReconcile();
}
this.log.info('pipe connected: PID=%d', this.pid);
} catch (error) {
this._error = errMsg(error);
@@ -381,6 +402,7 @@ export class HookSession extends EventEmitter {
}
private tearDownClient(): void {
this.stopLoginReconcile();
const client = this.client;
if (client) {
client.removeAllListeners();
@@ -398,6 +420,9 @@ export class HookSession extends EventEmitter {
const previousUin = this._uin;
this._uin = state.uin || state.uinNumber.toString();
this.loggedIn = state.loggedIn && isRealUin(this._uin);
// However login was observed (pushed frame or the active probe), the
// safety net's job is done.
if (this.loggedIn) this.stopLoginReconcile();
// Only the connected/logged-in states are ours to set here; when fully
// down we leave the status the teardown path already settled.
@@ -416,6 +441,55 @@ export class HookSession extends EventEmitter {
this.log.success('login detected: PID=%d UIN=%s', this.pid, this._uin);
}
// ─────────────── login reconcile (Docker auto-login safety net) ───────────
// The hook's loginState frame is edge-triggered (pushed only when the native
// observes the login transition). When that edge is missed — QQ auto-logged
// in before connect, or a silent session-restore path the hook doesn't
// intercept — we'd sit at 'loaded'/'connecting' forever. So while connected
// but not logged in, actively re-probe QQ's own ports and synthesize the
// login once it reports a real uin. Idempotent with the pushed-frame path
// (handleLoginState's wasLoggedIn guard dedups the 'login' emit).
private startLoginReconcile(): void {
if (this.loginProbeTimer || this.disposed) return;
void this.probeLoginOnce(); // immediate — catch already-logged-in fast
this.loginProbeTimer = setInterval(() => void this.probeLoginOnce(), LOGIN_RECONCILE_INTERVAL_MS);
this.loginProbeTimer.unref?.();
}
private stopLoginReconcile(): void {
if (this.loginProbeTimer) {
clearInterval(this.loginProbeTimer);
this.loginProbeTimer = null;
}
}
private async probeLoginOnce(): Promise<void> {
// A port-scan probe can outlast the interval; skip overlapping ticks so a
// slow probe never stacks concurrent subprocess-spawning scans.
if (this.probing) return;
if (this.disposed || !this.connected || this.loggedIn) { this.stopLoginReconcile(); return; }
this.probing = true;
try {
let info: QqPortLoginInfo | null;
try {
info = await this.probeLogin(this.pid);
} catch {
return; // best-effort; the interval retries
}
// The await yielded — re-check we still want this before mutating state.
if (this.disposed || !this.connected || this.loggedIn) { this.stopLoginReconcile(); return; }
if (info?.loggedIn && isRealUin(info.uin)) {
this.log.info('login reconciled via active probe: PID=%d UIN=%s', this.pid, info.uin);
// isRealUin guarantees a pure non-empty digit string, so BigInt() here
// cannot throw (keep that contract if isRealUin's regex is ever changed).
this.handleLoginState({ loggedIn: true, uin: info.uin, uinNumber: BigInt(info.uin) });
}
} finally {
this.probing = false;
}
}
private handlePacket(packet: QqHookPacket): void {
if (!this.loggedIn) return;
const uin = packet.uin || this._uin;
+139
View File
@@ -3,6 +3,7 @@ import { EventEmitter } from 'events';
import { HookSession } from '../src/hook-session';
import type { ManualMapHandle } from '../src/injector';
import type { QqHookClient, QqHookPacket } from '../src/qq-hook-client';
import type { QqPortLoginInfo } from '../src/qq-port-probe';
import type { PacketSink } from '@snowluma/common/protocol-types';
const DUMMY_HANDLE: ManualMapHandle = { base: 0n, entry: 0n, exceptionTable: 0n, size: 0 };
@@ -42,6 +43,7 @@ function makeSession(opts: {
pipeLive?: boolean;
clientFailsConnect?: boolean;
onPacket?: PacketSink;
probeLogin?: (pid: number) => Promise<QqPortLoginInfo | null>;
} = {}) {
const pid = opts.pid ?? 1234;
let pipeLive = opts.pipeLive ?? false;
@@ -50,6 +52,9 @@ function makeSession(opts: {
inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })),
unload: vi.fn(),
};
// Default probe reports "not logged in" so the reconcile safety net is inert
// unless a test opts into a logged-in probe (never hits the real port scan).
const probeLogin = opts.probeLogin ?? (async () => ({ port: 0, uin: '', loggedIn: false }));
const session = new HookSession(pid, {
injector,
@@ -60,6 +65,7 @@ function makeSession(opts: {
// Cast: FakeClient mirrors only the surface HookSession touches.
return c as unknown as QqHookClient;
},
probeLogin,
pipeWatcher: { isPipeLive: () => pipeLive },
onPacket: opts.onPacket,
});
@@ -533,3 +539,136 @@ describe('HookSession — packet forwarding', () => {
});
});
});
describe('HookSession — login reconcile (Docker auto-login safety net)', () => {
it('reconciles login via the active probe when the pushed frame is missed', async () => {
// Probe reports logged-in; the FakeClient never fires a loginState frame
// (the missed-edge Docker case). The immediate reconcile probe must detect
// it and emit "login".
const ctx = makeSession({
pipeLive: true,
probeLogin: async () => ({ port: 4301, uin: '10001', loggedIn: true }),
});
const loginSpy = vi.fn();
ctx.session.on('login', loginSpy);
await ctx.session.load();
ctx.session.onPipeUp();
await flush(); // connect (not logged in via frame) → starts reconcile
await flush(); // immediate probe resolves → handleLoginState
expect(loginSpy).toHaveBeenCalledOnce();
expect(loginSpy.mock.calls[0]![0]).toBe('10001');
expect(ctx.session.status).toBe('online');
expect(ctx.session.uin).toBe('10001');
});
it('does not log in when the probe reports not-logged-in', async () => {
const ctx = makeSession({
pipeLive: true,
probeLogin: async () => ({ port: 0, uin: '', loggedIn: false }),
});
const loginSpy = vi.fn();
ctx.session.on('login', loginSpy);
await ctx.session.load();
ctx.session.onPipeUp();
await flush(); await flush();
expect(loginSpy).not.toHaveBeenCalled();
expect(ctx.session.status).toBe('loaded');
});
it('ignores a probe with a non-real uin (0)', async () => {
const ctx = makeSession({
pipeLive: true,
probeLogin: async () => ({ port: 4301, uin: '0', loggedIn: true }),
});
const loginSpy = vi.fn();
ctx.session.on('login', loginSpy);
await ctx.session.load();
ctx.session.onPipeUp();
await flush(); await flush();
expect(loginSpy).not.toHaveBeenCalled();
});
it('tolerates a throwing probe (best-effort, no crash/login)', async () => {
const ctx = makeSession({
pipeLive: true,
probeLogin: async () => { throw new Error('port scan failed'); },
});
const loginSpy = vi.fn();
ctx.session.on('login', loginSpy);
await ctx.session.load();
ctx.session.onPipeUp();
await flush(); await flush();
expect(loginSpy).not.toHaveBeenCalled();
expect(ctx.session.status).toBe('loaded');
});
it('detects a login that lands on a LATER interval probe', async () => {
vi.useFakeTimers();
try {
let loggedIn = false;
const ctx = makeSession({
pipeLive: true,
probeLogin: async () => ({ port: 4301, uin: '10001', loggedIn }),
});
const loginSpy = vi.fn();
ctx.session.on('login', loginSpy);
await ctx.session.load();
ctx.session.onPipeUp();
await vi.advanceTimersByTimeAsync(0); // connect + immediate probe (not logged in yet)
expect(loginSpy).not.toHaveBeenCalled();
loggedIn = true; // QQ finishes auto-login
await vi.advanceTimersByTimeAsync(3000); // next interval probe picks it up
expect(loginSpy).toHaveBeenCalledOnce();
expect(ctx.session.status).toBe('online');
} finally {
vi.useRealTimers();
}
});
it('does not double-emit when the pushed frame logs in first', async () => {
// Pushed-frame login wins; a subsequent probe with the same uin must not
// re-emit (handleLoginState dedups), and the reconcile timer is stopped.
const probeLogin = vi.fn(async () => ({ port: 4301, uin: '10001', loggedIn: true }));
const ctx = makeSession({ pipeLive: true, probeLogin });
const loginSpy = vi.fn();
ctx.session.on('login', loginSpy);
await ctx.session.load();
ctx.session.onPipeUp();
await flush();
ctx.currentClient().fireLogin('10001'); // pushed-frame login first
await flush();
expect(loginSpy).toHaveBeenCalledOnce();
expect(ctx.session.status).toBe('online');
});
});
describe('HookSession — login reconcile does not stack concurrent probes', () => {
it('skips overlapping ticks while a slow probe is in flight', async () => {
vi.useFakeTimers();
try {
// A probe that never resolves — simulates a slow port scan spanning
// multiple intervals. The in-flight guard must call it only once.
const probeLogin = vi.fn(() => new Promise<never>(() => { /* pending */ }));
const ctx = makeSession({ pipeLive: true, probeLogin });
await ctx.session.load();
ctx.session.onPipeUp();
await vi.advanceTimersByTimeAsync(0); // connect + immediate probe (starts, stays pending)
await vi.advanceTimersByTimeAsync(9000); // 3 more interval ticks
expect(probeLogin).toHaveBeenCalledTimes(1); // not stacked
} finally {
vi.useRealTimers();
}
});
});