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
+21 -4
View File
@@ -39,7 +39,7 @@ describe('S3 API', () => {
}
})
it('GET /files/* sets Content-Disposition: attachment only when download=1 query param is present', async () => {
it('GET /files/* sets Content-Disposition with filename when download=1 & filename query params are present', async () => {
// We need to capture the onFound callback from serveStatic options
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let onFoundCallback: ((path: string, c: any) => void) | undefined
@@ -54,19 +54,36 @@ describe('S3 API', () => {
const { default: route } = await import('./s3')
const app = new Hono().route('/files', route)
await app.request('/files/b1/test.webp?download=1')
await app.request('/files/b1/test.webp?download=1&filename=foo.png')
expect(onFoundCallback).toBeDefined()
// Test with download=1
// Test with download=1 and filename
const mockContextWithDownload = {
req: { query: (key: string) => (key === 'download' ? '1' : undefined) },
req: {
query: (key: string) =>
key === 'download' ? '1' : key === 'filename' ? 'foo.png' : undefined,
},
header: vi.fn(),
}
if (onFoundCallback) {
onFoundCallback('/files/b1/test.webp', mockContextWithDownload)
expect(mockContextWithDownload.header).toHaveBeenCalledWith(
'Content-Disposition',
'attachment; filename="foo.png"; filename*=UTF-8\'\'foo.png',
)
}
// Test with download=1 but no filename
const mockContextDownloadNoFilename = {
req: { query: (key: string) => (key === 'download' ? '1' : undefined) },
header: vi.fn(),
}
if (onFoundCallback) {
onFoundCallback('/files/b1/test.webp', mockContextDownloadNoFilename)
expect(mockContextDownloadNoFilename.header).toHaveBeenCalledWith(
'Content-Disposition',
'attachment',
)
+2 -2
View File
@@ -1,5 +1,5 @@
import { Hono } from 'hono'
import { s3Service } from '@shumai/core/src/s3/s3'
import { buildContentDisposition, s3Service } from '@shumai/core/src/s3/s3'
import { serveStatic } from 'hono/bun'
const route = new Hono()
@@ -10,7 +10,7 @@ const route = new Hono()
rewriteRequestPath: (path) => path.replace(/^\/files\//, ''),
onFound: (_path, c) => {
if (c.req.query('download') === '1') {
c.header('Content-Disposition', 'attachment')
c.header('Content-Disposition', buildContentDisposition(c.req.query('filename')))
}
},
}),
+47
View File
@@ -4,6 +4,7 @@ import { setupTestDbHooks } from '@shumai/db/test'
import { HTTPException } from 'hono/http-exception'
import { AssetType, AssetStatus, Prisma } from '@shumai/db'
import { s3Service } from '@shumai/core/src/s3/s3'
import { AssetService } from './asset'
vi.mock('@shumai/core/src/s3/s3', () => ({
@@ -2229,6 +2230,18 @@ describe('AssetService — natural sort by name', () => {
for (const item of result) {
expect(item.url).toBe('http://mock-s3-url')
}
// Renamed file names must be passed to presign so the download
// Content-Disposition header uses the asset name, not the storage key
for (const name of ['file1.txt', 'file2.txt', 'version2.txt']) {
expect(s3Service.presign).toHaveBeenCalledWith(
expect.any(String),
expect.any(String),
'GET',
true,
name,
)
}
})
it('resolves top-level symlinks to their targets when passed as direct starting IDs', async () => {
@@ -2539,6 +2552,40 @@ describe('AssetService — natural sort by name', () => {
)
expect(url).toBe('http://mock-s3-url')
expect(s3Service.presign).toHaveBeenCalledWith(
expect.any(String),
'files/01TESTULID000000000000000/test-720p.mp4',
'GET',
true,
'test.mp4',
)
})
it('should use the renamed asset name as the download filename', async () => {
const asset = await prisma.asset.create({
data: {
name: 'foo.png',
type: AssetType.file,
status: AssetStatus.uploaded,
storageKey: {
create: { key: 'files/01RENAMEDULID0000000000000/test.png' },
},
},
})
const url = await assetService.getDownloadUrl(
asset.id,
'files/01RENAMEDULID0000000000000/test.png',
)
expect(url).toBe('http://mock-s3-url')
expect(s3Service.presign).toHaveBeenCalledWith(
expect.any(String),
'files/01RENAMEDULID0000000000000/test.png',
'GET',
true,
'foo.png',
)
})
it('should return a presigned download URL for the original key', async () => {
+15 -3
View File
@@ -1966,7 +1966,13 @@ export class AssetService {
const key = file.storageKeyId ? storageKeyMap.get(file.storageKeyId) : null
if (!key) return null
const url = await s3Service.presign(process.env.S3_BUCKET || 'shumai', key, 'GET', true)
const url = await s3Service.presign(
process.env.S3_BUCKET || 'shumai',
key,
'GET',
true,
file.name,
)
return {
id: file.id,
@@ -1988,7 +1994,7 @@ export class AssetService {
const targetAssetId = await this.resolveLatestVersionId(assetId)
const asset = await this.prismaClient.asset.findUnique({
where: { id: targetAssetId },
select: { id: true, parentId: true, storageKey: { select: { key: true } } },
select: { id: true, name: true, parentId: true, storageKey: { select: { key: true } } },
})
if (!asset?.storageKey?.key) {
@@ -2022,7 +2028,13 @@ export class AssetService {
throw new Error('Key does not belong to this asset')
}
return s3Service.presign(process.env.S3_BUCKET || 'shumai', key, 'GET', true)
return s3Service.presign(
process.env.S3_BUCKET || 'shumai',
key,
'GET',
true,
asset.name ?? undefined,
)
}
private async toPreviewInfo(asset: Asset | AssetWithIncludes): Promise<PreviewInfo | null> {
+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
}