diff --git a/src/__tests__/unit/import/docx-unzip.test.ts b/src/__tests__/unit/import/docx-unzip.test.ts new file mode 100644 index 00000000..588672a0 --- /dev/null +++ b/src/__tests__/unit/import/docx-unzip.test.ts @@ -0,0 +1,51 @@ +// @vitest-environment node +/** + * docx 解压加固:只解压解析所需部件,并拒绝超过单件/累计上限的 Zip 炸弹。 + */ +import { describe, expect, it } from "vitest"; +import { zipSync } from "fflate"; +import { unzipDocx } from "@/lib/import/file-parsers/docx/docx-xml"; + +const encoder = new TextEncoder(); +const documentXml = encoder.encode(""); +const MB = 1024 * 1024; + +describe("unzipDocx", () => { + it("只解压主文档、样式、关系与媒体,忽略无关部件", () => { + const entries = unzipDocx(zipSync({ + "word/document.xml": documentXml, + "word/styles.xml": encoder.encode(""), + "word/media/pic.png": new Uint8Array([1, 2, 3]), + "customXml/item1.xml": encoder.encode(""), + "docProps/core.xml": encoder.encode(""), + })); + expect(Object.keys(entries).sort()).toEqual([ + "word/document.xml", + "word/media/pic.png", + "word/styles.xml", + ]); + }); + + it("单个部件超过 10MB 时拒绝解压", () => { + const zip = zipSync({ + "word/document.xml": documentXml, + "word/media/huge.bin": new Uint8Array(11 * MB), + }); + expect(() => unzipDocx(zip)).toThrow("INVALID_DOCX"); + }); + + it("多个部件累计超过 30MB 时拒绝解压", () => { + const zip = zipSync({ + "word/document.xml": documentXml, + "word/media/a.bin": new Uint8Array(8 * MB), + "word/media/b.bin": new Uint8Array(8 * MB), + "word/media/c.bin": new Uint8Array(8 * MB), + "word/media/d.bin": new Uint8Array(8 * MB), + }); + expect(() => unzipDocx(zip)).toThrow("INVALID_DOCX"); + }); + + it("损坏的 zip 仍归一化为 INVALID_DOCX", () => { + expect(() => unzipDocx(encoder.encode("not a zip"))).toThrow("INVALID_DOCX"); + }); +}); diff --git a/src/__tests__/unit/openclaw/agent-client.test.ts b/src/__tests__/unit/openclaw/agent-client.test.ts new file mode 100644 index 00000000..6e12e101 --- /dev/null +++ b/src/__tests__/unit/openclaw/agent-client.test.ts @@ -0,0 +1,51 @@ +// @vitest-environment node +/** + * Openclaw 智能体客户端:URL 尾斜杠规范化,以及响应体读取阶段的超时保护。 + */ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { callOpenclawAgent } from "@/lib/openclaw/agent-client"; + +const originalUrl = process.env.OPENCLAW_API_URL; + +afterEach(() => { + vi.unstubAllGlobals(); + if (originalUrl === undefined) delete process.env.OPENCLAW_API_URL; + else process.env.OPENCLAW_API_URL = originalUrl; +}); + +describe("callOpenclawAgent", () => { + it("去掉 OPENCLAW_API_URL 末尾斜杠后再拼接识别接口", async () => { + process.env.OPENCLAW_API_URL = "http://agent.local/"; + const fetchMock = vi.fn(async () => ({ + ok: true, + status: 200, + json: async () => ({ success: true }), + }) as unknown as Response); + vi.stubGlobal("fetch", fetchMock); + + await expect(callOpenclawAgent("base64", "image/png", 1000)).resolves.toEqual({ success: true }); + expect(fetchMock).toHaveBeenCalledWith("http://agent.local/api/recognize", expect.anything()); + }); + + it("响应头已返回但响应体卡死时按 timeout 中止", async () => { + const fetchMock = vi.fn((_url: string, init?: RequestInit) => Promise.resolve({ + ok: true, + status: 200, + json: () => { + const { promise, reject } = Promise.withResolvers(); + init?.signal?.addEventListener("abort", () => { + const error = new Error("aborted"); + error.name = "AbortError"; + reject(error); + }); + return promise; + }, + }) as unknown as Response); + vi.stubGlobal("fetch", fetchMock); + + await expect(callOpenclawAgent("base64", "image/png", 20)).resolves.toMatchObject({ + success: false, + error: "识别服务超时", + }); + }); +}); diff --git a/src/lib/import/file-parsers/docx/docx-xml.ts b/src/lib/import/file-parsers/docx/docx-xml.ts index 064e58b4..32034dba 100644 --- a/src/lib/import/file-parsers/docx/docx-xml.ts +++ b/src/lib/import/file-parsers/docx/docx-xml.ts @@ -28,11 +28,37 @@ export function isLegacyDocFile(bytes: Uint8Array): boolean { return LEGACY_DOC_MAGIC.every((value, index) => bytes[index] === value); } -/** zip 中央目录损坏或不是 zip 包时 fflate 抛出的错误归一化为 INVALID_DOCX */ +/** 解析所需部件:主文档、编号、样式、关系与媒体;其余模板/自定义 XML 不解压 */ +const DOCX_PART_NAMES: Record = { + "word/document.xml": true, + "word/numbering.xml": true, + "word/styles.xml": true, + "word/_rels/document.xml.rels": true, +}; +const DOCX_MEDIA_PREFIX = "word/media/"; +/** 单个部件解压上限 10MB,全部部件累计上限 30MB,防止高压缩比 Zip 炸弹耗尽内存 */ +const MAX_DOCX_ENTRY_BYTES = 10 * 1024 * 1024; +const MAX_DOCX_UNCOMPRESSED_BYTES = 30 * 1024 * 1024; + +/** + * 只解压解析所需部件并校验解压后体积;zip 中央目录损坏、非 zip 包或超限时统一抛 INVALID_DOCX。 + * 高压缩比的恶意 docx 在解压阶段即被拒绝,不会解出整个归档。 + */ export function unzipDocx(bytes: Uint8Array): Record { let entries: Record; try { - entries = unzipSync(bytes); + let totalBytes = 0; + entries = unzipSync(bytes, { + filter: (file) => { + const name = file.name.toLowerCase(); + if (!DOCX_PART_NAMES[name] && !name.startsWith(DOCX_MEDIA_PREFIX)) return false; + const size = file.originalSize ?? 0; + if (size > MAX_DOCX_ENTRY_BYTES) throw new Error("INVALID_DOCX"); + totalBytes += size; + if (totalBytes > MAX_DOCX_UNCOMPRESSED_BYTES) throw new Error("INVALID_DOCX"); + return true; + }, + }); } catch { throw new Error("INVALID_DOCX"); } diff --git a/src/lib/openclaw/agent-client.ts b/src/lib/openclaw/agent-client.ts index 07e97300..f8250706 100644 --- a/src/lib/openclaw/agent-client.ts +++ b/src/lib/openclaw/agent-client.ts @@ -29,7 +29,8 @@ export interface OpenclawResponse { * 调用外部 Openclaw 智能体识别单张题目图片。 */ export async function callOpenclawAgent(imageBase64: string, mimeType: string, timeout: number): Promise { - const openclawUrl = process.env.OPENCLAW_API_URL || 'http://localhost:8080'; + // 去掉末尾斜杠,避免 OPENCLAW_API_URL 以 / 结尾时拼出 //api/recognize + const openclawUrl = (process.env.OPENCLAW_API_URL || 'http://localhost:8080').replace(/\/+$/, ''); const openclawApiKey = process.env.OPENCLAW_API_KEY || ''; const controller = new AbortController(); @@ -49,8 +50,6 @@ export async function callOpenclawAgent(imageBase64: string, mimeType: string, t signal: controller.signal, }); - clearTimeout(timeoutId); - if (!response.ok) { const errorText = await response.text(); logger.error({ status: response.status, error: errorText }, 'Openclaw agent error'); @@ -63,8 +62,6 @@ export async function callOpenclawAgent(imageBase64: string, mimeType: string, t const data = await response.json() as OpenclawResponse; return data; } catch (error) { - clearTimeout(timeoutId); - if (error instanceof Error && error.name === 'AbortError') { logger.error('Openclaw agent timeout'); return { @@ -78,5 +75,8 @@ export async function callOpenclawAgent(imageBase64: string, mimeType: string, t success: false, error: `识别服务请求失败: ${getErrorMessage(error)}`, }; + } finally { + // 覆盖 response.text()/response.json() 的完整生命周期,响应头后卡死也会按时中止 + clearTimeout(timeoutId); } }