diff --git a/lib/utils/file-download-response.ts b/lib/utils/file-download-response.ts new file mode 100644 index 0000000..431b73c --- /dev/null +++ b/lib/utils/file-download-response.ts @@ -0,0 +1,45 @@ +import { + decodeBase64ToUint8Array, + uint8ArrayToArrayBuffer, +} from "lib/utils/decode-base64" + +// RFC 6266: plain ASCII `filename` for old clients, `filename*` for the real +// name. Header values must be ASCII, so non-ASCII names can't go in as-is. +export const getContentDisposition = (filePath: string): string => { + const filename = filePath.split("/").pop() || "download" + const asciiFallback = filename.replace(/[^\x20-\x7e]|["\\]/g, "_") + if (asciiFallback === filename) { + return `attachment; filename="${filename}"` + } + const encoded = encodeURIComponent(filename).replace( + /['()*]/g, + (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`, + ) + return `attachment; filename="${asciiFallback}"; filename*=UTF-8''${encoded}` +} + +export const createFileDownloadResponse = (file: { + file_path: string + text_content?: string + binary_content_b64?: string +}): Response => { + const contentDisposition = getContentDisposition(file.file_path) + + if (file.text_content === undefined && file.binary_content_b64) { + const binaryBody = decodeBase64ToUint8Array(file.binary_content_b64) + return new Response(uint8ArrayToArrayBuffer(binaryBody), { + headers: { + "Content-Type": "application/octet-stream", + "Content-Disposition": contentDisposition, + "Content-Length": binaryBody.byteLength.toString(), + }, + }) + } + + return new Response(file.text_content ?? "", { + headers: { + "Content-Type": "text/plain", + "Content-Disposition": contentDisposition, + }, + }) +} diff --git a/routes/files/download.ts b/routes/files/download.ts index 4bb47d3..47b18b9 100644 --- a/routes/files/download.ts +++ b/routes/files/download.ts @@ -1,9 +1,6 @@ import { withRouteSpec } from "lib/middleware/with-winter-spec" import { z } from "zod" -import { - decodeBase64ToUint8Array, - uint8ArrayToArrayBuffer, -} from "lib/utils/decode-base64" +import { createFileDownloadResponse } from "lib/utils/file-download-response" import { resolveFileProxy } from "lib/utils/resolve-file-proxy" export default withRouteSpec({ @@ -27,27 +24,5 @@ export default withRouteSpec({ return new Response("File not found", { status: 404 }) } - const isText = file.text_content !== undefined - if (!isText && file.binary_content_b64) { - const binaryBody = decodeBase64ToUint8Array(file.binary_content_b64) - const responseBody = uint8ArrayToArrayBuffer(binaryBody) - return new Response(responseBody, { - headers: { - "Content-Type": "application/octet-stream", - "Content-Disposition": `attachment; filename="${file.file_path - .split("/") - .pop()}"`, - "Content-Length": binaryBody.byteLength.toString(), - }, - }) - } - - return new Response(file.text_content!, { - headers: { - "Content-Type": "text/plain", - "Content-Disposition": `attachment; filename="${file.file_path - .split("/") - .pop()}"`, - }, - }) + return createFileDownloadResponse(file) }) diff --git a/routes/files/download/[[...file_path]].ts b/routes/files/download/[[...file_path]].ts index 3e8fa02..efbb605 100644 --- a/routes/files/download/[[...file_path]].ts +++ b/routes/files/download/[[...file_path]].ts @@ -1,9 +1,6 @@ import { withRouteSpec } from "lib/middleware/with-winter-spec" import { z } from "zod" -import { - decodeBase64ToUint8Array, - uint8ArrayToArrayBuffer, -} from "lib/utils/decode-base64" +import { createFileDownloadResponse } from "lib/utils/file-download-response" import { resolveFileProxy } from "lib/utils/resolve-file-proxy" export default withRouteSpec({ @@ -28,27 +25,5 @@ export default withRouteSpec({ return new Response("File not found", { status: 404 }) } - const isText = file.text_content !== undefined - if (!isText && file.binary_content_b64) { - const binaryBody = decodeBase64ToUint8Array(file.binary_content_b64) - const responseBody = uint8ArrayToArrayBuffer(binaryBody) - return new Response(responseBody, { - headers: { - "Content-Type": "application/octet-stream", - "Content-Disposition": `attachment; filename="${file.file_path - .split("/") - .pop()}"`, - "Content-Length": binaryBody.byteLength.toString(), - }, - }) - } - - return new Response(file.text_content!, { - headers: { - "Content-Type": "text/plain", - "Content-Disposition": `attachment; filename="${file.file_path - .split("/") - .pop()}"`, - }, - }) + return createFileDownloadResponse(file) }) diff --git a/tests/routes/files.test.ts b/tests/routes/files.test.ts index 196c354..bff444f 100644 --- a/tests/routes/files.test.ts +++ b/tests/routes/files.test.ts @@ -395,3 +395,32 @@ test("file static serving operations", async () => { data: "File not found", }) }) + +test("download works for file names with non-ascii characters and quotes", async () => { + const { url, axios } = await getTestServer() + + for (const filePath of ["/日本語.txt", '/say "hi".txt']) { + await axios.post("/files/upsert", { + file_path: filePath, + text_content: "hello", + }) + const name = filePath.slice(1) + + const byQuery = await fetch( + `${url}/files/download?file_path=${encodeURIComponent(filePath)}`, + ) + const byPath = await fetch( + `${url}/files/download/${encodeURIComponent(name)}`, + ) + + for (const res of [byQuery, byPath]) { + expect(res.status).toBe(200) + expect(await res.text()).toBe("hello") + const disposition = res.headers.get("content-disposition")! + expect(disposition).toContain( + `filename*=UTF-8''${encodeURIComponent(name)}`, + ) + expect(disposition).not.toContain('""') + } + } +})