diff --git a/packages/onebot/tests/friend-dress-action.test.ts b/packages/onebot/tests/friend-dress-action.test.ts new file mode 100644 index 00000000..805fc12c --- /dev/null +++ b/packages/onebot/tests/friend-dress-action.test.ts @@ -0,0 +1,43 @@ +import { describe, expect, it, vi } from 'vitest'; +import { FriendDressError } from '@snowluma/protocol/web/friend-dress'; +import { ApiHandler, type ApiActionContext } from '../src/api-handler'; + +function makeHandler(getFriendDress: ReturnType): ApiHandler { + const bridge = { apis: { web: { getFriendDress } } }; + return new ApiHandler({ bridge } as unknown as ApiActionContext); +} + +describe('_get_friend_dress action', () => { + it('validates the target and returns the queried dress data', async () => { + const dress = { + target_uin: '10000', + is_svip: false, + avatar_url: '', + items: [], + }; + const getFriendDress = vi.fn().mockResolvedValue(dress); + + const response = await makeHandler(getFriendDress).handle( + '_get_friend_dress', + { user_id: '10000' }, + ); + + expect(response).toMatchObject({ status: 'ok', retcode: 0, data: dress }); + expect(getFriendDress).toHaveBeenCalledWith(10000); + }); + + it('preserves the structured failure kind in the Action response', async () => { + const getFriendDress = vi.fn().mockRejectedValue( + new FriendDressError('uin_mismatch', 'returned account does not match'), + ); + + const response = await makeHandler(getFriendDress).handle( + '_get_friend_dress', + { user_id: 10000 }, + ); + + expect(response).toMatchObject({ status: 'failed', retcode: 100 }); + expect(response.wording).toContain('(uin_mismatch)'); + expect(response.wording).toContain('returned account does not match'); + }); +}); diff --git a/packages/protocol/src/web/friend-dress.ts b/packages/protocol/src/web/friend-dress.ts index 8a1ba25e..a37dc722 100644 --- a/packages/protocol/src/web/friend-dress.ts +++ b/packages/protocol/src/web/friend-dress.ts @@ -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; - 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; - 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)['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)['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)['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), }; } diff --git a/packages/protocol/src/web/request-util.ts b/packages/protocol/src/web/request-util.ts index af03b7e3..afdcde9a 100644 --- a/packages/protocol/src/web/request-util.ts +++ b/packages/protocol/src/web/request-util.ts @@ -3,6 +3,52 @@ import https from 'node:https'; type RequestBody = string | Buffer | Uint8Array | Record | 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; + 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, + source: URL, + target: URL, +): Record { + 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(url: string, method: string = 'GET', data?: RequestBody, headers: { [key: string]: string; - } = {}, isJsonRet: boolean = true, isArgJson: boolean = true, maxRedirects: number = 5): Promise { - const option = new URL(url); - const protocol = url.startsWith('https://') ? https : http; + } = {}, isJsonRet: boolean = true, isArgJson: boolean = true, maxRedirects: number = 5, + responseLimits: HttpResponseLimits = {}): Promise { + validateLimit('timeoutMs', responseLimits.timeoutMs); + validateLimit('maxResponseBytes', responseLimits.maxResponseBytes); + + return this.request({ + url, + method, + data, + headers, + isJsonRet, + isArgJson, + maxRedirects, + responseLimits, + deadlineAt: responseLimits.timeoutMs === undefined + ? undefined + : Date.now() + responseLimits.timeoutMs, + }); + } + + private static async request(context: HttpRequestContext): Promise { + 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) => { + 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(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({ + ...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(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( + url, + method, + data, + headers, + false, + false, + 5, + responseLimits, + ); } } diff --git a/packages/protocol/tests/web/fixtures/friend-dress-sample.html b/packages/protocol/tests/web/fixtures/friend-dress-sample.html index a649b168..e756053a 100644 --- a/packages/protocol/tests/web/fixtures/friend-dress-sample.html +++ b/packages/protocol/tests/web/fixtures/friend-dress-sample.html @@ -1,320 +1,66 @@ - + - - - - - - - + + - -好友装扮 - - - - - - - - - - - -
好友正在用
他是尊贵的SVIP,免费用7000多款装扮
- 气泡 -
在说什么呢
- 用同款 -
- 名片 -
二次元少女
- 用同款 -
- 浮屏 -
花瓣
- 用同款 -
- 来电 -
岁月成碑
- 用同款 -
- 挂件 -
默认挂件
- 去商城 -
- 头像 -
自定义头像
- 去商城 -
更多
热门推荐
- 去商城 -
- 气泡 -
- 字体 -
- 挂件 -
- 名片 -
- 主题 -
- 背景 -
- 头像 -
- 来电 -
- 数据加载中 -
- - - - - - - - + diff --git a/packages/protocol/tests/web/friend-dress.test.ts b/packages/protocol/tests/web/friend-dress.test.ts index aa62d1d1..df2e4339 100644 --- a/packages/protocol/tests/web/friend-dress.test.ts +++ b/packages/protocol/tests/web/friend-dress.test.ts @@ -31,7 +31,7 @@ describe('friend-dress / real sample parsing', () => { const request = mockHtml(SAMPLE_HTML); await getFriendDressWebAPI(cookies, '10000'); - const [url, method, , headers] = request.mock.calls[0]!; + const [url, method, , headers, limits] = request.mock.calls[0]!; expect(url).toContain('https://zb.vip.qq.com/v2/pages/aioDressPage?'); expect(url).toContain('targetUin=10000'); // traceDetail 是预编码的 base64 串,必须原样出现(不能被二次编码成 base64%2D…)。 @@ -41,6 +41,10 @@ describe('friend-dress / real sample parsing', () => { Cookie: 'uin=o10001; skey=SKEY; p_uin=o10001; p_skey=PSKEY', }); expect((headers as Record)['User-Agent']).toContain('QQ/'); + expect(limits).toEqual({ + timeoutMs: 10_000, + maxResponseBytes: 2 * 1024 * 1024, + }); }); it('parses the real page: svip, avatar, and only resolvable dress items', async () => { @@ -107,23 +111,16 @@ describe('friend-dress / synthetic payloads', () => { expect(dress.items[0]!.preview_url).toBe('https://cdn.example/funCall/1/preview.png'); }); - it('extracts the card video from immersiveMaterial and survives broken JSON there', async () => { + it('extracts the card video from immersiveMaterial', async () => { mockHtml(wrapHtml({ ...base, - rawUsingList: [ - { - appId: 15, itemId: 1, name: 'a', image: 'https://cdn.example/a.jpg', - extraappinfo: { extraInfo: { immersiveMaterial: '{"videoUrl":"https://cdn.example/a.mp4"}' } }, - }, - { - appId: 15, itemId: 2, name: 'b', image: 'https://cdn.example/b.jpg', - extraappinfo: { extraInfo: { immersiveMaterial: '{not json' } }, - }, - ], + rawUsingList: [{ + appId: 15, itemId: 1, name: 'a', image: 'https://cdn.example/a.jpg', + extraappinfo: { extraInfo: { immersiveMaterial: '{"videoUrl":"https://cdn.example/a.mp4"}' } }, + }], })); const dress = await getFriendDressWebAPI(cookies, '10000'); expect(dress.items[0]!.video_url).toBe('https://cdn.example/a.mp4'); - expect(dress.items[1]!.video_url).toBe(''); }); it('labels unknown appIds without dropping them', async () => { @@ -167,10 +164,46 @@ describe('friend-dress / error classification', () => { await expectKind('10000', 'parse'); }); + it('structure: malformed immersiveMaterial is not silently discarded', async () => { + mockHtml(wrapHtml({ + targetUin: '10000', + rawUsingList: [{ + appId: 15, + itemId: 2, + name: 'broken', + image: 'https://cdn.example/b.jpg', + extraappinfo: { extraInfo: { immersiveMaterial: '{not json' } }, + }], + })); + const e = await expectKind('10000', 'structure'); + expect(e.message).toContain('immersiveMaterial'); + }); + + it.each([ + ['not a string', { videoUrl: 'https://cdn.example/video.mp4' }], + ['an array', '[]'], + ['missing videoUrl', '{}'], + ['non-string videoUrl', '{"videoUrl":42}'], + ])('structure: immersiveMaterial %s is not silently discarded', async (_label, material) => { + mockHtml(wrapHtml({ + targetUin: '10000', + rawUsingList: [{ + appId: 15, + itemId: 2, + name: 'broken', + image: 'https://cdn.example/b.jpg', + extraappinfo: { extraInfo: { immersiveMaterial: material } }, + }], + })); + const e = await expectKind('10000', 'structure'); + expect(e.message).toContain('immersiveMaterial'); + }); + it.each([ ['rawUsingList missing', { targetUin: '10000' }], ['rawUsingList not an array', { targetUin: '10000', rawUsingList: 'nope' }], ['item not an object', { targetUin: '10000', rawUsingList: ['nope'] }], + ['item appId missing', { targetUin: '10000', rawUsingList: [{}] }], ['item appId not a number', { targetUin: '10000', rawUsingList: [{ appId: 'four' }] }], ['targetUin not a string', { targetUin: 10000, rawUsingList: [] }], ])('structure: %s', async (_label, payload) => { @@ -185,9 +218,9 @@ describe('friend-dress / error classification', () => { expect(e.message).toContain('10000'); }); - it('tolerates a missing targetUin by echoing the requested uin', async () => { + it('structure: targetUin missing cannot prove which account owns the response', async () => { mockHtml(wrapHtml({ rawUsingList: [] })); - const dress = await getFriendDressWebAPI(cookies, '10000'); - expect(dress.target_uin).toBe('10000'); + const e = await expectKind('10000', 'structure'); + expect(e.message).toContain('targetUin'); }); }); diff --git a/packages/protocol/tests/web/request-util.test.ts b/packages/protocol/tests/web/request-util.test.ts new file mode 100644 index 00000000..bfc240d3 --- /dev/null +++ b/packages/protocol/tests/web/request-util.test.ts @@ -0,0 +1,255 @@ +import http from 'node:http'; +import type { AddressInfo } from 'node:net'; +import { afterEach, describe, expect, it } from 'vitest'; +import { RequestUtil } from '@snowluma/protocol/web/request-util'; + +const servers = new Set(); + +async function serve( + handler: http.RequestListener, +): Promise<{ server: http.Server; url: string }> { + const server = http.createServer(handler); + servers.add(server); + await new Promise((resolve, reject) => { + server.once('error', reject); + server.listen(0, '127.0.0.1', resolve); + }); + const address = server.address() as AddressInfo; + return { server, url: `http://127.0.0.1:${address.port}` }; +} + +afterEach(async () => { + await Promise.all([...servers].map(async (server) => { + server.closeAllConnections(); + await new Promise((resolve) => server.close(() => resolve())); + servers.delete(server); + })); +}); + +describe('RequestUtil bounded text responses', () => { + it('rejects a response once it exceeds the byte limit', async () => { + const { url } = await serve((_req, res) => { + res.end('x'.repeat(65)); + }); + + await expect(RequestUtil.HttpGetText( + url, + 'GET', + undefined, + {}, + { maxResponseBytes: 64 }, + )).rejects.toThrow('response body exceeds 64 bytes'); + }); + + it('rejects a request that does not complete before its deadline', async () => { + const { url } = await serve((_req, res) => { + res.writeHead(200); + res.write('partial'); + }); + + await expect(RequestUtil.HttpGetText( + url, + 'GET', + undefined, + {}, + { timeoutMs: 30 }, + )).rejects.toThrow('request timed out after 30 ms'); + }); + + it('measures the response limit in bytes and accepts the exact boundary', async () => { + const exact = '界'.repeat(16); + const { url } = await serve((_req, res) => { + res.end(exact); + }); + + await expect(RequestUtil.HttpGetText( + url, + 'GET', + undefined, + {}, + { maxResponseBytes: Buffer.byteLength(exact) }, + )).resolves.toBe(exact); + }); + + it('rejects a multibyte response that exceeds the byte boundary', async () => { + const tooLarge = '界'.repeat(17); + const { url } = await serve((_req, res) => { + res.end(tooLarge); + }); + + await expect(RequestUtil.HttpGetText( + url, + 'GET', + undefined, + {}, + { maxResponseBytes: 48 }, + )).rejects.toThrow('response body exceeds 48 bytes'); + }); + + it('closes a non-success response without waiting for its body to end', async () => { + let markClosed!: () => void; + const closed = new Promise((resolve) => { markClosed = resolve; }); + const { url } = await serve((_req, res) => { + res.once('close', markClosed); + res.writeHead(403); + res.flushHeaders(); + res.write('body that never ends'); + }); + + await expect(RequestUtil.HttpGetText(url)).rejects.toThrow('Unexpected status code: 403'); + await expect(Promise.race([ + closed.then(() => true), + new Promise((resolve) => setTimeout(() => resolve(false), 250)), + ])).resolves.toBe(true); + }); +}); + +describe('RequestUtil redirects', () => { + it('strips credentials when a redirect crosses origins', async () => { + let redirectedHeaders: http.IncomingHttpHeaders | undefined; + const target = await serve((req, res) => { + redirectedHeaders = req.headers; + res.end('ok'); + }); + const source = await serve((_req, res) => { + res.writeHead(302, { location: target.url }); + res.end(); + }); + + await expect(RequestUtil.HttpGetText( + source.url, + 'GET', + undefined, + { + Cookie: 'uin=secret', + Authorization: 'Bearer secret', + 'Proxy-Authorization': 'Basic secret', + 'X-SnowLuma-Test': 'kept', + }, + )).resolves.toBe('ok'); + + expect(redirectedHeaders?.cookie).toBeUndefined(); + expect(redirectedHeaders?.authorization).toBeUndefined(); + expect(redirectedHeaders?.['proxy-authorization']).toBeUndefined(); + expect(redirectedHeaders?.['x-snowluma-test']).toBe('kept'); + }); + + it('never forwards a write request body across origins', async () => { + let targetReached = false; + const target = await serve((_req, res) => { + targetReached = true; + res.end('unexpected'); + }); + const source = await serve((_req, res) => { + res.writeHead(307, { location: target.url }); + res.end(); + }); + + await expect(RequestUtil.HttpGetText( + source.url, + 'POST', + 'secret-body', + { 'Content-Type': 'text/plain' }, + )).rejects.toThrow('cross-origin redirect cannot forward method POST'); + expect(targetReached).toBe(false); + }); + + it('preserves credentials for same-origin redirects', async () => { + let redirectedCookie: string | undefined; + const { url } = await serve((req, res) => { + if (req.url === '/start') { + res.writeHead(302, { location: '/finish' }); + res.end(); + return; + } + redirectedCookie = req.headers.cookie; + res.end('ok'); + }); + + await expect(RequestUtil.HttpGetText( + `${url}/start`, + 'GET', + undefined, + { Cookie: 'uin=same-origin' }, + )).resolves.toBe('ok'); + expect(redirectedCookie).toBe('uin=same-origin'); + }); + + it('inherits response limits after a redirect', async () => { + const target = await serve((_req, res) => { + res.end('x'.repeat(65)); + }); + const source = await serve((_req, res) => { + res.writeHead(302, { location: target.url }); + res.end(); + }); + + await expect(RequestUtil.HttpGetText( + source.url, + 'GET', + undefined, + {}, + { maxResponseBytes: 64 }, + )).rejects.toThrow('response body exceeds 64 bytes'); + }); + + it('shares one wall-clock deadline across the redirect chain', async () => { + const target = await serve((_req, res) => { + setTimeout(() => res.end('late'), 80); + }); + const source = await serve((_req, res) => { + setTimeout(() => { + res.writeHead(302, { location: target.url }); + res.end(); + }, 80); + }); + + await expect(RequestUtil.HttpGetText( + source.url, + 'GET', + undefined, + {}, + { timeoutMs: 100 }, + )).rejects.toThrow('request timed out after 100 ms'); + }); + + it('rejects malformed redirect locations instead of throwing outside the Promise', async () => { + const { url } = await serve((_req, res) => { + res.writeHead(302, { location: 'http://[' }); + res.end(); + }); + + await expect(RequestUtil.HttpGetText(url)).rejects.toThrow('invalid redirect location'); + }); + + it('rejects redirects to non-HTTP protocols', async () => { + const { url } = await serve((_req, res) => { + res.writeHead(302, { location: 'file:///tmp/not-a-web-response' }); + res.end(); + }); + + await expect(RequestUtil.HttpGetText(url)).rejects.toThrow( + 'unsupported redirect protocol: file:', + ); + }); + + it('closes the previous response before following a redirect', async () => { + const target = await serve((_req, res) => { + res.end('ok'); + }); + let markClosed!: () => void; + const closed = new Promise((resolve) => { markClosed = resolve; }); + const source = await serve((_req, res) => { + res.once('close', markClosed); + res.writeHead(302, { location: target.url }); + res.flushHeaders(); + res.write('body that never ends'); + }); + + await expect(RequestUtil.HttpGetText(source.url)).resolves.toBe('ok'); + await expect(Promise.race([ + closed.then(() => true), + new Promise((resolve) => setTimeout(() => resolve(false), 250)), + ])).resolves.toBe(true); + }); +});