feat(bridge): detect local QQ accounts with shared process snapshots (#525)
Read QQ account databases and attribute identities to their owning processes. Share snapshots across REST, watcher updates and login reconciliation, discard stale results, and report detection failures.
This commit is contained in:
1 parent
8e24995fc3
commit
f6ca9d5f65
38 files changed
+2979
-1534
No files matched your search
@@ -14,11 +14,13 @@ import {
|
||||
import { PipeWatcher } from './pipe-watcher';
|
||||
import { createNativeProcessEnumerator, type ProcessEnumerator } from './process-enumerator';
|
||||
import { QqHookClient } from './qq-hook-client';
|
||||
import { probeQqLoginInfo, type QqPortLoginInfo } from './qq-port-probe';
|
||||
import type { HookProcessInfo } from './types';
|
||||
import { detectAccountLoginsForPids, type AccountLoginState } from './qq-account';
|
||||
import type { HookProcessAccount, HookProcessInfo } from './types';
|
||||
|
||||
const AUTO_LOAD_MAX_ATTEMPTS = 3;
|
||||
|
||||
const DEFAULT_ACCOUNT_REPROBE_INTERVAL_MS = 5000;
|
||||
|
||||
type AutoLoadAttempt = {
|
||||
attempts: number;
|
||||
inFlight: boolean;
|
||||
@@ -54,6 +56,14 @@ export type HookManagerDeps = {
|
||||
watcherIntervalMs?: number;
|
||||
/** Native process lister used by `listProcesses()`. Defaults to the native addon. */
|
||||
listProcesses?: () => HookProcessBaseInfo[];
|
||||
/** Local account detection used to label each process with the account QQ is
|
||||
* signed in as. Receives the pids to label so each one is resolved against
|
||||
* the HOME it actually runs under (a container can give every QQ instance
|
||||
* its own). Defaults to reading QQ's own account data. */
|
||||
detectAccounts?: (pids: readonly number[]) => Promise<AccountLoginState[]>;
|
||||
/** How often the watcher re-probes the account label of each process, in
|
||||
* milliseconds. Defaults to `DEFAULT_ACCOUNT_REPROBE_INTERVAL_MS`. */
|
||||
accountReprobeIntervalMs?: number;
|
||||
/** When true, every newly-discovered QQ process is auto-injected (fires
|
||||
* `loadProcess(pid)` from the watcher's 'process-discovered' handler).
|
||||
* Failed loads are logged and leave the session in the 'error' state.
|
||||
@@ -101,6 +111,8 @@ export class HookManager {
|
||||
/** The owned enumerator (worker lifecycle), or null when a custom lister was
|
||||
* injected (tests) — nothing to tear down in that case. */
|
||||
private readonly enumerator: ProcessEnumerator | null;
|
||||
private readonly detectAccounts: (pids: readonly number[]) => Promise<AccountLoginState[]>;
|
||||
private readonly accountReprobeIntervalMs: number;
|
||||
private readonly autoLoadOnDiscovery: boolean;
|
||||
private readonly onSessionsChangedRaw?: () => void;
|
||||
private readonly log: Logger;
|
||||
@@ -108,6 +120,11 @@ export class HookManager {
|
||||
private readonly autoLoadAttempts = new Map<number, AutoLoadAttempt>();
|
||||
private readonly startPromise: Promise<void>;
|
||||
|
||||
private accounts = new Map<number, HookProcessAccount>();
|
||||
private accountProbe: Promise<void> | null = null;
|
||||
private nextAccountProbeAt = 0;
|
||||
private lastAccountProbeFailure = '';
|
||||
|
||||
private disposed = false;
|
||||
|
||||
constructor(deps: HookManagerDeps) {
|
||||
@@ -127,6 +144,9 @@ export class HookManager {
|
||||
},
|
||||
};
|
||||
this.makeClient = deps.makeClient ?? ((pid: number) => new QqHookClient(pid));
|
||||
this.detectAccounts = deps.detectAccounts ?? detectAccountLoginsForPids;
|
||||
this.accountReprobeIntervalMs =
|
||||
deps.accountReprobeIntervalMs ?? DEFAULT_ACCOUNT_REPROBE_INTERVAL_MS;
|
||||
this.autoLoadOnDiscovery = deps.autoLoadOnDiscovery ?? false;
|
||||
|
||||
// A custom lister (tests) is used directly — no worker, no isolation, just
|
||||
@@ -177,22 +197,20 @@ export class HookManager {
|
||||
async listProcesses(): Promise<HookProcessInfo[]> {
|
||||
await this.startPromise;
|
||||
const processes = await this.enumerate();
|
||||
|
||||
if (processes === null) {
|
||||
// Enumeration timed out / failed — report the last-known sessions rather
|
||||
// than an empty list (which the WebUI would render as "no QQ").
|
||||
return [...this.sessions.values()].map((s) => s.toInfo()).sort((a, b) => a.pid - b.pid);
|
||||
}
|
||||
|
||||
const result: HookProcessInfo[] = [];
|
||||
|
||||
for (const proc of processes) {
|
||||
const session = this.ensureSession(proc.pid);
|
||||
session.attachProcessInfo(proc);
|
||||
result.push(session.toInfo());
|
||||
}
|
||||
|
||||
return result.sort((a, b) => a.pid - b.pid);
|
||||
// A failed enumeration preserves the last known process set.
|
||||
const sessions =
|
||||
processes === null
|
||||
? [...this.sessions.values()]
|
||||
: processes.map((proc) => {
|
||||
const session = this.ensureSession(proc.pid);
|
||||
session.attachProcessInfo(proc);
|
||||
return session;
|
||||
});
|
||||
await this.refreshAccounts();
|
||||
return sessions
|
||||
.filter((session) => this.sessions.get(session.pid) === session)
|
||||
.map((session) => this.processInfo(session))
|
||||
.sort((a, b) => a.pid - b.pid);
|
||||
}
|
||||
|
||||
async loadProcess(pid: number): Promise<HookProcessInfo> {
|
||||
@@ -200,11 +218,10 @@ export class HookManager {
|
||||
await this.startPromise;
|
||||
this.autoLoadAttempts.delete(pid);
|
||||
const session = this.ensureSession(pid);
|
||||
const info = await session.load();
|
||||
// Pull the next tick forward so a freshly-injected pipe gets noticed
|
||||
// within the next event-loop turn instead of after the full interval.
|
||||
await session.load();
|
||||
this.pipeWatcher.wake();
|
||||
return info;
|
||||
await this.refreshAccounts();
|
||||
return this.processInfo(session);
|
||||
}
|
||||
|
||||
async unloadProcess(pid: number): Promise<HookProcessInfo> {
|
||||
@@ -212,19 +229,18 @@ export class HookManager {
|
||||
await this.startPromise;
|
||||
this.autoLoadAttempts.delete(pid);
|
||||
const session = this.ensureSession(pid);
|
||||
return session.unload();
|
||||
await session.unload();
|
||||
await this.refreshAccounts();
|
||||
return this.processInfo(session);
|
||||
}
|
||||
|
||||
async refreshProcess(pid: number): Promise<HookProcessInfo> {
|
||||
this.assertValidPid(pid);
|
||||
await this.startPromise;
|
||||
const session = this.ensureSession(pid);
|
||||
return session.refresh();
|
||||
}
|
||||
|
||||
async probeProcessLoginInfo(pid: number): Promise<QqPortLoginInfo | null> {
|
||||
this.assertValidPid(pid);
|
||||
return probeQqLoginInfo(pid);
|
||||
await session.refresh();
|
||||
await this.refreshAccounts();
|
||||
return this.processInfo(session);
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
@@ -239,6 +255,7 @@ export class HookManager {
|
||||
}
|
||||
|
||||
this.sessions.clear();
|
||||
this.accounts.clear();
|
||||
this.autoLoadAttempts.clear();
|
||||
this.enumerator?.dispose();
|
||||
|
||||
@@ -249,6 +266,80 @@ export class HookManager {
|
||||
|
||||
// ─────────────── wiring ───────────────
|
||||
|
||||
private processInfo(session: HookSession): HookProcessInfo {
|
||||
return { ...session.toInfo(), account: this.accounts.get(session.pid) ?? null };
|
||||
}
|
||||
|
||||
/** REST, watcher ticks and login reconciliation share the same account snapshot. */
|
||||
private async refreshAccounts(): Promise<void> {
|
||||
if (this.disposed) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.accountProbe) {
|
||||
await this.accountProbe;
|
||||
|
||||
// Process discovery invalidates the snapshot while a read is in flight.
|
||||
if (this.nextAccountProbeAt === 0) {
|
||||
await this.refreshAccounts();
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (Date.now() < this.nextAccountProbeAt || this.sessions.size === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.nextAccountProbeAt = Date.now() + this.accountReprobeIntervalMs;
|
||||
this.accountProbe = runWithTraceRequest(() => this.readAccounts()).finally(() => {
|
||||
this.accountProbe = null;
|
||||
});
|
||||
await this.accountProbe;
|
||||
}
|
||||
|
||||
private async readAccounts(): Promise<void> {
|
||||
const sessions = new Map(this.sessions);
|
||||
const accounts = new Map<number, HookProcessAccount>();
|
||||
|
||||
try {
|
||||
for (const state of await this.detectAccounts([...sessions.keys()])) {
|
||||
if (
|
||||
state.pid !== null &&
|
||||
sessions.has(state.pid) &&
|
||||
this.sessions.get(state.pid) === sessions.get(state.pid)
|
||||
) {
|
||||
accounts.set(state.pid, { uin: state.uin, nickname: state.nickname });
|
||||
}
|
||||
}
|
||||
|
||||
this.lastAccountProbeFailure = '';
|
||||
} catch (error) {
|
||||
const message = errMsg(error);
|
||||
|
||||
if (this.lastAccountProbeFailure !== message) {
|
||||
this.lastAccountProbeFailure = message;
|
||||
this.log.warn('account detection failed: %s', message);
|
||||
}
|
||||
}
|
||||
|
||||
if (this.disposed) {
|
||||
return;
|
||||
}
|
||||
|
||||
const changed =
|
||||
accounts.size !== this.accounts.size ||
|
||||
[...accounts].some(([pid, account]) => {
|
||||
const previous = this.accounts.get(pid);
|
||||
return previous?.uin !== account.uin || previous.nickname !== account.nickname;
|
||||
});
|
||||
this.accounts = accounts;
|
||||
|
||||
if (changed) {
|
||||
this.notifySessionsChanged();
|
||||
}
|
||||
}
|
||||
|
||||
private bindWatcher(): void {
|
||||
this.pipeWatcher.on('process-discovered', (info: HookProcessBaseInfo) => {
|
||||
if (this.disposed) {
|
||||
@@ -338,6 +429,8 @@ export class HookManager {
|
||||
return;
|
||||
}
|
||||
|
||||
void this.refreshAccounts();
|
||||
|
||||
for (const session of this.sessions.values()) {
|
||||
const autoLoad = this.autoLoadAttempts.get(session.pid);
|
||||
|
||||
@@ -500,6 +593,10 @@ export class HookManager {
|
||||
makeClient: this.makeClient,
|
||||
pipeWatcher: this.pipeWatcher,
|
||||
onPacket: this.onPacket,
|
||||
detectLoginUin: async () => {
|
||||
await this.refreshAccounts();
|
||||
return this.accounts.get(pid)?.uin ?? null;
|
||||
},
|
||||
log: this.log,
|
||||
});
|
||||
session.attachProcessInfo({ name: defaultProcessName() });
|
||||
@@ -523,9 +620,12 @@ export class HookManager {
|
||||
});
|
||||
session.on('disposed', () => {
|
||||
this.sessions.delete(pid);
|
||||
this.accounts.delete(pid);
|
||||
this.nextAccountProbeAt = 0;
|
||||
});
|
||||
|
||||
this.sessions.set(pid, session);
|
||||
this.nextAccountProbeAt = 0;
|
||||
return session;
|
||||
}
|
||||
|
||||
@@ -612,5 +712,4 @@ export function shouldAutoLoadPid(pid: number, log: Logger): boolean {
|
||||
}
|
||||
|
||||
export type { HookProcessBaseInfo } from './injector';
|
||||
export type { QqPortLoginInfo } from './qq-port-probe';
|
||||
export type { HookProcessInfo, HookProcessStatus } from './types';
|
||||
export type { HookProcessAccount, HookProcessInfo, HookProcessStatus } from './types';
|
||||
@@ -10,8 +10,8 @@ import { isRealUin } from '@snowluma/common/uin';
|
||||
import { EventEmitter } from 'events';
|
||||
import { HookPacketClient } from './hook-packet-client';
|
||||
import type { HookInjectResult } from './injector';
|
||||
import { detectUinForPid } from './qq-account';
|
||||
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';
|
||||
|
||||
@@ -36,10 +36,10 @@ export type HookSessionDeps = {
|
||||
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>;
|
||||
/** Account QQ's local data reports as signed in on `pid`, or null. Drives the
|
||||
* login-reconcile safety net; injectable for tests. Defaults to
|
||||
* `detectUinForPid`. */
|
||||
detectLoginUin?: (pid: number) => Promise<string | 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
|
||||
@@ -80,7 +80,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 detectLoginUin: (pid: number) => Promise<string | null>;
|
||||
private readonly pipeWatcher: HookSessionDeps['pipeWatcher'];
|
||||
private readonly onPacket: PacketSink | null;
|
||||
private readonly log: Logger;
|
||||
@@ -101,9 +101,9 @@ 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;
|
||||
private lastProbeFailure = '';
|
||||
private loginReconcileTimer: ReturnType<typeof setInterval> | null = null;
|
||||
private detecting = false;
|
||||
private lastDetectFailure = '';
|
||||
private acceptedLoginHintUin = '';
|
||||
private loginHintAttemptUin = '';
|
||||
private loginHintAttempts = 0;
|
||||
@@ -121,7 +121,7 @@ export class HookSession extends EventEmitter {
|
||||
this.pid = pid;
|
||||
this.injector = deps.injector;
|
||||
this.makeClient = deps.makeClient;
|
||||
this.probeLogin = deps.probeLogin ?? probeQqLoginInfo;
|
||||
this.detectLoginUin = deps.detectLoginUin ?? detectUinForPid;
|
||||
this.pipeWatcher = deps.pipeWatcher;
|
||||
this.onPacket = deps.onPacket ?? null;
|
||||
this.log = deps.log ?? createLogger('HookSession');
|
||||
@@ -170,6 +170,8 @@ export class HookSession extends EventEmitter {
|
||||
status: this._status,
|
||||
error: this._error,
|
||||
method: this._method,
|
||||
// Filled in by HookManager from the client's local account data.
|
||||
account: null,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -636,7 +638,7 @@ export class HookSession extends EventEmitter {
|
||||
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.
|
||||
// is missed and we'd wait forever. Keep re-detecting until logged in.
|
||||
runWithoutRequestContext(() => this.startLoginReconcile());
|
||||
}
|
||||
|
||||
@@ -796,39 +798,41 @@ export class HookSession extends EventEmitter {
|
||||
}
|
||||
|
||||
// ─────────────── login reconcile (Docker auto-login safety net) ───────────
|
||||
// The local endpoint can identify an auto-restored account before the
|
||||
// runtime is ready. Forward identity for reconciliation, but never synthesize
|
||||
// online state from the probe.
|
||||
// QQ can restore an account on its own before the runtime is ready, and its
|
||||
// local account data names that account. Forward the identity for
|
||||
// reconciliation, but never synthesize online state from the detection.
|
||||
|
||||
private startLoginReconcile(): void {
|
||||
if (this.loginProbeTimer || this.disposed) {
|
||||
if (this.loginReconcileTimer || this.disposed) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.log.info('awaiting login: PID=%d', this.pid);
|
||||
void this.probeLoginOnce(); // immediate — catch already-logged-in fast
|
||||
this.loginProbeTimer = setInterval(
|
||||
() => void this.probeLoginOnce(),
|
||||
void this.detectLoginOnce(); // immediate — catch already-logged-in fast
|
||||
this.loginReconcileTimer = setInterval(
|
||||
() => void this.detectLoginOnce(),
|
||||
LOGIN_RECONCILE_INTERVAL_MS,
|
||||
);
|
||||
this.loginProbeTimer.unref?.();
|
||||
this.loginReconcileTimer.unref?.();
|
||||
}
|
||||
|
||||
private stopLoginReconcile(): void {
|
||||
if (this.loginProbeTimer) {
|
||||
clearInterval(this.loginProbeTimer);
|
||||
this.loginProbeTimer = null;
|
||||
if (this.loginReconcileTimer) {
|
||||
clearInterval(this.loginReconcileTimer);
|
||||
this.loginReconcileTimer = 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) {
|
||||
private async detectLoginOnce(): Promise<void> {
|
||||
// Detecting the account reads the filesystem; skip overlapping ticks so a
|
||||
// slow read never stacks on top of the interval.
|
||||
if (this.detecting) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.disposed || !this.connected || this.loggedIn) {
|
||||
const client = this.client;
|
||||
|
||||
if (this.disposed || !client || !this.connected || this.loggedIn) {
|
||||
this.stopLoginReconcile();
|
||||
return;
|
||||
}
|
||||
@@ -837,46 +841,44 @@ export class HookSession extends EventEmitter {
|
||||
return;
|
||||
}
|
||||
|
||||
this.probing = true;
|
||||
this.detecting = true;
|
||||
|
||||
try {
|
||||
let info: QqPortLoginInfo | null;
|
||||
let uin: string | null;
|
||||
|
||||
try {
|
||||
info = await this.probeLogin(this.pid);
|
||||
uin = await this.detectLoginUin(this.pid);
|
||||
} catch (error) {
|
||||
const message = errMsg(error);
|
||||
const note = `${this.pid}:${message}`;
|
||||
|
||||
if (this.lastProbeFailure !== note) {
|
||||
this.lastProbeFailure = note;
|
||||
this.log.warn('login probe failed: PID=%d err=%s', this.pid, message);
|
||||
if (this.lastDetectFailure !== message) {
|
||||
this.lastDetectFailure = message;
|
||||
this.log.warn(
|
||||
'login identity detection failed: PID=%d err=%s',
|
||||
this.pid,
|
||||
message,
|
||||
);
|
||||
}
|
||||
|
||||
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();
|
||||
// A reconnect owns a new client; an older read cannot supply its identity.
|
||||
if (this.client !== client || this.disposed || !this.connected || this.loggedIn) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (info?.identityKnown && isRealUin(info.uin)) {
|
||||
const client = this.client;
|
||||
this.lastDetectFailure = '';
|
||||
|
||||
if (!client) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.acceptedLoginHintUin === info.uin) {
|
||||
if (uin !== null && isRealUin(uin)) {
|
||||
if (this.acceptedLoginHintUin === uin) {
|
||||
this.nextLoginIdentityObservationAt =
|
||||
Date.now() + LOGIN_IDENTITY_OBSERVE_INTERVAL_MS;
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.loginHintAttemptUin !== info.uin) {
|
||||
this.loginHintAttemptUin = info.uin;
|
||||
if (this.loginHintAttemptUin !== uin) {
|
||||
this.loginHintAttemptUin = uin;
|
||||
this.loginHintAttempts = 0;
|
||||
this.nextLoginHintAt = 0;
|
||||
this.nextLoginIdentityObservationAt = 0;
|
||||
@@ -893,11 +895,11 @@ export class HookSession extends EventEmitter {
|
||||
this.log.info(
|
||||
'login identity discovered: PID=%d UIN=%s; awaiting readiness',
|
||||
this.pid,
|
||||
info.uin,
|
||||
uin,
|
||||
);
|
||||
|
||||
try {
|
||||
await client.reconcileLoginIdentity(info.uin);
|
||||
await client.reconcileLoginIdentity(uin);
|
||||
|
||||
if (
|
||||
this.client !== client ||
|
||||
@@ -908,7 +910,7 @@ export class HookSession extends EventEmitter {
|
||||
return;
|
||||
}
|
||||
|
||||
this.acceptedLoginHintUin = info.uin;
|
||||
this.acceptedLoginHintUin = uin;
|
||||
this.nextLoginIdentityObservationAt =
|
||||
Date.now() + LOGIN_IDENTITY_OBSERVE_INTERVAL_MS;
|
||||
} catch (error) {
|
||||
@@ -920,7 +922,7 @@ export class HookSession extends EventEmitter {
|
||||
this.log.warn(
|
||||
'login identity reconciliation failed: PID=%d UIN=%s attempts=%d err=%s',
|
||||
this.pid,
|
||||
info.uin,
|
||||
uin,
|
||||
attempt,
|
||||
errMsg(error),
|
||||
);
|
||||
@@ -932,7 +934,7 @@ export class HookSession extends EventEmitter {
|
||||
this.log.trace(
|
||||
'login identity hint failed: PID=%d UIN=%s attempt=%d err=%s',
|
||||
this.pid,
|
||||
info.uin,
|
||||
uin,
|
||||
attempt,
|
||||
errMsg(error),
|
||||
);
|
||||
@@ -940,7 +942,7 @@ export class HookSession extends EventEmitter {
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
this.probing = false;
|
||||
this.detecting = false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -950,7 +952,7 @@ export class HookSession extends EventEmitter {
|
||||
this.loginHintAttempts = 0;
|
||||
this.nextLoginHintAt = 0;
|
||||
this.nextLoginIdentityObservationAt = 0;
|
||||
this.lastProbeFailure = '';
|
||||
this.lastDetectFailure = '';
|
||||
}
|
||||
|
||||
private handlePacket(packet: QqHookPacket): void {
|
||||
|
||||
@@ -2,11 +2,12 @@ export {
|
||||
HookManager,
|
||||
type BridgeManagerSink,
|
||||
type HookManagerDeps,
|
||||
type HookProcessAccount,
|
||||
type HookProcessBaseInfo,
|
||||
type HookProcessInfo,
|
||||
type HookProcessStatus,
|
||||
type QqPortLoginInfo,
|
||||
} from './hook-manager';
|
||||
export { type AccountLoginState, type LocalAccount } from './qq-account';
|
||||
export {
|
||||
getRuntimeIntegrity,
|
||||
hasLowProcessIntegrity,
|
||||
|
||||
@@ -16,6 +16,7 @@ export interface ManualMapHandle {
|
||||
interface NativeHookAddon {
|
||||
getRuntimeIntegrity?(): unknown;
|
||||
getAllMainProcess(): number[];
|
||||
probeDbLock?(dbPath: string): { pid: number; name: string }[];
|
||||
loadModuleManual(pid: number, dylibPath: string): ManualMapHandle | Promise<ManualMapHandle>;
|
||||
unloadModuleManual(pid: number, handle: ManualMapHandle): void;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
import fs from 'node:fs';
|
||||
import { getNativeHookAddon } from '../injector';
|
||||
|
||||
export interface DbLockHolder {
|
||||
pid: number;
|
||||
|
||||
name: string;
|
||||
}
|
||||
|
||||
export function probeDbLock(dbPath: string): DbLockHolder[] {
|
||||
if (process.platform === 'win32') {
|
||||
return probeWindowsHolders(dbPath);
|
||||
}
|
||||
|
||||
return process.platform === 'linux' ? probeLinuxLocks(dbPath) : [];
|
||||
}
|
||||
|
||||
function probeWindowsHolders(dbPath: string): DbLockHolder[] {
|
||||
const addon = getNativeHookAddon();
|
||||
|
||||
if (!addon?.probeDbLock) {
|
||||
throw new Error('Windows account detection requires a hook addon with probeDbLock');
|
||||
}
|
||||
|
||||
const holders = addon.probeDbLock(dbPath);
|
||||
|
||||
if (
|
||||
!Array.isArray(holders) ||
|
||||
holders.some(
|
||||
(holder) =>
|
||||
!holder ||
|
||||
!Number.isInteger(holder.pid) ||
|
||||
holder.pid <= 0 ||
|
||||
typeof holder.name !== 'string',
|
||||
)
|
||||
) {
|
||||
throw new Error('Invalid database holders returned by the hook addon');
|
||||
}
|
||||
|
||||
return holders;
|
||||
}
|
||||
|
||||
export function isQqProcessName(name: string): boolean {
|
||||
return (
|
||||
name
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.replace(/\.exe$/, '') === 'qq'
|
||||
);
|
||||
}
|
||||
|
||||
/** 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 });
|
||||
|
||||
if (!stat) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const key = deviceInodeKey(stat.dev, stat.ino);
|
||||
const table = fs.readFileSync('/proc/locks', 'utf8');
|
||||
const holders: DbLockHolder[] = [];
|
||||
const seen = new Set<number>();
|
||||
|
||||
for (const line of table.split('\n')) {
|
||||
// `<id>: <type> <advisory|mandatory> <read|write> <pid> <dev>:<inode> <start> <end>`
|
||||
const fields = line.trim().split(/\s+/);
|
||||
|
||||
if (fields.length < 8 || fields[5] !== key) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const pid = Number(fields[4]);
|
||||
|
||||
if (!Number.isInteger(pid) || pid <= 0 || seen.has(pid)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
seen.add(pid);
|
||||
holders.push({ pid, name: readProcessName(pid) });
|
||||
}
|
||||
|
||||
return holders;
|
||||
}
|
||||
|
||||
function deviceInodeKey(device: number, inode: number): string {
|
||||
const major = (device >> 8) & 0xfff;
|
||||
const minor = (device & 0xff) | ((device >> 12) & 0xfff00);
|
||||
return `${major.toString(16).padStart(2, '0')}:${minor.toString(16).padStart(2, '0')}:${inode}`;
|
||||
}
|
||||
|
||||
function readProcessName(pid: number): string {
|
||||
try {
|
||||
return fs.readFileSync(`/proc/${pid}/comm`, 'utf8').trim();
|
||||
} catch {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import { isQqProcessName, probeDbLock } from './db-lock';
|
||||
import { readLocalAccounts, type LocalAccount } from './login-db';
|
||||
import { loginDbPaths, ntMsgDbPath, qqDataRoots, qqDataRootsForPid } from './paths';
|
||||
|
||||
const log = createLogger('QqAccount');
|
||||
const reportedFailures = new Map<string, string>();
|
||||
|
||||
export interface AccountLoginState extends LocalAccount {
|
||||
pid: number | null;
|
||||
}
|
||||
|
||||
export async function detectAccountLogins(
|
||||
roots: readonly string[] = qqDataRoots(),
|
||||
): Promise<AccountLoginState[]> {
|
||||
const states: AccountLoginState[] = [];
|
||||
|
||||
for (const root of roots) {
|
||||
const report = await readLocalAccounts(root);
|
||||
|
||||
for (const dbPath of loginDbPaths(root)) {
|
||||
const failure = report.failures.find((item) => item.path === dbPath);
|
||||
|
||||
if (!failure) {
|
||||
reportedFailures.delete(dbPath);
|
||||
continue;
|
||||
}
|
||||
|
||||
const detail =
|
||||
failure.error instanceof Error
|
||||
? failure.error.message
|
||||
: String(failure.error ?? '');
|
||||
const reason = detail ? failure.reason + ': ' + detail : failure.reason;
|
||||
|
||||
if (reportedFailures.get(dbPath) !== reason) {
|
||||
reportedFailures.set(dbPath, reason);
|
||||
log.warn('login.db unreadable: path=%s reason=%s', dbPath, reason);
|
||||
}
|
||||
}
|
||||
|
||||
for (const account of report.accounts) {
|
||||
const holder = probeDbLock(ntMsgDbPath(root, account)).find((candidate) =>
|
||||
isQqProcessName(candidate.name),
|
||||
);
|
||||
states.push({ ...account, pid: holder?.pid ?? null });
|
||||
}
|
||||
}
|
||||
|
||||
return states;
|
||||
}
|
||||
|
||||
export async function detectAccountLoginsForPids(
|
||||
pids: readonly number[],
|
||||
): Promise<AccountLoginState[]> {
|
||||
const roots = [...new Set(pids.flatMap((pid) => qqDataRootsForPid(pid)))];
|
||||
return detectAccountLogins(roots);
|
||||
}
|
||||
|
||||
export async function detectUinForPid(pid: number): Promise<string | null> {
|
||||
const accounts = await detectAccountLoginsForPids([pid]);
|
||||
return accounts.find((account) => account.pid === pid)?.uin ?? null;
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
export { isQqProcessName, probeDbLock, type DbLockHolder } from './db-lock';
|
||||
export {
|
||||
detectAccountLogins,
|
||||
detectAccountLoginsForPids,
|
||||
detectUinForPid,
|
||||
type AccountLoginState,
|
||||
} from './detect';
|
||||
export {
|
||||
readLocalAccounts,
|
||||
type LocalAccount,
|
||||
type LocalAccountReport,
|
||||
type LoginDbFailure,
|
||||
} from './login-db';
|
||||
export { accountDirName, loginDbPaths, ntMsgDbPath, qqDataRoots, qqDataRootsForPid } from './paths';
|
||||
export {
|
||||
decryptDatabase,
|
||||
detectAlgorithm,
|
||||
type DecryptedDatabase,
|
||||
type KdfHmacAlgorithm,
|
||||
type PageHmacAlgorithm,
|
||||
type SqlcipherAlgorithm,
|
||||
} from './sqlcipher';
|
||||
@@ -0,0 +1,199 @@
|
||||
import { isRealUin } from '@snowluma/common/uin';
|
||||
import { SqliteDatabase } from '@snowluma/sqlite';
|
||||
import { mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { loginDbPaths } from './paths';
|
||||
import { decryptDatabase, detectAlgorithm } from './sqlcipher';
|
||||
|
||||
const LOGIN_DB_PASSPHRASE = 'BD156D6710D54D8782F4';
|
||||
const COLUMN_UIN = '1000';
|
||||
const COLUMN_UID = '1001';
|
||||
const COLUMN_NICKNAME = '1007';
|
||||
|
||||
export interface LocalAccount {
|
||||
uin: string;
|
||||
uid: string;
|
||||
nickname: string;
|
||||
}
|
||||
|
||||
export type LoginDbFailure = 'read-failed' | 'undecryptable' | 'query-failed';
|
||||
|
||||
type LoginDbResult = { accounts: LocalAccount[] } | { failure: LoginDbFailure; error?: unknown };
|
||||
|
||||
export interface LocalAccountReport {
|
||||
accounts: LocalAccount[];
|
||||
failures: Array<{ path: string; reason: LoginDbFailure; error?: unknown }>;
|
||||
}
|
||||
|
||||
// Share concurrent reads and invalidate when either the database or its WAL changes.
|
||||
const accountCache = new Map<string, { stamp: string; result: Promise<LoginDbResult> }>();
|
||||
|
||||
export async function readLocalAccounts(root: string): Promise<LocalAccountReport> {
|
||||
const merged = new Map<string, LocalAccount>();
|
||||
const failures: LocalAccountReport['failures'] = [];
|
||||
|
||||
for (const dbPath of loginDbPaths(root)) {
|
||||
const result = await readLoginDb(dbPath);
|
||||
|
||||
if ('failure' in result) {
|
||||
failures.push({ path: dbPath, reason: result.failure, error: result.error });
|
||||
continue;
|
||||
}
|
||||
|
||||
for (const account of result.accounts) {
|
||||
if (!merged.has(account.uin)) {
|
||||
merged.set(account.uin, account);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return { accounts: [...merged.values()], failures };
|
||||
}
|
||||
|
||||
async function readLoginDb(dbPath: string): Promise<LoginDbResult> {
|
||||
let stamp: string;
|
||||
|
||||
try {
|
||||
const files = await Promise.all([statIfPresent(dbPath), statIfPresent(dbPath + '-wal')]);
|
||||
stamp = files.map((info) => (info ? info.mtimeMs + ':' + info.size : '-')).join('|');
|
||||
} catch (error) {
|
||||
accountCache.delete(dbPath);
|
||||
return { failure: 'read-failed', error };
|
||||
}
|
||||
|
||||
const cached = accountCache.get(dbPath);
|
||||
|
||||
if (cached?.stamp === stamp) {
|
||||
return cached.result;
|
||||
}
|
||||
|
||||
const entry = { stamp, result: decryptAndQuery(dbPath) };
|
||||
accountCache.set(dbPath, entry);
|
||||
const result = await entry.result;
|
||||
|
||||
if ('failure' in result && accountCache.get(dbPath) === entry) {
|
||||
accountCache.delete(dbPath);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
async function decryptAndQuery(dbPath: string): Promise<LoginDbResult> {
|
||||
let image: Buffer;
|
||||
let wal: Buffer | null;
|
||||
|
||||
try {
|
||||
const contents = await readIfPresent(dbPath);
|
||||
|
||||
if (!contents) {
|
||||
return { accounts: [] };
|
||||
}
|
||||
|
||||
image = contents;
|
||||
wal = await readIfPresent(dbPath + '-wal');
|
||||
} catch (error) {
|
||||
return { failure: 'read-failed', error };
|
||||
}
|
||||
|
||||
const algorithm = detectAlgorithm(image, LOGIN_DB_PASSPHRASE);
|
||||
|
||||
if (!algorithm) {
|
||||
return { failure: 'undecryptable' };
|
||||
}
|
||||
|
||||
const decrypted = decryptDatabase(image, wal, LOGIN_DB_PASSPHRASE, algorithm);
|
||||
|
||||
if (!decrypted) {
|
||||
return { failure: 'undecryptable' };
|
||||
}
|
||||
|
||||
try {
|
||||
return { accounts: await queryLoginTable(decrypted.image) };
|
||||
} catch (error) {
|
||||
return { failure: 'query-failed', error };
|
||||
}
|
||||
}
|
||||
|
||||
// SQLite opens a private temporary image; QQ's database and sidecars stay read-only.
|
||||
async function queryLoginTable(image: Buffer): Promise<LocalAccount[]> {
|
||||
const directory = await mkdtemp(path.join(os.tmpdir(), 'snowluma-qq-login-'));
|
||||
const dbPath = path.join(directory, 'login.db');
|
||||
|
||||
try {
|
||||
await writeFile(dbPath, image, { mode: 0o600 });
|
||||
const db = new SqliteDatabase(dbPath, { readOnly: true });
|
||||
|
||||
try {
|
||||
const rows = await db
|
||||
.prepare(
|
||||
`SELECT [${COLUMN_UIN}], [${COLUMN_UID}], [${COLUMN_NICKNAME}] FROM login_table`,
|
||||
)
|
||||
.all();
|
||||
const accounts: LocalAccount[] = [];
|
||||
|
||||
for (const row of rows) {
|
||||
const account = {
|
||||
uin: asText(row[COLUMN_UIN]),
|
||||
uid: asText(row[COLUMN_UID]),
|
||||
nickname: asText(row[COLUMN_NICKNAME]),
|
||||
};
|
||||
|
||||
if (isRealUin(account.uin) && account.uid.length > 0) {
|
||||
accounts.push(account);
|
||||
}
|
||||
}
|
||||
|
||||
return accounts;
|
||||
} finally {
|
||||
await db.close();
|
||||
}
|
||||
} finally {
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
async function readIfPresent(file: string): Promise<Buffer | null> {
|
||||
try {
|
||||
return await readFile(file);
|
||||
} catch (error) {
|
||||
if (isNotFound(error)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
function isNotFound(error: unknown): boolean {
|
||||
return error instanceof Error && 'code' in error && error.code === 'ENOENT';
|
||||
}
|
||||
|
||||
async function statIfPresent(file: string) {
|
||||
try {
|
||||
return await stat(file);
|
||||
} catch (error) {
|
||||
if (isNotFound(error)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/** SQLite values arrive as numbers, strings or blobs depending on the column. */
|
||||
function asText(value: unknown): string {
|
||||
if (typeof value === 'string') {
|
||||
return value;
|
||||
}
|
||||
|
||||
if (typeof value === 'number' || typeof value === 'bigint') {
|
||||
return String(value);
|
||||
}
|
||||
|
||||
if (value instanceof Uint8Array) {
|
||||
return Buffer.from(value).toString('utf8');
|
||||
}
|
||||
|
||||
return '';
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { homedir } from 'node:os';
|
||||
import path from 'node:path';
|
||||
|
||||
const LOGIN_DB_SEGMENTS = ['nt_db', 'login.db'] as const;
|
||||
|
||||
export function qqDataRoots(): string[] {
|
||||
if (process.platform === 'win32') {
|
||||
return windowsDataRoots();
|
||||
}
|
||||
|
||||
if (process.platform === 'linux') {
|
||||
return linuxDataRoots({ ...process.env, HOME: process.env.HOME || homedir() });
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
/** Each Linux client owns its HOME; an unavailable process has no known root. */
|
||||
export function qqDataRootsForPid(pid: number): string[] {
|
||||
if (process.platform === 'win32') {
|
||||
return windowsDataRoots();
|
||||
}
|
||||
|
||||
if (process.platform !== 'linux') {
|
||||
return [];
|
||||
}
|
||||
|
||||
const environment = readProcessEnvironment(pid);
|
||||
return environment ? linuxDataRoots(environment) : [];
|
||||
}
|
||||
|
||||
function linuxDataRoots(environment: { HOME?: string; XDG_CONFIG_HOME?: string }): string[] {
|
||||
const base =
|
||||
environment.XDG_CONFIG_HOME ||
|
||||
(environment.HOME ? path.join(environment.HOME, '.config') : null);
|
||||
return base ? [path.join(base, 'QQ')] : [];
|
||||
}
|
||||
|
||||
function readProcessEnvironment(pid: number): { HOME?: string; XDG_CONFIG_HOME?: string } | null {
|
||||
let raw: string;
|
||||
|
||||
try {
|
||||
raw = readFileSync(`/proc/${pid}/environ`, 'utf8');
|
||||
} catch (error) {
|
||||
if (error instanceof Error && 'code' in error && error.code === 'ENOENT') {
|
||||
return null;
|
||||
}
|
||||
|
||||
throw error;
|
||||
}
|
||||
|
||||
const environment: { HOME?: string; XDG_CONFIG_HOME?: string } = {};
|
||||
|
||||
for (const entry of raw.split('\0')) {
|
||||
const separator = entry.indexOf('=');
|
||||
|
||||
if (separator <= 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const name = entry.slice(0, separator);
|
||||
|
||||
if (name === 'HOME' || name === 'XDG_CONFIG_HOME') {
|
||||
environment[name] = entry.slice(separator + 1);
|
||||
}
|
||||
}
|
||||
|
||||
return environment;
|
||||
}
|
||||
|
||||
/** Both Linux layouts occur in QQ installations; the primary takes precedence. */
|
||||
export function loginDbPaths(root: string): string[] {
|
||||
if (process.platform === 'win32') {
|
||||
return [path.join(root, 'nt_qq', 'global', ...LOGIN_DB_SEGMENTS)];
|
||||
}
|
||||
|
||||
return [
|
||||
path.join(root, 'global', ...LOGIN_DB_SEGMENTS),
|
||||
path.join(root, 'nt_qq', 'global', ...LOGIN_DB_SEGMENTS),
|
||||
];
|
||||
}
|
||||
|
||||
export function ntMsgDbPath(root: string, account: { uin: string; uid: string }): string {
|
||||
if (process.platform === 'win32') {
|
||||
return path.join(root, account.uin, 'nt_qq', 'nt_db', 'nt_msg.db');
|
||||
}
|
||||
|
||||
return path.join(root, accountDirName(account.uid), 'nt_db', 'nt_msg.db');
|
||||
}
|
||||
|
||||
export function accountDirName(uid: string): string {
|
||||
const digest = createHash('md5').update(uid, 'utf8').digest('hex');
|
||||
return `nt_qq_${createHash('md5').update(`${digest}nt_kernel`, 'utf8').digest('hex')}`;
|
||||
}
|
||||
|
||||
function windowsDataRoots(): string[] {
|
||||
const configured = tencentFilesRootFromUserDataInfo();
|
||||
return [configured ?? path.join(homedir(), 'Documents', 'Tencent Files')];
|
||||
}
|
||||
|
||||
export function tencentFilesRootFromUserDataInfo(home = homedir()): string | null {
|
||||
const ini = path.join(
|
||||
path.dirname(home),
|
||||
'Public',
|
||||
'Documents',
|
||||
'Tencent',
|
||||
'QQ',
|
||||
'UserDataInfo.ini',
|
||||
);
|
||||
let text: string;
|
||||
|
||||
try {
|
||||
text = readFileSync(ini, 'utf8');
|
||||
} catch (error) {
|
||||
if (error instanceof Error && 'code' in error && error.code === 'ENOENT') {
|
||||
return null;
|
||||
}
|
||||
|
||||
throw error;
|
||||
}
|
||||
|
||||
let inDataSet = false;
|
||||
|
||||
for (const raw of text.split(/\r?\n/)) {
|
||||
const line = raw.trim();
|
||||
|
||||
if (line.startsWith('[') && line.endsWith(']')) {
|
||||
inDataSet = line.toLowerCase() === '[userdataset]';
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!inDataSet) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const separator = line.indexOf('=');
|
||||
|
||||
if (
|
||||
separator === -1 ||
|
||||
line.slice(0, separator).trim().toLowerCase() !== 'userdatasavepath'
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const value = line.slice(separator + 1).trim();
|
||||
|
||||
if (value.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// The ini always holds Windows paths, so resolve them with the win32
|
||||
// flavor wherever this runs.
|
||||
return path.win32.basename(value).toLowerCase() === 'tencent files'
|
||||
? value
|
||||
: path.win32.join(value, 'Tencent Files');
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,461 @@
|
||||
/**
|
||||
* SQLCipher v4 page decryption for QQ NT's local databases.
|
||||
*
|
||||
* QQ NT stores every database under `nt_db/` as a SQLCipher v4 stream behind a
|
||||
* 1024-byte client header:
|
||||
*
|
||||
* [ 1024-byte client header ][ page 1 ][ page 2 ] ...
|
||||
* ^ KDF salt = first 16 bytes of page 1
|
||||
*
|
||||
* Each page ends with `IV (16 bytes) || page HMAC`, rounded up to the AES block
|
||||
* size; the page size is 4096 on every database QQ writes. Page 1's ciphertext
|
||||
* starts after its 16-byte salt, which replaces the plaintext "SQLite format 3"
|
||||
* magic — so the decrypted body of page 1 starts at page offset 16 and can never
|
||||
* contain that magic. A candidate key is therefore confirmed by recomputing the
|
||||
* page HMAC over the *ciphertext*, which is independent of the AES pass.
|
||||
*
|
||||
* The page-HMAC and KDF-HMAC algorithms are not fixed across client builds, so
|
||||
* they are probed per database (12 combinations) instead of assumed.
|
||||
*/
|
||||
|
||||
import { createDecipheriv, createHmac, pbkdf2Sync } from 'node:crypto';
|
||||
|
||||
/** QQ NT prepends this many bytes before the SQLCipher stream. */
|
||||
export const DATABASE_HEADER_SIZE = 1024;
|
||||
|
||||
const PAGE_SIZE = 4096;
|
||||
const SALT_SIZE = 16;
|
||||
const IV_SIZE = 16;
|
||||
const KEY_SIZE = 32;
|
||||
|
||||
/** SQLCipher v4 derives the AES key with this many PBKDF2 iterations. */
|
||||
const KDF_ITERATIONS = 4000;
|
||||
/** The per-page HMAC key uses a fast derivation over the page salt. */
|
||||
const HMAC_KEY_ITERATIONS = 2;
|
||||
/** SQLCipher's HMAC salt is the page salt XOR this mask. */
|
||||
const HMAC_SALT_MASK = 0x3a;
|
||||
|
||||
const WAL_HEADER_SIZE = 32;
|
||||
const WAL_FRAME_HEADER_SIZE = 24;
|
||||
|
||||
const SQLITE_MAGIC = Buffer.from('SQLite format 3\0', 'latin1');
|
||||
|
||||
export type PageHmacAlgorithm = 'none' | 'sha1' | 'sha256' | 'sha512';
|
||||
export type KdfHmacAlgorithm = 'sha1' | 'sha256' | 'sha512';
|
||||
|
||||
/** One SQLCipher algorithm pair, as probed against a database's page 1. */
|
||||
export interface SqlcipherAlgorithm {
|
||||
pageHmac: PageHmacAlgorithm;
|
||||
kdfHmac: KdfHmacAlgorithm;
|
||||
}
|
||||
|
||||
/** Every pair to probe, in order: `cipher_use_hmac = OFF` first, then each digest. */
|
||||
const PAGE_HMAC_ALGORITHMS: readonly PageHmacAlgorithm[] = ['none', 'sha1', 'sha256', 'sha512'];
|
||||
const KDF_HMAC_ALGORITHMS: readonly KdfHmacAlgorithm[] = ['sha1', 'sha256', 'sha512'];
|
||||
|
||||
const PAGE_HMAC_DIGEST_BYTES: Record<PageHmacAlgorithm, number> = {
|
||||
none: 0,
|
||||
sha1: 20,
|
||||
sha256: 32,
|
||||
sha512: 64,
|
||||
};
|
||||
|
||||
/** A database image decrypted from disk, with its `-wal` frames folded in. */
|
||||
export interface DecryptedDatabase {
|
||||
/** A self-contained plaintext SQLite image (rollback-journal mode). */
|
||||
image: Buffer;
|
||||
/** Frames folded in from the `-wal` sidecar, 0 when there was nothing to merge. */
|
||||
walFrames: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Probe the algorithm pair of an encrypted database.
|
||||
*
|
||||
* Returns null when the page-1 HMAC matches no combination under `passphrase`,
|
||||
* which means either the passphrase or the file layout is not what we expect.
|
||||
*/
|
||||
export function detectAlgorithm(image: Buffer, passphrase: string): SqlcipherAlgorithm | null {
|
||||
const pageOne = readPageOne(image);
|
||||
|
||||
if (!pageOne) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const salt = pageOne.subarray(0, SALT_SIZE);
|
||||
|
||||
for (const pageHmac of PAGE_HMAC_ALGORITHMS) {
|
||||
for (const kdfHmac of KDF_HMAC_ALGORITHMS) {
|
||||
const algorithm: SqlcipherAlgorithm = { pageHmac, kdfHmac };
|
||||
const key = deriveKey(passphrase, salt, kdfHmac);
|
||||
|
||||
if (verifyPageOne(pageOne, key, algorithm)) {
|
||||
return algorithm;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Decrypt a whole database and fold in the `-wal` sidecar when there is one.
|
||||
*
|
||||
* QQ keeps a long-lived WAL, so everything committed since the last checkpoint
|
||||
* — including an account that just signed in — lives only in the sidecar.
|
||||
* Returns null when the image cannot be decrypted.
|
||||
*/
|
||||
export function decryptDatabase(
|
||||
image: Buffer,
|
||||
wal: Buffer | null,
|
||||
passphrase: string,
|
||||
algorithm: SqlcipherAlgorithm,
|
||||
): DecryptedDatabase | null {
|
||||
const pageOne = readPageOne(image);
|
||||
|
||||
if (!pageOne) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const key = deriveKey(passphrase, pageOne.subarray(0, SALT_SIZE), algorithm.kdfHmac);
|
||||
const base = decryptPages(image, key, algorithm);
|
||||
|
||||
if (!base) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const merged = applyWal(base, wal, key, algorithm);
|
||||
normalizeImage(merged.image);
|
||||
return merged;
|
||||
}
|
||||
|
||||
/** Page 1 as stored, or null when the file is too short to hold a header + page 1. */
|
||||
function readPageOne(image: Buffer): Buffer | null {
|
||||
if (image.length < DATABASE_HEADER_SIZE + PAGE_SIZE) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return image.subarray(DATABASE_HEADER_SIZE, DATABASE_HEADER_SIZE + PAGE_SIZE);
|
||||
}
|
||||
|
||||
/** Per-page reserve = IV + page HMAC digest, rounded up to the AES block size. */
|
||||
function reserveBytes(algorithm: SqlcipherAlgorithm): number {
|
||||
const digestBytes = PAGE_HMAC_DIGEST_BYTES[algorithm.pageHmac];
|
||||
return Math.ceil((IV_SIZE + digestBytes) / 16) * 16;
|
||||
}
|
||||
|
||||
function deriveKey(passphrase: string, salt: Buffer, kdfHmac: KdfHmacAlgorithm): Buffer {
|
||||
return pbkdf2Sync(passphrase, salt, KDF_ITERATIONS, KEY_SIZE, kdfHmac);
|
||||
}
|
||||
|
||||
/**
|
||||
* Confirm a candidate key against page 1.
|
||||
*
|
||||
* With the page HMAC enabled the check runs over the stored ciphertext, exactly
|
||||
* like SQLCipher's own verification. With HMAC off there is nothing to verify on
|
||||
* the ciphertext, so page 1 is decrypted and the SQLite header fields that live
|
||||
* past the salt-occupied first 16 bytes are checked instead.
|
||||
*/
|
||||
function verifyPageOne(pageOne: Buffer, key: Buffer, algorithm: SqlcipherAlgorithm): boolean {
|
||||
const reserve = reserveBytes(algorithm);
|
||||
const digestBytes = PAGE_HMAC_DIGEST_BYTES[algorithm.pageHmac];
|
||||
|
||||
if (digestBytes === 0) {
|
||||
const body = decryptPageBody(pageOne, key, SALT_SIZE, reserve);
|
||||
return body !== null && hasSqliteHeaderFields(body);
|
||||
}
|
||||
|
||||
const hmacSalt = Buffer.alloc(SALT_SIZE);
|
||||
|
||||
for (let index = 0; index < SALT_SIZE; index++) {
|
||||
hmacSalt[index] = pageOne[index] ^ HMAC_SALT_MASK;
|
||||
}
|
||||
|
||||
const hmacKey = pbkdf2Sync(key, hmacSalt, HMAC_KEY_ITERATIONS, KEY_SIZE, algorithm.kdfHmac);
|
||||
const bodyEnd = PAGE_SIZE - reserve;
|
||||
const pageNumber = Buffer.alloc(4);
|
||||
pageNumber.writeUInt32LE(1);
|
||||
const input = Buffer.concat([
|
||||
pageOne.subarray(SALT_SIZE, bodyEnd),
|
||||
pageOne.subarray(bodyEnd, bodyEnd + IV_SIZE),
|
||||
pageNumber,
|
||||
]);
|
||||
const computed = createHmac(algorithm.pageHmac, hmacKey).update(input).digest();
|
||||
const stored = pageOne.subarray(bodyEnd + IV_SIZE, bodyEnd + IV_SIZE + digestBytes);
|
||||
return equalsBytes(computed, stored);
|
||||
}
|
||||
|
||||
/** The decrypted page-1 body starts at file offset 16 (the salt replaces 0..16). */
|
||||
function hasSqliteHeaderFields(body: Buffer): boolean {
|
||||
if (body.length < 8) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const pageSize = body.readUInt16BE(0);
|
||||
const pageSizeOk = pageSize === 1 || (pageSize >= 512 && (pageSize & (pageSize - 1)) === 0);
|
||||
return pageSizeOk && body[5] === 64 && body[6] === 32 && body[7] === 32;
|
||||
}
|
||||
|
||||
function equalsBytes(left: Buffer, right: Buffer): boolean {
|
||||
if (left.length !== right.length) {
|
||||
return false;
|
||||
}
|
||||
|
||||
let diff = 0;
|
||||
|
||||
for (let index = 0; index < left.length; index++) {
|
||||
diff |= left[index]! ^ right[index]!;
|
||||
}
|
||||
|
||||
return diff === 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Decrypt every page of the main file, in place on a fresh buffer.
|
||||
*
|
||||
* `skip` drops the salt prefix of page 1; the reserve region of each page is
|
||||
* left zeroed, which is how SQLCipher lays the plaintext out.
|
||||
*/
|
||||
function decryptPages(image: Buffer, key: Buffer, algorithm: SqlcipherAlgorithm): Buffer | null {
|
||||
const stream = image.subarray(DATABASE_HEADER_SIZE);
|
||||
const pageCount = Math.floor(stream.length / PAGE_SIZE);
|
||||
|
||||
if (pageCount === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const reserve = reserveBytes(algorithm);
|
||||
const plain = Buffer.alloc(pageCount * PAGE_SIZE);
|
||||
|
||||
for (let index = 0; index < pageCount; index++) {
|
||||
const pageNumber = index + 1;
|
||||
const page = stream.subarray(index * PAGE_SIZE, (index + 1) * PAGE_SIZE);
|
||||
const body = decryptPageBody(page, key, pageNumber === 1 ? SALT_SIZE : 0, reserve);
|
||||
|
||||
if (body === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
writePlaintextPage(plain, index * PAGE_SIZE, pageNumber, body);
|
||||
}
|
||||
|
||||
return plain;
|
||||
}
|
||||
|
||||
/** Decrypt one page body, or null when the page cannot hold an IV + digest. */
|
||||
function decryptPageBody(page: Buffer, key: Buffer, skip: number, reserve: number): Buffer | null {
|
||||
const cipherLength = PAGE_SIZE - skip - reserve;
|
||||
|
||||
if (cipherLength <= 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const ciphertext = page.subarray(skip, skip + cipherLength);
|
||||
const iv = page.subarray(skip + cipherLength, skip + cipherLength + IV_SIZE);
|
||||
const decipher = createDecipheriv('aes-256-cbc', key, iv);
|
||||
decipher.setAutoPadding(false);
|
||||
return Buffer.concat([decipher.update(ciphertext), decipher.final()]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Write one decrypted page into the plaintext image.
|
||||
*
|
||||
* Page 1 is special in both the main file and the WAL: its first 16 on-disk
|
||||
* bytes hold the KDF salt in place of SQLite's magic, so the magic and the
|
||||
* page-size field have to be restored. Every other page's body starts at offset
|
||||
* 0 of the page.
|
||||
*/
|
||||
function writePlaintextPage(image: Buffer, offset: number, pageNumber: number, body: Buffer): void {
|
||||
if (pageNumber !== 1) {
|
||||
body.copy(image, offset, 0, Math.min(body.length, PAGE_SIZE));
|
||||
return;
|
||||
}
|
||||
|
||||
SQLITE_MAGIC.copy(image, offset);
|
||||
body.copy(image, offset + SALT_SIZE, 0, Math.min(body.length, PAGE_SIZE - SALT_SIZE));
|
||||
image.writeUInt16BE(PAGE_SIZE, offset + 16);
|
||||
}
|
||||
|
||||
/**
|
||||
* Fold the `-wal` sidecar into a decrypted image and return the frame count.
|
||||
*
|
||||
* A WAL is not wrapped in SQLCipher's envelope the way the main file is: its
|
||||
* 32-byte header and every 24-byte frame header stay plaintext, and each frame
|
||||
* carries one encrypted page (page 1 keeping its salt prefix). SQLite's frame
|
||||
* checksums are computed over the frames *as stored*, i.e. over the ciphertext,
|
||||
* which is why the intact prefix is established before any decryption.
|
||||
*
|
||||
* Only frames up to the last commit are applied, and the database size recorded
|
||||
* by that commit decides how many pages the merged image has — a torn tail from
|
||||
* a running QQ therefore contributes nothing.
|
||||
*/
|
||||
function applyWal(
|
||||
base: Buffer,
|
||||
wal: Buffer | null,
|
||||
key: Buffer,
|
||||
algorithm: SqlcipherAlgorithm,
|
||||
): DecryptedDatabase {
|
||||
const log = wal === null ? null : parseWal(wal);
|
||||
|
||||
if (!log || log.frames.length === 0) {
|
||||
return { image: base, walFrames: 0 };
|
||||
}
|
||||
|
||||
let lastCommit = -1;
|
||||
|
||||
for (let index = 0; index < log.frames.length; index++) {
|
||||
if (log.frames[index]!.commitSize !== 0) {
|
||||
lastCommit = index;
|
||||
}
|
||||
}
|
||||
|
||||
if (lastCommit < 0) {
|
||||
return { image: base, walFrames: 0 };
|
||||
}
|
||||
|
||||
const pageCount = log.frames[lastCommit]!.commitSize;
|
||||
const basePageCount = base.length / PAGE_SIZE;
|
||||
|
||||
// A commit can only grow the database by the pages its own log carries, so
|
||||
// anything past that bound is a corrupt frame header rather than a size.
|
||||
if (pageCount < 1 || pageCount > basePageCount + log.frames.length) {
|
||||
return { image: base, walFrames: 0 };
|
||||
}
|
||||
|
||||
const merged = Buffer.alloc(pageCount * PAGE_SIZE);
|
||||
base.copy(merged, 0, 0, Math.min(base.length, merged.length));
|
||||
const reserve = reserveBytes(algorithm);
|
||||
|
||||
for (let index = 0; index <= lastCommit; index++) {
|
||||
const frame = log.frames[index]!;
|
||||
|
||||
if (frame.pageNumber === 0 || frame.pageNumber > pageCount) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const page = wal!.subarray(frame.offset, frame.offset + PAGE_SIZE);
|
||||
const body = decryptPageBody(page, key, frame.pageNumber === 1 ? SALT_SIZE : 0, reserve);
|
||||
|
||||
if (body === null) {
|
||||
return { image: base, walFrames: 0 };
|
||||
}
|
||||
|
||||
writePlaintextPage(merged, (frame.pageNumber - 1) * PAGE_SIZE, frame.pageNumber, body);
|
||||
}
|
||||
|
||||
return { image: merged, walFrames: lastCommit + 1 };
|
||||
}
|
||||
|
||||
interface WalFrame {
|
||||
pageNumber: number;
|
||||
/** Database size in pages recorded by a commit frame, 0 for a non-commit frame. */
|
||||
commitSize: number;
|
||||
/** Offset of the frame's page inside the `-wal` buffer. */
|
||||
offset: number;
|
||||
}
|
||||
|
||||
interface WalLog {
|
||||
frames: WalFrame[];
|
||||
littleEndian: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate a `-wal` buffer and collect its intact frames.
|
||||
*
|
||||
* Validation stops at the first frame whose checksum does not continue the
|
||||
* chain, mirroring SQLite's own recovery: everything after that frame is either
|
||||
* half-written or belongs to an aborted transaction.
|
||||
*/
|
||||
function parseWal(wal: Buffer): WalLog | null {
|
||||
if (wal.length < WAL_HEADER_SIZE + WAL_FRAME_HEADER_SIZE + PAGE_SIZE) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const magic = wal.readUInt32BE(0);
|
||||
const littleEndian = magic === 0x377f0682 ? true : magic === 0x377f0683 ? false : null;
|
||||
|
||||
if (littleEndian === null || wal.readUInt32BE(8) !== PAGE_SIZE) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// The header checksum covers its first 24 bytes; magic and page size are
|
||||
// excluded from the checksummed range by that length.
|
||||
const header = walChecksum([0, 0], [wal.subarray(0, WAL_HEADER_SIZE - 8)], littleEndian);
|
||||
|
||||
if (header[0] !== wal.readUInt32BE(24) || header[1] !== wal.readUInt32BE(28)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const frameSize = WAL_FRAME_HEADER_SIZE + PAGE_SIZE;
|
||||
const frames: WalFrame[] = [];
|
||||
let running = header;
|
||||
|
||||
for (let offset = WAL_HEADER_SIZE; offset + frameSize <= wal.length; offset += frameSize) {
|
||||
const frameHeader = wal.subarray(offset, offset + WAL_FRAME_HEADER_SIZE);
|
||||
const page = wal.subarray(offset + WAL_FRAME_HEADER_SIZE, offset + frameSize);
|
||||
running = walChecksum(running, [frameHeader.subarray(0, 8), page], littleEndian);
|
||||
|
||||
if (
|
||||
running[0] !== frameHeader.readUInt32BE(16) ||
|
||||
running[1] !== frameHeader.readUInt32BE(20)
|
||||
) {
|
||||
break;
|
||||
}
|
||||
|
||||
frames.push({
|
||||
pageNumber: frameHeader.readUInt32BE(0),
|
||||
commitSize: frameHeader.readUInt32BE(4),
|
||||
offset: offset + WAL_FRAME_HEADER_SIZE,
|
||||
});
|
||||
}
|
||||
|
||||
return { frames, littleEndian };
|
||||
}
|
||||
|
||||
/**
|
||||
* SQLite's rolling WAL checksum: two 32-bit accumulators advanced over 8-byte
|
||||
* word pairs. The byte order is fixed by the WAL magic (`0x377f0682` =
|
||||
* little-endian words, `0x377f0683` = big-endian) and is unrelated to the
|
||||
* host's byte order.
|
||||
*
|
||||
* Every chunk fed in here is a multiple of 8 bytes: the header contributes 24
|
||||
* bytes, a frame its first 8 header bytes plus a whole page.
|
||||
*/
|
||||
function walChecksum(
|
||||
seed: [number, number],
|
||||
chunks: readonly Buffer[],
|
||||
littleEndian: boolean,
|
||||
): [number, number] {
|
||||
let first = seed[0];
|
||||
let second = seed[1];
|
||||
|
||||
for (const chunk of chunks) {
|
||||
for (let offset = 0; offset + 8 <= chunk.length; offset += 8) {
|
||||
const high = littleEndian ? chunk.readUInt32LE(offset) : chunk.readUInt32BE(offset);
|
||||
const low = littleEndian
|
||||
? chunk.readUInt32LE(offset + 4)
|
||||
: chunk.readUInt32BE(offset + 4);
|
||||
first = (first + high + second) >>> 0;
|
||||
second = (second + low + first) >>> 0;
|
||||
}
|
||||
}
|
||||
|
||||
return [first, second];
|
||||
}
|
||||
|
||||
/**
|
||||
* Make the assembled image self-consistent before it is handed to SQLite.
|
||||
*
|
||||
* The merge can add or remove pages relative to the base image, and the header
|
||||
* fields that describe the database are only trusted while page 1's change
|
||||
* counter and version-valid-for agree. The write/read version bytes are reset
|
||||
* to the legacy journal so the image can be opened read-only without needing a
|
||||
* `-wal`/`-shm` pair next to it.
|
||||
*/
|
||||
function normalizeImage(image: Buffer): void {
|
||||
const pageCount = image.length / PAGE_SIZE;
|
||||
const changeCounter = image.readUInt32BE(24);
|
||||
image[18] = 1;
|
||||
image[19] = 1;
|
||||
image.writeUInt32BE(pageCount, 28);
|
||||
image.writeUInt32BE(changeCounter, 92);
|
||||
}
|
||||
@@ -1,293 +0,0 @@
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import { exec } from 'child_process';
|
||||
import http from 'http';
|
||||
import https from 'https';
|
||||
import { promisify } from 'util';
|
||||
|
||||
const execAsync = promisify(exec);
|
||||
const log = createLogger('LoginProbe');
|
||||
const probeNotes = new Map<number, string>();
|
||||
|
||||
function noteProbe(pid: number, result: string, ports: number, processes: number | null): void {
|
||||
const processText = processes === null ? '' : ` processes=${processes}`;
|
||||
const message = `login probe: PID=${pid} result=${result} ports=${ports}${processText}`;
|
||||
|
||||
if (probeNotes.get(pid) === message) {
|
||||
return;
|
||||
}
|
||||
|
||||
probeNotes.set(pid, message);
|
||||
log.info(message);
|
||||
}
|
||||
|
||||
const CONNECTION_TIMEOUT_MS = 500;
|
||||
const COMMAND_TIMEOUT_MS = 1500;
|
||||
const OVERALL_PROBE_TIMEOUT_MS = 5000;
|
||||
const EXEC_OPTIONS = { timeout: COMMAND_TIMEOUT_MS, killSignal: 'SIGKILL' as const };
|
||||
// QQ's Ptlogin quick-login ports plus its main process mean a single
|
||||
// logged-in client surfaces roughly this many processes. When no usable
|
||||
// probe port is found, a count BELOW this implies the target PID is still at
|
||||
// the login screen; AT/ABOVE it the environment is ambiguous (multiple or
|
||||
// unrelated `qq` processes), so the passive probe returns no conclusion.
|
||||
const LOGGED_OUT_PROCESS_COUNT_MAX = 6;
|
||||
|
||||
export interface QqPortLoginInfo {
|
||||
port: number;
|
||||
uin: string;
|
||||
uid?: string;
|
||||
nickName?: string;
|
||||
/** The local QQ endpoint exposed an account identity. This does not prove
|
||||
* the native protocol session is ready to send or receive packets. */
|
||||
identityKnown: boolean;
|
||||
}
|
||||
|
||||
/** One entry of the Ptlogin `pt_get_uins` JSONP array. Only the fields the
|
||||
* probe reads are modelled; QQ sends more but they're irrelevant here. */
|
||||
interface PtloginUin {
|
||||
uin?: string | number;
|
||||
account?: string | number;
|
||||
nickname?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* One `pt_get_uins` call. Returns the parsed account array (possibly empty —
|
||||
* an EMPTY array is a real answer: "0 accounts", NOT an error) or `null` when
|
||||
* the port could not be reached / the body was not a usable pt_get_uins
|
||||
* response (connect refused, timeout, unparseable). Callers MUST distinguish
|
||||
* the two: `[]` feeds the logged-in/out decision, `null` means "network
|
||||
* problem, no answer". Neither outcome triggers interactive probing.
|
||||
*/
|
||||
async function fetchPtlogin(port: number, useHttps: boolean): Promise<PtloginUin[] | null> {
|
||||
return new Promise((resolve) => {
|
||||
const protocol = useHttps ? 'https' : 'http';
|
||||
const url = `${protocol}://127.0.0.1:${port}/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0`;
|
||||
|
||||
const headers = {
|
||||
Host: 'localhost.ptlogin2.qq.com',
|
||||
Referer: 'https://xui.ptlogin2.qq.com/',
|
||||
Cookie: 'pt_local_token=0',
|
||||
};
|
||||
|
||||
const handleResponse = (res: http.IncomingMessage) => {
|
||||
let text = '';
|
||||
res.on('data', (chunk) => {
|
||||
text += chunk.toString();
|
||||
});
|
||||
res.on('end', () => {
|
||||
try {
|
||||
const inner = text.split('[')[1].split(']')[0];
|
||||
const data = JSON.parse('[' + inner + ']') as PtloginUin[];
|
||||
resolve(data);
|
||||
} catch {
|
||||
resolve(null);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const req = useHttps
|
||||
? https.get(
|
||||
url,
|
||||
{ headers, timeout: CONNECTION_TIMEOUT_MS, rejectUnauthorized: false },
|
||||
handleResponse,
|
||||
)
|
||||
: http.get(url, { headers, timeout: CONNECTION_TIMEOUT_MS }, handleResponse);
|
||||
|
||||
req.on('error', () => resolve(null));
|
||||
req.on('timeout', () => {
|
||||
req.destroy();
|
||||
resolve(null);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function tryPtloginMethod(port: number): Promise<QqPortLoginInfo | null> {
|
||||
const useHttps = port % 2 !== 0;
|
||||
|
||||
const res1 = await fetchPtlogin(port, useHttps);
|
||||
const res2 = await fetchPtlogin(port, useHttps);
|
||||
|
||||
if (res1 === null && res2 === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const usable = [res1, res2].filter((r): r is PtloginUin[] => r !== null);
|
||||
const target = usable.reduce((a, b) => (a.length <= b.length ? a : b));
|
||||
|
||||
if (target.length === 1) {
|
||||
const account = target[0];
|
||||
return {
|
||||
port,
|
||||
uin: String(account.uin || account.account || ''),
|
||||
nickName: account.nickname || '',
|
||||
identityKnown: true,
|
||||
};
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
async function getQqProcessCount(): Promise<number> {
|
||||
try {
|
||||
if (process.platform === 'win32') {
|
||||
const { stdout } = await execAsync(
|
||||
'tasklist /fi "imagename eq QQ.exe" /nh',
|
||||
EXEC_OPTIONS,
|
||||
);
|
||||
return stdout
|
||||
.toLowerCase()
|
||||
.split('\n')
|
||||
.filter((line) => line.includes('qq.exe')).length;
|
||||
} else {
|
||||
const { stdout } = await execAsync('pgrep -c qq', EXEC_OPTIONS);
|
||||
return parseInt(stdout.trim(), 10) || 0;
|
||||
}
|
||||
} catch {
|
||||
// On failure report the ambiguous threshold so we never falsely
|
||||
// conclude "logged out".
|
||||
return LOGGED_OUT_PROCESS_COUNT_MAX;
|
||||
}
|
||||
}
|
||||
|
||||
async function getProcessPorts(pid: number): Promise<number[] | null> {
|
||||
try {
|
||||
if (process.platform === 'win32') {
|
||||
const { stdout } = await execAsync('netstat -ano', EXEC_OPTIONS);
|
||||
const ports = new Set<number>();
|
||||
const lines = stdout.split('\n');
|
||||
|
||||
for (const line of lines) {
|
||||
const parts = line.trim().split(/\s+/);
|
||||
|
||||
if (parts.length < 5) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const owningPid = parts[parts.length - 1];
|
||||
|
||||
if (owningPid !== String(pid)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const localAddr = parts[1];
|
||||
const portMatch = localAddr.match(/:(\d+)$/);
|
||||
|
||||
if (!portMatch) {
|
||||
continue;
|
||||
}
|
||||
|
||||
ports.add(Number(portMatch[1]));
|
||||
}
|
||||
|
||||
return Array.from(ports);
|
||||
} else {
|
||||
const { stdout } = await execAsync('ss -tlnp', EXEC_OPTIONS);
|
||||
const ports = new Set<number>();
|
||||
const lines = stdout.split('\n');
|
||||
|
||||
for (const line of lines) {
|
||||
if (!line.includes(`pid=${pid},`) && !line.includes(`pid=${pid})`)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const match = line.match(/:(\d+)\s/);
|
||||
|
||||
if (match) {
|
||||
ports.add(Number(match[1]));
|
||||
}
|
||||
}
|
||||
|
||||
return Array.from(ports);
|
||||
}
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function probeQqLoginInfoInternal(pid: number): Promise<QqPortLoginInfo | null> {
|
||||
const ports = await getProcessPorts(pid);
|
||||
|
||||
if (ports === null) {
|
||||
noteProbe(pid, 'unavailable', 0, null);
|
||||
return null;
|
||||
}
|
||||
|
||||
if (ports.length === 0) {
|
||||
const totalPids = await getQqProcessCount();
|
||||
|
||||
if (totalPids < LOGGED_OUT_PROCESS_COUNT_MAX) {
|
||||
noteProbe(pid, 'no-ports', 0, totalPids);
|
||||
return { port: 0, uin: '', identityKnown: false };
|
||||
}
|
||||
|
||||
noteProbe(pid, 'inconclusive', 0, totalPids);
|
||||
return null;
|
||||
}
|
||||
|
||||
const ODD_PT_PORTS = [4301, 4303, 4305, 4307, 4309];
|
||||
const EVEN_PT_PORTS = [4302, 4304, 4306, 4308, 4310];
|
||||
|
||||
const matchedOddPorts = ports.filter((p) => ODD_PT_PORTS.includes(p));
|
||||
const matchedEvenPorts = ports.filter((p) => EVEN_PT_PORTS.includes(p));
|
||||
|
||||
let ptPortsToTry: number[] = [];
|
||||
|
||||
if (matchedOddPorts.length > 0) {
|
||||
ptPortsToTry = matchedOddPorts;
|
||||
} else if (matchedEvenPorts.length > 0) {
|
||||
ptPortsToTry = matchedEvenPorts;
|
||||
}
|
||||
|
||||
if (ptPortsToTry.length > 0) {
|
||||
for (const port of ptPortsToTry) {
|
||||
const ptResult = await tryPtloginMethod(port);
|
||||
|
||||
if (ptResult !== null) {
|
||||
return ptResult;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
const totalPids = await getQqProcessCount();
|
||||
|
||||
if (totalPids < LOGGED_OUT_PROCESS_COUNT_MAX) {
|
||||
noteProbe(pid, 'no-ports', ports.length, totalPids);
|
||||
return {
|
||||
port: ports[0],
|
||||
uin: '',
|
||||
identityKnown: false,
|
||||
};
|
||||
}
|
||||
|
||||
noteProbe(pid, 'inconclusive', ports.length, totalPids);
|
||||
return null;
|
||||
}
|
||||
|
||||
// Background discovery must remain passive. Interactive application
|
||||
// endpoints are deliberately excluded from automatic probing.
|
||||
noteProbe(pid, 'no-match', ptPortsToTry.length, null);
|
||||
return null;
|
||||
}
|
||||
|
||||
export async function probeQqLoginInfo(pid: number): Promise<QqPortLoginInfo | null> {
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
let timedOut = false;
|
||||
const timeout = new Promise<null>((resolve) => {
|
||||
timer = setTimeout(() => {
|
||||
timedOut = true;
|
||||
resolve(null);
|
||||
}, OVERALL_PROBE_TIMEOUT_MS);
|
||||
});
|
||||
|
||||
try {
|
||||
const result = await Promise.race([probeQqLoginInfoInternal(pid), timeout]);
|
||||
|
||||
if (timedOut) {
|
||||
log.warn('login check timed out: PID=%d', pid);
|
||||
}
|
||||
|
||||
return result;
|
||||
} finally {
|
||||
if (timer) {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,12 @@ import type { HookProcessBaseInfo } from './injector';
|
||||
export type HookProcessStatus =
|
||||
'available' | 'loading' | 'connecting' | 'loaded' | 'online' | 'error' | 'disconnected';
|
||||
|
||||
/** Account the QQ client is signed in as, as reported by its local data. */
|
||||
export interface HookProcessAccount {
|
||||
uin: string;
|
||||
nickname: string;
|
||||
}
|
||||
|
||||
/** Public-facing snapshot of a per-PID HookSession. */
|
||||
export interface HookProcessInfo extends HookProcessBaseInfo {
|
||||
injected: boolean;
|
||||
@@ -12,4 +18,6 @@ export interface HookProcessInfo extends HookProcessBaseInfo {
|
||||
status: HookProcessStatus;
|
||||
error: string;
|
||||
method: string;
|
||||
/** Locally detected identity; null means unknown, not necessarily signed out. */
|
||||
account: HookProcessAccount | null;
|
||||
}
|
||||
Reference in new issue
Block a user