Fix(Qzone) -10000风控修复 && Fix(port-probe) PID探测多pid逻辑修复和偶数端口 (#192)

* fix(protocol): retry qzone msglist via user.qzone route on -10000

emotion_cgi_msglist_v6 through the legacy h5.qzone.qq.com →
taotao.qzone.qq.com gateway can be rejected with `-10000 使用人数过多`
for some accounts (issue #182). Real-device captures show the same CGI
via user.qzone.qq.com → taotao.qq.com is not rate-limited, so retry once
through that route when the legacy route returns -10000.

Behaviour-preserving for accounts the legacy route already serves: the
retry only fires on a -10000 envelope; all other codes, transport
errors, and the missing-msglist case are unchanged.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(port-probe): fix port probe logic (parse accounts more than 2) and add description for 4302-4310 port.

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
H3CoF6
2026-07-04 14:33:02 +08:00
committed by GitHub
co-authored by Claude Opus 4.8
parent d3eb3bae14
commit 0d03b00643
3 changed files with 172 additions and 61 deletions
+58 -40
View File
@@ -1,5 +1,6 @@
import { exec } from 'child_process';
import net from 'net';
import http from 'http';
import https from 'https';
import { promisify } from 'util';
@@ -126,51 +127,61 @@ interface PtloginUin {
nickname?: string;
}
async function fetchPtlogin(port: number): Promise<PtloginUin[]> {
/**
* 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" and should fall through to the deep-link fallback.
*/
async function fetchPtlogin(port: number, useHttps: boolean): Promise<PtloginUin[] | null> {
return new Promise((resolve) => {
const url = `https://127.0.0.1:${port}/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0`;
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 req = https.get(
url,
{
headers: {
Host: 'localhost.ptlogin2.qq.com',
Referer: 'https://xui.ptlogin2.qq.com/',
Cookie: 'pt_local_token=0',
},
rejectUnauthorized: false, // 忽略本地自签证书报错
timeout: CONNECTION_TIMEOUT_MS,
},
(res) => {
let text = '';
res.on('data', (chunk) => { text += chunk.toString(); });
res.on('end', () => {
try {
// 100% 复刻 Python 切片逻辑:获取两个方括号中间的字符串,再包装成数组
const inner = text.split('[')[1].split(']')[0];
const data = JSON.parse('[' + inner + ']') as PtloginUin[];
resolve(data);
} catch {
resolve([]);
}
});
}
);
const headers = {
Host: 'localhost.ptlogin2.qq.com',
Referer: 'https://xui.ptlogin2.qq.com/',
Cookie: 'pt_local_token=0',
};
req.on('error', () => resolve([]));
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([]);
resolve(null);
});
});
}
async function tryPtloginMethod(port: number): Promise<QqPortLoginInfo | 'fallback'> {
// 抽象的 QQNT
const res1 = await fetchPtlogin(port);
const res2 = await fetchPtlogin(port);
const useHttps = port % 2 !== 0;
const target = res1.length < res2.length ? res1 : res2;
const res1 = await fetchPtlogin(port, useHttps);
const res2 = await fetchPtlogin(port, useHttps);
if (res1 === null && res2 === null) return 'fallback';
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];
@@ -182,8 +193,6 @@ async function tryPtloginMethod(port: number): Promise<QqPortLoginInfo | 'fallba
};
}
// Any non-1 result — the 2+0 alternation, both-2, both-empty, etc. — is
// inconclusive; hand off to the deep-link / process-count fallback.
return 'fallback';
}
@@ -250,12 +259,21 @@ export async function probeQqLoginInfo(pid: number): Promise<QqPortLoginInfo | n
}
return null;
}
const ODD_PT_PORTS = [4301, 4303, 4305, 4307, 4309];
const EVEN_PT_PORTS = [4302, 4304, 4306, 4308, 4310];
const PT_PORTS = [4301, 4303, 4305, 4307, 4309];
const matchedPtPorts = ports.filter(p => PT_PORTS.includes(p));
const matchedOddPorts = ports.filter(p => ODD_PT_PORTS.includes(p));
const matchedEvenPorts = ports.filter(p => EVEN_PT_PORTS.includes(p));
if (matchedPtPorts.length > 0) {
for (const port of matchedPtPorts) {
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 !== 'fallback') {
return ptResult;
+89 -21
View File
@@ -308,11 +308,86 @@ export function mapMsgList(data: RawMsgListResponse): QzoneMsgListResult {
};
}
interface MsgListRoute {
url: string;
headers: Record<string, string>;
}
/** Legacy route (default): h5.qzone.qq.com → taotao.qzone.qq.com. */
function legacyMsgListRoute(
cookieObject: Record<string, string>,
targetUin: string,
pos: number,
num: number,
bkn: string,
): MsgListRoute {
const url = `https://h5.qzone.qq.com/proxy/domain/taotao.qzone.qq.com/cgi-bin/emotion_cgi_msglist_v6?${new URLSearchParams(
{
uin: targetUin,
ftype: '0',
sort: '0',
pos: String(pos),
num: String(num),
replynum: '100',
g_tk: bkn,
callback: '_preloadCallback',
code_version: '1',
format: 'jsonp',
need_private_comment: '1',
},
).toString()}`;
return { url, headers: { Cookie: cookieToString(cookieObject) } };
}
/**
* Fallback route: user.qzone.qq.com → taotao.qq.com (NOT taotao.qzone.qq.com).
* Live captures show this pair is not subject to the `-10000` rate-limit the
* legacy route can hit.
*/
function userMsgListRoute(
cookieObject: Record<string, string>,
targetUin: string,
pos: number,
num: number,
bkn: string,
): MsgListRoute {
const url = `https://user.qzone.qq.com/proxy/domain/taotao.qq.com/cgi-bin/emotion_cgi_msglist_v6?${new URLSearchParams(
{
uin: targetUin,
ftype: '0',
sort: '0',
pos: String(pos),
num: String(num),
g_tk: bkn,
code_version: '1',
format: 'json',
},
).toString()}`;
return {
url,
headers: {
Cookie: cookieToString(cookieObject),
Referer: `https://user.qzone.qq.com/${targetUin}`,
},
};
}
async function requestMsgList(
route: MsgListRoute,
targetUin: string,
): Promise<{ data: RawMsgListResponse; text: string }> {
const text = await RequestUtil.HttpGetText(route.url, 'GET', '', route.headers);
log.trace('getQzoneMsgList raw body (uin=%s): %s', targetUin, text);
return { data: parseQzoneJson<RawMsgListResponse>(text), text };
}
/**
* Fetch a 说说 (Qzone emotion/feed) list via the taotao.qzone.qq.com web
* API, proxied through h5.qzone.qq.com — the same cookie/g_tk plumbing the
* group-album helper uses. Defaults to the bot's own space; `targetUin`
* can name any space the bot may view.
* can name any space the bot may view. On a `-10000` rate-limit from that
* route, retries once via the user.qzone.qq.com route (see
* {@link userMsgListRoute}).
*
* Errors PROPAGATE: a transport failure, a non-zero `code` (Qzone's own
* error envelope, e.g. auth/permission), or a missing `msglist` (the body
@@ -333,27 +408,20 @@ export async function getQzoneMsgList(
}
const bkn = getBknFromCookie(cookieObject);
const url = `https://h5.qzone.qq.com/proxy/domain/taotao.qzone.qq.com/cgi-bin/emotion_cgi_msglist_v6?${new URLSearchParams(
{
uin: targetUin,
ftype: '0',
sort: '0',
pos: String(pos),
num: String(num),
replynum: '100',
g_tk: bkn,
callback: '_preloadCallback',
code_version: '1',
format: 'jsonp',
need_private_comment: '1',
},
).toString()}`;
let { data, text } = await requestMsgList(
legacyMsgListRoute(cookieObject, targetUin, pos, num, bkn),
targetUin,
);
const text = await RequestUtil.HttpGetText(url, 'GET', '', {
Cookie: cookieToString(cookieObject),
});
log.trace('getQzoneMsgList raw body (uin=%s): %s', targetUin, text);
const data = parseQzoneJson<RawMsgListResponse>(text);
// -10000「使用人数过多」is route-specific to the legacy gateway; retry once
// via the user.qzone.qq.com route, which live captures show is not limited.
if (data.code === -10000) {
log.warn('getQzoneMsgList: legacy route rate-limited (uin=%s), retrying via user.qzone route', targetUin);
({ data, text } = await requestMsgList(
userMsgListRoute(cookieObject, targetUin, pos, num, bkn),
targetUin,
));
}
if (typeof data.code === 'number' && data.code !== 0) {
log.warn('getQzoneMsgList: non-zero code (uin=%s) code=%d msg=%s', targetUin, data.code, data.message);
+25
View File
@@ -93,6 +93,31 @@ describe('qzone / getQzoneMsgList (HTTP layer)', () => {
expect(q.get('format')).toBe('jsonp');
});
it('retries via the user.qzone.qq.com route on a -10000 rate-limit', async () => {
const spy = vi
.spyOn(RequestUtil, 'HttpGetText')
.mockResolvedValueOnce('{"code":-10000,"message":"使用人数过多,请稍后再试"}')
.mockResolvedValueOnce(
'{"code":0,"total":1,"msglist":[{"tid":"T1","content":"hi","created_time":1700000000,"cmtnum":0,"secret":0,"pic":[]}]}',
);
const out = await getQzoneMsgList(cookies, '10000', 0, 20);
expect(out).toEqual({
total: 1,
msglist: [{ tid: 'T1', content: 'hi', time: 1700000000, comment_num: 0, is_private: false, images: [] }],
});
expect(spy).toHaveBeenCalledTimes(2);
expect(spy.mock.calls[0]![0]).toContain('https://h5.qzone.qq.com/proxy/domain/taotao.qzone.qq.com/');
const [retryUrl, , , retryHeaders] = spy.mock.calls[1]!;
expect(retryUrl).toContain('https://user.qzone.qq.com/proxy/domain/taotao.qq.com/cgi-bin/emotion_cgi_msglist_v6?');
expect((retryHeaders as Record<string, string>).Referer).toBe('https://user.qzone.qq.com/10000');
const q = new URLSearchParams((retryUrl as string).split('?')[1]);
expect(q.get('format')).toBe('json');
expect(q.get('g_tk')).toBe(expectedGtk);
});
it('returns an empty list (not a throw) for a genuinely empty space', async () => {
// The throw-on-auth-failure contract hinges on distinguishing a missing
// msglist (cookie failure → throw) from an empty msglist (no 说说 → []).