fix(bridge): restore active sessions after delayed startup
Allow SnowLuma to discover and restore accounts that were already active before startup. Avoid reporting sessions ready before they can serve requests, preserve account changes, and keep discovery failures observable. Add regression coverage for delayed startup, recovery, and process isolation. Refs #305 Refs #307
This commit is contained in:
9 files changed
+591
-126
No files matched your search
@@ -0,0 +1,67 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { resolveHookRuntimeDir } from '../src/hook-runtime-dir';
|
||||
|
||||
function procReader(files: Record<string, string>) {
|
||||
return (file: string): string => {
|
||||
const value = files[file];
|
||||
if (value === undefined) throw new Error(`missing fixture: ${file}`);
|
||||
return value;
|
||||
};
|
||||
}
|
||||
|
||||
describe('resolveHookRuntimeDir — Linux target process ownership', () => {
|
||||
it('uses the QQ process runtime directory instead of the supervisor user directory', () => {
|
||||
expect(resolveHookRuntimeDir(46301, {
|
||||
platform: 'linux',
|
||||
env: { XDG_RUNTIME_DIR: '/run/user/0' },
|
||||
ownUid: 0,
|
||||
readText: procReader({
|
||||
'/proc/46301/environ': 'HOME=/home/rikka\0XDG_RUNTIME_DIR=/run/user/1000\0',
|
||||
'/proc/46301/status': 'Name:\tqq\nUid:\t1000\t1000\t1000\t1000\n',
|
||||
}),
|
||||
})).toBe('/run/user/1000');
|
||||
});
|
||||
|
||||
it('falls back to the QQ process uid when its environment has no runtime directory', () => {
|
||||
expect(resolveHookRuntimeDir(46301, {
|
||||
platform: 'linux',
|
||||
env: { XDG_RUNTIME_DIR: '/run/user/0' },
|
||||
ownUid: 0,
|
||||
readText: procReader({
|
||||
'/proc/46301/environ': 'HOME=/home/rikka\0',
|
||||
'/proc/46301/status': 'Name:\tqq\nUid:\t1000\t1000\t1000\t1000\n',
|
||||
}),
|
||||
})).toBe('/tmp/snowluma-1000');
|
||||
});
|
||||
|
||||
it('fails visibly when target ownership cannot be determined', () => {
|
||||
expect(() => resolveHookRuntimeDir(46301, {
|
||||
platform: 'linux',
|
||||
env: { XDG_RUNTIME_DIR: '/run/user/0' },
|
||||
ownUid: 0,
|
||||
readText: () => { throw new Error('permission denied'); },
|
||||
})).toThrow(/cannot resolve hook runtime directory.*permission denied/);
|
||||
});
|
||||
|
||||
it('uses the current convention when the target disappears during discovery', () => {
|
||||
const gone = Object.assign(new Error('process disappeared'), { code: 'ENOENT' });
|
||||
expect(resolveHookRuntimeDir(46301, {
|
||||
platform: 'linux',
|
||||
env: { XDG_RUNTIME_DIR: '/run/user/0' },
|
||||
ownUid: 0,
|
||||
readText: () => { throw gone; },
|
||||
})).toBe('/run/user/0');
|
||||
});
|
||||
|
||||
it('honours an explicit runtime directory inherited by the QQ process', () => {
|
||||
expect(resolveHookRuntimeDir(46301, {
|
||||
platform: 'linux',
|
||||
env: {},
|
||||
ownUid: 0,
|
||||
readText: procReader({
|
||||
'/proc/46301/environ': 'SNOWLUMA_HOOK_RUNTIME_DIR=/srv/snowluma-hook\0',
|
||||
'/proc/46301/status': 'Uid:\t1000\t1000\t1000\t1000\n',
|
||||
}),
|
||||
})).toBe('/srv/snowluma-hook');
|
||||
});
|
||||
});
|
||||
@@ -33,7 +33,10 @@ class FakeClient extends EventEmitter {
|
||||
isClosed = false;
|
||||
isLoggedIn = false;
|
||||
shouldFailConnect = false;
|
||||
nativeReadyOnIdentityHint = false;
|
||||
identityHintFailures = 0;
|
||||
readonly sentPackets: Array<{ serviceCmd: string; body: Buffer }> = [];
|
||||
readonly loginIdentityHints: string[] = [];
|
||||
private loginState = { loggedIn: false, uin: '0', uinNumber: 0n };
|
||||
|
||||
async connectAll(_opts: { recv: boolean }): Promise<void> {
|
||||
@@ -46,6 +49,14 @@ class FakeClient extends EventEmitter {
|
||||
this.loginState = { ...state };
|
||||
this.emit('loginState', { ...this.loginState });
|
||||
}
|
||||
async reconcileLoginIdentity(uin: string): Promise<void> {
|
||||
this.loginIdentityHints.push(uin);
|
||||
if (this.identityHintFailures > 0) {
|
||||
this.identityHintFailures--;
|
||||
throw new Error('identity hint unavailable');
|
||||
}
|
||||
if (this.nativeReadyOnIdentityHint) this.fireLogin(uin);
|
||||
}
|
||||
async send(serviceCmd: string, body: Buffer) {
|
||||
this.sentPackets.push({ serviceCmd, body: Buffer.from(body) });
|
||||
return {
|
||||
@@ -76,6 +87,8 @@ function makeSession(opts: {
|
||||
clientFailsConnect?: boolean;
|
||||
onPacket?: PacketSink;
|
||||
probeLogin?: (pid: number) => Promise<QqPortLoginInfo | null>;
|
||||
nativeReadyOnIdentityHint?: boolean;
|
||||
identityHintFailures?: number;
|
||||
} = {}) {
|
||||
const pid = opts.pid ?? 1234;
|
||||
let pipeLive = opts.pipeLive ?? false;
|
||||
@@ -93,6 +106,8 @@ function makeSession(opts: {
|
||||
makeClient: () => {
|
||||
const c = new FakeClient();
|
||||
if (opts.clientFailsConnect) c.shouldFailConnect = true;
|
||||
c.nativeReadyOnIdentityHint = opts.nativeReadyOnIdentityHint ?? false;
|
||||
c.identityHintFailures = opts.identityHintFailures ?? 0;
|
||||
clients.push(c);
|
||||
// Cast: FakeClient mirrors only the surface HookSession touches.
|
||||
return c as unknown as QqHookClient;
|
||||
@@ -810,10 +825,11 @@ describe('HookSession — packet forwarding', () => {
|
||||
});
|
||||
|
||||
describe('HookSession — login reconcile (Docker auto-login safety net)', () => {
|
||||
it('keeps the packet sender usable when login is reconciled by the active probe', async () => {
|
||||
it('keeps the packet sender usable only after native readiness confirms the identity hint', async () => {
|
||||
const ctx = makeSession({
|
||||
pipeLive: true,
|
||||
probeLogin: async () => ({ port: 4301, uin: '10001', loggedIn: true }),
|
||||
nativeReadyOnIdentityHint: true,
|
||||
});
|
||||
let sender: PacketSender | undefined;
|
||||
ctx.session.on('login', (_uin: string, nextSender: PacketSender) => {
|
||||
@@ -839,10 +855,9 @@ 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".
|
||||
it('treats a port-probed account as an identity hint, not native login proof', async () => {
|
||||
// Account identity does not prove request readiness. The bridge must wait
|
||||
// for a login-state confirmation instead of synthesizing one.
|
||||
const ctx = makeSession({
|
||||
pipeLive: true,
|
||||
probeLogin: async () => ({ port: 4301, uin: '10001', loggedIn: true }),
|
||||
@@ -853,12 +868,83 @@ describe('HookSession — login reconcile (Docker auto-login safety net)', () =>
|
||||
await ctx.session.load();
|
||||
ctx.session.onPipeUp();
|
||||
await flush(); // connect (not logged in via frame) → starts reconcile
|
||||
await flush(); // immediate probe resolves → handleLoginState
|
||||
await flush(); // immediate probe resolves → forwards identity hint
|
||||
|
||||
expect(loginSpy).toHaveBeenCalledOnce();
|
||||
expect(loginSpy.mock.calls[0]![0]).toBe('10001');
|
||||
expect(ctx.session.status).toBe('online');
|
||||
expect(ctx.session.uin).toBe('10001');
|
||||
expect(ctx.currentClient().loginIdentityHints).toEqual(['10001']);
|
||||
expect(loginSpy).not.toHaveBeenCalled();
|
||||
expect(ctx.session.status).toBe('loaded');
|
||||
expect(ctx.session.uin).toBe('0');
|
||||
});
|
||||
|
||||
it('forwards the same identity at most once per pipe connection', async () => {
|
||||
vi.useFakeTimers();
|
||||
const ctx = makeSession({
|
||||
pipeLive: true,
|
||||
probeLogin: async () => ({ port: 4301, uin: '10001', loggedIn: true }),
|
||||
});
|
||||
try {
|
||||
await ctx.session.load();
|
||||
ctx.session.onPipeUp();
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
await vi.advanceTimersByTimeAsync(9000);
|
||||
|
||||
expect(ctx.currentClient().loginIdentityHints).toEqual(['10001']);
|
||||
} finally {
|
||||
ctx.session.dispose();
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it('keeps observing identity after acknowledgement and forwards an account change', async () => {
|
||||
vi.useFakeTimers();
|
||||
let uin = '10001';
|
||||
const ctx = makeSession({
|
||||
pipeLive: true,
|
||||
probeLogin: async () => ({ port: 4301, uin, loggedIn: true }),
|
||||
});
|
||||
try {
|
||||
await ctx.session.load();
|
||||
ctx.session.onPipeUp();
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(ctx.currentClient().loginIdentityHints).toEqual(['10001']);
|
||||
|
||||
uin = '20002';
|
||||
await vi.advanceTimersByTimeAsync(29_999);
|
||||
expect(ctx.currentClient().loginIdentityHints).toEqual(['10001']);
|
||||
|
||||
await vi.advanceTimersByTimeAsync(1);
|
||||
expect(ctx.currentClient().loginIdentityHints).toEqual(['10001', '20002']);
|
||||
} finally {
|
||||
ctx.session.dispose();
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it('retries identity forwarding failures with a strict bound', async () => {
|
||||
vi.useFakeTimers();
|
||||
const ctx = makeSession({
|
||||
pipeLive: true,
|
||||
probeLogin: async () => ({ port: 4301, uin: '10001', loggedIn: true }),
|
||||
identityHintFailures: 3,
|
||||
});
|
||||
try {
|
||||
await ctx.session.load();
|
||||
ctx.session.onPipeUp();
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(ctx.currentClient().loginIdentityHints).toEqual(['10001']);
|
||||
|
||||
await vi.advanceTimersByTimeAsync(3000);
|
||||
expect(ctx.currentClient().loginIdentityHints).toEqual(['10001', '10001']);
|
||||
|
||||
await vi.advanceTimersByTimeAsync(9000);
|
||||
expect(ctx.currentClient().loginIdentityHints).toEqual(['10001', '10001', '10001']);
|
||||
|
||||
await vi.advanceTimersByTimeAsync(30_000);
|
||||
expect(ctx.currentClient().loginIdentityHints).toHaveLength(3);
|
||||
} finally {
|
||||
ctx.session.dispose();
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it('does not log in when the probe reports not-logged-in', async () => {
|
||||
@@ -912,6 +998,7 @@ describe('HookSession — login reconcile (Docker auto-login safety net)', () =>
|
||||
const ctx = makeSession({
|
||||
pipeLive: true,
|
||||
probeLogin: async () => ({ port: 4301, uin: '10001', loggedIn }),
|
||||
nativeReadyOnIdentityHint: true,
|
||||
});
|
||||
const loginSpy = vi.fn();
|
||||
ctx.session.on('login', loginSpy);
|
||||
|
||||
@@ -30,6 +30,27 @@ function captureEvents(watcher: PipeWatcher): EventRow[] {
|
||||
}
|
||||
|
||||
describe('PipeWatcher', () => {
|
||||
it('passes the current process snapshot to pipe discovery', async () => {
|
||||
const processes = [
|
||||
{ pid: 1234, name: 'qq', path: '/opt/QQ/qq' },
|
||||
{ pid: 5678, name: 'qq', path: '/opt/QQ/qq' },
|
||||
];
|
||||
let observed: readonly HookProcessBaseInfo[] | undefined;
|
||||
const watcher = new PipeWatcher({
|
||||
listProcesses: () => processes,
|
||||
listLivePipes: async current => {
|
||||
observed = current;
|
||||
return new Set();
|
||||
},
|
||||
intervalMs: 60_000,
|
||||
});
|
||||
|
||||
await watcher.start();
|
||||
|
||||
expect(observed).toEqual(processes);
|
||||
watcher.stop();
|
||||
});
|
||||
|
||||
it('start() emits process-discovered + pipe-up for live PIDs on first tick', async () => {
|
||||
const ctx = setupWatcher({
|
||||
processes: [{ pid: 1234, name: 'QQ.exe', path: '' }],
|
||||
@@ -193,6 +214,38 @@ describe('PipeWatcher', () => {
|
||||
watcher.stop();
|
||||
});
|
||||
|
||||
it('preserves live sessions when pipe discovery temporarily fails', async () => {
|
||||
let processes = [{ pid: 1234, name: 'QQ.exe', path: '' }];
|
||||
let failPipeDiscovery = false;
|
||||
const watcher = new PipeWatcher({
|
||||
listProcesses: () => processes,
|
||||
listLivePipes: async () => {
|
||||
if (failPipeDiscovery) throw new Error('permission denied');
|
||||
return new Set([1234]);
|
||||
},
|
||||
intervalMs: 60_000,
|
||||
});
|
||||
|
||||
await watcher.start();
|
||||
expect(watcher.isPipeLive(1234)).toBe(true);
|
||||
const events = captureEvents(watcher);
|
||||
|
||||
failPipeDiscovery = true;
|
||||
await watcher.tickNow();
|
||||
|
||||
expect(events).toEqual([]);
|
||||
expect(watcher.isProcessAlive(1234)).toBe(true);
|
||||
expect(watcher.isPipeLive(1234)).toBe(true);
|
||||
|
||||
processes = [];
|
||||
await watcher.tickNow();
|
||||
|
||||
expect(events).toEqual([['down', 1234], ['gone', 1234]]);
|
||||
expect(watcher.isProcessAlive(1234)).toBe(false);
|
||||
expect(watcher.isPipeLive(1234)).toBe(false);
|
||||
watcher.stop();
|
||||
});
|
||||
|
||||
it('UNKNOWN (null) enumeration keeps prior state — no false process-gone (issue #158)', async () => {
|
||||
let result: HookProcessBaseInfo[] | null = [{ pid: 1234, name: 'qq', path: '' }];
|
||||
let live = new Set<number>([1234]);
|
||||
|
||||
@@ -151,6 +151,35 @@ describe('listLiveLinuxPipePids', () => {
|
||||
});
|
||||
|
||||
describe('QqHookClient — pipe frame limits', () => {
|
||||
it('forwards a probed account as a native identity hint without changing login state', async () => {
|
||||
const pid = 778819;
|
||||
const writes: Buffer[] = [];
|
||||
const connection = mockControlPipe(pid, (socket, payload) => {
|
||||
writes.push(Buffer.from(payload));
|
||||
const requestId = payload.readUInt32LE(8);
|
||||
queueMicrotask(() => socket.emit('data', pipeFrame({
|
||||
op: PipeOp.sendAck,
|
||||
requestId,
|
||||
})));
|
||||
});
|
||||
const client = new QqHookClient(pid);
|
||||
try {
|
||||
await client.reconcileLoginIdentity('10001');
|
||||
|
||||
expect(writes).toHaveLength(1);
|
||||
expect(writes[0]!.readUInt16LE(6)).toBe(PipeOp.loginIdentityHint);
|
||||
expect(writes[0]!.readBigUInt64LE(32)).toBe(10001n);
|
||||
expect(client.getLoginState()).toEqual({
|
||||
loggedIn: false,
|
||||
uin: '0',
|
||||
uinNumber: 0n,
|
||||
});
|
||||
} finally {
|
||||
client.close();
|
||||
connection.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it.each([
|
||||
['command', 20, MAX_PIPE_CMD_BYTES],
|
||||
['message', 24, MAX_PIPE_MSG_BYTES],
|
||||
|
||||
Reference in new issue
Block a user