fix: 加固 DOCX 解压防 Zip 炸弹与 OpenClaw 响应体超时

docx 解压只保留解析所需部件并限制单件 10MB、累计 30MB;OpenClaw 客户端将超时定时器移到 finally 覆盖响应体读取,并规范化 OPENCLAW_API_URL 尾斜杠。
Refs: https://github.com/margrop/wrong-notebook/issues/186
This commit is contained in:
margrop
2026-12-04 07:32:41 +08:00
parent c72da31e54
commit 0929d3fba1
4 changed files with 135 additions and 7 deletions

View File

@@ -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("<w:document xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\"/>");
const MB = 1024 * 1024;
describe("unzipDocx", () => {
it("只解压主文档、样式、关系与媒体,忽略无关部件", () => {
const entries = unzipDocx(zipSync({
"word/document.xml": documentXml,
"word/styles.xml": encoder.encode("<styles/>"),
"word/media/pic.png": new Uint8Array([1, 2, 3]),
"customXml/item1.xml": encoder.encode("<item/>"),
"docProps/core.xml": encoder.encode("<core/>"),
}));
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");
});
});

View File

@@ -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<unknown>();
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: "识别服务超时",
});
});
});

View File

@@ -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<string, true> = {
"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<string, Uint8Array> {
let entries: Record<string, Uint8Array>;
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");
}

View File

@@ -29,7 +29,8 @@ export interface OpenclawResponse {
* 调用外部 Openclaw 智能体识别单张题目图片。
*/
export async function callOpenclawAgent(imageBase64: string, mimeType: string, timeout: number): Promise<OpenclawResponse> {
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);
}
}