From 0110b71dd388f2340edee2c61d7a6920566412c0 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Fri, 29 May 2026 17:37:10 +0800 Subject: [PATCH] fix(protocol): send browser UA + Referer retry on media downloads MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit loadBinarySource issued a header-less fetch(source) for remote media. Anti-hotlink / anti-bot front-ends reset such requests, surfacing as undici `TypeError: fetch failed` (not a clean 403) — so quoting a command and sending an image/GIF whose source is a guarded URL bounced with send_group_msg retcode 1200 "fetch failed". Mirror NapCat's download path: send a browser User-Agent on every request and retry once with a Referer pointing at the resource when the first attempt is refused (network error or 403/4xx). Size-limit rejections are tagged noRetry so an oversized body isn't re-downloaded. Also route set_group_notice's image fetch through loadBinarySource so it inherits the same hardening (plus http/file/base64 handling). --- packages/core/src/bridge/apis/web.ts | 16 ++- packages/core/tests/highway-utils.test.ts | 78 ++++++++++++++ packages/protocol/src/highway/utils.ts | 125 +++++++++++++++------- 3 files changed, 172 insertions(+), 47 deletions(-) diff --git a/packages/core/src/bridge/apis/web.ts b/packages/core/src/bridge/apis/web.ts index 6198f924..e59c144c 100644 --- a/packages/core/src/bridge/apis/web.ts +++ b/packages/core/src/bridge/apis/web.ts @@ -1,3 +1,4 @@ +import { loadBinarySource } from '@snowluma/protocol/highway/utils'; import { ForceFetchClientKey, type ClientKeyInfo as NamespaceClientKeyInfo } from '@snowluma/protocol/oidb-services/web/force-fetch-client-key'; import { GetPskey } from '@snowluma/protocol/oidb-services/web/get-pskey'; import { getGroupEssenceMsg, getGroupEssenceMsgAll, type GroupEssenceMsgRet } from '@snowluma/protocol/web/group-essence'; @@ -247,16 +248,11 @@ export class WebApi { let imgHeight = 300; if (options?.image) { - let imageBuffer: Buffer; - - if (options.image.startsWith('http://') || options.image.startsWith('https://')) { - const response = await fetch(options.image); - if (!response.ok) throw new Error(`Failed to download image: ${response.status}`); - imageBuffer = Buffer.from(await response.arrayBuffer()); - } else { - const { readFileSync } = await import('fs'); - imageBuffer = readFileSync(options.image); - } + // Route through loadBinarySource so the group-notice image download + // gets the same browser-UA + Referer-retry hardening as every other + // media fetch — and http/file/base64 source handling for free. + const loaded = await loadBinarySource(options.image, 'group-notice image'); + const imageBuffer = Buffer.from(loaded.bytes); const picInfo = await uploadGroupNoticeImage(cookieObject, imageBuffer); if (picInfo) { diff --git a/packages/core/tests/highway-utils.test.ts b/packages/core/tests/highway-utils.test.ts index 87f5c6c0..a6fa17d6 100644 --- a/packages/core/tests/highway-utils.test.ts +++ b/packages/core/tests/highway-utils.test.ts @@ -99,3 +99,81 @@ describe('loadBinarySource maxBytes enforcement', () => { ).rejects.toThrow(/too large: 128 > 64/); }); }); + +describe('loadBinarySource HTTP header hardening', () => { + const originalFetch = globalThis.fetch; + afterEach(() => { + globalThis.fetch = originalFetch; + vi.restoreAllMocks(); + }); + + it('sends a browser User-Agent on the first attempt, without a Referer', async () => { + const calls: Array> = []; + globalThis.fetch = vi.fn(async (_url: unknown, init?: RequestInit) => { + calls.push((init?.headers ?? {}) as Record); + return new Response(new Uint8Array([1, 2, 3]), { status: 200 }); + }) as typeof fetch; + + await loadBinarySource('https://example.test/a.png', 'image'); + expect(calls).toHaveLength(1); + expect(calls[0]['User-Agent']).toMatch(/Mozilla\/5\.0/); + expect(calls[0]['Referer']).toBeUndefined(); + }); + + it('retries with a Referer when the first fetch fails at the network level', async () => { + // Reproduces the reported bug: an anti-bot front-end resets the + // header-less request → undici `TypeError: fetch failed`. The retry + // carries a Referer pointing at the resource itself and succeeds. + const calls: Array> = []; + globalThis.fetch = vi.fn(async (_url: unknown, init?: RequestInit) => { + calls.push((init?.headers ?? {}) as Record); + if (calls.length === 1) throw new TypeError('fetch failed'); + return new Response(new Uint8Array([9, 9]), { status: 200 }); + }) as typeof fetch; + + const loaded = await loadBinarySource('https://img.example.test/x.gif', 'image'); + expect(Array.from(loaded.bytes)).toEqual([9, 9]); + expect(calls).toHaveLength(2); + expect(calls[0]['Referer']).toBeUndefined(); + expect(calls[1]['Referer']).toBe('https://img.example.test/x.gif'); + }); + + it('retries with a Referer on a 403 (anti-hotlink)', async () => { + let n = 0; + globalThis.fetch = vi.fn(async () => { + n++; + if (n === 1) return new Response(new Uint8Array(0), { status: 403 }); + return new Response(new Uint8Array([7]), { status: 200 }); + }) as typeof fetch; + + const loaded = await loadBinarySource('https://cdn.example.test/y.jpg', 'image'); + expect(Array.from(loaded.bytes)).toEqual([7]); + expect(n).toBe(2); + }); + + it('does not retry a size-limit rejection (deterministic, no second download)', async () => { + const fetchMock = vi.fn(async () => new Response(new Uint8Array(0), { + status: 200, + headers: { 'content-length': String(10 * 1024 * 1024) }, + })); + globalThis.fetch = fetchMock as typeof fetch; + + await expect( + loadBinarySource('https://example.test/big.bin', 'image', 1024), + ).rejects.toThrow(/too large/); + expect(fetchMock).toHaveBeenCalledTimes(1); + }); + + it('surfaces the first error when the Referer retry also fails', async () => { + let n = 0; + globalThis.fetch = vi.fn(async () => { + n++; + throw new TypeError('fetch failed'); + }) as typeof fetch; + + await expect( + loadBinarySource('https://example.test/z.png', 'image'), + ).rejects.toThrow(/fetch failed/); + expect(n).toBe(2); + }); +}); diff --git a/packages/protocol/src/highway/utils.ts b/packages/protocol/src/highway/utils.ts index c1c2c89f..d42c09a8 100644 --- a/packages/protocol/src/highway/utils.ts +++ b/packages/protocol/src/highway/utils.ts @@ -22,6 +22,19 @@ const DEFAULT_MAX_BINARY_SIZE = 1024 * 1024 * 1024; // 1 GiB export const FILE_UPLOAD_MAX_BYTES = 4 * 1024 * 1024 * 1024; // 4 GiB const FETCH_TIMEOUT_MS = 60_000; +/** + * Browser-like User-Agent for remote media downloads. Many image / CDN + * hosts (and anti-hotlink front-ends) reject or RST a header-less, + * non-browser request — which surfaces as undici `TypeError: fetch + * failed` rather than a clean 403. Sending a normal browser UA on every + * request (and retrying with a Referer when the first try is refused) is + * what lets NapCat fetch sources our bare `fetch(source)` couldn't. + * Cross-checked against + * `dev/napcatQQInside/packages/napcat-common/src/file.ts:101-142,359-369`. + */ +const DOWNLOAD_USER_AGENT = + 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36'; + export interface ImageHashes { md5: Uint8Array; sha1: Uint8Array; @@ -65,6 +78,14 @@ export function resolveLocalFilePath(source: string): string | null { return filePath; } +/** + * Tag a size-limit error so the HTTP retry path leaves it alone — retrying + * a too-large response just re-downloads the same oversized body. + */ +function tooLarge(message: string): Error { + return Object.assign(new Error(message), { noRetry: true }); +} + export async function loadBinarySource( source: string, resourceName: string, @@ -81,49 +102,79 @@ export async function loadBinarySource( } if (/^https?:\/\//i.test(source)) { - const resp = await fetch(source, { signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) }); - if (!resp.ok) throw new Error(`HTTP download failed: ${resp.status}`); - const declared = Number(resp.headers.get('content-length') ?? '0'); - if (Number.isFinite(declared) && declared > maxBytes) { - throw new Error(`${resourceName} too large: ${declared} > ${maxBytes}`); - } const fileName = guessFileNameFromUrl(source); - // Stream the body incrementally so a server that omits or - // understates Content-Length can't make us buffer a chunked response - // past maxBytes — `await resp.arrayBuffer()` would happily allocate - // the entire payload before we get a chance to length-check it. - const reader = resp.body?.getReader(); - if (!reader) { - const bytes = new Uint8Array(await resp.arrayBuffer()); - if (bytes.length > maxBytes) { - throw new Error(`${resourceName} too large: ${bytes.length} > ${maxBytes}`); + + // A single fetch attempt with the given headers. Streams the body + // incrementally so a server that omits or understates Content-Length + // can't make us buffer a chunked response past maxBytes — `await + // resp.arrayBuffer()` would happily allocate the entire payload before + // we get a chance to length-check it. Size-limit rejections are tagged + // `noRetry` so the outer retry doesn't re-download an oversized body. + const attempt = async (headers: Record): Promise => { + const resp = await fetch(source, { + headers, + redirect: 'follow', + signal: AbortSignal.timeout(FETCH_TIMEOUT_MS), + }); + if (!resp.ok) throw new Error(`HTTP download failed: ${resp.status}`); + const declared = Number(resp.headers.get('content-length') ?? '0'); + if (Number.isFinite(declared) && declared > maxBytes) { + throw tooLarge(`${resourceName} too large: ${declared} > ${maxBytes}`); + } + const reader = resp.body?.getReader(); + if (!reader) { + const bytes = new Uint8Array(await resp.arrayBuffer()); + if (bytes.length > maxBytes) { + throw tooLarge(`${resourceName} too large: ${bytes.length} > ${maxBytes}`); + } + return { bytes, fileName }; + } + const chunks: Uint8Array[] = []; + let total = 0; + try { + while (true) { + const { done, value } = await reader.read(); + if (done) break; + if (!value) continue; + total += value.byteLength; + if (total > maxBytes) { + await reader.cancel().catch(() => { /* ignore */ }); + throw tooLarge(`${resourceName} too large: > ${maxBytes}`); + } + chunks.push(value); + } + } finally { + reader.releaseLock(); + } + const bytes = new Uint8Array(total); + let offset = 0; + for (const chunk of chunks) { + bytes.set(chunk, offset); + offset += chunk.byteLength; } return { bytes, fileName }; - } - const chunks: Uint8Array[] = []; - let total = 0; + }; + + // First try with a browser UA only. On any non-size failure — a + // network-level `fetch failed` (connection reset by an anti-bot + // front-end) or a 403/4xx from anti-hotlink — retry once with a + // Referer pointing at the resource itself, the common bypass for + // same-origin hotlink checks. Mirrors NapCat's with/without-Referer + // strategy. + const baseHeaders: Record = { + 'User-Agent': DOWNLOAD_USER_AGENT, + Accept: '*/*', + }; try { - while (true) { - const { done, value } = await reader.read(); - if (done) break; - if (!value) continue; - total += value.byteLength; - if (total > maxBytes) { - await reader.cancel().catch(() => { /* ignore */ }); - throw new Error(`${resourceName} too large: > ${maxBytes}`); - } - chunks.push(value); + return await attempt(baseHeaders); + } catch (err) { + if ((err as { noRetry?: boolean } | null)?.noRetry) throw err; + try { + return await attempt({ ...baseHeaders, Referer: source }); + } catch { + throw err; } - } finally { - reader.releaseLock(); } - const bytes = new Uint8Array(total); - let offset = 0; - for (const chunk of chunks) { - bytes.set(chunk, offset); - offset += chunk.byteLength; - } - return { bytes, fileName }; } const filePath = resolveLocalFilePath(source);