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
45 changes: 45 additions & 0 deletions lib/utils/file-download-response.ts
Original file line number Diff line number Diff line change
@@ -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,
},
})
}
29 changes: 2 additions & 27 deletions routes/files/download.ts
Original file line number Diff line number Diff line change
@@ -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({
Expand All @@ -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)
})
29 changes: 2 additions & 27 deletions routes/files/download/[[...file_path]].ts
Original file line number Diff line number Diff line change
@@ -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({
Expand All @@ -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)
})
29 changes: 29 additions & 0 deletions tests/routes/files.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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('""')
}
}
})
Loading