From 63ab7a184627f90176cf8394dea26367ce2234a4 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Wed, 1 Jul 2026 21:56:28 +0800 Subject: [PATCH] fix(protocol): parse Qzone feeds without eval + stop getCookies hanging (#182) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 真机抓包定位到 get_qzone_feeds 的两个问题: 1) feeds3_html_more 的响应体是**JS 对象字面量**(键无引号、单引号字符串、\xNN 转义、数组含 undefined),不是 JSON → JSON.parse 报 "Expected property name at position 66"(报告者看到的「响应结构问题」)。实测调参数(outputhtmlfeed/ format)改不掉这个格式,且 feeds 是纯远程 H5(native i64 里无相关 CGI),没有 干净 JSON 端点。改用**非执行的递归下降解析器** parseJsLiteral 把它当数据解析—— 绝不 eval 远程内容(vm 沙箱不是安全边界,被篡改的响应可逃逸到 RCE)。解析器只认 对象/数组/字符串/数字/true|false|null|undefined,丢弃 __proto__ 键防原型污染; mapFeeds 过滤数组尾部的 undefined 洞。 2) getCookies 卡死:HttpsGetCookies 无超时、无深度上限地递归跟随 302;当某跳目标 不可达(数据中心/Docker 上 qzone.qq.com 裸域超时)→ 永久挂死所有 cookie-backed web 动作。加 8s 超时 + 深度上限(5) + 失败/超时保留已收集 cookie(不再 reject)。 两处修复均在 tempserver 真机验证:getCookies 从卡死 3 分钟变正常返回;抓到的真实 feeds 响应体做成测试 fixture,非执行解析器正确解出 uin/nickname/html(\x3C→<)。 读接口加了 TRACE 原始体日志 + 结构失败错误带响应片段,方便后续排查。 (msglist 的 -10000「使用人数过多」判定为 taotao 服务端风控——同 cookie 下 feeds 能成功、msglist 单独挂,非代码 bug,代码已正确透传。) protocol 572 全绿、typecheck 干净;两轮对抗性 Agent:先揪出 vm 版可 RCE 逼我换非执行 解析器,再确认新解析器构造上不执行代码、无原型污染、真机数据解析正确。 --- packages/protocol/src/web/qzone.ts | 142 +++++++++++++++++- packages/protocol/src/web/request-util.ts | 55 +++---- .../web/fixtures/qzone-feeds-sample.jsonp | 8 + .../tests/web/qzone-feeds-parse.test.ts | 75 +++++++++ packages/protocol/tests/web/qzone.test.ts | 6 +- 5 files changed, 251 insertions(+), 35 deletions(-) create mode 100644 packages/protocol/tests/web/fixtures/qzone-feeds-sample.jsonp create mode 100644 packages/protocol/tests/web/qzone-feeds-parse.test.ts diff --git a/packages/protocol/src/web/qzone.ts b/packages/protocol/src/web/qzone.ts index fca10501..222f55ce 100644 --- a/packages/protocol/src/web/qzone.ts +++ b/packages/protocol/src/web/qzone.ts @@ -80,6 +80,131 @@ export function parseQzoneJson(text: string): T { return JSON.parse(s.slice(start, end + 1)) as T; } +/** + * Parse the JavaScript OBJECT-LITERAL payload of a Qzone JSONP feeds response + * WITHOUT executing it. feeds3_html_more returns `_preloadCallback({ … })` where + * the `data` value uses unquoted keys, single-quoted strings, `\xNN` escapes and + * literal `undefined`s — it is meant to be eval'd by the browser callback, so + * JSON.parse chokes on it. We ran the alternatives to ground: no param combo + * (outputhtmlfeed/format) makes the CGI emit real JSON, and feeds are pure + * remote H5 (absent from the native client), so there is no cleaner endpoint. + * Rather than eval remote-controlled content (a `vm` sandbox is not a security + * boundary — a tampered body escapes it to RCE), we recursively DESCEND the + * literal as data: it can only ever produce a value, never run code. + * + * Handles the subset the CGI emits: objects (unquoted or quoted keys), arrays + * (incl. `undefined`/elided holes), single/double-quoted strings with JS escapes + * (`\xNN`, `\uNNNN`, `\/`, …), numbers and `true|false|null|undefined`. + * `__proto__` keys are dropped (no prototype pollution). + */ +function parseJsLiteral(src: string): unknown { + let i = 0; + const n = src.length; + const isWs = (c: string): boolean => c === ' ' || c === '\t' || c === '\n' || c === '\r' || c === '\f' || c === '\v'; + const skipWs = (): void => { while (i < n && isWs(src[i]!)) i++; }; + + function parseString(quote: string): string { + i++; // opening quote + let out = ''; + while (i < n) { + const c = src[i]!; + if (c === '\\') { + const e = src[i + 1]; + if (e === 'x') { out += String.fromCharCode(parseInt(src.slice(i + 2, i + 4), 16)); i += 4; continue; } + if (e === 'u') { out += String.fromCharCode(parseInt(src.slice(i + 2, i + 6), 16)); i += 6; continue; } + const simple: Record = { n: '\n', t: '\t', r: '\r', b: '\b', f: '\f', v: '\v', '0': '\0' }; + out += e !== undefined ? (simple[e] ?? e) : ''; // \/ → /, \' → ', unknown → the char + i += 2; + continue; + } + if (c === quote) { i++; return out; } + out += c; + i++; + } + throw new Error('unterminated string in qzone feeds payload'); + } + + function parseKey(): string { + skipWs(); + const c = src[i]; + if (c === '"' || c === "'") return parseString(c); + let s = ''; + while (i < n && /[A-Za-z0-9_$]/.test(src[i]!)) { s += src[i]; i++; } + if (!s) throw new Error('expected object key in qzone feeds payload'); + return s; + } + + function parseObject(): Record { + i++; // { + const obj: Record = {}; + skipWs(); + if (src[i] === '}') { i++; return obj; } + for (;;) { + const key = parseKey(); + skipWs(); + if (src[i] !== ':') throw new Error('expected ":" in qzone feeds payload'); + i++; + const value = parseValue(); + if (key !== '__proto__') obj[key] = value; + skipWs(); + const ch = src[i]; + if (ch === ',') { i++; skipWs(); if (src[i] === '}') { i++; return obj; } continue; } + if (ch === '}') { i++; return obj; } + throw new Error('expected "," or "}" in qzone feeds payload'); + } + } + + function parseArray(): unknown[] { + i++; // [ + const arr: unknown[] = []; + skipWs(); + if (src[i] === ']') { i++; return arr; } + for (;;) { + arr.push(parseValue()); + skipWs(); + const ch = src[i]; + if (ch === ',') { i++; skipWs(); if (src[i] === ']') { i++; return arr; } continue; } + if (ch === ']') { i++; return arr; } + throw new Error('expected "," or "]" in qzone feeds payload'); + } + } + + function parseValue(): unknown { + skipWs(); + const c = src[i]; + if (c === undefined) throw new Error('unexpected end of qzone feeds payload'); + if (c === '{') return parseObject(); + if (c === '[') return parseArray(); + if (c === '"' || c === "'") return parseString(c); + let token = ''; + while (i < n && !/[,}\]:\s]/.test(src[i]!)) { token += src[i]; i++; } + if (token === 'true') return true; + if (token === 'false') return false; + if (token === 'null') return null; + if (token === 'undefined') return undefined; + if (token !== '') { const num = Number(token); if (!Number.isNaN(num)) return num; } + throw new Error('unexpected token in qzone feeds payload: ' + token.slice(0, 20)); + } + + return parseValue(); +} + +/** + * Extract the object a Qzone feeds JSONP body hands to its callback, parsed as + * data (never executed — see {@link parseJsLiteral}). Slices from the first `{` + * (the callback argument) and parses one balanced value; trailing `);` is + * ignored. Throws if the payload is not an object. + */ +export function parseQzoneCallback(text: string): T { + const start = text.indexOf('{'); + if (start === -1) throw new Error('invalid feeds response from qzone api'); + const value = parseJsLiteral(text.slice(start)); + if (value === null || typeof value !== 'object') { + throw new Error('invalid feeds response from qzone api'); + } + return value as T; +} + function assertRichParams(richType?: number, richval?: string): void { const hasRichType = richType !== undefined; const hasRichval = richval !== undefined && richval.trim() !== ''; @@ -194,6 +319,7 @@ export async function getQzoneMsgList( const text = await RequestUtil.HttpGetText(url, 'GET', '', { Cookie: cookieToString(cookieObject), }); + log.trace('getQzoneMsgList raw body (uin=%s): %s', targetUin, text); const data = parseQzoneJson(text); if (typeof data.code === 'number' && data.code !== 0) { @@ -201,8 +327,8 @@ export async function getQzoneMsgList( throw new Error(`qzone msglist failed: code=${data.code} ${data.message ?? ''}`.trim()); } if (!Array.isArray(data.msglist)) { - log.warn('getQzoneMsgList: no msglist in response (uin=%s) — likely auth/cookie failure', targetUin); - throw new Error('无法获取空间说说列表'); + log.warn('getQzoneMsgList: no msglist in response (uin=%s) — likely auth/cookie failure or unverified response shape; body head=%s', targetUin, text.slice(0, 300)); + throw new Error(`无法获取空间说说列表(响应结构异常): ${text.slice(0, 200)}`); } return mapMsgList(data); @@ -262,7 +388,8 @@ export interface QzoneFeedsResult { /** Pure transform from the raw feeds response into the OneBot list. */ export function mapFeeds(data: RawFeedsResponse): QzoneFeedsResult { - const list = data.data?.data ?? []; + // The CGI pads the array with trailing `undefined`/null holes — drop them. + const list = (data.data?.data ?? []).filter((f): f is RawFeedItem => !!f); return { feeds: list.map((f) => ({ uin: Number(f.uin ?? 0), @@ -335,15 +462,18 @@ export async function getQzoneFeeds( const text = await RequestUtil.HttpGetText(url, 'GET', '', { Cookie: cookieToString(cookieObject), }); - const data = parseQzoneJson(text); + log.trace('getQzoneFeeds raw body (uin=%s): %s', selfUin, text); + // feeds3_html_more's payload is a JS object literal, not JSON — parse it as + // inert data (see parseQzoneCallback; never executed) rather than JSON.parse. + const data = parseQzoneCallback(text); if (typeof data.code === 'number' && data.code !== 0) { log.warn('getQzoneFeeds: non-zero code (uin=%s) code=%d msg=%s', selfUin, data.code, data.message); throw new Error(`qzone feeds failed: code=${data.code} ${data.message ?? ''}`.trim()); } if (!Array.isArray(data.data?.data)) { - log.warn('getQzoneFeeds: no data array in response (uin=%s) — likely auth/cookie failure', selfUin); - throw new Error('无法获取空间好友动态'); + log.warn('getQzoneFeeds: no data array in response (uin=%s) — likely auth/cookie failure or unverified response shape; body head=%s', selfUin, text.slice(0, 300)); + throw new Error(`无法获取空间好友动态(响应结构异常): ${text.slice(0, 200)}`); } return mapFeeds(data); diff --git a/packages/protocol/src/web/request-util.ts b/packages/protocol/src/web/request-util.ts index 92d3d39c..af03b7e3 100644 --- a/packages/protocol/src/web/request-util.ts +++ b/packages/protocol/src/web/request-util.ts @@ -4,41 +4,44 @@ import https from 'node:https'; type RequestBody = string | Buffer | Uint8Array | Record | undefined; export class RequestUtil { - static async HttpsGetCookies(url: string): Promise<{ [key: string]: string; }> { + // Collect Set-Cookie across the ptlogin2 jump's redirect chain. NEVER hangs: + // a per-request timeout + a redirect-depth cap guarantee termination, and any + // failed/slow hop resolves with the cookies gathered so far rather than + // throwing. This matters because the jump's final hop can target a host the + // deployment can't reach (e.g. a datacenter网络 that times out on + // qzone.qq.com) — without the ceiling that would hang every cookie-backed web + // action forever (the essential cookies are already set by the first hop). + static async HttpsGetCookies(url: string, depth = 0): Promise<{ [key: string]: string; }> { const client = url.startsWith('https') ? https : http; - return new Promise((resolve, reject) => { + return new Promise((resolve) => { + const cookies: { [key: string]: string; } = {}; + let settled = false; + const done = (extra?: { [key: string]: string; }) => { + if (settled) return; + settled = true; + resolve(extra ? { ...cookies, ...extra } : cookies); + }; const req = client.get(url, (res) => { - const cookies: { [key: string]: string; } = {}; - - res.on('data', () => { }); // 必须消耗流 - res.on('end', () => { - this.handleRedirect(res, url, cookies) - .then(resolve) - .catch(reject); - }); - if (res.headers['set-cookie']) { this.extractCookies(res.headers['set-cookie'], cookies); } + res.on('data', () => { }); // 必须消耗流 + res.on('end', () => { + const location = res.headers.location; + if ((res.statusCode === 301 || res.statusCode === 302) && location && depth < 5) { + this.HttpsGetCookies(new URL(location, url).href, depth + 1) + .then((rc) => done(rc)) + .catch(() => done()); + } else { + done(); + } + }); }); - - req.on('error', (error: Error) => { - reject(error); - }); + req.setTimeout(8000, () => { req.destroy(); done(); }); + req.on('error', () => done()); }); } - private static async handleRedirect(res: http.IncomingMessage, url: string, cookies: { [key: string]: string; }): Promise<{ [key: string]: string; }> { - if (res.statusCode === 301 || res.statusCode === 302) { - if (res.headers.location) { - const redirectUrl = new URL(res.headers.location, url); - const redirectCookies = await this.HttpsGetCookies(redirectUrl.href); - return { ...cookies, ...redirectCookies }; - } - } - return cookies; - } - private static extractCookies(setCookieHeaders: string[], cookies: { [key: string]: string; }) { setCookieHeaders.forEach((cookie) => { const parts = cookie.split(';')[0]?.split('='); diff --git a/packages/protocol/tests/web/fixtures/qzone-feeds-sample.jsonp b/packages/protocol/tests/web/fixtures/qzone-feeds-sample.jsonp new file mode 100644 index 00000000..0ff00769 --- /dev/null +++ b/packages/protocol/tests/web/fixtures/qzone-feeds-sample.jsonp @@ -0,0 +1,8 @@ +_preloadCallback({ + "code":0, + "subcode":0, + "message":"", + "default":0, + "data": +{main:{attach:'',searchtype :'',hasMoreFeeds:false,daylist:'',uinlist:'',error:'',hotkey:'',icGroupData:[],host_level:'',friend_level:'',lastaccesstime:'',lastAccessRelateTime:'',begintime:'1780711209',endtime:'',dayspac:'11',hidedNameList:[], aisortBeginTime:'', aisortEndTime:'', aisortOffset:'', aisortNextTime:'',owner_bitmap:'08009c8802000401',pagenum:'2',externparam:'basetime=1780711209&pagenum=2&dayvalue=11&getadvlast=0&hasgetadv=&lastentertime=0&LastAdvPos=0&UnReadCount=1&UnReadSum=1&LastIsADV=0&UpdatedFollowUins=&UpdatedFollowCount=0&LastRecomBrandID=&TRKPreciList=&gdtadvcookie=eyJsYXN0X2Fkdl9wb3NpdGlvbiI6LTF9'},data:[{ver:'1',appid:'311',typeid:'0',key:'aef23101297f236ae4f10600',flag:'0',dataonly:'0',titleTemp:'',summaryTemp:'',feedno:'0',title:'',summary:'',appiconid:'311',clscFold:'icenter_list_extend',abstime:'1780711209',feedstime:'6月6日 10:00',userHome:'http://user.qzone.qq.com/20050606',namecardLink:'nameCard_20050606',opuin:'20050606',uin:'20050606',ouin:'',foldFeed:'',foldFeedTitle:'',showEbtn:'',scope:'0',hideExtend:'',nickname:'官方Qzone',emoji:[],remark:'',type:'',vip:'novip',bitmap:'989d9de01513c081',yybitmap:'100008000000000b',info_user_name:'',logimg:'http://qlogo3.store.qq.com/qzone/20050606/20050606/50?1450773587',bor:'',lastFeedBor:'',list_bor2:'',info_user_display:'',upernum:'',oprType:'0',moreflag:'',otherflag:'1_0_1_0_0_0_1',rightflag:'',sameuser:{},uper_isfriend:[],uperlist:[],smallstar:'',html:' \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \t\t\t\t\t\t\t\t\t\t\t\t\t\t \x3Cli class=\x22f-single f-s-s\x22 id=\x22fct_20050606_311_0_1780711209_0_1\x22>\x3Cdiv class=\x22f-single-head f-aside\x22>\x3Cdiv class=\x22f-adorn-top\x22>\x3C\/div> \x3Cdiv class=\x22user-pto\x22>\x3Ca href=\x22http:\/\/user.qzone.qq.com\/20050606\x22 target=\x22_blank\x22 class=\x22user-avatar q_namecard f-s-a\x22 link=\x22nameCard_20050606\x22 data-clicklog=\x22avatar\x22>\x3Cimg src=\x22https:\/\/qlogo3.store.qq.com\/qzone\/20050606\/20050606\/50?1450773587\x22>\x3C\/a>\x3C\/div>\x3Cdiv class=\x22user-op\x22>\x3Ca href=\x22javascript:;\x22 class=\x22arrow-down\x22 data-cmd=\x22qz_opr_more\x22 data-moreoperate=\x220\x22>\x3Ci class=\x22fui-icon icon-arrow-down\x22>\x3C\/i>\x3C\/a> \x3C\/div>\x3Cdiv class=\x22user-info\x22>\x3Cdiv class=\x22f-nick\x22>\x3Ca target=\x22_blank\x22 href=\x22http:\/\/user.qzone.qq.com\/20050606\x22 data-clicklog=\x22nick\x22 class=\x22f-name q_namecard \x22 link=\x22nameCard_20050606\x22>官方Qzone\x3C\/a> \x3Ca target=\x22_blank\x22 href=\x22http:\/\/page.qq.com\x22 class=\x22user-medal\x22>\x3Cimg class=\x22ui_mr5\x22 src=\x22\/ac\/qzone_v5\/client\/auth_icon.png\x22 title=\x22腾讯认证\x22 alt=\x22腾讯认证\x22 \/>\x3C\/a> \x3C\/div>\x3Cdiv class=\x22info-detail\x22>\t\t\t\t\t\x3Cspan class=\x22 ui-mr8 state\x22 >\t\t6月6日 10:00\t\t\x3C\/span>\t\t\x3Ca href=\x22javascript:;\x22 data-cmd=\x22qz_sign\x22 class=\x22f-sign-show state\x22 title=\x22我也要设置\x22>\x3C\/a>\x3C\/div>\x3C\/div>\x3C\/div>\x3Cdiv class=\x22f-single-content f-wrap\x22>\x3Cdiv class=\x22f-item f-s-i\t\x22 id=\x22feed_20050606_311_0_1780711209_0_1\x22 data-feedsflag=\x22\x22 data-iswupfeed=\x221\x22 data-key=\x22aef23101297f236ae4f10600\x22 data-specialtype=\x22\x22 data-extend-info=\x221_0_1_0_0_0_1|989d9de01513c081|100008000000000b\x22 data-functype=\x22func_friend_feed\x22 data-hasfollowed=\x221\x22>\x3Cdiv class=\x22f-info qz_info_cut\x22>\t\t\t\t\t时间从不说谎,它把你以为的妄想,悄悄兑换成了现实;它把你以为忘了的那些日子,原原本本保存了下来。\x3Cbr\/>21年了,QQ空间也记得。\x3Cbr\/>今天,「那年今日」更新了—— 翻开那些年的说说、照片和动态,被收进时光里的每一个你,都还在。\x3Cbr\/>不用刻意回忆,不用费力寻找,它自己找到你,轻轻拍了拍你的肩。\x3Cbr\/>\t\t \x3Ca href=\x22javascript:;\x22 data-cmd=\x22qz_toggle\x22 data-pos=\x221\x22>展开全文\x3C\/a>\x3Cimg src=\x22http:\/\/qzonestyle.gtimg.cn\/qzone_v6\/img\/feed\/loading.gif\x22 class=\x22load_img none\x22>\x3C\/div>\x3Cdiv class=\x22f-info qz_info_complete none\x22>\x3C\/div>\x3Cdiv class=\x22qz_summary wupfeed\x22 id=\x22hex_20050606_311_0_1780711209_0_1\x22>\x3Ci class=\x22none\x22 name=\x22feed_data\x22 \t data-bitmap=\x22989d9de01513c081\x22\t data-yybitmap=\x22100008000000000b\x22\t data-vipstarbitmap=\x220100004002000080\x22\t\t data-fkey=\x22aef23101297f236ae4f10600\x22\t data-tid=\x22aef23101297f236ae4f10600\x22\t data-uin=\x2220050606\x22\t data-origfkey=\x22\x22\t data-origtid=\x22aef23101297f236ae4f10600\x22\t data-origuin=\x2220050606\x22\t data-subid=\x22\x22\t data-totweet=\x22\x22\t data-issignin=\x22\x22\t data-source=\x22\x22\t data-retweetcount=\x221\x22\t data-stat=\x22exNDgYmCtvjmonh4K6e5PbvTJDuPAUSNib6qlt2tPSxjX2r0nouNT4bs6UTPWfIfxQBQa7z!kH9ELZBD0r25iV6FuCL0P8cG6914CLBsLy297p1QCYK618bKYmDnJRgWOJRuWEuCwKpiEkd3B!O!uSIc!Hpwf5zceJM2h16yaSuK3pjKxpNwq1oLq4MIM4BZMzAkbzg1AwK34lk5dZEXd8aRZL0TQrBX_\x22 \t data-topicid=\x2220050606_aef23101297f236ae4f10600__1\x22 \t \t data-feedstype=\x22100\x22 \t data-abstime=\x221780711209\x22 \t data-iswupfeed=\x221\x22 \t\t\t data-platformid=\x2252\x22 \t\t\t\t\t data-accessright=\x221\x22\t\t\t\t\t\t\t\t\t\t\t\t>\x3C\/i>\x3Cdiv class=\x22f-ct \x22>\x3Cdiv class=\x22f-ct-txtimg fui-txtimg f-ct-video \x22> \x3Cdiv class=\x22txt-box \x22> \t\t\t\t\t\t\t\t\t \x3C\/div> \x3Cdiv class=\x22img-box f-video-wrap play\x22 url3=\x22https:\/\/photovideo.photo.qq.com\/1074_0b53eyz7eaicg4ai2kzbwzvdajqe6keaeaca.f20.mp4?dis_k=af9adeffd476b770519e37826170e96a&dis_t=1782911754&vuin=3433035623&owner=MjAwNTA2MDY=\x22 > \x3Ca class=\x22img-item \x22data-cmd=\x22qz_popup\x22 href=\x22https:\/\/user.qzone.qq.com\/20050606\/311\/1074_0b53eyz7eaicg4ai2kzbwzvdajqe6keaeaca\x22 data-v_itemid=\x221074_0b53eyz7eaicg4ai2kzbwzvdajqe6keaeaca\x22 data-v_type=\x221\x22 data-v_picinfo_url=\x22https:\/\/m.qpic.cn\/psc?\/eabfd933-2c89-47cc-8138-5b5463dab9e9\/MgefXoixntJCvPruFHdJTSW.iR0yk*dsdY1s2MYZO1w1*EHOCLeibHhhEFGLCO98HKhHMnNLec2Vz6nVgZnqGo9yAiFqlb*K5FC72D3XGY4!\/c&bo=OASABwAAAAABJ7s!\x22 data-v_picinfo_width=\x22512\x22 data-v_picinfo_height=\x22910\x22 data-v_vidiourl=\x22\x22 data-v_vidioswfurl=\x22https:\/\/photovideo.photo.qq.com\/1074_0b53eyz7eaicg4ai2kzbwzvdajqe6keaeaca.f20.mp4?dis_k=af9adeffd476b770519e37826170e96a&dis_t=1782911754&vuin=3433035623&owner=MjAwNTA2MDY=\x22 data-v_h265=\x22\x22 data-v_source_website=\x22\x22 data-v_writefrom=\x22\x22 data-videotype= \x22mood\x22 data-clicklog=\x22video\x22 hotclickPath=\x22\x22 hotdomain=\x22\x22 data-weishi_feedid=\x22\x22 data-version=\x223\x22 data-param=\x223&videosrc=https%3A%2F%2Fphotovideo.photo.qq.com%2F1074_0b53eyz7eaicg4ai2kzbwzvdajqe6keaeaca.f20.mp4%3Fdis_k%3Daf9adeffd476b770519e37826170e96a%26dis_t%3D1782911754%26vuin%3D3433035623%26owner%3DMjAwNTA2MDY%3D&type=1&org_vidio_url=\x22 data-src=\x22\/qzone\/app\/mood\/richinfo_view.html\x22 data-width=\x22512\x22 data-height=\x22512\x22 data-type=\x22popup\x22 data-title=\x22\x22 data-config=\x22\x22 data-extendinfo1 =\x22\x22 data-extendinfo2 =\x22\x22 data-extendinfo3 =\x22\x22 data-extendinfo4 =\x22\x22 data-extendinfo11 =\x22\x22> \x3Cdiv class=\x22video-img\x22> \x3Ci class=\x22inner icon-media-play\x22>\x3C\/i> \x3Cimg alt=\x22视频缩略图\x22 style=\x22object-fit: contain; max-width:560px; max-height:560px; width:100%; height: 100%; margin: \x22 src=\x22https:\/\/m.qpic.cn\/psc?\/eabfd933-2c89-47cc-8138-5b5463dab9e9\/MgefXoixntJCvPruFHdJTSW.iR0yk*dsdY1s2MYZO1w1*EHOCLeibHhhEFGLCO98HKhHMnNLec2Vz6nVgZnqGo9yAiFqlb*K5FC72D3XGY4!\/c&bo=OASABwAAAAABJ7s!\x22 \/> \x3C\/div> \x3C\/a> \x3C\/div> \x3C\/div>\x3Cdiv class=\x22f-reprint\x22> \x3Cp class=\x22item\x22> \x3Ci class=\x22fui-icon icon-print-phone\x22>\x3C\/i>\x3Cspan class=\x22ui-mr8 state\x22>来自\t\t\t\t\t\t\t\t\t \t\t\t\t\t\t\t\x3Ca href=\x22http:\/\/z.qzone.com?from=iphonegrzxpl\x22 \t\t\t\t\t\t\t\t\t\t\ttarget=\x22_blank\x22 \t\t\t\t\t\t\t\t\t\t\t\t class=\x22 phone-style state\x22\t>\t\tiPhone\t\t\x3C\/a>\t\t\t \t\t\t\x3C\/span> \x3C\/p> \x3C\/div> \x3C\/div>\x3C\/div>\x3C\/div>\x3C\/div>\x3Cdiv class=\x22f-single-foot\x22>\x3Cdiv class=\x22f-op-detail f-detail \x22>\t\t\x3Cp class=\x22op-list\x22>\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\x3Ca \t\t\tclass=\x22item qz_retweet_btn \x22 \t\t\thref=\x22javascript:;\x22 \t\t\tdata-cmd=\x22qz_popup\x22 \t\t\tdata-version=\x224\x22 \t\t\t\t\t\tdata-isnewtype=\x221\x22 \t\t\tdata-type=\x22ForwardingBox\x22 \t\t\tdata-src=\x22\/qzone\/app\/controls\/forwardingBox\/forwardingBoxFacade.js\x22 \t\t\tdata-clicklog=\x22retweet\x22 \t\t\tdata-publicpav=\x22\x22 \t\t\t\t\t>\t\t\t\x3Ci class=\x22fui-icon icon-op-share\x22>\x3C\/i>\t\t\x3C\/a>\t\t\t\t\t\t\t\t\t\t\x3Cspan class=\x22item-line\x22>\x3C\/span>\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \t\t\t\t\t\x3Ca href=\x22javascript:;\x22 \t\t\t\t\t\t\t\t\t\t\t\t\tdata-version=\x226.3\x22 \t\t\t\t\tdata-cmd=\x22qz_reply\x22 \t\t\t\t\tdata-link=\x221\x22 \t\t\t\t\tdata-clicklog=\x22comment\x22 \t\t\t\t\t\t\t class=\x22 qz_btn_reply item \x22\t>\t\t\t\x3Ci class=\x22fui-icon icon-op-comment\x22>\x3C\/i>\t\t\t\t\t\t\x3C\/a>\t\t\t \t\t\t\t\t\t\t\t\t\t\t\x3Cspan class=\x22item-line\x22>\x3C\/span>\t\t\t\x3Ca class=\x22item qz_like_btn_v3 \x22 \t\t\t\t\t\tdata-islike=\x220\x22 \t\t\t\t\t\tdata-likecnt=\x223173513\x22 \t\t\tdata-showcount=\x220\x22 \t\t\tdata-unikey=\x22http:\/\/user.qzone.qq.com\/20050606\/mood\/aef23101297f236ae4f10600\x22 \t\t\tdata-curkey=\x22http:\/\/user.qzone.qq.com\/20050606\/mood\/aef23101297f236ae4f10600\x22 \t\t\t\t\t\t\tdata-clicklog=\x22like\x22 \t\t\t\t\t\t\t\t\thref=\x22javascript:;\x22\t\t>\t\t\t\x3Ci class=\x22fui-icon icon-op-praise\x22>\x3C\/i>\t\t\x3C\/a>\t\t\t\t\x3C\/p>\x3Ca href=\x22javascript:;\x22 class=\x22state qz_feed_plugin\x22 data-role=\x22Visitor\x22 data-config=\x22311|aef23101297f236ae4f10600|20050606\x22 data-clicklog=\x22visitor\x22>浏览173581134次\x3C\/a>\x3C\/div> \x3Cdiv class=\x22f-like-list f-like _likeInfo\x22 likeinfo=\x223173513\x22>\x3Cdiv class=\x22icon-btn\x22>\x3Ca href=\x22javascript:;\x22 data-islike=\x220\x22 data-likecnt=\x223173513\x22 data-showcount=\x223173513\x22 data-unikey=\x22http:\/\/user.qzone.qq.com\/20050606\/mood\/aef23101297f236ae4f10600\x22 data-curkey=\x22http:\/\/user.qzone.qq.com\/20050606\/mood\/aef23101297f236ae4f10600\x22 data-clicklog=\x22like\x22 class=\x22praise qz_like_prase\x22>\x3Ci class=\x22fui-icon icon-list-praise\x22>\x3C\/i>\x3C\/a>\x3Cdiv class=\x22bubble\x22 style=\x22display:none;\x22>\x3Cdiv class=\x22bd\x22>+1\x3C\/div>\x3Cb class=\x22arrow arrow-down\x22>\x3C\/b>\x3C\/div>\x3C\/div>\x3Cdiv class=\x22user-list\x22>\x3Cspan class=\x22f-like-cnt f-famous-qzone\x22>3173513\x3C\/span>人觉得很赞\x3C\/div>\x3C\/div>\x3Cdiv class=\x22mod-comments\x22 style=\x22padding:0\x22>\x3Cdiv class=\x22mod-commnets-poster feedClickCmd comment_default_inputentry\x22 data-cmd=\x22qz_reply\x22 data-version=\x226\x22 data-action=\x22http:\/\/taotao.qq.com\/cgi-bin\/emotion_cgi_re_feeds\x22 data-param=\x22t1_source=&t1_uin=20050606&t1_tid=aef23101297f236ae4f10600&signin=0&sceneid=100\x22 data-charset=\x22utf-8\x22 data-maxLength=\x22\x22 data-tuin=\x2220050606\x22 data-config=\x221|1|1|1,b52,with_fwd,同时转发;0|1,taotaoact.qzone.qq.com,@InputReply|1,taotaoact.qzone.qq.com,@ClickReply|1,taotaoact.qzone.qq.com,commentPresentClick\x22 data-tid=\x22\x22 >\x3Cdiv class=\x22comments-poster-bd comments-poster-default\x22>\x3Cdiv class=\x22comments-box\x22 data-clicklog=\x22comment\x22>\x3Cdiv class=\x22textinput textinput-default bor2\x22 contenteditable=\x22true\x22 alt=\x22replybtn\x22 placeholder=\x22评论\x22>\x3Ca class=\x22c_tx3\x22 href=\x22javascript:void(0);\x22 alt=\x22replybtn\x22>评论\x3C\/a>\x3C\/div>\x3Cdiv class=\x22mod-insert-img\x22>\x3Ca href=\x22javascript:;\x22 data-cmd=\x22qz_quick_upload_img\x22 class=\x22btn-insert-img bg\x22>\x3Ci class=\x22icon-camera-16\x22>\x3C\/i>\x3C\/a>\x3C\/div>\x3C\/div>\x3C\/div>\x3C\/div>\x3C\/div> \x3C\/div>\x3C\/li>\t', mergeData:[undefined], likecnt:'', relycnt:'', commentcnt:''},undefined]}} +); diff --git a/packages/protocol/tests/web/qzone-feeds-parse.test.ts b/packages/protocol/tests/web/qzone-feeds-parse.test.ts new file mode 100644 index 00000000..7511f14a --- /dev/null +++ b/packages/protocol/tests/web/qzone-feeds-parse.test.ts @@ -0,0 +1,75 @@ +import { describe, it, expect } from 'vitest'; +import { readFileSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; +import { mapFeeds, parseQzoneCallback } from '@snowluma/protocol/web/qzone'; + +// Real feeds3_html_more response captured live (issue #182). Its `data` value +// is a JS object literal (unquoted keys, single-quoted strings, \xNN escapes, +// trailing `undefined`) — JSON.parse throws on it; parseQzoneCallback must not. +const SAMPLE = readFileSync( + fileURLToPath(new URL('./fixtures/qzone-feeds-sample.jsonp', import.meta.url)), + 'utf8', +); + +interface RawFeeds { + code?: number; + data?: { data?: unknown[]; hasmore?: number | string }; +} + +describe('qzone feeds JS-literal parsing (issue #182)', () => { + it('JSON.parse chokes on the real body (regression baseline)', () => { + const inner = SAMPLE.slice(SAMPLE.indexOf('{'), SAMPLE.lastIndexOf('}') + 1); + expect(() => JSON.parse(inner)).toThrow(); + }); + + it('parseQzoneCallback evaluates the JS-literal payload', () => { + const data = parseQzoneCallback(SAMPLE); + expect(data.code).toBe(0); + expect(Array.isArray(data.data?.data)).toBe(true); + // The array carries a trailing `undefined` hole alongside the real feed. + expect(data.data!.data!.length).toBe(2); + expect(data.data!.data!.some((x) => x === undefined)).toBe(true); + }); + + it('mapFeeds drops the undefined hole and normalises the feed', () => { + const data = parseQzoneCallback(SAMPLE); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const result = mapFeeds(data as any); + expect(result.feeds).toHaveLength(1); + const f = result.feeds[0]!; + expect(f.uin).toBe(20050606); + expect(f.nickname).toBe('官方Qzone'); + expect(f.appid).toBe(311); + expect(f.time).toBe(1780711209); + expect(f.key).toBe('aef23101297f236ae4f10600'); + // \xNN escapes decoded by the JS eval, html passed through verbatim. + expect(f.html).toContain('
  • { + // The parser has no notion of globals, member access, or calls: any such + // token is rejected, so a tampered body cannot reach `process`/`Function` + // etc. (the whole reason we do NOT eval this payload). + expect(() => parseQzoneCallback('_preloadCallback({x: process})')).toThrow(); + expect(() => parseQzoneCallback('_preloadCallback({x: callback.constructor})')).toThrow(); + expect(() => parseQzoneCallback('_preloadCallback({x: (function(){return 1})()})')).toThrow(); + expect(() => parseQzoneCallback('_preloadCallback(eval("1+1"))')).toThrow(); + }); + + it('does not pollute Object.prototype via a __proto__ key', () => { + parseQzoneCallback('_preloadCallback({"__proto__":{"polluted":1},"code":0})'); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + expect(({} as any).polluted).toBeUndefined(); + }); + + it('decodes JS string escapes (\\xNN, \\/) literally, not as markup', () => { + const d = parseQzoneCallback<{ s?: string }>("_preloadCallback({s:'\\x3Cb\\x3E&\\/x'})"); + expect(d.s).toBe('&/x'); + }); + + it('rejects a body that captures no object', () => { + expect(() => parseQzoneCallback('_preloadCallback(42)')).toThrow('invalid feeds response'); + expect(() => parseQzoneCallback('void 0')).toThrow('invalid feeds response'); + }); +}); diff --git a/packages/protocol/tests/web/qzone.test.ts b/packages/protocol/tests/web/qzone.test.ts index d45d4629..83790511 100644 --- a/packages/protocol/tests/web/qzone.test.ts +++ b/packages/protocol/tests/web/qzone.test.ts @@ -175,17 +175,17 @@ describe('qzone / getQzoneFeeds (HTTP layer)', () => { }); it('returns an empty list (not a throw) for a genuinely empty feed', async () => { - vi.spyOn(RequestUtil, 'HttpGetText').mockResolvedValue('{"code":0,"data":{"data":[],"hasmore":0}}'); + vi.spyOn(RequestUtil, 'HttpGetText').mockResolvedValue('_preloadCallback({"code":0,"data":{"data":[],"hasmore":0}});'); await expect(getQzoneFeeds(cookies, '10000')).resolves.toEqual({ feeds: [], has_more: false }); }); it('throws on a non-zero qzone code', async () => { - vi.spyOn(RequestUtil, 'HttpGetText').mockResolvedValue('{"code":-3000,"message":"need login"}'); + vi.spyOn(RequestUtil, 'HttpGetText').mockResolvedValue('_preloadCallback({"code":-3000,"message":"need login"});'); await expect(getQzoneFeeds(cookies, '10000')).rejects.toThrow('code=-3000'); }); it('throws when the data array is absent (cookie failure), not an empty list', async () => { - vi.spyOn(RequestUtil, 'HttpGetText').mockResolvedValue('{"code":0,"data":{}}'); + vi.spyOn(RequestUtil, 'HttpGetText').mockResolvedValue('_preloadCallback({"code":0,"data":{}});'); await expect(getQzoneFeeds(cookies, '10000')).rejects.toThrow('无法获取空间好友动态'); }); });