Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

fix(server): bound a skill archive from its central directory, before it inflates (#601)

Yaowei Zhengbe11f3c2778b
diff --git a/changelog/unreleased/2026-09-03-skill-archive-inflation-bounds.md b/changelog/unreleased/2026-09-03-skill-archive-inflation-bounds.md
new file mode 100644
index 00000000..bea26f42
--- /dev/null
+++ b/changelog/unreleased/2026-09-03-skill-archive-inflation-bounds.md
@@ -0,0 +1,16 @@
+# Skill archive caps are enforced before the zip inflates
+
+- **Date:** 2026-09-03
+- **Type:** fix
+- **Scope:** `server`
+- **PR:** [#601](https://github.com/Prism-Shadow/penguin-harness/pull/601)
+
+[中文版](2026-09-03-skill-archive-inflation-bounds.zh.md)
+
+`POST /api/projects/:p/agents/:a/skills/archive` applied its 200-file, 5MB-per-file and 20MB-total caps to the entries `unzipSync` had already returned. `unzipSync` allocates a buffer of each entry's declared uncompressed size and inflates into it, so caps read off the result bound nothing: the 14MB the route accepts is enough compressed zeros to declare about 14GB, and an entry whose header overstates its size hands back a short view onto a buffer of the declared length — which passed every check and installed.
+
+## Details
+
+- `unzipBounded` (`services/skill-import-limits.ts`) wraps `unzipSync` with a `filter` that enforces the three caps from the central directory, before an entry inflates. The archive route calls it in place of `unzipSync`, and its after-the-fact byte and count checks are gone. Status codes and messages are unchanged: the same 400s, with the same text.
+- Bounding against the declared sizes is exact in both directions — fflate inflates into a buffer of exactly that size and never grows it, so an entry can only ever yield fewer bytes than it claimed.
+- A file entry named exactly like the archive's single top-level directory left an empty path once the prefix came off, and the write landed on the Skill directory itself; that `EISDIR` surfaced as a 500 with an unhandled-exception log line, and is now a 400 like the other rejected entry paths.
diff --git a/changelog/unreleased/2026-09-03-skill-archive-inflation-bounds.zh.md b/changelog/unreleased/2026-09-03-skill-archive-inflation-bounds.zh.md
new file mode 100644
index 00000000..f49ab829
--- /dev/null
+++ b/changelog/unreleased/2026-09-03-skill-archive-inflation-bounds.zh.md
@@ -0,0 +1,16 @@
+# Skill 压缩包的上限在解压之前生效
+
+- **Date:** 2026-09-03
+- **Type:** fix
+- **Scope:** `server`
+- **PR:** [#601](https://github.com/Prism-Shadow/penguin-harness/pull/601)
+
+[English](2026-09-03-skill-archive-inflation-bounds.md)
+
+`POST /api/projects/:p/agents/:a/skills/archive` 此前把 200 个文件、单文件 5MB、总计 20MB 三条上限,施加在 `unzipSync` 已经返回的条目上。而 `unzipSync` 会按每个条目声明的解压后大小分配缓冲区再往里解压,因此对结果做的检查什么也框不住:路由放行的 14MB 用全零压缩足以声明约 14GB,而一个把大小报大的条目返回的是指向声明长度缓冲区的一小段视图——它能通过全部检查并完成安装。
+
+## 详情
+
+- `unzipBounded`(`services/skill-import-limits.ts`)为 `unzipSync` 加上 `filter`,在条目解压之前从中央目录读出并施加这三条上限。压缩包路由改调用它,事后的字节与计数检查随之删除。状态码与文案不变:仍是同样的 400 与同样的文字。
+- 以声明大小为界在两个方向上都是准确的——fflate 只会解压进恰好这么大的缓冲区且从不扩容,因此一个条目产出的字节只可能少于它声明的数量。
+- 名字与压缩包内唯一顶层目录完全相同的文件条目,去掉前缀后只剩空路径,写入会落到 Skill 目录本身;该 `EISDIR` 此前表现为一条未处理异常日志加 500,现在与其他被拒绝的条目路径一样返回 400。
diff --git a/packages/server/src/http/routes/skills.ts b/packages/server/src/http/routes/skills.ts
index 0048981e..081b0d66 100644
--- a/packages/server/src/http/routes/skills.ts
+++ b/packages/server/src/http/routes/skills.ts
@@ -14,7 +14,7 @@
*/
import fs from "node:fs/promises";
import path from "node:path";
-import { unzipSync, strFromU8, zipSync } from "fflate";
+import { strFromU8, zipSync } from "fflate";
import { Hono } from "hono";
import {
listInstalledSkills,
@@ -35,6 +35,7 @@ import {
MAX_FILE_BYTES,
MAX_TOTAL_BYTES,
skillTooLarge,
+ unzipBounded,
} from "../../services/skill-import-limits.js";
/** Decoded zip cap: aligned with the Agent snapshot import (stays within the 20MB body limit after base64). */
@@ -65,34 +66,22 @@ interface ArchiveSkill {
* Decodes and validates an uploaded skill zip. Accepted layouts: SKILL.md at the zip root
* (name comes from frontmatter), or exactly one top-level directory containing SKILL.md
* (the directory name is the Skill name, consistent with listInstalledSkills where the
- * directory name always wins). Directory entries are ignored (paths recreate them); every
- * file path is zip-slip-checked and the count/size limits enforced before anything is
- * returned. Frontmatter must parse to a non-null name, and the resolved Skill name must
+ * directory name always wins). Directory entries are ignored (paths recreate them); the count
+ * and size limits are enforced by unzipBounded before anything inflates, and every file path is
+ * zip-slip-checked. Frontmatter must parse to a non-null name, and the resolved Skill name must
* match PLUGIN_NAME_PATTERN.
*/
function parseSkillArchive(archive: Buffer): ArchiveSkill {
let entries: Record<string, Uint8Array>;
try {
- entries = unzipSync(new Uint8Array(archive));
- } catch {
+ entries = unzipBounded(new Uint8Array(archive));
+ } catch (err) {
+ if (err instanceof HttpError) throw err;
throw badRequest("dataBase64 is not a valid zip archive.");
}
const files = Object.entries(entries).filter(([name]) => !name.endsWith("/"));
if (files.length === 0) throw badRequest("The zip archive contains no files.");
- if (files.length > MAX_ARCHIVE_FILES) {
- throw badRequest(`The zip archive exceeds the ${MAX_ARCHIVE_FILES}-file limit.`);
- }
- let total = 0;
- for (const [name, data] of files) {
- assertSafeEntryPath(name);
- if (data.byteLength > MAX_FILE_BYTES) {
- throw badRequest(`Zip entry exceeds the 5MB uncompressed limit: ${name}`);
- }
- total += data.byteLength;
- if (total > MAX_TOTAL_BYTES) {
- throw badRequest("The zip archive exceeds the 20MB uncompressed limit.");
- }
- }
+ for (const [name] of files) assertSafeEntryPath(name);
const names = files.map(([name]) => name);
let prefix = "";
let dirName: string | undefined;
@@ -116,7 +105,19 @@ function parseSkillArchive(archive: Buffer): ArchiveSkill {
`Invalid skill name ${JSON.stringify(name)}: only letters, digits, "_" and "-" are allowed.`,
);
}
- return { name, files: new Map(files.map(([n, data]) => [n.slice(prefix.length), data])) };
+ return {
+ name,
+ files: new Map(
+ files.map(([n, data]) => {
+ const rel = n.slice(prefix.length);
+ // A file entry named exactly like the top-level directory leaves nothing behind once
+ // the prefix comes off, and the write would land on the Skill directory itself rather
+ // than a file in it — EISDIR, surfacing as a 500 instead of a rejection.
+ if (rel === "") throw badRequest(`Invalid zip entry path (names a directory): ${n}`);
+ return [rel, data] as const;
+ }),
+ ),
+ };
}
/**
diff --git a/packages/server/src/services/skill-import-limits.ts b/packages/server/src/services/skill-import-limits.ts
index 27f2d5ac..35f5cb11 100644
--- a/packages/server/src/services/skill-import-limits.ts
+++ b/packages/server/src/services/skill-import-limits.ts
@@ -2,14 +2,55 @@
* Caps shared by every path that pulls Skill files in from outside the library — the archive
* upload/download routes and the directory import. One set of numbers, so a limit raised for one
* entry point cannot quietly leave another behind, and one message, so the failure reads the same
- * wherever the user hit it.
+ * wherever the user hit it. `unzipBounded` is where they are enforced on the way in, since an
+ * archive can only be bounded before it is inflated.
*/
+import { unzipSync } from "fflate";
import { HttpError } from "../http/errors.js";
+import { badRequest } from "../http/validate.js";
export const MAX_ARCHIVE_FILES = 200;
export const MAX_FILE_BYTES = 5 * 1024 * 1024;
export const MAX_TOTAL_BYTES = 20 * 1024 * 1024;
+/**
+ * `unzipSync` with the caps above enforced from the central directory, before a byte is inflated.
+ *
+ * They have to be read there, because `unzipSync` allocates a buffer of each entry's declared
+ * uncompressed size and inflates into it — so caps measured on what comes back bound nothing.
+ * Zeros deflate at roughly 1000:1, which turns the largest archive the route accepts into
+ * gigabytes of allocation; and an entry whose header overstates its size hands back a short view
+ * onto a buffer of the declared length, passing every after-the-fact byte check outright.
+ *
+ * Bounding against the declared sizes is sound in the other direction too: the buffer is exactly
+ * the declared size and fflate never grows it, so an entry can only ever yield fewer bytes than
+ * it claimed. Directory entries carry no content and are left to the caller to filter.
+ *
+ * Throws the caps as 400s, matching the archive route this was factored out of; a corrupt
+ * archive still throws whatever fflate throws, for the caller to translate.
+ */
+export function unzipBounded(archive: Uint8Array): Record<string, Uint8Array> {
+ let files = 0;
+ let declared = 0;
+ return unzipSync(archive, {
+ filter: ({ name, originalSize }) => {
+ if (name.endsWith("/")) return true;
+ files += 1;
+ if (files > MAX_ARCHIVE_FILES) {
+ throw badRequest(`The zip archive exceeds the ${MAX_ARCHIVE_FILES}-file limit.`);
+ }
+ if (originalSize > MAX_FILE_BYTES) {
+ throw badRequest(`Zip entry exceeds the 5MB uncompressed limit: ${name}`);
+ }
+ declared += originalSize;
+ if (declared > MAX_TOTAL_BYTES) {
+ throw badRequest("The zip archive exceeds the 20MB uncompressed limit.");
+ }
+ return true;
+ },
+ });
+}
+
export function skillTooLarge(): HttpError {
return new HttpError(
413,
diff --git a/packages/server/test/skills.test.ts b/packages/server/test/skills.test.ts
index dfdc5c15..b38f5907 100644
--- a/packages/server/test/skills.test.ts
+++ b/packages/server/test/skills.test.ts
@@ -355,6 +355,39 @@ describe("skills api", () => {
const zipB64 = (files: Record<string, Uint8Array>): string =>
Buffer.from(zipSync(files)).toString("base64");
+ /**
+ * Builds a zip and then rewrites the declared uncompressed size of the named entries, in both
+ * the local header and the central-directory record, leaving the compressed payload untouched.
+ * That is the shape of a zip bomb: the size a reader allocates comes from the header, not from
+ * the bytes that follow it.
+ */
+ const zipB64Declaring = (
+ files: Record<string, Uint8Array>,
+ declared: Record<string, number>,
+ ): string => {
+ const zip = zipSync(files);
+ const view = new DataView(zip.buffer, zip.byteOffset, zip.byteLength);
+ const decoder = new TextDecoder();
+ const entryName = (start: number, lenAt: number, nameAt: number): string =>
+ decoder.decode(
+ zip.subarray(start + nameAt, start + nameAt + view.getUint16(start + lenAt, true)),
+ );
+ for (let i = 0; i + 4 <= zip.byteLength; i++) {
+ const signature = view.getUint32(i, true);
+ // Local file header (PK\3\4): name length at +26, name at +30, uncompressed size at +22.
+ if (signature === 0x04034b50) {
+ const size = declared[entryName(i, 26, 30)];
+ if (size !== undefined) view.setUint32(i + 22, size, true);
+ }
+ // Central-directory record (PK\1\2): name length at +28, name at +46, size at +24.
+ if (signature === 0x02014b50) {
+ const size = declared[entryName(i, 28, 46)];
+ if (size !== undefined) view.setUint32(i + 24, size, true);
+ }
+ }
+ return Buffer.from(zip).toString("base64");
+ };
+
it("archive: nested top-dir layout — all files written (subdirs preserved), directory name wins over frontmatter", async () => {
await createPlainAgent("zip_agent");
const url = `${base("zip_agent")}/archive`;
@@ -409,6 +442,16 @@ describe("skills api", () => {
});
expect(res.status, entry).toBe(400);
}
+ // A file entry named exactly like the top-level directory leaves an empty path once the
+ // prefix is stripped, so the write lands on the skill directory itself (EISDIR) instead of
+ // a file inside it — a rejection, not a crash.
+ const collision = await owner.post(`${url}/archive`, {
+ dataBase64: zipB64({
+ "zip-skill/SKILL.md": strToU8(ZIP_SKILL_MD),
+ "zip-skill": strToU8("x"),
+ }),
+ });
+ expect(collision.status).toBe(400);
const list = (await (await owner.get(url)).json()) as AgentSkillsResponse;
expect(list.skills).toEqual([]);
});
@@ -477,6 +520,33 @@ describe("skills api", () => {
expect((await owner.post(url, { dataBase64: zipB64(total) })).status).toBe(400);
});
+ it("archive: the uncompressed caps come off the central directory, not off what inflated", async () => {
+ await createPlainAgent("zip_declared_agent");
+ const url = `${base("zip_declared_agent")}/archive`;
+ // Both archives are a few hundred bytes on the wire and inflate to one byte per entry, so
+ // caps measured on what came back would pass them — while the reader has already allocated
+ // every declared byte to inflate into.
+ const perFile = zipB64Declaring(
+ { "zip-skill/SKILL.md": strToU8(ZIP_SKILL_MD), "zip-skill/big.bin": strToU8("x") },
+ { "zip-skill/big.bin": 6 * 1024 * 1024 },
+ );
+ expect((await owner.post(url, { dataBase64: perFile })).status).toBe(400);
+ // Six entries, each declaring less than the 5MB per-file cap and together more than 20MB.
+ const parts: Record<string, Uint8Array> = { "zip-skill/SKILL.md": strToU8(ZIP_SKILL_MD) };
+ const declared: Record<string, number> = {};
+ for (let i = 0; i < 6; i++) {
+ parts[`zip-skill/part${i}.bin`] = strToU8("x");
+ declared[`zip-skill/part${i}.bin`] = 4 * 1024 * 1024;
+ }
+ expect((await owner.post(url, { dataBase64: zipB64Declaring(parts, declared) })).status).toBe(
+ 400,
+ );
+ const list = (await (
+ await owner.get(base("zip_declared_agent"))
+ ).json()) as AgentSkillsResponse;
+ expect(list.skills).toEqual([]);
+ });
+
it("archive: already installed is 409 skill_exists; overwrite replaces the directory (stale files removed)", async () => {
await createPlainAgent("zip_over_agent");
const url = `${base("zip_over_agent")}/archive`;