Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

fix(ok): decode multipart upload filenames as UTF-8 (PRD-7993) (#3466)

Andrew Mikofalvye0f9229a586d
diff --git a/.changeset/upload-filename-charset.md b/.changeset/upload-filename-charset.md
new file mode 100644
index 000000000..c9f916f34
--- /dev/null
+++ b/.changeset/upload-filename-charset.md
@@ -0,0 +1,9 @@
+---
+'@inkeep/open-knowledge': patch
+---
+
+Uploaded filenames with non-ASCII characters are no longer mangled. Dragging a file named `café.png` into a document stored it as `café.png`; a macOS screenshot, whose name contains a narrow no-break space before AM/PM, arrived as `Screenshot ... 10.48.44â_AM.png`. Non-Latin scripts fared worse still, with `会議メモ.pdf` losing nearly all of its characters. The multipart parser was reading the filename as Latin-1, while browsers and every other conformant client send it as UTF-8, so each multi-byte character was split into one garbled character per byte before anything else in the upload path could see it. Both upload endpoints are affected, asset uploads and skill imports alike.
+
+Files uploaded before this release keep their mangled names. The original name was never recorded anywhere, so there is nothing to restore them from, and the mangling is not reliably reversible. Links and images still resolve, because the stored name and the reference in your document have always matched each other. Renaming the file fixes the display.
+
+One narrow tradeoff: a client that genuinely sends a Latin-1 filename, rather than the UTF-8 that browsers and standard HTTP tooling send, will now have the non-ASCII characters in that name read as unrecognized. An asset upload stores them as underscores; a skill import, which does not run the same name cleanup, keeps them as the standard replacement character. There is no signal on the wire that would let the server tell the two cases apart, and UTF-8 is what browsers and every standard client send.
diff --git a/biome-plugins/README.md b/biome-plugins/README.md
index 58e08beb7..f7736c3a6 100644
--- a/biome-plugins/README.md
+++ b/biome-plugins/README.md
@@ -238,6 +238,29 @@ The rule does NOT catch: bare `exec(...)` (the identifier is too commonly shadow
Plugin: [`biome-plugins/require-windowshide-on-spawn.grit`](require-windowshide-on-spawn.grit). Fixture: [`biome-plugins/__fixtures__/require-windowshide-on-spawn.fixture.tsx`](__fixtures__/require-windowshide-on-spawn.fixture.tsx). Test: [`packages/server/src/lint-plugins/require-windowshide-on-spawn.test.ts`](../packages/server/src/lint-plugins/require-windowshide-on-spawn.test.ts). See [PRECEDENTS.md #42](../PRECEDENTS.md#custom-lint-enforcement-precedent-42) for the GritQL-plugin convention.
+### `require-utf8-multipart-parser.grit`
+
+Multipart filename charset correctness. `busboy(...)` may only be constructed inside [`packages/server/src/multipart.ts`](../packages/server/src/multipart.ts); every other multipart body is parsed through its `createMultipartParser(req, limits)` factory, which hardcodes `defParamCharset: 'utf8'`.
+
+**Why.** busboy defaults `defParamCharset` to `latin1` — an inheritance from `Content-Disposition`'s original MIME/email definition, not from the `multipart/form-data` rules. RFC 7578 governs this surface instead. It issues no receiver mandate — section 5.1.3 is explicit that a parser cannot assume any particular charset was used — so the default is ours to choose, and UTF-8 is the only defensible choice: section 4.2 records that "the encoding used for the file names is typically UTF-8", and the sender-side form-charset ladder in section 5.1.2 terminates at UTF-8. Browsers and Node/undici both put the name on the wire as raw UTF-8 bytes in the plain `filename=` parameter, so at the default every multi-byte sequence is read back as one mojibake code point per byte: `café.png` arrives as `café.png`, `会議メモ.pdf` loses essentially all of its information. The damage lands at the transport-decode boundary, before any sanitizer or storage layer sees it, and it is not invertible there — the mojibake is indistinguishable from a filename the user legitimately owns.
+
+The omission is invisible in review: `busboy({ headers, limits })` reads as complete unless you happen to know the default. It shipped at two construction sites for exactly that reason, the second copied from the first along with its `limits` shape, which is why this is a mechanical gate rather than a review convention.
+
+**Presence match, not absence match.** The sibling `require-windowshide-on-spawn` rule is shaped as "the call must contain `windowsHide`", because there the option's only correct value is `true`. That shape is too weak here: "the call must contain `defParamCharset:`" is satisfied by `defParamCharset: 'latin1'`, which passes lint and reintroduces the bug. The factory takes no charset parameter, so routing through it removes the value hole entirely and reduces this rule to a plain presence check on the constructor. Both the wrong-value and the right-value-wrong-place cases are pinned as must-fire fixtures.
+
+**Registered via `overrides[].plugins`** repo-wide (`**/*.ts`, `**/*.tsx`, `**/*.mts`) rather than per-package: server owns the only busboy dependency today, and that is exactly the state a new dependency elsewhere would change, silently. Excluded are `!packages/server/src/multipart.ts` (the one sanctioned construction site), `!**/*.test.ts`, `!**/*.test.tsx`, and `!**/*.test-helper.ts`. The test exclusion is deliberate rather than copied: [`packages/server/src/http/local-api-dispatch.test.ts`](../packages/server/src/http/local-api-dispatch.test.ts) drives its own parser inside a synthetic `/api/upload-lite` handler that counts bytes and never decodes a non-ASCII name.
+
+**Opting out.** There is no legitimate second construction site. A caller that needs different parser options (`preservePath`, `highWaterMark`, …) should widen the factory — that keeps the charset decision in one place, and forces the path-traversal reasoning `preservePath` demands rather than letting it be set in passing. If you genuinely must construct in place, suppress the one call with a reason:
+
+```ts
+// biome-ignore lint/plugin/require-utf8-multipart-parser: <reason>
+const bb = busboy({ headers, defParamCharset: 'utf8' });
+```
+
+The rule does NOT catch: member calls (`parsers.busboy(...)` — a different AST); a call through a renamed binding (`import bb from 'busboy'; bb(...)`). Both are defeatable on purpose rather than by accident. A `ReturnType<typeof busboy>` type annotation is not a call expression and correctly does not fire; it is pinned as a negative fixture so a future pattern change cannot silently start flagging type positions. The behavioural backstop for all of these is [`packages/app/tests/integration/api-error-envelope/upload-filename-charset.test.ts`](../packages/app/tests/integration/api-error-envelope/upload-filename-charset.test.ts), which asserts the decode end to end over real HTTP through both endpoints.
+
+Plugin: [`biome-plugins/require-utf8-multipart-parser.grit`](require-utf8-multipart-parser.grit). Fixture: [`biome-plugins/__fixtures__/require-utf8-multipart-parser.fixture.tsx`](__fixtures__/require-utf8-multipart-parser.fixture.tsx). Test: [`packages/server/src/lint-plugins/require-utf8-multipart-parser.test.ts`](../packages/server/src/lint-plugins/require-utf8-multipart-parser.test.ts). See [PRECEDENTS.md #42](../PRECEDENTS.md#custom-lint-enforcement-precedent-42) for the GritQL-plugin convention.
+
### `no-blind-agent-host-fanout.grit`
Scope discipline for user-global Agent Skill installs. Bans the `skills` CLI npm specs (`skills@~1.5.0` and its caret / exact / `latest` variants) and the bare `'--agent'` argv token anywhere under `packages/{server,cli}/src/**`.
diff --git a/biome-plugins/__fixtures__/require-utf8-multipart-parser.fixture.tsx b/biome-plugins/__fixtures__/require-utf8-multipart-parser.fixture.tsx
new file mode 100644
index 000000000..87eff2f4f
--- /dev/null
+++ b/biome-plugins/__fixtures__/require-utf8-multipart-parser.fixture.tsx
@@ -0,0 +1,62 @@
+// FIXTURE - drives `require-utf8-multipart-parser.test.ts` via shell-out to
+// `pnpm exec biome check` on this path. The override's `includes[]` self-includes
+// this file, so the rule DOES apply here; what keeps the 3 fires below out of a
+// normal `pnpm run lint` is that `lint:biome` passes biome an explicit path list
+// (`packages docs *.json *.jsonc *.ts`) that never visits `biome-plugins/`.
+//
+// 3 expected diagnostic fires (one per direct `busboy(...)` construction):
+// P1 the exact pre-fix shape that shipped the bug (no charset declared)
+// P2 an explicit `defParamCharset: 'latin1'` - the case an absence-match rule
+// would wave through, which is why this rule is a presence match
+// P3 an inline `defParamCharset: 'utf8'` - correct today, but it re-opens the
+// value hole the factory exists to close
+//
+// Negatives (0 fires): the sanctioned `createMultipartParser(...)` call, a
+// `ReturnType<typeof busboy>` type annotation (the form a call site uses to
+// name a parser's type without constructing one), a member call, and an
+// unrelated identifier. Exact-equality (`toBe(3)`) catches false-negative regressions
+// (< 3) and false-positive widenings (> 3) - the type-annotation negative in
+// particular guards against a pattern change that starts matching type positions.
+//
+// This file deliberately contains no non-ASCII characters. The defect under
+// enforcement is a charset misdecode, and a fixture whose bytes an editor may
+// silently rewrite is the wrong place to encode one.
+
+type Headers = Record<string, string>;
+type Limits = Record<string, number>;
+interface Req {
+ headers: Headers;
+}
+declare function busboy(cfg: { headers: Headers; defParamCharset?: string; limits?: Limits }): {
+ on: (event: string, cb: () => void) => void;
+};
+declare function createMultipartParser(req: Req, limits: Limits): ReturnType<typeof busboy>;
+declare function notBusboy(cfg: object): unknown;
+declare const parsers: { busboy: (cfg: object) => unknown };
+declare const req: Req;
+
+// === Positive cases - must fire (3 total) ===
+
+// (P1) The shape that shipped the bug, copied from `readUploadBody`.
+export const p1 = busboy({
+ headers: req.headers,
+ limits: { files: 1, fields: 10, fieldSize: 2048 },
+});
+// (P2) A declared charset that is the WRONG one. An absence-match rule
+// ("must contain `defParamCharset:`") would accept this.
+export const p2 = busboy({ headers: req.headers, defParamCharset: 'latin1' });
+// (P3) The right value, still at the wrong place - the next editor of this line
+// has no signal that the literal is load-bearing.
+export const p3 = busboy({ headers: req.headers, defParamCharset: 'utf8' });
+
+// === Negative cases - must NOT fire ===
+
+// (1) The sanctioned form.
+export const n1 = createMultipartParser(req, { files: 1 });
+// (2) Type position, not a call expression. `api-extension.ts` carried exactly
+// this annotation at both call sites before the factory landed.
+export type N2 = ReturnType<typeof busboy>;
+// (3) Member call - a different AST (documented gap).
+export const n3 = parsers.busboy({ headers: req.headers });
+// (4) An unrelated identifier - the rule matches a literal callee name.
+export const n4 = notBusboy({ headers: req.headers });
diff --git a/biome-plugins/require-utf8-multipart-parser.grit b/biome-plugins/require-utf8-multipart-parser.grit
new file mode 100644
index 000000000..aa3344f51
--- /dev/null
+++ b/biome-plugins/require-utf8-multipart-parser.grit
@@ -0,0 +1,69 @@
+// require-utf8-multipart-parser — multipart filename charset correctness.
+//
+// `busboy(...)` may only be constructed inside
+// `packages/server/src/multipart.ts`. Everything else parses multipart bodies
+// through its factory:
+//
+// const bb = createMultipartParser(req, { files: 1, fields: 10 }); // only form
+//
+// Why: busboy's `defParamCharset` defaults to `latin1`, an inheritance from
+// `Content-Disposition`'s original MIME/email definition. RFC 7578 governs
+// `multipart/form-data` instead. It issues no receiver mandate, so the default
+// is ours to pick, and UTF-8 is the only defensible pick: section 4.2 records
+// that file names are "typically UTF-8", and it is what browsers and
+// Node/undici actually send. Left at its default, busboy reads every
+// multi-byte sequence back as one mojibake code point per byte, at the
+// transport-decode boundary — before any sanitizer or storage layer can see it,
+// and irreversibly, because the damage is indistinguishable from a filename the
+// user legitimately owns.
+//
+// The omission is invisible in review: `busboy({ headers, limits })` reads as
+// complete unless you happen to know the default. It shipped twice for exactly
+// that reason — the second construction site was copied from the first, limits
+// and all — which is why this is a mechanical gate rather than a convention.
+//
+// This is a PRESENCE match, not an absence match, and that is deliberate. A
+// rule shaped as "a `busboy(...)` call must contain `defParamCharset:`" would be
+// satisfied by `defParamCharset: 'latin1'` — it enforces that a charset is
+// declared, not that the right one is. The factory takes no charset parameter,
+// so routing through it removes the value hole entirely and reduces this rule to
+// a plain presence check.
+//
+// OPTING OUT — there is no legitimate second construction site. A caller that
+// needs different parser options (`preservePath`, `highWaterMark`, …) should
+// widen the factory, which keeps the charset decision in one place and forces
+// the path-traversal reasoning `preservePath` demands. If you genuinely must
+// construct in place, suppress the one call with a reason:
+//
+// // biome-ignore lint/plugin/require-utf8-multipart-parser: <reason>
+// const bb = busboy({ headers, defParamCharset: 'utf8' });
+//
+// Registered via `overrides[].plugins` repo-wide rather than per-package:
+// server owns the only busboy dependency today, and that is exactly the state a
+// new dependency elsewhere would change, silently. The factory module itself and
+// tests are excluded. The test exclusion covers the synthetic `/api/upload-lite`
+// handler in `http/local-api-dispatch.test.ts`, which drives its own parser to
+// count bytes and never decodes a non-ASCII name; that was a deliberate call,
+// not an oversight.
+//
+// The rule keys on the CALL-EXPRESSION CALLEE IDENTIFIER. Known gaps, stated
+// honestly: a member call (`parsers.busboy(...)`) is a different AST and is not
+// matched; neither is a call through a renamed binding (`import bb from
+// 'busboy'; bb(...)`). Both are defeatable on purpose rather than by accident,
+// and the behavioural backstop is
+// `packages/app/tests/integration/api-error-envelope/upload-filename-charset.test.ts`,
+// which asserts the decode end to end through both endpoints. A `ReturnType<typeof
+// busboy>` type annotation is NOT a call expression and does not fire — pinned
+// as a negative fixture case so a future pattern change cannot silently start
+// flagging type positions.
+//
+// See PRECEDENTS.md #42 (custom Biome enforcement is GritQL plugins).
+
+language js
+
+`busboy($...)` as $call where {
+ register_diagnostic(
+ span = $call,
+ message = "busboy constructed directly - route multipart parsing through `createMultipartParser(...)` from `packages/server/src/multipart.ts`, which hardcodes `defParamCharset: 'utf8'`. busboy defaults that option to `latin1`, so every non-ASCII filename is mojibaked at the transport-decode boundary before any sanitizer sees it, irreversibly; RFC 7578 section 4.2 records that multipart/form-data file names are typically UTF-8, which is what every standard client sends. Need different parser options? widen the factory rather than construct here. See https://github.com/inkeep/open-knowledge/blob/main/biome-plugins/README.md#require-utf8-multipart-parsergrit"
+ )
+}
diff --git a/biome.jsonc b/biome.jsonc
index 974f53331..71cfb6b18 100644
--- a/biome.jsonc
+++ b/biome.jsonc
@@ -124,6 +124,35 @@
],
"plugins": ["./biome-plugins/require-windowshide-on-spawn.grit"]
},
+ {
+ // Multipart filename charset: busboy may only be constructed inside
+ // `multipart.ts`, whose factory hardcodes `defParamCharset: 'utf8'`.
+ // busboy defaults that option to `latin1`, which mojibakes every
+ // non-ASCII filename at the transport-decode boundary, irreversibly and
+ // invisibly in review. Repo-wide rather than server-scoped: server owns
+ // the only busboy dependency today, and that is exactly the state a new
+ // dependency in another package would change, silently. The factory
+ // itself is excluded so it can make the one sanctioned call. Tests are
+ // excluded deliberately, not by copy: `http/local-api-dispatch.test.ts`
+ // drives its own parser in a synthetic `/api/upload-lite` handler that
+ // counts bytes and never decodes a non-ASCII name. `**/*.mts` matches
+ // nothing today (the sibling class-proof override omits it) and is here
+ // as forward coverage: this gate exists because the defect spread by
+ // copy-paste, so an extension it cannot see is a hole by construction.
+ "includes": [
+ "**/*.ts",
+ "**/*.tsx",
+ "**/*.mts",
+ "!**/node_modules/**",
+ "!**/dist/**",
+ "!**/*.test.ts",
+ "!**/*.test.tsx",
+ "!**/*.test-helper.ts",
+ "!packages/server/src/multipart.ts",
+ "biome-plugins/__fixtures__/require-utf8-multipart-parser.fixture.tsx"
+ ],
+ "plugins": ["./biome-plugins/require-utf8-multipart-parser.grit"]
+ },
{
// Scope discipline for user-global Agent Skill installs (issue #820).
// OK writes these dirs itself, gated on `detectUserSkillHosts`; shelling
diff --git a/packages/app/tests/integration/api-error-envelope/upload-filename-charset.test.ts b/packages/app/tests/integration/api-error-envelope/upload-filename-charset.test.ts
new file mode 100644
index 000000000..a3a161900
--- /dev/null
+++ b/packages/app/tests/integration/api-error-envelope/upload-filename-charset.test.ts
@@ -0,0 +1,331 @@
+/**
+ * Charset fidelity of the multipart `filename` parameter, end to end.
+ *
+ * Contract: a filename supplied by the client must reach the server's filename
+ * handling as the same sequence of Unicode scalar values the client sent.
+ * Browsers and Node/undici both put the name on the wire as raw UTF-8 bytes in
+ * the plain `filename=` parameter of `Content-Disposition` -- never as an
+ * RFC 5987 / RFC 2231 extended `filename*` -- so a parser that reads that
+ * parameter as latin1 turns every multi-byte sequence into one mojibake code
+ * point per byte, irreversibly.
+ *
+ * Both multipart entry points are covered, because the same decode decision is
+ * made independently at each. Both land a BASENAME: busboy strips any directory
+ * component from `filename` unless `preservePath` is set, and it is not set at
+ * either site. What differs is only what happens after the decode:
+ * - `POST /api/upload` -- the name is sanitized, then stored as an asset.
+ * - `POST /api/skill-upload` -- no sanitizer runs, so the decoded name must
+ * round-trip byte-identically.
+ *
+ * Fidelity: real server, real HTTP, real multipart serializer, real parser,
+ * real disk. Nothing on the failing seam is stubbed. A test that mocked the
+ * multipart parser would be asserting the stub's decoding, which is the very
+ * behavior under test.
+ *
+ * SOURCE-INTEGRITY RULE for this file: every non-ASCII character in a fixture
+ * is written as a `\u` escape, never as a literal. U+202F NARROW NO-BREAK SPACE
+ * in particular is silently rewritten to an ASCII space by several editors and
+ * file-writing tools, and that rewrite would make this suite pass against the
+ * exact defect it pins. The `fixture integrity` tests re-derive the code points
+ * at runtime, so a fixture that loses its characters fails loudly instead of
+ * quietly weakening every assertion below it.
+ */
+
+import { mkdirSync, readdirSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
+import { HARNESS_BOOT_TIMEOUT_MS } from '../harness-boot-timeout';
+import { createTestServer, type TestServer } from '../test-harness';
+
+let server: TestServer;
+const base = () => `http://127.0.0.1:${server.port}`;
+
+/**
+ * U+202F NARROW NO-BREAK SPACE -- what macOS 13+ puts before AM/PM in a
+ * screenshot filename. UTF-8 `E2 80 AF`; read as latin1 it becomes the three
+ * code points U+00E2 U+0080 U+00AF.
+ */
+const NNBSP = '\u202F';
+
+interface UploadCase {
+ /**
+ * Also the per-case parent directory. Same-dir sha256 dedup and filesystem
+ * collision-retry would otherwise let one case return a sibling's basename
+ * and hide a decode failure behind a green assertion.
+ */
+ id: string;
+ /** The name the client puts on the wire. */
+ uploaded: string;
+ /** The basename the server must produce. */
+ expected: string;
+ /**
+ * Code points `uploaded` must still contain at runtime -- the guard against
+ * a fixture that got normalized on its way into this file.
+ */
+ requiredCodePoints: number[];
+}
+
+const UPLOAD_CASES: readonly UploadCase[] = [
+ {
+ // The reported real-world case. U+202F is outside `sanitizeFilename`'s
+ // whitelist, so it becomes `_` even after a correct decode -- that is the
+ // sanitizer's pre-existing, deliberate policy and is not what this pins.
+ // What must disappear is the U+00E2 mojibake a latin1 read produces.
+ id: 'macos-screenshot-nnbsp',
+ uploaded: `Screenshot 2026-08-12 at 10.48.44${NNBSP}AM.png`,
+ expected: 'Screenshot 2026-08-12 at 10.48.44_AM.png',
+ requiredCodePoints: [0x202f],
+ },
+ {
+ // Japanese: the worst-affected class. Every code point is three UTF-8
+ // bytes, so a latin1 read destroys essentially all of the information.
+ id: 'cjk-japanese',
+ uploaded: '\u4F1A\u8B70\u30E1\u30E2.png',
+ expected: '\u4F1A\u8B70\u30E1\u30E2.png',
+ requiredCodePoints: [0x4f1a, 0x8b70, 0x30e1, 0x30e2],
+ },
+ {
+ id: 'hangul',
+ uploaded: '\uBB38\uC11C.png',
+ expected: '\uBB38\uC11C.png',
+ requiredCodePoints: [0xbb38, 0xc11c],
+ },
+ {
+ id: 'cyrillic',
+ uploaded: '\u041F\u0440\u043E\u0435\u043A\u0442.png',
+ expected: '\u041F\u0440\u043E\u0435\u043A\u0442.png',
+ requiredCodePoints: [0x041f, 0x0442],
+ },
+ {
+ id: 'arabic',
+ uploaded: '\u0642\u0635\u0629.png',
+ expected: '\u0642\u0635\u0629.png',
+ requiredCodePoints: [0x0642, 0x0635, 0x0629],
+ },
+ {
+ // Astral plane -- a surrogate pair in UTF-16, four bytes in UTF-8.
+ id: 'emoji-astral',
+ uploaded: 'party \u{1F389}.png',
+ expected: 'party \u{1F389}.png',
+ requiredCodePoints: [0x1f389],
+ },
+ {
+ // Precomposed and decomposed are DIFFERENT byte sequences and must both
+ // survive unchanged; nothing on this path is entitled to normalize them.
+ id: 'latin-precomposed',
+ uploaded: 'caf\u00E9.png',
+ expected: 'caf\u00E9.png',
+ requiredCodePoints: [0x00e9],
+ },
+ {
+ id: 'latin-decomposed',
+ uploaded: 'cafe\u0301.png',
+ expected: 'cafe\u0301.png',
+ requiredCodePoints: [0x0301],
+ },
+ {
+ // Control: a fix that mangles the common case must not pass.
+ id: 'plain-ascii',
+ uploaded: 'plain-ascii.png',
+ expected: 'plain-ascii.png',
+ requiredCodePoints: [],
+ },
+];
+
+/** Minimal valid PNG (1x1 transparent pixel). */
+function pngFixture(): Buffer {
+ return Buffer.from(
+ 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVQI12NgAAIABQABNjN9GQAAAABJRElEQrkJggg==',
+ 'base64',
+ );
+}
+
+function codePointsOf(s: string): number[] {
+ return [...s].map((c) => c.codePointAt(0) as number);
+}
+
+/** Hex code points -- readable evidence of WHICH bytes diverged on failure. */
+function hexPointsOf(s: string): string {
+ return codePointsOf(s)
+ .map((p) => p.toString(16).toUpperCase().padStart(4, '0'))
+ .join(' ');
+}
+
+function assertFixtureIntact(id: string, value: string, required: number[]): void {
+ const points = codePointsOf(value);
+ for (const cp of required) {
+ expect(points, `fixture ${id} lost U+${cp.toString(16).toUpperCase()}`).toContain(cp);
+ }
+ // Keyed off `required`, not off the id: a case declares whether it is meant
+ // to carry non-ASCII by whether it lists any code points. Deriving it from
+ // the id instead would hold only while exactly one case is ASCII-only and is
+ // named a particular way, and would misfire on the next ASCII case added.
+ const hasNonAscii = points.some((p) => p > 0x7f);
+ expect(hasNonAscii, `fixture ${id} non-ASCII presence`).toBe(required.length > 0);
+}
+
+beforeAll(async () => {
+ server = await createTestServer();
+ for (const c of UPLOAD_CASES) {
+ const dir = join(server.contentDir, 'docs', c.id);
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(join(dir, 'guide.md'), '# Guide\n');
+ }
+}, HARNESS_BOOT_TIMEOUT_MS);
+
+afterAll(async () => {
+ await server.cleanup();
+});
+
+describe('multipart filename charset -- POST /api/upload', () => {
+ test('fixture integrity: the uploaded names still carry their non-ASCII code points', () => {
+ // A literal U+202F is the one character here that tooling silently
+ // rewrites to U+0020. Pin its identity and its UTF-8 bytes.
+ expect(codePointsOf(NNBSP)).toEqual([0x202f]);
+ expect([...Buffer.from(NNBSP, 'utf8')]).toEqual([0xe2, 0x80, 0xaf]);
+
+ for (const c of UPLOAD_CASES) {
+ assertFixtureIntact(c.id, c.uploaded, c.requiredCodePoints);
+ }
+ });
+
+ for (const c of UPLOAD_CASES) {
+ test(`${c.id}: the uploaded filename survives the multipart decode`, async () => {
+ const form = new FormData();
+ form.append('parentDocName', `docs/${c.id}/guide.md`);
+ form.append('file', new Blob([pngFixture()]), c.uploaded);
+
+ const res = await fetch(`${base()}/api/upload`, { method: 'POST', body: form });
+ expect(res.status).toBe(200);
+
+ const body = (await res.json()) as { src: string; path: string; deduped: boolean };
+ expect(body.deduped).toBe(false);
+ expect(
+ hexPointsOf(body.src),
+ `sent U+ ${hexPointsOf(c.uploaded)}\nas string "${c.uploaded}" -> got "${body.src}"`,
+ ).toBe(hexPointsOf(c.expected));
+ expect(body.src).toBe(c.expected);
+ expect(body.path).toBe(`docs/${c.id}/${c.expected}`);
+
+ // The name the API reports is the name on disk. Compared under NFC
+ // because a filesystem is entitled to store its own normal form of the
+ // bytes we hand it; the byte-exact contract is the response assertion.
+ const entries = readdirSync(join(server.contentDir, 'docs', c.id));
+ expect(entries.map((e) => e.normalize('NFC'))).toContain(c.expected.normalize('NFC'));
+ });
+ }
+});
+
+// The folder-upload branch of skill import: each part's multipart filename is
+// the file's path relative to the skill folder, exactly as a browser's
+// `webkitRelativePath` supplies it. Unlike the asset path, no sanitizer runs on
+// these names, so a correctly decoded one must round-trip byte-identically --
+// U+202F included, since the sanitizer's whitelist is not in play here.
+//
+// The wire name carries a directory component because that is what the client
+// actually sends; the assertion compares BASENAMES because busboy discards the
+// directory unless `preservePath` is set. Whether that directory survives is a
+// separate question from whether the bytes decode correctly, and pinning it
+// here would make this suite fail on a correct charset fix.
+
+const SKILL_NAME = 'charset-probe';
+
+interface BundleCase {
+ id: string;
+ /** Path relative to the skill folder, as the client puts it on the wire. */
+ wire: string;
+ /** The bundle filename the server must produce. */
+ expected: string;
+ requiredCodePoints: number[];
+}
+
+function bundleCase(id: string, name: string, requiredCodePoints: number[]): BundleCase {
+ return { id, wire: `references/${name}`, expected: name, requiredCodePoints };
+}
+
+const BUNDLE_CASES: readonly BundleCase[] = [
+ bundleCase('macos-screenshot-nnbsp', `Screenshot 2026-08-12 at 10.48.44${NNBSP}AM.md`, [0x202f]),
+ bundleCase('cjk-japanese', '\u4F1A\u8B70\u30E1\u30E2.md', [0x4f1a, 0x8b70, 0x30e1, 0x30e2]),
+ bundleCase('cyrillic', '\u041F\u0440\u043E\u0435\u043A\u0442.md', [0x041f, 0x0442]),
+ bundleCase('emoji-astral', 'party \u{1F389}.md', [0x1f389]),
+ bundleCase('latin-precomposed', 'caf\u00E9.md', [0x00e9]),
+ bundleCase('plain-ascii', 'plain-ascii.md', []),
+];
+
+const SKILL_MD = [
+ '---',
+ `name: ${SKILL_NAME}`,
+ 'description: Use when probing multipart filename decoding.',
+ '---',
+ '',
+ '# Charset probe',
+ '',
+ 'Bundle files carry non-ASCII names.',
+ '',
+].join('\n');
+
+describe('multipart filename charset -- POST /api/skill-upload', () => {
+ let uploadStatus = 0;
+ /** Failure context surfaced into the assertion message, not the console. */
+ let uploadDiagnostic = '';
+ let bundleFiles: Array<{ path: string; text: string | null }> = [];
+
+ beforeAll(async () => {
+ const form = new FormData();
+ form.append('files', new Blob([SKILL_MD]), `${SKILL_NAME}/SKILL.md`);
+ for (const c of BUNDLE_CASES) {
+ form.append('files', new Blob([`# ${c.id}\n`]), `${SKILL_NAME}/${c.wire}`);
+ }
+
+ const res = await fetch(`${base()}/api/skill-upload?scope=project`, {
+ method: 'POST',
+ body: form,
+ });
+ uploadStatus = res.status;
+ uploadDiagnostic = await res.text();
+ if (uploadStatus !== 200) return;
+
+ const get = await fetch(`${base()}/api/skill?name=${SKILL_NAME}&scope=project`);
+ if (get.status !== 200) {
+ uploadDiagnostic = `GET /api/skill -> ${get.status} ${await get.text()}`;
+ return;
+ }
+ const payload = (await get.json()) as {
+ skill: { files?: Array<{ path: string; text: string | null }> };
+ };
+ bundleFiles = payload.skill.files ?? [];
+ }, HARNESS_BOOT_TIMEOUT_MS);
+
+ test('fixture integrity: the bundle names still carry their non-ASCII code points', () => {
+ for (const c of BUNDLE_CASES) {
+ assertFixtureIntact(c.id, c.expected, c.requiredCodePoints);
+ }
+ });
+
+ test('the folder upload is accepted and the skill is readable', () => {
+ expect(uploadStatus, uploadDiagnostic).toBe(200);
+ expect(bundleFiles.length, uploadDiagnostic).toBe(BUNDLE_CASES.length);
+ });
+
+ for (const c of BUNDLE_CASES) {
+ test(`${c.id}: the bundle filename survives the multipart decode`, () => {
+ // Correlate by the part's own body, not by scanning the aggregate name
+ // list: a `toContain` over every returned name stays green even if two
+ // parts swapped filenames, which is the corruption class under test.
+ const entry = bundleFiles.find((f) => f.text === `# ${c.id}\n`);
+ const listing = JSON.stringify(bundleFiles.map((f) => f.path));
+ expect(entry, `no bundle entry carried the ${c.id} body; got ${listing}`).toBeDefined();
+ const name = (entry?.path ?? '').slice((entry?.path ?? '').lastIndexOf('/') + 1);
+ // Byte-exact rather than NFC-folded, unlike the asset assertion above:
+ // the skill bundle's only observable is the directory listing, so folding
+ // here would fold away the contract itself. APFS and ext4 both store the
+ // bytes they are handed, so a normal-form difference surfacing here would
+ // be a real finding about the substrate, not noise to be absorbed.
+ expect(
+ hexPointsOf(name),
+ `sent U+ ${hexPointsOf(c.expected)}\nas "${c.expected}" -> got "${name}"`,
+ ).toBe(hexPointsOf(c.expected));
+ expect(name).toBe(c.expected);
+ });
+ }
+});
diff --git a/packages/app/tests/integration/api-error-envelope/upload-filename-reference-resolution.test.ts b/packages/app/tests/integration/api-error-envelope/upload-filename-reference-resolution.test.ts
new file mode 100644
index 000000000..aa20aa586
--- /dev/null
+++ b/packages/app/tests/integration/api-error-envelope/upload-filename-reference-resolution.test.ts
@@ -0,0 +1,170 @@
+/**
+ * What the reader ends up with: an asset whose name survived the multipart
+ * decode, a markdown reference that resolves to it, and the same result through
+ * the in-process transport.
+ *
+ * `upload-filename-charset.test.ts` pins the decode itself, at the HTTP
+ * boundary, across a wide table of scripts. This file is narrower and reaches
+ * one step further in three directions it deliberately leaves open:
+ *
+ * 1. RAW on-disk bytes, unfolded. The charset suite compares the directory
+ * listing under NFC, because a filesystem is entitled to store its own
+ * normal form. That fold is correct there, but it means no test asserts the
+ * exact byte sequence a reader's filesystem holds.
+ * 2. The reference INSIDE a document. The charset suite stops at the API
+ * response. Nothing pinned that the link written into markdown resolves to
+ * a file that exists, which is the outcome a user actually experiences.
+ * 3. The in-process arm of the same handler. The MCP `write` tool encodes its
+ * own multipart body and dispatches through `localApi` rather than a
+ * socket. Coverage there was previously by composition only (a separate
+ * test proves the two transports deliver byte-identical bodies).
+ *
+ * SOURCE-INTEGRITY RULE: every non-ASCII character is a `\u` escape. A literal
+ * U+202F is silently rewritten to an ASCII space by several editors and
+ * file-writing tools, and that rewrite would make this file pass against the
+ * exact defect it pins.
+ */
+
+import { existsSync, mkdirSync, readdirSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
+import { HARNESS_BOOT_TIMEOUT_MS } from '../harness-boot-timeout';
+import {
+ agentWriteMd,
+ createTestServer,
+ pollUntil,
+ readTestDoc,
+ type TestServer,
+} from '../test-harness';
+
+let server: TestServer;
+
+/** U+202F NARROW NO-BREAK SPACE, as macOS puts it before AM/PM. */
+const NNBSP = '\u202F';
+/** What the client sends. */
+const SENT = `Screenshot 2026-08-12 at 10.48.44${NNBSP}AM.png`;
+/** What the server must store: no mojibake, U+202F sanitized to `_`. */
+const EXPECTED = 'Screenshot 2026-08-12 at 10.48.44_AM.png';
+/** U+00E2 in UTF-8 - the leading byte pair of the mojibake this fix removes. */
+const MOJIBAKE_LEAD = Buffer.from([0xc3, 0xa2]);
+
+const CJK = '\u4F1A\u8B70\u30E1\u30E2.png';
+
+/** Minimal valid PNG (1x1 transparent pixel). */
+function pngFixture(): Buffer {
+ return Buffer.from(
+ 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVQI12NgAAIABQABNjN9GQAAAABJRElEQrkJggg==',
+ 'base64',
+ );
+}
+
+/** Hex bytes - readable evidence of WHICH bytes diverged on failure. */
+function hexOf(s: string): string {
+ return [...Buffer.from(s, 'utf8')].map((b) => b.toString(16).padStart(2, '0')).join(' ');
+}
+
+function codePointsOf(s: string): number[] {
+ return [...s].map((c) => c.codePointAt(0) as number);
+}
+
+/**
+ * Seed a per-case parent directory. One per case for the same reason the
+ * charset suite uses one: the fixture bytes are identical, so a shared
+ * destination would let same-dir sha256 dedup return a sibling's basename and
+ * hide a decode failure behind a green assertion.
+ */
+function seedDir(id: string): string {
+ const dir = join(server.contentDir, 'docs', id);
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(join(dir, 'guide.md'), '# Guide\n');
+ return dir;
+}
+
+beforeAll(async () => {
+ server = await createTestServer();
+}, HARNESS_BOOT_TIMEOUT_MS);
+
+afterAll(async () => {
+ await server.cleanup();
+});
+
+describe('uploaded asset names, from the wire to the reader', () => {
+ test('fixture integrity: the sent names still carry their non-ASCII code points', () => {
+ // U+202F is the one character here that tooling silently rewrites to
+ // U+0020. Were that to happen, every assertion below would still compare a
+ // sent name against a stored name and still pass -- while no longer
+ // exercising a multi-byte sequence at all. Pin its identity and its bytes
+ // so the loss fails here instead of quietly emptying the suite.
+ expect(codePointsOf(NNBSP)).toEqual([0x202f]);
+ expect([...Buffer.from(NNBSP, 'utf8')]).toEqual([0xe2, 0x80, 0xaf]);
+ expect(codePointsOf(SENT)).toContain(0x202f);
+ expect(codePointsOf(CJK)).toEqual([0x4f1a, 0x8b70, 0x30e1, 0x30e2, 0x2e, 0x70, 0x6e, 0x67]);
+ });
+
+ test('the bytes on disk are the bytes the reader gets, and the reference resolves', async () => {
+ const id = 'ref-resolution';
+ const dir = seedDir(id);
+
+ const form = new FormData();
+ form.append('parentDocName', `docs/${id}/guide.md`);
+ form.append('file', new Blob([pngFixture()]), SENT);
+ const res = await fetch(`${server.baseUrl}/api/upload`, { method: 'POST', body: form });
+ expect(res.status).toBe(200);
+ const body = (await res.json()) as { src: string; deduped: boolean };
+ expect(body.deduped).toBe(false);
+
+ // (1) Raw bytes on disk, no NFC fold.
+ const entries = readdirSync(dir).filter((e) => e !== 'guide.md');
+ expect(entries, `dir listing: ${JSON.stringify(readdirSync(dir))}`).toHaveLength(1);
+ const stored = entries[0] as string;
+ expect(hexOf(stored), `sent ${hexOf(SENT)} -> stored "${stored}"`).toBe(hexOf(EXPECTED));
+ expect(
+ Buffer.from(stored, 'utf8').includes(MOJIBAKE_LEAD),
+ `stored name still carries the latin1 mojibake: "${stored}"`,
+ ).toBe(false);
+
+ // (2) The reference inside the document. This is what the editor does with
+ // the API response: mint a markdown image whose target is the returned
+ // `src`. Persistence is debounced, so poll rather than read straight after.
+ await agentWriteMd(server.port, `\n![shot](${body.src})\n`, {
+ docName: `docs/${id}/guide`,
+ position: 'append',
+ });
+ await pollUntil(() => readTestDoc(server.contentDir, `docs/${id}/guide`).includes('![shot]('));
+
+ const doc = readTestDoc(server.contentDir, `docs/${id}/guide`);
+ const ref = /!\[shot\]\(([^)]*)\)/.exec(doc)?.[1];
+ expect(ref, `document was: ${JSON.stringify(doc)}`).toBeDefined();
+
+ const target = decodeURIComponent(ref as string);
+ expect(hexOf(target), `reference "${target}" vs on-disk "${stored}"`).toBe(hexOf(stored));
+ expect(existsSync(join(dir, target)), `reference does not resolve: "${target}"`).toBe(true);
+ });
+
+ test.each([
+ ['nnbsp', SENT, EXPECTED],
+ ['cjk', CJK, CJK],
+ ])('the in-process transport decodes identically to the socket: %s', async (id, sent, expected) => {
+ const dir = seedDir(`localapi-${id}`);
+
+ // Byte-for-byte the encoding `mcp/tools/write.ts` performs for an asset
+ // write: a Node FormData serialized once through `new Request(...)`, then
+ // handed to `localApi` as raw bytes plus the boundary-bearing
+ // content-type.
+ const form = new FormData();
+ form.append('parentDocName', `docs/localapi-${id}/guide.md`);
+ form.append('file', new Blob([pngFixture()]), sent);
+ const encoded = new Request('http://localhost/api/upload', { method: 'POST', body: form });
+ const contentType = encoded.headers.get('content-type') ?? 'multipart/form-data';
+ const bytes = new Uint8Array(await encoded.arrayBuffer());
+
+ const out = await server.instance.localApi('POST', '/api/upload', { body: bytes, contentType });
+ expect(out, 'localApi returned null - /api/upload left the dispatch allowlist').not.toBeNull();
+ expect(out?.status, out?.bodyText).toBe(200);
+
+ const parsed = JSON.parse(out?.bodyText ?? '{}') as { src: string; deduped: boolean };
+ expect(parsed.deduped).toBe(false);
+ expect(hexOf(parsed.src), `sent ${hexOf(sent)} -> got "${parsed.src}"`).toBe(hexOf(expected));
+ expect(existsSync(join(dir, parsed.src))).toBe(true);
+ });
+});
diff --git a/packages/server/src/api-extension.ts b/packages/server/src/api-extension.ts
index df944aebd..987572157 100644
--- a/packages/server/src/api-extension.ts
+++ b/packages/server/src/api-extension.ts
@@ -292,7 +292,6 @@ import {
upsertLockEntry,
type WellKnownIndex,
} from '@inkeep/open-knowledge-core/skills-catalog';
-import busboy from 'busboy';
import { parse as parseYaml, stringify as stringifyYaml } from 'yaml';
import { type Entry, fromBuffer as yauzlFromBuffer, type ZipFile } from 'yauzl';
import { z } from 'zod';
@@ -667,6 +666,7 @@ import {
incrementSummariesProvided,
incrementSummariesTruncated,
} from './metrics.ts';
+import { createMultipartParser, type MultipartParser } from './multipart.ts';
import { precomputeParse } from './parse-pool.ts';
import { isWithinDir, toPosix } from './path-utils.ts';
import {
@@ -1021,7 +1021,7 @@ interface UploadResult {
*/
function readUploadBody(req: IncomingMessage, projectDir: string): Promise<UploadResult> {
return new Promise((resolveP, reject) => {
- let bb: ReturnType<typeof busboy>;
+ let bb: MultipartParser;
try {
// `files: 1` caps the file part; `fields` + `fieldSize` cap non-file
// surface so a flooded multipart can't buffer thousands of fields or a
@@ -1032,10 +1032,7 @@ function readUploadBody(req: IncomingMessage, projectDir: string): Promise<Uploa
// ceiling in `sanitizeFilename` (the filesystem-portability layer);
// busboy does not expose a header-section-size limit (only headerPairs
// count), so the parsed-value cap is the right place.
- bb = busboy({
- headers: req.headers,
- limits: { files: 1, fields: 10, fieldSize: 2 * 1024 },
- });
+ bb = createMultipartParser(req, { files: 1, fields: 10, fieldSize: 2 * 1024 });
} catch (err) {
reject(new UploadWriteError('urn:ok:error:malformed-upload', err));
return;
@@ -17498,16 +17495,13 @@ export function createApiExtension(
/** Collect every multipart file part into a bounded in-memory buffer. */
function readSkillUploadParts(req: IncomingMessage): Promise<UploadedPart[]> {
return new Promise((resolveP, reject) => {
- let bb: ReturnType<typeof busboy>;
+ let bb: MultipartParser;
try {
- bb = busboy({
- headers: req.headers,
- limits: {
- files: UPLOAD_MAX_FILES,
- fields: 10,
- fieldSize: 2 * 1024,
- fileSize: UPLOAD_MAX_ENTRY_BYTES,
- },
+ bb = createMultipartParser(req, {
+ files: UPLOAD_MAX_FILES,
+ fields: 10,
+ fieldSize: 2 * 1024,
+ fileSize: UPLOAD_MAX_ENTRY_BYTES,
});
} catch (err) {
reject(err);
diff --git a/packages/server/src/lint-plugins/require-utf8-multipart-parser.test.ts b/packages/server/src/lint-plugins/require-utf8-multipart-parser.test.ts
new file mode 100644
index 000000000..73cac7bd1
--- /dev/null
+++ b/packages/server/src/lint-plugins/require-utf8-multipart-parser.test.ts
@@ -0,0 +1,106 @@
+/**
+ * Multipart filename charset correctness — `require-utf8-multipart-parser`
+ * GritQL plugin.
+ *
+ * Plugin: `biome-plugins/require-utf8-multipart-parser.grit`
+ * Fixture: `biome-plugins/__fixtures__/require-utf8-multipart-parser.fixture.tsx`
+ *
+ * The fixture pairs 3 positive cases (a `busboy(...)` with no charset declared —
+ * the shape that shipped the bug — plus one with an explicit `latin1` and one
+ * with an inline `utf8`) against negatives: the sanctioned
+ * `createMultipartParser(...)` call, a `ReturnType<typeof busboy>` type
+ * annotation, a member call, and an unrelated identifier.
+ *
+ * The `latin1` positive is the load-bearing one. It is what separates this
+ * presence-match rule from the absence-match shape a sibling rule uses: "a
+ * `busboy(...)` call must contain `defParamCharset:`" would wave that line
+ * through and reintroduce the defect while passing lint. The type-annotation
+ * negative is the other: it pins that the pattern does not reach type positions,
+ * so a future widening cannot start flagging them silently.
+ *
+ * Exact equality on the fire count catches drift in both directions — a
+ * false-negative regression (< 3) and a false-positive widening (> 3).
+ *
+ * The plugin is registered via `overrides[].plugins` in `biome.jsonc`, repo-wide
+ * rather than per-package (server owns the only busboy dependency today, which is
+ * the state a new dependency elsewhere would change silently), with the factory
+ * module and tests excluded.
+ */
+
+import { spawnSync } from 'node:child_process';
+import { join } from 'node:path';
+import { describe, expect, test } from 'vitest';
+import { readBiomeConfig } from '../../../../test-support/read-biome-config.test-helper.ts';
+
+const REPO_ROOT = join(__dirname, '..', '..', '..', '..');
+const FIXTURE_REL = 'biome-plugins/__fixtures__/require-utf8-multipart-parser.fixture.tsx';
+const PLUGIN_REL = './biome-plugins/require-utf8-multipart-parser.grit';
+
+describe('require-utf8-multipart-parser GritQL plugin', () => {
+ test('fires exactly 3 times — one per direct busboy construction', () => {
+ const result = spawnSync('pnpm', ['exec', 'biome', 'check', FIXTURE_REL], {
+ cwd: REPO_ROOT,
+ encoding: 'utf-8',
+ windowsHide: true,
+ });
+ // Guard against a vacuous pass if `pnpm exec biome` itself fails to spawn
+ // (missing binary / PATH) — `result.status` would be null and `not.toBe(0)`
+ // would pass while asserting nothing about biome's output.
+ expect(result.error).toBeUndefined();
+ expect(result.status).not.toBe(0);
+ const output = `${result.stdout}\n${result.stderr}`;
+
+ const fires = (output.match(/busboy constructed directly/g) ?? []).length;
+ expect(fires).toBe(3);
+
+ // Message names the fix as an action, and links the docs.
+ expect(output).toContain('createMultipartParser');
+ expect(output).toContain('packages/server/src/multipart.ts');
+ expect(output).toMatch(/https?:\/\/[^\s]+/);
+ expect(output).toContain('biome-plugins/README.md#require-utf8-multipart-parsergrit');
+ });
+
+ test('the factory module itself is exempt, so the sanctioned call passes', () => {
+ const result = spawnSync(
+ 'pnpm',
+ ['exec', 'biome', 'check', 'packages/server/src/multipart.ts'],
+ {
+ cwd: REPO_ROOT,
+ encoding: 'utf-8',
+ windowsHide: true,
+ },
+ );
+ expect(result.error).toBeUndefined();
+ const output = `${result.stdout}\n${result.stderr}`;
+ // Proves biome actually visited the file, so the `not.toContain` below is a
+ // real negative rather than a vacuous one. Asserting `status === 0` instead
+ // would fail this test for any unrelated formatting nit in `multipart.ts`.
+ expect(output).toMatch(/Checked \d+ file/);
+ expect(output).not.toContain('busboy constructed directly');
+ });
+
+ test('plugin is registered in biome.jsonc via overrides (not root plugins)', () => {
+ const config = readBiomeConfig(REPO_ROOT);
+
+ const rootPlugins = config.plugins ?? [];
+ expect(rootPlugins).not.toContain(PLUGIN_REL);
+
+ const overrides = config.overrides ?? [];
+ const matchingOverride = overrides.find((entry) => (entry.plugins ?? []).includes(PLUGIN_REL));
+ expect(matchingOverride).toBeDefined();
+
+ const includes = matchingOverride?.includes ?? [];
+ // Repo-wide, not per-package: the invariant is "no direct construction
+ // anywhere", and a busboy dependency added outside server is precisely the
+ // change a server-scoped glob would wave through.
+ expect(includes).toContain('**/*.ts');
+ expect(includes).toContain('**/*.tsx');
+ expect(includes).toContain('**/*.mts');
+ expect(includes).not.toContain('packages/server/src/**/*.ts');
+ // The factory is the one sanctioned construction site.
+ expect(includes).toContain('!packages/server/src/multipart.ts');
+ expect(includes).toContain('!**/*.test.ts');
+ // Fixture self-include so this test's positive cases still trigger.
+ expect(includes).toContain(FIXTURE_REL);
+ });
+});
diff --git a/packages/server/src/multipart.test.ts b/packages/server/src/multipart.test.ts
new file mode 100644
index 000000000..9762c08a5
--- /dev/null
+++ b/packages/server/src/multipart.test.ts
@@ -0,0 +1,211 @@
+/**
+ * Unit-level contract for `createMultipartParser`.
+ *
+ * The end-to-end contract (client filename to asset basename / skill bundle
+ * path) is pinned at full fidelity by
+ * `packages/app/tests/integration/api-error-envelope/upload-filename-charset.test.ts`,
+ * which drives real HTTP through both handlers. This file keeps the factory
+ * itself honest at its own level: the decode it declares, the extended-parameter
+ * path it must not disturb, and the throw it must not swallow.
+ *
+ * SOURCE-INTEGRITY RULE for this file: every non-ASCII character in a fixture is
+ * written as a `\u` escape, never as a literal. U+202F NARROW NO-BREAK SPACE in
+ * particular is silently rewritten to an ASCII space by several editors and
+ * file-writing tools, and that rewrite would make these tests pass against the
+ * exact defect they pin. The `fixture integrity` test re-derives the code points
+ * at runtime so a fixture that lost its characters fails loudly rather than
+ * quietly weakening every assertion below it.
+ */
+
+import type { IncomingMessage } from 'node:http';
+import { describe, expect, test } from 'vitest';
+import { createMultipartParser } from './multipart.ts';
+
+const BOUNDARY = 'okmultiparttestboundary';
+
+/**
+ * U+202F NARROW NO-BREAK SPACE, what macOS 13+ puts before AM/PM in a screenshot
+ * filename. UTF-8 `E2 80 AF`; read as latin1 it becomes U+00E2 U+0080 U+00AF.
+ */
+const NNBSP = '\u202F';
+
+interface FilenameCase {
+ label: string;
+ name: string;
+ /** Code points `name` must still contain at runtime. */
+ requiredCodePoints: number[];
+}
+
+const FILENAME_CASES: readonly FilenameCase[] = [
+ {
+ label: 'macOS screenshot U+202F',
+ name: `Screenshot 2026-08-12 at 10.48.44${NNBSP}AM.png`,
+ requiredCodePoints: [0x202f],
+ },
+ {
+ label: 'CJK',
+ name: '\u4F1A\u8B70\u30E1\u30E2.png',
+ requiredCodePoints: [0x4f1a, 0x8b70, 0x30e1, 0x30e2],
+ },
+ {
+ label: 'Cyrillic',
+ name: '\u041F\u0440\u043E\u0435\u043A\u0442.png',
+ requiredCodePoints: [0x041f, 0x0442],
+ },
+ {
+ label: 'astral emoji',
+ name: 'party \u{1F389}.png',
+ requiredCodePoints: [0x1f389],
+ },
+ {
+ label: 'precomposed Latin',
+ name: 'caf\u00E9.png',
+ requiredCodePoints: [0x00e9],
+ },
+ { label: 'plain ASCII control', name: 'plain-ascii.png', requiredCodePoints: [] },
+];
+
+function headersFor(contentType: string): IncomingMessage {
+ return { headers: { 'content-type': contentType } } as IncomingMessage;
+}
+
+/**
+ * A minimal single-part multipart body. `dispositionParams` is spliced into the
+ * `Content-Disposition` header verbatim so a test can send either a plain
+ * `filename=` or an RFC 5987 extended `filename*=`.
+ *
+ * Encoded as UTF-8, which is what a browser or undici puts on the wire: raw
+ * multi-byte sequences inside the quoted parameter value, never percent-encoded.
+ */
+function multipartBody(dispositionParams: string): Buffer {
+ return Buffer.concat([
+ Buffer.from(
+ `--${BOUNDARY}\r\n` +
+ `Content-Disposition: form-data; name="file"; ${dispositionParams}\r\n` +
+ 'Content-Type: application/octet-stream\r\n\r\n',
+ 'utf8',
+ ),
+ Buffer.from('payload', 'utf8'),
+ Buffer.from(`\r\n--${BOUNDARY}--\r\n`, 'utf8'),
+ ]);
+}
+
+/** Feed a body through a factory-built parser and report every decoded name. */
+function decodeFilenames(body: Buffer, files: number): Promise<string[]> {
+ return new Promise((resolveP, reject) => {
+ const bb = createMultipartParser(headersFor(`multipart/form-data; boundary=${BOUNDARY}`), {
+ files,
+ });
+ const seen: string[] = [];
+ bb.on('file', (_field, stream, info) => {
+ seen.push(info.filename);
+ stream.resume();
+ });
+ bb.on('error', reject);
+ bb.on('close', () => resolveP(seen));
+ bb.end(body);
+ });
+}
+
+function decodeFilename(dispositionParams: string): Promise<string[]> {
+ return decodeFilenames(multipartBody(dispositionParams), 1);
+}
+
+function codePointsOf(s: string): number[] {
+ return [...s].map((c) => c.codePointAt(0) as number);
+}
+
+describe('createMultipartParser', () => {
+ test('fixture integrity: the escapes still carry their code points', () => {
+ expect(codePointsOf(NNBSP)).toEqual([0x202f]);
+ expect([...Buffer.from(NNBSP, 'utf8')]).toEqual([0xe2, 0x80, 0xaf]);
+
+ for (const c of FILENAME_CASES) {
+ const points = codePointsOf(c.name);
+ for (const cp of c.requiredCodePoints) {
+ expect(points, `fixture ${c.label} lost U+${cp.toString(16).toUpperCase()}`).toContain(cp);
+ }
+ expect(
+ points.some((p) => p > 0x7f),
+ `fixture ${c.label} non-ASCII presence`,
+ ).toBe(c.requiredCodePoints.length > 0);
+ }
+ });
+
+ for (const c of FILENAME_CASES) {
+ test(`decodes a plain \`filename=\` parameter as UTF-8: ${c.label}`, async () => {
+ await expect(decodeFilename(`filename="${c.name}"`)).resolves.toEqual([c.name]);
+ });
+ }
+
+ test('leaves the RFC 5987 extended `filename*` path alone', async () => {
+ // Extended parameters carry their own charset and busboy decodes them
+ // independently of `defParamCharset`, preferring them when present. RFC 7578
+ // §4.2 forbids clients from sending them in a multipart/form-data body, so
+ // this is a non-regression pin: hardcoding the default charset must not have
+ // disturbed the path that was already correct.
+ await expect(decodeFilename("filename*=UTF-8''%E4%BC%9A%E8%AD%B0.png")).resolves.toEqual([
+ '\u4F1A\u8B70.png',
+ ]);
+ });
+
+ test('degrades a genuinely latin1 filename to the replacement character', async () => {
+ // Declaring UTF-8 is a choice against non-conformant senders: a client that
+ // really did encode `café.png` as latin1 puts a bare 0xE9 on the wire, which
+ // is not valid UTF-8. busboy's utf8 decoder is non-fatal, so that byte
+ // becomes U+FFFD rather than throwing. Downstream this is what the release
+ // note promises users, and the two upload paths diverge on it -- the asset
+ // path's sanitizer maps U+FFFD to `_`, while a skill import keeps it -- so
+ // pin the token here, where the decode actually happens, rather than let a
+ // future busboy change quietly rewrite a documented behavior.
+ const latin1Byte = Buffer.from([0xe9]);
+ const body = Buffer.concat([
+ Buffer.from(
+ `--${BOUNDARY}\r\nContent-Disposition: form-data; name="file"; filename="caf`,
+ 'utf8',
+ ),
+ latin1Byte,
+ Buffer.from(
+ `.png"\r\nContent-Type: application/octet-stream\r\n\r\npayload\r\n--${BOUNDARY}--\r\n`,
+ 'utf8',
+ ),
+ ]);
+
+ const [decoded] = await decodeFilenames(body, 1);
+
+ expect(codePointsOf(decoded as string)).toEqual([
+ 0x63, 0x61, 0x66, 0xfffd, 0x2e, 0x70, 0x6e, 0x67,
+ ]);
+ // Specifically NOT U+00E9: that would mean the byte was read as latin1,
+ // which is the default this factory exists to override.
+ expect(codePointsOf(decoded as string)).not.toContain(0x00e9);
+ });
+
+ test('propagates a missing Content-Type instead of swallowing it', () => {
+ // Each caller classifies this differently: the asset upload maps it to a
+ // typed `urn:ok:error:malformed-upload`, the skill upload rejects raw. A
+ // catch inside the factory would flatten both into one contract.
+ expect(() => createMultipartParser({ headers: {} } as IncomingMessage, {})).toThrow(
+ /Missing Content-Type/,
+ );
+ });
+
+ test('propagates an unsupported Content-Type instead of swallowing it', () => {
+ expect(() => createMultipartParser(headersFor('application/json'), {})).toThrow(
+ /Unsupported content type/,
+ );
+ });
+
+ test('passes the caller-supplied limits through to the parser', async () => {
+ // The factory owns the charset; each call site still owns the ingress bounds
+ // it sets for its own threat model.
+ const twoParts = Buffer.from(
+ `--${BOUNDARY}\r\nContent-Disposition: form-data; name="file"; filename="a.png"\r\n\r\nA\r\n` +
+ `--${BOUNDARY}\r\nContent-Disposition: form-data; name="file"; filename="b.png"\r\n\r\nB\r\n` +
+ `--${BOUNDARY}--\r\n`,
+ 'utf8',
+ );
+ await expect(decodeFilenames(twoParts, 1)).resolves.toEqual(['a.png']);
+ await expect(decodeFilenames(twoParts, 2)).resolves.toEqual(['a.png', 'b.png']);
+ });
+});
diff --git a/packages/server/src/multipart.ts b/packages/server/src/multipart.ts
new file mode 100644
index 000000000..9548b8a91
--- /dev/null
+++ b/packages/server/src/multipart.ts
@@ -0,0 +1,58 @@
+/**
+ * The one sanctioned way to construct a `multipart/form-data` parser.
+ *
+ * busboy's `defParamCharset` defaults to `latin1` — an inheritance from
+ * `Content-Disposition`'s original MIME/email definition, not from the
+ * `multipart/form-data` rules. RFC 7578 governs this surface instead. It issues
+ * no receiver mandate — §5.1.3 is explicit that a parser cannot assume any
+ * particular charset was used — so the default is ours to choose, and UTF-8 is
+ * the only defensible choice: §4.2 records that "the encoding used for the file
+ * names is typically UTF-8", and the sender-side form-charset ladder in §5.1.2
+ * terminates at UTF-8. Browsers and
+ * Node/undici both put the name on the wire as raw UTF-8 bytes in the plain
+ * `filename=` parameter, so the latin1 default reads every multi-byte sequence
+ * back as one mojibake code point per byte — `café.png` arrives as
+ * `café.png`, irreversibly, before any sanitizer or storage layer sees it.
+ *
+ * The charset is deliberately NOT a parameter. Declaring it per call site
+ * leaves a hole a future caller can fill with the wrong value; hardcoding it
+ * here makes `latin1` unreachable. A lint rule (`require-utf8-multipart-parser`)
+ * keeps `busboy(...)` from being called anywhere else.
+ *
+ * RFC 5987 / RFC 2231 extended parameters (`filename*`) are unaffected: they
+ * carry their own charset and busboy decodes them independently of
+ * `defParamCharset`, preferring them when present. RFC 7578 §4.2 forbids
+ * clients from sending them here, so in practice this path is what matters.
+ */
+
+import type { IncomingMessage } from 'node:http';
+import busboy from 'busboy';
+
+/**
+ * A constructed multipart parser. Call sites annotate with this instead of
+ * `ReturnType<typeof busboy>` so they never need to import busboy themselves.
+ */
+export type MultipartParser = ReturnType<typeof createMultipartParser>;
+
+/**
+ * Construct a multipart parser for `req` that decodes header parameters as
+ * UTF-8.
+ *
+ * Deliberately does NOT catch. busboy throws synchronously on a missing or
+ * unparseable `Content-Type` boundary, and each caller classifies that
+ * differently (the asset upload turns it into a typed
+ * `urn:ok:error:malformed-upload`; the skill upload rejects raw). Swallowing it
+ * here would flatten two distinct error contracts into one.
+ *
+ * `preservePath` is left at its `false` default, so `filename` arrives as a
+ * bare basename. Anything that needs the client's directory component has to
+ * widen this factory — and reason about path traversal while doing so — rather
+ * than construct its own parser.
+ */
+export function createMultipartParser(req: IncomingMessage, limits: busboy.Limits): busboy.Busboy {
+ return busboy({
+ headers: req.headers,
+ defParamCharset: 'utf8',
+ limits,
+ });
+}