fix: use renamed asset name in download Content-Disposition (#286)

* fix(core): use renamed asset name in download Content-Disposition

Downloads of renamed assets (e.g. test.png renamed to foo.png) previously
saved under the storage-key basename because the presigned URLs / local
file handler only set Content-Disposition: attachment without a filename,
and the HTML download attribute is ignored for cross-origin URLs.

- Add buildContentDisposition() helper that emits a sanitized
  'attachment; filename=...; filename*=UTF-8...' header (RFC 5987) so
  non-ASCII names survive.
- Thread an optional filename through S3Service.presign():
  * S3 backend passes it via contentDisposition (response-content-disposition)
  * Local backend carries it as a ?filename= query param consumed by the
    /files serveStatic onFound handler
- getDownloadLinks / getDownloadUrl now pass the renamed asset name from
  the DB, so all download flows (file browser, viewers, breadcrumb, share)
  save files under the current asset name.

* fix(core): keep Content-Disposition header ASCII for non-ASCII names

Bun's Headers API rejects header values containing non-ASCII bytes, so a
download of a renamed file with a non-ASCII name (e.g. 幻境边界.pptx) threw
'TypeError: Header Content-Disposition has invalid value' on the local
storage backend.

Per RFC 5987, non-ASCII names belong only in the percent-encoded
filename* parameter. buildContentDisposition now emits the quoted
filename="..." fallback only when the name is pure ASCII; otherwise the
header carries just 'attachment; filename*=UTF-8''...' (all-ASCII, accepted
by Bun/Node Headers and all modern browsers).
This commit is contained in:
Yiling-J
2026-08-09 16:39:15 +08:00
committed by GitHub
parent dbd30a815f
commit 8080acfb2e
6 changed files with 223 additions and 14 deletions
+81 -1
View File
@@ -1,7 +1,7 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import * as fs from 'fs'
import * as path from 'path'
import { LocalStorageService, S3StorageService } from './s3'
import { buildContentDisposition, LocalStorageService, S3StorageService } from './s3'
// Mock Bun S3Client
const s3ClientConstructorSpy = vi.fn()
@@ -140,6 +140,32 @@ describe('S3Service implementations', () => {
)
})
it('should set contentDisposition with the filename when download filename is provided', async () => {
const s3 = new S3StorageService('http://localhost:9000', 'key', 'secret', 'test-bucket')
await s3.presign('bucket', 'key', 'GET', true, 'foo.png')
expect(s3PresignSpy).toHaveBeenCalledWith(
'key',
expect.objectContaining({
contentDisposition: 'attachment; filename="foo.png"; filename*=UTF-8\'\'foo.png',
}),
)
})
it('should include an RFC 5987 filename* for non-ASCII filenames', async () => {
const s3 = new S3StorageService('http://localhost:9000', 'key', 'secret', 'test-bucket')
await s3.presign('bucket', 'key', 'GET', true, '报告.png')
expect(s3PresignSpy).toHaveBeenCalledWith(
'key',
expect.objectContaining({
// Non-ASCII names are conveyed only via filename* (percent-encoded),
// keeping the header value pure ASCII (RFC 7230).
contentDisposition: "attachment; filename*=UTF-8''%E6%8A%A5%E5%91%8A.png",
}),
)
})
it('should not cache download presign URLs', async () => {
const s3 = new S3StorageService('http://localhost:9000', 'key', 'secret', 'test-bucket')
@@ -248,6 +274,18 @@ describe('S3Service implementations', () => {
expect(url).toBe('http://localhost:3000/files/my-bucket/dir/file.txt?download=1')
})
it('should include an encoded filename in the local download URL', async () => {
const url = await localS3.presign('my-bucket', 'dir/file.txt', 'GET', true, 'foo bar.png')
expect(url).toBe(
'http://localhost:3000/files/my-bucket/dir/file.txt?download=1&filename=foo%20bar.png',
)
})
it('should not append a filename param when none is provided', async () => {
const url = await localS3.presign('my-bucket', 'dir/file.txt', 'GET', true)
expect(url).not.toContain('filename=')
})
it('should throw an error for unsupported presign methods', async () => {
await expect(localS3.presign('b', 'k', 'POST')).rejects.toThrow()
})
@@ -287,4 +325,46 @@ describe('S3Service implementations', () => {
expect(url).not.toContain('4567')
})
})
describe('buildContentDisposition', () => {
it('returns plain attachment when no filename is provided', () => {
expect(buildContentDisposition()).toBe('attachment')
expect(buildContentDisposition('')).toBe('attachment')
expect(buildContentDisposition(null)).toBe('attachment')
})
it('builds a disposition with quoted filename and RFC 5987 filename*', () => {
expect(buildContentDisposition('foo.png')).toBe(
'attachment; filename="foo.png"; filename*=UTF-8\'\'foo.png',
)
})
it('strips control characters and quotes to prevent header injection', () => {
expect(buildContentDisposition('a\r\nb"c\\d')).toBe(
'attachment; filename="abcd"; filename*=UTF-8\'\'abcd',
)
})
it('percent-encodes reserved RFC 5987 characters', () => {
expect(buildContentDisposition("it's (final).png")).toBe(
"attachment; filename=\"it's (final).png\"; filename*=UTF-8''it%27s%20%28final%29.png",
)
})
it('percent-encodes the * character in filename*', () => {
expect(buildContentDisposition('foo*bar.png')).toBe(
'attachment; filename="foo*bar.png"; filename*=UTF-8\'\'foo%2Abar.png',
)
})
it('omits the quoted filename fallback for non-ASCII names to keep the header ASCII', () => {
expect(buildContentDisposition('幻境边界.pptx')).toBe(
"attachment; filename*=UTF-8''%E5%B9%BB%E5%A2%83%E8%BE%B9%E7%95%8C.pptx",
)
// The whole header value must remain pure ASCII so Bun/Node Headers accept it
expect(
[...buildContentDisposition('幻境边界.pptx')].every((ch) => ch.charCodeAt(0) <= 0x7f),
).toBe(true)
})
})
})
+57 -4
View File
@@ -27,6 +27,38 @@ export function verifyLocalUrlSignature(bucket: string, key: string, signature:
}
}
/**
* Build a Content-Disposition header value for downloads.
* - Falls back to plain `attachment` when no filename is provided.
* - Strips control characters (CR/LF header injection), quotes, and backslashes.
* - Header values must be ASCII (RFC 7230): non-ASCII names are conveyed only
* via the percent-encoded RFC 5987 `filename*` parameter; the quoted
* `filename="..."` fallback is included only when the name is pure ASCII.
*/
export function buildContentDisposition(filename?: string | null): string {
if (!filename) return 'attachment'
// Strip C0 control characters (incl. CR/LF header injection) and DEL, then
// quotes/backslashes which would break the quoted-string form.
const sanitized = [...filename]
.filter((ch) => {
const code = ch.charCodeAt(0)
return code > 0x1f && code !== 0x7f && ch !== '"' && ch !== '\\'
})
.join('')
.trim()
if (!sanitized) return 'attachment'
// RFC 5987 attr-char excludes ' ( ) * — percent-encode them explicitly
const encoded = encodeURIComponent(sanitized).replace(
/['()*]/g,
(c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`,
)
const isAscii = [...sanitized].every((ch) => ch.charCodeAt(0) <= 0x7f)
if (!isAscii) {
return `attachment; filename*=UTF-8''${encoded}`
}
return `attachment; filename="${sanitized}"; filename*=UTF-8''${encoded}`
}
export interface S3Object {
buffer: Buffer
contentType: string
@@ -55,7 +87,13 @@ export interface S3Service {
listObjects: (bucket: string, prefix: string) => Promise<string[]>
uploadFile: (filePath: string, contentType: string) => Promise<string>
uploadFileToKey: (filePath: string, key: string, contentType: string) => Promise<void>
presign: (bucket: string, key: string, method: string, download?: boolean) => Promise<string>
presign: (
bucket: string,
key: string,
method: string,
download?: boolean,
filename?: string,
) => Promise<string>
}
export class S3StorageService implements S3Service {
@@ -214,7 +252,13 @@ export class S3StorageService implements S3Service {
})
}
async presign(bucket: string, key: string, method: string, download?: boolean): Promise<string> {
async presign(
bucket: string,
key: string,
method: string,
download?: boolean,
filename?: string,
): Promise<string> {
const expireHours = parseInt(process.env.PRESIGNED_URL_EXPIRES_IN || '5', 10)
const expiresInSeconds = expireHours * 3600
// Cache time is 2/3 of expire time, rounded to minute
@@ -237,7 +281,7 @@ export class S3StorageService implements S3Service {
}
if (download) {
options.contentDisposition = 'attachment'
options.contentDisposition = buildContentDisposition(filename)
}
const url = this.client.presign(key, options)
@@ -461,7 +505,13 @@ export class LocalStorageService implements S3Service {
await fs.promises.copyFile(filePath, destPath)
}
async presign(bucket: string, key: string, method: string, download?: boolean): Promise<string> {
async presign(
bucket: string,
key: string,
method: string,
download?: boolean,
filename?: string,
): Promise<string> {
if (method !== 'GET' && method !== 'PUT') {
throw new Error(`Invalid method: ${method}`)
}
@@ -471,6 +521,9 @@ export class LocalStorageService implements S3Service {
let url = `${this.endpoint}/files/${bucket}/${key}`
if (download) {
url += '?download=1'
if (filename) {
url += `&filename=${encodeURIComponent(filename)}`
}
}
return url
}