diff --git a/packages/core/src/bridge/apis/flash-transfer.ts b/packages/core/src/bridge/apis/flash-transfer.ts index 489a70ea..15a0f3ed 100644 --- a/packages/core/src/bridge/apis/flash-transfer.ts +++ b/packages/core/src/bridge/apis/flash-transfer.ts @@ -49,6 +49,99 @@ function entryToInfo(e: FlashFileEntry): FlashFileInfo { }; } +const QFILE_SHARE_ORIGIN = 'https://qfile.qq.com'; +const QFILE_SHARE_PAGE_MAX_BYTES = 2 * 1024 * 1024; +const QFILE_SHARE_TIMEOUT_MS = 20_000; + +function officialQfileShareUrl(input: string): string { + const value = input.trim(); + if (!value) throw new Error('get_fileset_id: share code is empty'); + + let code = value; + if (/^[a-z][a-z\d+.-]*:/i.test(value) || value.startsWith('//')) { + let parsed: URL; + try { + parsed = new URL(value); + } catch (error) { + throw new Error('get_fileset_id: expected an official QQ share URL', { cause: error }); + } + if ( + parsed.protocol !== 'https:' + || parsed.hostname !== 'qfile.qq.com' + || parsed.port !== '' + || parsed.username !== '' + || parsed.password !== '' + ) { + throw new Error('get_fileset_id: expected an official QQ share URL'); + } + const match = /^\/q\/([^/]+)\/?$/.exec(parsed.pathname); + if (!match) throw new Error('get_fileset_id: expected an official QQ share URL'); + try { + code = decodeURIComponent(match[1]); + } catch (error) { + throw new Error('get_fileset_id: expected an official QQ share URL', { cause: error }); + } + } + + const hasForbiddenCharacter = Array.from(code).some((char) => { + const codePoint = char.codePointAt(0) ?? 0; + return codePoint <= 0x20 || codePoint === 0x7f || '/\\?#'.includes(char); + }); + if (code.length > 256 || hasForbiddenCharacter) { + throw new Error('get_fileset_id: invalid share code'); + } + return `${QFILE_SHARE_ORIGIN}/q/${encodeURIComponent(code)}`; +} + +async function rejectShareResponse(response: Response, error: Error): Promise { + try { + await response.body?.cancel(error); + } catch (cleanupError) { + throw new AggregateError([error, cleanupError], error.message); + } + throw error; +} + +async function readSharePage(response: Response): Promise { + const declaredLength = response.headers.get('content-length'); + if (declaredLength !== null) { + if (!/^\d+$/.test(declaredLength)) { + await rejectShareResponse(response, new Error('get_fileset_id: invalid response length')); + } + if (Number(declaredLength) > QFILE_SHARE_PAGE_MAX_BYTES) { + await rejectShareResponse(response, new Error('get_fileset_id: share page too large')); + } + } + if (!response.body) throw new Error('get_fileset_id: share page response has no body'); + + const reader = response.body.getReader(); + const decoder = new TextDecoder(); + let total = 0; + let html = ''; + try { + while (true) { + const { done, value } = await reader.read(); + if (done) break; + if (!value) continue; + total += value.byteLength; + if (total > QFILE_SHARE_PAGE_MAX_BYTES) { + const error = new Error('get_fileset_id: share page too large'); + try { + await reader.cancel(error); + } catch (cleanupError) { + throw new AggregateError([error, cleanupError], error.message); + } + throw error; + } + html += decoder.decode(value, { stream: true }); + } + html += decoder.decode(); + return html; + } finally { + reader.releaseLock(); + } +} + // 手写 PNG 编码(zlib 压缩,避免引入图像库)。缩略图用随机纯色,每次 SHA1 不同, // 避免命中服务端秒传缓存。 const CRC_TABLE: Uint32Array = (() => { @@ -207,10 +300,26 @@ export class FlashTransferApi { * 接口数据),直接 GET + 正则提取即可,无需复刻带签名的 trpc 调用。 */ async getFilesetIdByCode(shareCode: string): Promise { - const url = /^https?:\/\//i.test(shareCode) ? shareCode : `https://qfile.qq.com/q/${shareCode}`; - const resp = await fetch(url); - if (!resp.ok) throw new Error(`get_fileset_id: HTTP ${resp.status}`); - const html = await resp.text(); + const url = officialQfileShareUrl(shareCode); + let resp: Response; + try { + resp = await fetch(url, { + redirect: 'manual', + signal: AbortSignal.timeout(QFILE_SHARE_TIMEOUT_MS), + }); + } catch (error) { + if (error instanceof Error && (error.name === 'AbortError' || error.name === 'TimeoutError')) { + throw new Error('get_fileset_id: share page request timed out', { cause: error }); + } + throw error; + } + if (resp.status >= 300 && resp.status < 400) { + await rejectShareResponse(resp, new Error('get_fileset_id: share page redirect is not allowed')); + } + if (!resp.ok) { + await rejectShareResponse(resp, new Error(`get_fileset_id: HTTP ${resp.status}`)); + } + const html = await readSharePage(resp); // 网页里 fileset_id 以 JSON 嵌入(引号可能被转义为 \"),正则兼容两种形态。 const m = /fileset_id\\?"\s*:\s*\\?"([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/.exec(html); if (!m) throw new Error('get_fileset_id: fileset_id not found in share page'); diff --git a/packages/core/tests/flash-transfer-share-link.test.ts b/packages/core/tests/flash-transfer-share-link.test.ts new file mode 100644 index 00000000..051b1e82 --- /dev/null +++ b/packages/core/tests/flash-transfer-share-link.test.ts @@ -0,0 +1,101 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { FlashTransferApi } from '../src/bridge/apis/flash-transfer'; + +const FILESET_ID = '8e40afa1-829d-498b-852f-092394ddb31f'; +const SHARE_HTML = ``; +const originalFetch = globalThis.fetch; + +afterEach(() => { + globalThis.fetch = originalFetch; + vi.restoreAllMocks(); +}); + +function api(): FlashTransferApi { + return new FlashTransferApi({} as never); +} + +describe('FlashTransferApi.getFilesetIdByCode', () => { + it('resolves a plain share code through the canonical production page', async () => { + const fetchMock = vi.fn(async (..._args: Parameters) => ( + new Response(SHARE_HTML, { status: 200 }) + )); + globalThis.fetch = fetchMock as typeof fetch; + + await expect(api().getFilesetIdByCode('K0sEqhYria')).resolves.toBe(FILESET_ID); + expect(fetchMock).toHaveBeenCalledOnce(); + expect(fetchMock.mock.calls[0]?.[0]).toBe('https://qfile.qq.com/q/K0sEqhYria'); + expect(fetchMock.mock.calls[0]?.[1]).toMatchObject({ redirect: 'manual' }); + expect(fetchMock.mock.calls[0]?.[1]?.signal).toBeInstanceOf(AbortSignal); + }); + + it('accepts the production HTTPS share URL and removes nonessential URL parts', async () => { + const fetchMock = vi.fn(async (..._args: Parameters) => ( + new Response(SHARE_HTML, { status: 200 }) + )); + globalThis.fetch = fetchMock as typeof fetch; + + await expect( + api().getFilesetIdByCode('HTTPS://QFILE.QQ.COM:443/q/K0sEqhYria?from=copy#copied'), + ).resolves.toBe(FILESET_ID); + expect(fetchMock.mock.calls[0]?.[0]).toBe('https://qfile.qq.com/q/K0sEqhYria'); + }); + + it.each([ + 'http://qfile.qq.com/q/K0sEqhYria', + 'https://qfile.qq.com.evil.example/q/K0sEqhYria', + 'https://user@qfile.qq.com/q/K0sEqhYria', + 'https://qfile.qq.com:444/q/K0sEqhYria', + 'https://qfile.qq.com/not-a-share/K0sEqhYria', + 'https://test.qfile.qq.com/q/K0sEqhYria', + 'https://qfile.qq.com./q/K0sEqhYria', + '//127.0.0.1/private', + ])('rejects a non-production share URL before fetching: %s', async (input) => { + const fetchMock = vi.fn(); + globalThis.fetch = fetchMock as typeof fetch; + + await expect(api().getFilesetIdByCode(input)).rejects.toThrow(/official QQ share URL/i); + expect(fetchMock).not.toHaveBeenCalled(); + }); + + it('rejects encoded path separators instead of reinterpreting them as a code', async () => { + const fetchMock = vi.fn(); + globalThis.fetch = fetchMock as typeof fetch; + + await expect( + api().getFilesetIdByCode('https://qfile.qq.com/q/%2F%2F127.0.0.1%2Fprivate'), + ).rejects.toThrow(/invalid share code/i); + expect(fetchMock).not.toHaveBeenCalled(); + }); + + it('does not follow redirects returned by the share page', async () => { + globalThis.fetch = vi.fn(async () => new Response(null, { + status: 302, + headers: { Location: 'http://127.0.0.1/private' }, + })) as typeof fetch; + + await expect(api().getFilesetIdByCode('K0sEqhYria')).rejects.toThrow(/redirect/i); + }); + + it('rejects an oversized streamed share page even if it contains an id', async () => { + const oversized = `${SHARE_HTML}${'x'.repeat(2 * 1024 * 1024)}`; + globalThis.fetch = vi.fn(async () => new Response(oversized, { status: 200 })) as typeof fetch; + + await expect(api().getFilesetIdByCode('K0sEqhYria')).rejects.toThrow(/too large/i); + }); + + it('rejects an oversized declared response before reading its body', async () => { + let cancelled = false; + const body = new ReadableStream({ + cancel() { + cancelled = true; + }, + }); + globalThis.fetch = vi.fn(async () => new Response(body, { + status: 200, + headers: { 'Content-Length': String(2 * 1024 * 1024 + 1) }, + })) as typeof fetch; + + await expect(api().getFilesetIdByCode('K0sEqhYria')).rejects.toThrow(/too large/i); + expect(cancelled).toBe(true); + }); +}); diff --git a/packages/mcp/src/generated/catalog.json b/packages/mcp/src/generated/catalog.json index fb5af9c0..76014256 100644 --- a/packages/mcp/src/generated/catalog.json +++ b/packages/mcp/src/generated/catalog.json @@ -3038,7 +3038,7 @@ { "name": "get_fileset_id", "aliases": [], - "summary": "从分享码/链接获取 fileset_id", + "summary": "从 QQ 闪传分享码或官方分享链接获取 fileset_id", "returns": "{ fileset_id }:解析出的文件集 ID。", "returnsSchema": { "type": "object", @@ -3061,7 +3061,8 @@ "schema": { "type": "string", "minLength": 1 - } + }, + "desc": "QQ 闪传分享码,或 https://qfile.qq.com/q/... 官方分享链接" } ], "invariants": [], @@ -3070,7 +3071,8 @@ "properties": { "share_code": { "type": "string", - "minLength": 1 + "minLength": 1, + "description": "QQ 闪传分享码,或 https://qfile.qq.com/q/... 官方分享链接" } }, "required": [ diff --git a/packages/mcp/src/generated/catalog.ts b/packages/mcp/src/generated/catalog.ts index cb1b6f1d..74bcd7d2 100644 --- a/packages/mcp/src/generated/catalog.ts +++ b/packages/mcp/src/generated/catalog.ts @@ -3041,7 +3041,7 @@ export const ACTIONS: CatalogAction[] = [ { "name": "get_fileset_id", "aliases": [], - "summary": "从分享码/链接获取 fileset_id", + "summary": "从 QQ 闪传分享码或官方分享链接获取 fileset_id", "returns": "{ fileset_id }:解析出的文件集 ID。", "returnsSchema": { "type": "object", @@ -3064,7 +3064,8 @@ export const ACTIONS: CatalogAction[] = [ "schema": { "type": "string", "minLength": 1 - } + }, + "desc": "QQ 闪传分享码,或 https://qfile.qq.com/q/... 官方分享链接" } ], "invariants": [], @@ -3073,7 +3074,8 @@ export const ACTIONS: CatalogAction[] = [ "properties": { "share_code": { "type": "string", - "minLength": 1 + "minLength": 1, + "description": "QQ 闪传分享码,或 https://qfile.qq.com/q/... 官方分享链接" } }, "required": [ diff --git a/packages/onebot/src/actions/extended.ts b/packages/onebot/src/actions/extended.ts index 7959a237..fe55263b 100644 --- a/packages/onebot/src/actions/extended.ts +++ b/packages/onebot/src/actions/extended.ts @@ -2605,7 +2605,7 @@ export const actions = [ defineAction({ name: 'get_fileset_id', - summary: '从分享码/链接获取 fileset_id', + summary: '从 QQ 闪传分享码或官方分享链接获取 fileset_id', readOnly: true, returns: '{ fileset_id }:解析出的文件集 ID。', returnsSchema: { @@ -2615,7 +2615,10 @@ export const actions = [ }, required: ['fileset_id'], }, - params: { share_code: f.string({ allowEmpty: false }) }, + params: { + share_code: f.string({ allowEmpty: false }) + .describe('QQ 闪传分享码,或 https://qfile.qq.com/q/... 官方分享链接'), + }, run: async (p, ctx) => { const filesetId = await ctx.bridge.apis.flashTransfer.getFilesetIdByCode(p.share_code); return okResponse({ fileset_id: filesetId });