Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions lib/utils/content-disposition.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
/**
* Build a safe `Content-Disposition: attachment` header value for a file
* download (RFC 6266 / RFC 5987).
*
* The download routes used to interpolate the raw file name into the
* header, which breaks in two ways:
* - a non-ASCII file name (e.g. `报告.pdf`) makes `new Response()` throw
* `TypeError: Header 'Content-Disposition' has invalid value`, so the
* download fails entirely instead of returning the file.
* - a file name containing `"` produces a malformed header
* (`filename="my "quoted".txt"`).
*
* To keep existing behavior (and tests) untouched, plain ASCII file names
* keep the exact historical form `attachment; filename="name.txt"`.
* Anything else gets a sanitized ASCII fallback plus an RFC 5987
* `filename*` parameter carrying the exact UTF-8 name, so browsers still
* save the file under its real name.
*/
export function getAttachmentContentDisposition(filePath: string): string {
const fileName = filePath.split("/").pop() ?? ""

if (!fileName) {
return `attachment; filename="file"`
}

// Safe for a quoted-string: printable ASCII except `"` and `\`.
const isSafeAscii = /^[\x20-\x7e]+$/.test(fileName) && !/["\\]/.test(fileName)
if (isSafeAscii) {
return `attachment; filename="${fileName}"`
}

const fallback = fileName
.replace(/[^\x20-\x7e]/g, "_")
.replace(/["\\]/g, "_")
.trim()
const safeFallback = fallback.length > 0 ? fallback : "file"

return (
`attachment; filename="${safeFallback}"; ` +
`filename*=UTF-8''${encodeURIComponent(fileName)}`
)
}
8 changes: 6 additions & 2 deletions lib/utils/resolve-file-proxy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import type { FileProxy } from "../db/schema"
import { readFile } from "node:fs/promises"
import { join } from "node:path"
import { normalizePath } from "./normalize-path"
import { getAttachmentContentDisposition } from "./content-disposition"

export async function resolveFileProxy(
proxy: FileProxy,
Expand Down Expand Up @@ -36,7 +37,7 @@ async function resolveDiskProxy(
return new Response(content, {
headers: {
"Content-Type": contentType,
"Content-Disposition": `attachment; filename="${fileName}"`,
"Content-Disposition": getAttachmentContentDisposition(fileName),
"Content-Length": content.byteLength.toString(),
},
})
Expand Down Expand Up @@ -79,7 +80,10 @@ async function resolveHttpProxy(
headers.set("Content-Length", contentLength)
}
const fileName = relativePath.split("/").pop() || "file"
headers.set("Content-Disposition", `attachment; filename="${fileName}"`)
headers.set(
"Content-Disposition",
getAttachmentContentDisposition(fileName),
)

return new Response(response.body, {
status: response.status,
Expand Down
9 changes: 3 additions & 6 deletions routes/files/download.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
uint8ArrayToArrayBuffer,
} from "lib/utils/decode-base64"
import { resolveFileProxy } from "lib/utils/resolve-file-proxy"
import { getAttachmentContentDisposition } from "lib/utils/content-disposition"

export default withRouteSpec({
methods: ["GET"],
Expand Down Expand Up @@ -34,9 +35,7 @@ export default withRouteSpec({
return new Response(responseBody, {
headers: {
"Content-Type": "application/octet-stream",
"Content-Disposition": `attachment; filename="${file.file_path
.split("/")
.pop()}"`,
"Content-Disposition": getAttachmentContentDisposition(file.file_path),
"Content-Length": binaryBody.byteLength.toString(),
},
})
Expand All @@ -45,9 +44,7 @@ export default withRouteSpec({
return new Response(file.text_content!, {
headers: {
"Content-Type": "text/plain",
"Content-Disposition": `attachment; filename="${file.file_path
.split("/")
.pop()}"`,
"Content-Disposition": getAttachmentContentDisposition(file.file_path),
},
})
})
9 changes: 3 additions & 6 deletions routes/files/download/[[...file_path]].ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
uint8ArrayToArrayBuffer,
} from "lib/utils/decode-base64"
import { resolveFileProxy } from "lib/utils/resolve-file-proxy"
import { getAttachmentContentDisposition } from "lib/utils/content-disposition"

export default withRouteSpec({
methods: ["GET"],
Expand Down Expand Up @@ -35,9 +36,7 @@ export default withRouteSpec({
return new Response(responseBody, {
headers: {
"Content-Type": "application/octet-stream",
"Content-Disposition": `attachment; filename="${file.file_path
.split("/")
.pop()}"`,
"Content-Disposition": getAttachmentContentDisposition(file.file_path),
"Content-Length": binaryBody.byteLength.toString(),
},
})
Expand All @@ -46,9 +45,7 @@ export default withRouteSpec({
return new Response(file.text_content!, {
headers: {
"Content-Type": "text/plain",
"Content-Disposition": `attachment; filename="${file.file_path
.split("/")
.pop()}"`,
"Content-Disposition": getAttachmentContentDisposition(file.file_path),
},
})
})
83 changes: 83 additions & 0 deletions tests/routes/files-download-disposition.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
import { test, expect } from "bun:test"
import { getTestServer } from "tests/fixtures/get-test-server"
import { getAttachmentContentDisposition } from "lib/utils/content-disposition"
import { Buffer } from "node:buffer"

test("content-disposition helper keeps plain ASCII names unchanged", () => {
expect(getAttachmentContentDisposition("download-test.txt")).toBe(
'attachment; filename="download-test.txt"',
)
expect(getAttachmentContentDisposition("/some/dir/report-2026.pdf")).toBe(
'attachment; filename="report-2026.pdf"',
)
})

test("content-disposition helper adds RFC 5987 filename* for non-ASCII names", () => {
expect(getAttachmentContentDisposition("报告-2026.txt")).toBe(
`attachment; filename="__-2026.txt"; filename*=UTF-8''%E6%8A%A5%E5%91%8A-2026.txt`,
)
})

test("content-disposition helper sanitizes quotes in the fallback", () => {
expect(getAttachmentContentDisposition('my "quoted".txt')).toBe(
`attachment; filename="my _quoted_.txt"; filename*=UTF-8''my%20%22quoted%22.txt`,
)
})

test("content-disposition helper falls back to a plain name when empty", () => {
expect(getAttachmentContentDisposition("")).toBe(
`attachment; filename="file"`,
)
})

test("downloading a file with a non-ASCII name returns it instead of throwing", async () => {
const { axios } = await getTestServer()

await axios.post("/files/upsert", {
file_path: "/报告-2026.txt",
text_content: "Non-ASCII filename content",
})

// Query-param download form
const queryRes = await axios.get("/files/download", {
params: { file_path: "/报告-2026.txt" },
})
expect(queryRes.status).toBe(200)
expect(queryRes.data).toBe("Non-ASCII filename content")
expect(queryRes.headers.get("content-disposition")).toBe(
`attachment; filename="__-2026.txt"; filename*=UTF-8''%E6%8A%A5%E5%91%8A-2026.txt`,
)

// Path-param download form
const pathRes = await axios.get(
`/files/download/${encodeURI("报告-2026.txt")}`,
)
expect(pathRes.status).toBe(200)
expect(pathRes.data).toBe("Non-ASCII filename content")
expect(pathRes.headers.get("content-disposition")).toBe(
`attachment; filename="__-2026.txt"; filename*=UTF-8''%E6%8A%A5%E5%91%8A-2026.txt`,
)
})

test("downloading a binary file with a quoted name keeps a valid header", async () => {
const { axios } = await getTestServer()

const buffer = Buffer.from([0, 1, 2, 3, 128, 255, 200])
await axios.post("/files/upsert", {
file_path: '/my "quoted".bin',
binary_content_b64: buffer.toString("base64"),
})

const downloadRes = await axios.get("/files/download", {
params: { file_path: '/my "quoted".bin' },
responseType: "arrayBuffer",
})
expect(downloadRes.status).toBe(200)
expect(Buffer.from(downloadRes.data)).toEqual(buffer)
expect(downloadRes.headers.get("content-type")).toBe(
"application/octet-stream",
)
expect(downloadRes.headers.get("content-disposition")).toBe(
`attachment; filename="my _quoted_.bin"; filename*=UTF-8''my%20%22quoted%22.bin`,
)
})