fix(bridge): restore Windows account readiness

Keep account confirmation active until a valid login is ready and clear stale bindings when readiness is lost.

Update Windows components and cover login recovery.

Refs #638
This commit is contained in:
DrSmoothl committed 2026-11-06 22:49:52 +08:00
1 parent 1b80487119
commit 7425cfae20
4 files changed
+366 -26

No files matched your search

+70 -26
View File
@@ -117,6 +117,8 @@ export class HookSession extends EventEmitter {
private cancelConnectAttempt: (() => void) | null = null;
private pipeUpPending = false;
private loginReconcileTimer: ReturnType<typeof setInterval> | null = null;
private loginIdentityEpoch = 0;
private invalidLoginStateReported = false;
private detecting = false;
private lastDetectFailure = '';
private acceptedLoginHintUin = '';
@@ -693,20 +695,10 @@ export class HookSession extends EventEmitter {
this.hasConnected = true;
this.stopInitialConnectionWatch();
this.initialConnectionError = '';
const loginState = client.getLoginState();
// 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();
// 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. Keep re-detecting until logged in.
runWithoutRequestContext(() => this.startLoginReconcile());
}
this._error = '';
// Identity validation owns readiness and whether to keep checking.
// A reported login alone does not establish a usable account.
this.handleLoginState(client.getLoginState());
this.log.info('pipe connected: PID=%d', this.pid);
this.log.trace(() => [
@@ -915,19 +907,32 @@ export class HookSession extends EventEmitter {
this.bound = false;
this.connected = false;
this.loggedIn = false;
this.invalidLoginStateReported = false;
this._outboundHealthy = true;
this.resetLoginHint();
}
private handleLoginState(state: QqHookLoginState): void {
if (this.runtimeFailure) {
if (this.disposed || this.runtimeFailure) {
return;
}
const wasLoggedIn = this.loggedIn;
const previousUin = this._uin;
this._uin = state.uin || state.uinNumber.toString();
this.loggedIn = state.loggedIn && isRealUin(this._uin);
const uin = state.uin || state.uinNumber.toString();
const validIdentity = isRealUin(uin);
const invalidLoginState = state.loggedIn && !validIdentity;
if (invalidLoginState && !this.invalidLoginStateReported) {
this.log.warn(
'Login readiness rejected: PID=%d reason=invalid_account_identity',
this.pid,
);
}
this.invalidLoginStateReported = invalidLoginState;
this._uin = validIdentity ? uin : '0';
this.loggedIn = state.loggedIn && validIdentity;
// Login readiness has now been confirmed, so identity probing is done.
if (this.loggedIn) {
@@ -942,19 +947,30 @@ export class HookSession extends EventEmitter {
} else {
this.resetReceiveWatch();
this._outboundHealthy = true;
if (wasLoggedIn) {
this.resetLoginHint();
}
}
// Only the connected/logged-in states are ours to set here; when fully
// down we leave the status the teardown path already settled.
// Load-bearing invariant: `loggedIn ⇒ connected` (login can only be
// observed on a live client, and teardown clears `loggedIn` before
// `connected`), so statusFor lands 'online' here rather than the
// disconnected/connecting branch.
// Login may arrive while another channel is still handshaking; the
// connection attempt revokes that binding if it fails to complete.
if (this.connected || this.loggedIn) {
this.applyStatus(wasLoggedIn, this.loggedIn ? '' : this._error);
}
if (!this.loggedIn || !this.sender) {
if (!this.loggedIn) {
if (wasLoggedIn) {
this.emit('disconnected', true);
}
runWithoutRequestContext(() => this.startLoginReconcile());
return;
}
if (!this.sender) {
return;
}
@@ -1001,17 +1017,23 @@ export class HookSession extends EventEmitter {
// reconciliation, but never synthesize online state from the detection.
private startLoginReconcile(): void {
if (this.loginReconcileTimer || this.disposed || this.runtimeFailure) {
if (
this.loginReconcileTimer ||
this.disposed ||
this.runtimeFailure ||
!this.connected ||
this.loggedIn
) {
return;
}
this.log.info('awaiting login: PID=%d', this.pid);
void this.detectLoginOnce(); // immediate — catch already-logged-in fast
this.loginReconcileTimer = setInterval(
() => void this.detectLoginOnce(),
LOGIN_RECONCILE_INTERVAL_MS,
);
this.loginReconcileTimer.unref();
void this.detectLoginOnce();
}
private stopLoginReconcile(): void {
@@ -1029,6 +1051,7 @@ export class HookSession extends EventEmitter {
}
const client = this.client;
const identityEpoch = this.loginIdentityEpoch;
if (this.disposed || !client || !this.connected || this.loggedIn || this.runtimeFailure) {
this.stopLoginReconcile();
@@ -1047,6 +1070,17 @@ export class HookSession extends EventEmitter {
try {
uin = await this.detectLoginUin(this.pid);
} catch (error) {
if (
this.client !== client ||
this.loginIdentityEpoch !== identityEpoch ||
this.disposed ||
!this.connected ||
this.loggedIn ||
this.runtimeFailure
) {
return;
}
const message = errorMessage(error);
if (this.lastDetectFailure !== message) {
@@ -1061,9 +1095,10 @@ export class HookSession extends EventEmitter {
return; // best-effort; the interval retries
}
// A reconnect owns a new client; an older read cannot supply its identity.
// A connection or readiness change invalidates earlier identity work.
if (
this.client !== client ||
this.loginIdentityEpoch !== identityEpoch ||
this.disposed ||
!this.connected ||
this.loggedIn ||
@@ -1107,6 +1142,7 @@ export class HookSession extends EventEmitter {
if (
this.client !== client ||
this.loginIdentityEpoch !== identityEpoch ||
this.disposed ||
!this.connected ||
this.loggedIn ||
@@ -1119,7 +1155,14 @@ export class HookSession extends EventEmitter {
this.nextLoginIdentityObservationAt =
Date.now() + LOGIN_IDENTITY_OBSERVE_INTERVAL_MS;
} catch (error) {
if (this.client !== client || this.disposed || this.runtimeFailure) {
if (
this.client !== client ||
this.loginIdentityEpoch !== identityEpoch ||
this.disposed ||
!this.connected ||
this.loggedIn ||
this.runtimeFailure
) {
return;
}
@@ -1152,6 +1195,7 @@ export class HookSession extends EventEmitter {
}
private resetLoginHint(): void {
this.loginIdentityEpoch++;
this.acceptedLoginHintUin = '';
this.loginHintAttemptUin = '';
this.loginHintAttempts = 0;
+296
View File
@@ -1479,6 +1479,302 @@ describe('HookSession — packet forwarding', () => {
});
describe('HookSession — login reconcile (Docker auto-login safety net)', () => {
it.each([
{ uin: '1700000000000', uinNumber: 1700000000000n },
{ uin: 'not-an-account', uinNumber: 0n },
{ uin: '0', uinNumber: 0n },
{ uin: '', uinNumber: 1700000000000n },
])(
'reconciles a rejected login identity received during connection: $uin',
async (identity) => {
vi.useFakeTimers();
setLogLevel('warn');
const entries: LogEntry[] = [];
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
const detectLoginUin = vi.fn(async () => '10001');
const onPacket = vi.fn<PacketSink>();
const state = { loggedIn: true, ...identity };
const ctx = makeSession({
pipeLive: true,
detectLoginUin,
onPacket,
connectClient: async (client) => client.reconcileLoginState(state),
});
const login = vi.fn();
ctx.session.on('login', login);
try {
await ctx.session.load();
ctx.session.onPipeUp();
await vi.advanceTimersByTimeAsync(0);
expect(ctx.currentClient().loginIdentityHints).toEqual(['10001']);
expect(ctx.session.toInfo()).toMatchObject({
connected: true,
loggedIn: false,
status: 'loaded',
uin: '0',
});
expect(login).not.toHaveBeenCalled();
const packet = {
seq: 1,
error: 0,
cmd: 'Test.Message',
uin: '10001',
body: Buffer.alloc(0),
};
ctx.currentClient().firePacket(packet);
expect(onPacket).not.toHaveBeenCalled();
ctx.currentClient().reconcileLoginState(state);
await vi.advanceTimersByTimeAsync(9000);
expect(ctx.currentClient().loginIdentityHints).toEqual(['10001']);
expect(
entries
.filter((entry) => entry.scope === 'HookSession' && entry.level === 'warn')
.map((entry) => entry.message),
).toEqual(['Login readiness rejected: PID=1234 reason=invalid_account_identity']);
ctx.currentClient().fireLogin('10001');
ctx.currentClient().firePacket(packet);
expect(login).toHaveBeenCalledOnce();
expect(onPacket).toHaveBeenCalledOnce();
expect(ctx.session.toInfo()).toMatchObject({
loggedIn: true,
status: 'online',
uin: '10001',
});
const detections = detectLoginUin.mock.calls.length;
await vi.advanceTimersByTimeAsync(30_000);
expect(detectLoginUin).toHaveBeenCalledTimes(detections);
} finally {
ctx.session.dispose();
unsubscribe();
vi.useRealTimers();
}
},
);
it('revokes a ready account and starts a fresh identity check when login readiness is lost', async () => {
vi.useFakeTimers();
const ctx = makeSession({ pipeLive: true, detectLoginUin: async () => '10001' });
const login = vi.fn();
const disconnected = vi.fn();
ctx.session.on('login', login);
ctx.session.on('disconnected', disconnected);
try {
await ctx.session.load();
ctx.session.onPipeUp();
await vi.advanceTimersByTimeAsync(0);
expect(ctx.currentClient().loginIdentityHints).toEqual(['10001']);
ctx.currentClient().fireLogin('10001');
expect(login).toHaveBeenCalledOnce();
ctx.currentClient().fireLogin('1700000000000');
ctx.currentClient().fireLogin('1700000000001');
await vi.advanceTimersByTimeAsync(0);
expect(disconnected).toHaveBeenCalledExactlyOnceWith(true);
expect(ctx.session.toInfo()).toMatchObject({
status: 'loaded',
loggedIn: false,
uin: '0',
});
expect(ctx.currentClient().loginIdentityHints).toEqual(['10001', '10001']);
expect(login).toHaveBeenCalledOnce();
ctx.currentClient().fireLogin('10001');
expect(login).toHaveBeenCalledTimes(2);
expect(ctx.session.status).toBe('online');
} finally {
ctx.session.dispose();
vi.useRealTimers();
}
});
it('does not probe a rejected login identity before a stalled connection times out', async () => {
vi.useFakeTimers();
const handshake = Promise.withResolvers<void>();
const detectLoginUin = vi.fn(async () => '10001');
const ctx = makeSession({ detectLoginUin, connectClient: () => handshake.promise });
const login = vi.fn();
ctx.session.on('login', login);
try {
await ctx.session.load();
ctx.setPipeLive(true);
ctx.session.onPipeUp();
await vi.advanceTimersByTimeAsync(0);
const previous = ctx.currentClient();
previous.fireLogin('1700000000000');
await vi.advanceTimersByTimeAsync(60_000);
expect(ctx.session.toInfo()).toMatchObject({
status: 'error',
connected: false,
loggedIn: false,
});
expect(detectLoginUin).not.toHaveBeenCalled();
expect(previous.isClosed).toBe(true);
expect(vi.getTimerCount()).toBe(0);
previous.fireLogin('10001');
handshake.resolve();
await vi.advanceTimersByTimeAsync(0);
expect(login).not.toHaveBeenCalled();
await ctx.session.load();
ctx.session.onPipeUp();
await vi.advanceTimersByTimeAsync(0);
expect(ctx.currentClient()).not.toBe(previous);
expect(ctx.currentClient().loginIdentityHints).toEqual(['10001']);
expect(ctx.session.toInfo()).toMatchObject({
status: 'loaded',
connected: true,
loggedIn: false,
});
} finally {
handshake.resolve();
ctx.session.dispose();
vi.useRealTimers();
}
});
it('discards an identity acknowledgement from before login readiness was lost', async () => {
vi.useFakeTimers();
const hint = Promise.withResolvers<void>();
const ctx = makeSession({
pipeLive: true,
detectLoginUin: async () => '10001',
connectClient: async (client) => {
vi.spyOn(client, 'reconcileLoginIdentity').mockImplementationOnce(async (uin) => {
client.loginIdentityHints.push(uin);
await hint.promise;
});
},
});
try {
await ctx.session.load();
ctx.session.onPipeUp();
await vi.advanceTimersByTimeAsync(0);
expect(ctx.currentClient().loginIdentityHints).toEqual(['10001']);
ctx.currentClient().fireLogin('10001');
ctx.currentClient().fireLogin('1700000000000');
hint.resolve();
await vi.advanceTimersByTimeAsync(3000);
expect(ctx.currentClient().loginIdentityHints).toEqual(['10001', '10001']);
expect(ctx.session.toInfo()).toMatchObject({ status: 'loaded', loggedIn: false });
} finally {
hint.resolve();
ctx.session.dispose();
vi.useRealTimers();
}
});
it('discards an account observation from before login readiness was lost', async () => {
vi.useFakeTimers();
const observation = Promise.withResolvers<string | null>();
const detectLoginUin = vi.fn<() => Promise<string | null>>().mockResolvedValue('20002');
detectLoginUin.mockReturnValueOnce(observation.promise);
const ctx = makeSession({ pipeLive: true, detectLoginUin });
try {
await ctx.session.load();
ctx.session.onPipeUp();
await vi.advanceTimersByTimeAsync(0);
ctx.currentClient().fireLogin('10001');
ctx.currentClient().fireLogin('1700000000000');
observation.resolve('10001');
await vi.advanceTimersByTimeAsync(0);
expect(ctx.currentClient().loginIdentityHints).toEqual([]);
await vi.advanceTimersByTimeAsync(3000);
expect(ctx.currentClient().loginIdentityHints).toEqual(['20002']);
} finally {
observation.resolve(null);
ctx.session.dispose();
vi.useRealTimers();
}
});
it.each(['observation', 'hint'] as const)(
'ignores a late %s failure after login readiness is confirmed',
async (phase) => {
vi.useFakeTimers();
setLogLevel('trace');
const entries: LogEntry[] = [];
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
const pending = Promise.withResolvers<void>();
const detectLoginUin = vi.fn(async () => {
if (phase === 'observation') {
await pending.promise;
}
return '10001';
});
const ctx = makeSession({
pipeLive: true,
detectLoginUin,
connectClient: async (client) => {
if (phase === 'hint') {
vi.spyOn(client, 'reconcileLoginIdentity').mockImplementationOnce(
async (uin) => {
client.loginIdentityHints.push(uin);
await pending.promise;
},
);
}
},
});
try {
await ctx.session.load();
ctx.session.onPipeUp();
await vi.advanceTimersByTimeAsync(0);
expect(detectLoginUin).toHaveBeenCalledOnce();
expect(ctx.currentClient().loginIdentityHints).toEqual(
phase === 'hint' ? ['10001'] : [],
);
ctx.currentClient().fireLogin('10001');
entries.length = 0;
pending.reject(new Error('expired identity request'));
await vi.advanceTimersByTimeAsync(30_000);
expect(
entries.some((entry) => entry.message.includes('expired identity request')),
).toBe(false);
expect(detectLoginUin).toHaveBeenCalledOnce();
expect(ctx.session.toInfo()).toMatchObject({
status: 'online',
loggedIn: true,
uin: '10001',
});
} finally {
pending.resolve();
ctx.session.dispose();
unsubscribe();
vi.useRealTimers();
}
},
);
it('clears the login check timer when identity detection disposes the session synchronously', async () => {
vi.useFakeTimers();
const detectLoginUin = vi.fn<() => Promise<string | null>>();
const ctx = makeSession({ pipeLive: true, detectLoginUin });
detectLoginUin.mockImplementation(async () => {
ctx.session.dispose();
return null;
});
try {
await ctx.session.load();
ctx.session.onPipeUp();
await vi.advanceTimersByTimeAsync(0);
expect(ctx.session.isDisposed).toBe(true);
expect(vi.getTimerCount()).toBe(0);
} finally {
ctx.session.dispose();
vi.useRealTimers();
}
});
it('discards an identity read started before a pipe reconnect', async () => {
const detection = Promise.withResolvers<string | null>();
const ctx = makeSession({ pipeLive: true, detectLoginUin: () => detection.promise });
Binary file not shown.
Binary file not shown.