fix(protocol): harden friend dress queries

Require the dress page to identify the requested account and every returned item before exposing the result. Reject malformed nested media metadata instead of silently degrading it.

Bound the HTML request to a 10-second redirect-chain deadline and a 2 MiB response body. Secure redirects by closing previous connections, stripping cross-origin credentials, rejecting cross-origin write forwarding, and surfacing malformed locations.

Replace the captured page with a minimal sanitized fixture and add protocol plus OneBot Action regression coverage for resource limits, redirect safety, response ownership, and structured failures.
This commit is contained in:
DrSmoothl committed 2026-07-25 20:22:49 +08:00
1 parent 3517257aa6
commit 13a32a2865
6 files changed
+681 -377

No files matched your search

+63 -19
View File
@@ -79,8 +79,13 @@ const TRACE_DETAIL =
const DRESS_UA =
'Mozilla/5.0 (Linux; Android 13; 2109119BC Build/TKQ1.221114.001; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/121.0.6167.71 MQQBrowser/6.2 TBS/047925 Mobile Safari/537.36 V1_AND_SQ_9.2.66_13188_YYB_D QQ/9.2.66.33870 NetType/WIFI WebP/0.3.0 AppId/537339358';
const DRESS_RESPONSE_LIMITS = {
timeoutMs: 10_000,
maxResponseBytes: 2 * 1024 * 1024,
} as const;
interface RawDressItem {
appId?: number;
appId: number;
itemId?: number;
name?: string;
image?: string;
@@ -130,13 +135,15 @@ function parseAsyncData(html: string): unknown {
}
/** 运行时结构校验:不符合预期的一律抛 structure,绝不带着畸形数据继续。 */
function validateAsyncData(data: unknown): RawAsyncData & { rawUsingList: RawDressItem[] } {
function validateAsyncData(
data: unknown,
): RawAsyncData & { targetUin: string; rawUsingList: RawDressItem[] } {
if (data === null || typeof data !== 'object' || Array.isArray(data)) {
throw new FriendDressError('structure', '__INITIAL_ASYNCDATA__ 顶层不是对象');
}
const d = data as Record<string, unknown>;
if (d['targetUin'] !== undefined && typeof d['targetUin'] !== 'string') {
throw new FriendDressError('structure', 'targetUin 不是字符串');
if (typeof d['targetUin'] !== 'string' || d['targetUin'].length === 0) {
throw new FriendDressError('structure', 'targetUin 缺失或不是非空字符串');
}
if (d['isSvip'] !== undefined && typeof d['isSvip'] !== 'boolean') {
throw new FriendDressError('structure', 'isSvip 不是布尔值');
@@ -152,8 +159,8 @@ function validateAsyncData(data: unknown): RawAsyncData & { rawUsingList: RawDre
throw new FriendDressError('structure', `rawUsingList[${i}] 不是对象`);
}
const r = item as Record<string, unknown>;
if (r['appId'] !== undefined && typeof r['appId'] !== 'number') {
throw new FriendDressError('structure', `rawUsingList[${i}].appId 不是数字`);
if (typeof r['appId'] !== 'number') {
throw new FriendDressError('structure', `rawUsingList[${i}].appId 缺失或不是数字`);
}
if (r['itemId'] !== undefined && typeof r['itemId'] !== 'number') {
throw new FriendDressError('structure', `rawUsingList[${i}].itemId 不是数字`);
@@ -164,8 +171,28 @@ function validateAsyncData(data: unknown): RawAsyncData & { rawUsingList: RawDre
if (r['image'] !== undefined && typeof r['image'] !== 'string') {
throw new FriendDressError('structure', `rawUsingList[${i}].image 不是字符串`);
}
if (r['extraappinfo'] !== undefined) {
if (r['extraappinfo'] === null
|| typeof r['extraappinfo'] !== 'object'
|| Array.isArray(r['extraappinfo'])) {
throw new FriendDressError('structure', `rawUsingList[${i}].extraappinfo 不是对象`);
}
const extraInfo = (r['extraappinfo'] as Record<string, unknown>)['extraInfo'];
if (extraInfo !== undefined) {
if (extraInfo === null || typeof extraInfo !== 'object' || Array.isArray(extraInfo)) {
throw new FriendDressError('structure', `rawUsingList[${i}].extraappinfo.extraInfo 不是对象`);
}
const immersiveMaterial = (extraInfo as Record<string, unknown>)['immersiveMaterial'];
if (immersiveMaterial !== undefined && typeof immersiveMaterial !== 'string') {
throw new FriendDressError(
'structure',
`rawUsingList[${i}].extraappinfo.extraInfo.immersiveMaterial 不是字符串`,
);
}
}
}
});
return data as RawAsyncData & { rawUsingList: RawDressItem[] };
return data as RawAsyncData & { targetUin: string; rawUsingList: RawDressItem[] };
}
/**
@@ -177,13 +204,31 @@ function validateAsyncData(data: unknown): RawAsyncData & { rawUsingList: RawDre
function resolveVideoUrl(r: RawDressItem): string {
if (r.appId === 15) {
const raw = r.extraappinfo?.extraInfo?.immersiveMaterial;
if (typeof raw !== 'string' || !raw) return '';
if (raw === undefined) return '';
let material: unknown;
try {
const videoUrl = (JSON.parse(raw) as { videoUrl?: unknown }).videoUrl;
return typeof videoUrl === 'string' ? videoUrl : '';
} catch {
return '';
material = JSON.parse(raw) as unknown;
} catch (error) {
throw new FriendDressError(
'structure',
`装扮 appId=${r.appId} itemId=${r.itemId ?? 0} 的 immersiveMaterial 不是合法 JSON`,
{ cause: error },
);
}
if (material === null || typeof material !== 'object' || Array.isArray(material)) {
throw new FriendDressError(
'structure',
`装扮 appId=${r.appId} itemId=${r.itemId ?? 0} 的 immersiveMaterial 不是对象`,
);
}
const videoUrl = (material as Record<string, unknown>)['videoUrl'];
if (typeof videoUrl !== 'string' || videoUrl.length === 0) {
throw new FriendDressError(
'structure',
`装扮 appId=${r.appId} itemId=${r.itemId ?? 0} 的 immersiveMaterial.videoUrl 缺失或不是非空字符串`,
);
}
return videoUrl;
}
if (r.appId === 17 && r.image && /\/(?:web_)?image\.jpg$/.test(r.image)) {
return r.image.replace(/\/(?:web_)?image\.jpg$/, '/media.mp4');
@@ -192,10 +237,9 @@ function resolveVideoUrl(r: RawDressItem): string {
}
function toItem(r: RawDressItem): WebFriendDressItem {
const appId = r.appId ?? 0;
return {
app_id: appId,
kind: APP_KIND[appId] ?? `appId=${appId}`,
app_id: r.appId,
kind: APP_KIND[r.appId] ?? `appId=${r.appId}`,
item_id: r.itemId ?? 0,
name: r.name ?? '',
preview_url: r.image ?? '',
@@ -220,22 +264,22 @@ export async function getFriendDressWebAPI(
'User-Agent': DRESS_UA,
Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language': 'zh-CN,zh;q=0.9',
});
}, DRESS_RESPONSE_LIMITS);
} catch (e) {
throw new FriendDressError('network', `装扮页请求失败: ${e instanceof Error ? e.message : String(e)}`, { cause: e });
}
const data = validateAsyncData(parseAsyncData(html));
if (data.targetUin !== undefined && data.targetUin !== targetUin) {
if (data.targetUin !== targetUin) {
throw new FriendDressError('uin_mismatch', `装扮页返回账号 ${data.targetUin} 与请求账号 ${targetUin} 不一致`);
}
return {
target_uin: data.targetUin ?? targetUin,
target_uin: data.targetUin,
is_svip: data.isSvip ?? false,
avatar_url: data.avatarImage ?? '',
items: data.rawUsingList
.filter((r) => !UNRESOLVABLE_APPS.has(r.appId ?? 0))
.filter((r) => !UNRESOLVABLE_APPS.has(r.appId))
.map(toItem),
};
}
+209 -26
View File
@@ -3,6 +3,52 @@ import https from 'node:https';
type RequestBody = string | Buffer | Uint8Array | Record<string, unknown> | undefined;
export interface HttpResponseLimits {
/** Wall-clock deadline shared by the complete redirect chain. */
timeoutMs?: number;
/** Maximum response body size measured in bytes before decoding. */
maxResponseBytes?: number;
}
function validateLimit(name: keyof HttpResponseLimits, value: number | undefined): void {
const exceedsTimerRange = name === 'timeoutMs' && value !== undefined && value > 2_147_483_647;
if (value !== undefined && (!Number.isSafeInteger(value) || value <= 0 || exceedsTimerRange)) {
throw new Error(`${name} must be a positive safe integer`);
}
}
interface HttpRequestContext {
url: string;
method: string;
data?: RequestBody;
headers: Record<string, string>;
isJsonRet: boolean;
isArgJson: boolean;
maxRedirects: number;
responseLimits: HttpResponseLimits;
deadlineAt?: number;
}
const SENSITIVE_REDIRECT_HEADERS = new Set([
'authorization',
'cookie',
'cookie2',
'host',
'proxy-authorization',
]);
function headersForRedirect(
headers: Record<string, string>,
source: URL,
target: URL,
): Record<string, string> {
if (source.origin === target.origin) return headers;
return Object.fromEntries(
Object.entries(headers)
.filter(([name]) => !SENSITIVE_REDIRECT_HEADERS.has(name.toLowerCase())),
);
}
export class RequestUtil {
// Collect Set-Cookie across the ptlogin2 jump's redirect chain. NEVER hangs:
// a per-request timeout + a redirect-depth cap guarantee termination, and any
@@ -57,61 +103,198 @@ export class RequestUtil {
static async HttpGetJson<T>(url: string, method: string = 'GET', data?: RequestBody, headers: {
[key: string]: string;
} = {}, isJsonRet: boolean = true, isArgJson: boolean = true, maxRedirects: number = 5): Promise<T> {
const option = new URL(url);
const protocol = url.startsWith('https://') ? https : http;
} = {}, isJsonRet: boolean = true, isArgJson: boolean = true, maxRedirects: number = 5,
responseLimits: HttpResponseLimits = {}): Promise<T> {
validateLimit('timeoutMs', responseLimits.timeoutMs);
validateLimit('maxResponseBytes', responseLimits.maxResponseBytes);
return this.request<T>({
url,
method,
data,
headers,
isJsonRet,
isArgJson,
maxRedirects,
responseLimits,
deadlineAt: responseLimits.timeoutMs === undefined
? undefined
: Date.now() + responseLimits.timeoutMs,
});
}
private static async request<T>(context: HttpRequestContext): Promise<T> {
const option = new URL(context.url);
const protocol = option.protocol === 'https:'
? https
: option.protocol === 'http:'
? http
: undefined;
if (!protocol) {
throw new Error(`unsupported request protocol: ${option.protocol}`);
}
const remainingTimeoutMs = context.deadlineAt === undefined
? undefined
: context.deadlineAt - Date.now();
if (remainingTimeoutMs !== undefined && remainingTimeoutMs <= 0) {
throw new Error(`request timed out after ${context.responseLimits.timeoutMs} ms`);
}
const options = {
hostname: option.hostname,
port: option.port,
path: option.pathname + option.search,
method,
headers,
method: context.method,
headers: context.headers,
};
return new Promise((resolve, reject) => {
let settled = false;
let timeout: NodeJS.Timeout | undefined;
const clearDeadline = () => {
if (timeout !== undefined) clearTimeout(timeout);
};
const resolveOnce = (value: T) => {
if (settled) return;
settled = true;
clearDeadline();
resolve(value);
};
const rejectOnce = (error: Error) => {
if (settled) return;
settled = true;
clearDeadline();
reject(error);
};
const handOff = (next: Promise<T>) => {
if (settled) return;
settled = true;
clearDeadline();
next.then(resolve).catch(reject);
};
const req = protocol.request(options, (res: http.IncomingMessage) => {
const closeCurrent = () => {
res.destroy();
req.destroy();
};
res.once('error', (error: Error) => rejectOnce(error));
if ((res.statusCode === 301 || res.statusCode === 302 || res.statusCode === 307 || res.statusCode === 308) && res.headers.location) {
if (maxRedirects <= 0) {
reject(new Error('Too many redirects'));
if (context.maxRedirects <= 0) {
rejectOnce(new Error('Too many redirects'));
closeCurrent();
return;
}
const redirectUrl = new URL(res.headers.location, url).href;
this.HttpGetJson<T>(redirectUrl, method, data, headers, isJsonRet, isArgJson, maxRedirects - 1)
.then(resolve)
.catch(reject);
let redirectUrl: URL;
try {
redirectUrl = new URL(res.headers.location, option);
} catch (error) {
rejectOnce(new Error('invalid redirect location', { cause: error }));
closeCurrent();
return;
}
if (redirectUrl.protocol !== 'http:' && redirectUrl.protocol !== 'https:') {
rejectOnce(new Error(`unsupported redirect protocol: ${redirectUrl.protocol}`));
closeCurrent();
return;
}
if (option.origin !== redirectUrl.origin
&& context.method.toUpperCase() !== 'GET'
&& context.method.toUpperCase() !== 'HEAD') {
rejectOnce(new Error(
`cross-origin redirect cannot forward method ${context.method.toUpperCase()}`,
));
closeCurrent();
return;
}
handOff(this.request<T>({
...context,
url: redirectUrl.href,
headers: headersForRedirect(context.headers, option, redirectUrl),
maxRedirects: context.maxRedirects - 1,
}));
closeCurrent();
return;
}
let responseBody = '';
res.on('data', (chunk: string | Buffer) => { responseBody += chunk.toString(); });
if (!res.statusCode || res.statusCode < 200 || res.statusCode >= 300) {
rejectOnce(new Error(`Unexpected status code: ${res.statusCode}`));
closeCurrent();
return;
}
const chunks: Buffer[] = [];
let responseBytes = 0;
res.on('data', (chunk: string | Buffer) => {
if (settled) return;
const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
responseBytes += bytes.length;
if (context.responseLimits.maxResponseBytes !== undefined
&& responseBytes > context.responseLimits.maxResponseBytes) {
const error = new Error(
`response body exceeds ${context.responseLimits.maxResponseBytes} bytes`,
);
rejectOnce(error);
closeCurrent();
return;
}
chunks.push(bytes);
});
res.on('end', () => {
if (settled) return;
const responseBody = Buffer.concat(chunks, responseBytes).toString();
try {
if (res.statusCode && res.statusCode >= 200 && res.statusCode < 300) {
if (isJsonRet) {
resolve(JSON.parse(responseBody) as T);
} else {
resolve(responseBody as T);
}
if (context.isJsonRet) {
resolveOnce(JSON.parse(responseBody) as T);
} else {
reject(new Error(`Unexpected status code: ${res.statusCode}`));
resolveOnce(responseBody as T);
}
} catch (parseError: unknown) {
reject(new Error(parseError instanceof Error ? parseError.message : String(parseError)));
rejectOnce(new Error(parseError instanceof Error ? parseError.message : String(parseError)));
}
});
});
req.on('error', (error: Error) => reject(error));
if (method === 'POST' || method === 'PUT' || method === 'PATCH') {
req.write(isArgJson ? JSON.stringify(data) : data);
if (remainingTimeoutMs !== undefined) {
timeout = setTimeout(() => {
const error = new Error(
`request timed out after ${context.responseLimits.timeoutMs} ms`,
);
rejectOnce(error);
req.destroy();
}, remainingTimeoutMs);
}
req.on('error', (error: Error) => rejectOnce(error));
if (context.method === 'POST' || context.method === 'PUT' || context.method === 'PATCH') {
req.write(context.isArgJson ? JSON.stringify(context.data) : context.data);
}
req.end();
});
}
static async HttpGetText(url: string, method: string = 'GET', data?: RequestBody, headers: { [key: string]: string; } = {}) {
return this.HttpGetJson<string>(url, method, data, headers, false, false);
static async HttpGetText(
url: string,
method: string = 'GET',
data?: RequestBody,
headers: { [key: string]: string; } = {},
responseLimits: HttpResponseLimits = {},
) {
return this.HttpGetJson<string>(
url,
method,
data,
headers,
false,
false,
5,
responseLimits,
);
}
}