Skip to content

AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.

fix: encode UTF-8 resource filenames safely

tianma-if90474b2943cb
diff --git a/apps/api/src/resource-routes.test.mjs b/apps/api/src/resource-routes.test.mjs
index 63ed2f47..29e064d9 100644
--- a/apps/api/src/resource-routes.test.mjs
+++ b/apps/api/src/resource-routes.test.mjs
@@ -107,7 +107,7 @@ describe("resource route contracts", () => {
expect(await response.json()).toMatchObject({ error: { code: "forbidden" } });
});
- test("serves PDF attachments inline while preserving their filename", async () => {
+ test("serves PDF attachments with UTF-8 filenames inline using an ASCII-safe header", async () => {
const environment = createEnvironment();
environment.storage.resources = {
get: async () => ({
@@ -116,7 +116,11 @@ describe("resource route contracts", () => {
writeHttpMetadata: () => {},
}),
};
- const response = await createApp(agentAuth, async () => ({ ...resourceRow, storage_config_id: null })).request(
+ const response = await createApp(agentAuth, async () => ({
+ ...resourceRow,
+ filename: "季度报告.pdf",
+ storage_config_id: null,
+ })).request(
"/api/v1/resources/res_1/blob",
{},
environment,
@@ -124,7 +128,9 @@ describe("resource route contracts", () => {
expect(response.status).toBe(200);
expect(response.headers.get("Content-Type")).toBe("application/pdf");
- expect(response.headers.get("Content-Disposition")).toStartWith("inline;");
+ expect(response.headers.get("Content-Disposition")).toBe(
+ "inline; filename=\"download.pdf\"; filename*=UTF-8''%E5%AD%A3%E5%BA%A6%E6%8A%A5%E5%91%8A.pdf",
+ );
expect(response.headers.get("Accept-Ranges")).toBe("bytes");
});
diff --git a/apps/api/src/resource-service.test.mjs b/apps/api/src/resource-service.test.mjs
index 07c23086..fd0b31c9 100644
--- a/apps/api/src/resource-service.test.mjs
+++ b/apps/api/src/resource-service.test.mjs
@@ -55,9 +55,12 @@ describe("resource service contracts", () => {
test("normalizes filenames and keeps UTF-8 download names", () => {
expect(normalizeFilename(" reports/季度\u0000.pdf ")).toBe("reports-季度.pdf");
- expect(contentDispositionAttachment("季度报告.pdf")).toContain(
- "filename*=UTF-8''%E5%AD%A3%E5%BA%A6%E6%8A%A5%E5%91%8A.pdf",
+ const disposition = contentDispositionAttachment("季度报告 (最终版)'*.pdf");
+ expect(disposition).toBe(
+ "attachment; filename=\"download.pdf\"; filename*=UTF-8''%E5%AD%A3%E5%BA%A6%E6%8A%A5%E5%91%8A%20%28%E6%9C%80%E7%BB%88%E7%89%88%29%27%2A.pdf",
);
+ expect(new Headers({ "Content-Disposition": disposition }).get("Content-Disposition")).toBe(disposition);
+ expect(contentDispositionAttachment("résumé.pdf")).toContain('filename="resume.pdf"');
});
test("infers normalized image extensions", () => {
diff --git a/apps/api/src/resource-service.ts b/apps/api/src/resource-service.ts
index 621579de..9ed4b975 100644
--- a/apps/api/src/resource-service.ts
+++ b/apps/api/src/resource-service.ts
@@ -149,10 +149,23 @@ export const prepareImageForStorage = (input: {
},
});
+const encodeRfc5987Value = (value: string) => encodeURIComponent(
+ value.replace(/[\uD800-\uDFFF]/gu, "\uFFFD"),
+).replace(/['()*]/g, (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`);
+
+const asciiFilenameFallback = (filename: string) => {
+ const normalized = filename.normalize("NFKD").replace(/[\u0300-\u036f]/g, "");
+ const ascii = normalized.replace(/[^\x20-\x7e]/g, "_").replace(/["\\]/g, "_");
+ const extension = /\.[A-Za-z0-9]{1,16}$/.exec(ascii)?.[0] ?? "";
+ const basename = extension ? ascii.slice(0, -extension.length) : ascii;
+ return /[A-Za-z0-9]/.test(basename) ? ascii : `download${extension}`;
+};
+
const contentDisposition = (kind: "inline" | "attachment", filename: string | null) => {
if (!filename) return kind;
- const fallback = normalizeFilename(filename).replace(/"/g, "'");
- return `${kind}; filename="${fallback}"; filename*=UTF-8''${encodeURIComponent(filename)}`;
+ const normalized = normalizeFilename(filename);
+ if (!normalized) return kind;
+ return `${kind}; filename="${asciiFilenameFallback(normalized)}"; filename*=UTF-8''${encodeRfc5987Value(normalized)}`;
};
export const contentDispositionInline = (filename: string | null) => contentDisposition("inline", filename);
diff --git a/apps/api/src/share-routes.test.mjs b/apps/api/src/share-routes.test.mjs
index 41738095..70babadb 100644
--- a/apps/api/src/share-routes.test.mjs
+++ b/apps/api/src/share-routes.test.mjs
@@ -107,7 +107,7 @@ describe("public memo shares", () => {
const { sqlite, environment } = createDatabaseEnvironment();
sqlite.query(
`INSERT INTO resources (id, memo_id, object_key, kind, mime_type, filename, byte_size)
- VALUES (?, ?, ?, 'attachment', 'application/pdf', 'shared.pdf', 10)`,
+ VALUES (?, ?, ?, 'attachment', 'application/pdf', '共享报告.pdf', 10)`,
).run("res_shared", "memo_source", "shared-key");
let requestedOptions;
environment.storage.resources = {
@@ -133,6 +133,9 @@ describe("public memo shares", () => {
expect(requestedOptions).toEqual({ range: { offset: 2, length: 4 } });
expect(response.status).toBe(206);
expect(response.headers.get("Content-Range")).toBe("bytes 2-5/10");
+ expect(response.headers.get("Content-Disposition")).toBe(
+ "inline; filename=\"download.pdf\"; filename*=UTF-8''%E5%85%B1%E4%BA%AB%E6%8A%A5%E5%91%8A.pdf",
+ );
expect(response.headers.get("Cache-Control")).toBe("private, no-store");
expect(await response.text()).toBe("2345");
sqlite.close();
diff --git a/apps/api/src/share-routes.ts b/apps/api/src/share-routes.ts
index b8321fae..20cece08 100644
--- a/apps/api/src/share-routes.ts
+++ b/apps/api/src/share-routes.ts
@@ -8,6 +8,7 @@ import { createId, isoNow, parseJsonArray } from "./entity-utils";
import { notFound } from "./http-errors";
import { resolveObjectStorage } from "./object-storage";
import { getAuditActor, getWorkspaceId, requireUser } from "./request-auth";
+import { contentDispositionAttachment, contentDispositionInline } from "./resource-service";
const SHARE_TOKEN_BYTES = 32;
const SHARE_TOKEN_PATTERN = /^[A-Za-z0-9_-]{43}$/;
@@ -38,15 +39,9 @@ const mapMemoShare = (row: MemoShareRow): MemoShare => ({
updatedAt: row.updated_at,
});
-const normalizeFilename = (filename: string) =>
- filename.trim().replace(/[\\/]/g, "-").replace(/[\u0000-\u001f\u007f]/g, "").slice(0, 160);
-
const contentDisposition = (kind: SharedResourceRow["kind"], mimeType: string | null, filename: string | null) => {
const inline = kind === "image" || isPdfAttachment(mimeType, filename);
- if (!filename) return inline ? "inline" : "attachment";
- const fallback = normalizeFilename(filename).replace(/"/g, "'");
- const disposition = inline ? "inline" : "attachment";
- return `${disposition}; filename="${fallback}"; filename*=UTF-8''${encodeURIComponent(filename)}`;
+ return inline ? contentDispositionInline(filename) : contentDispositionAttachment(filename);
};
const normalizeShareToken = (value: string) => {