Files
shumai/packages/api/src/s3.ts
T
Yiling-J 8080acfb2e 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).
2026-08-09 16:39:15 +08:00

34 lines
1019 B
TypeScript

import { Hono } from 'hono'
import { buildContentDisposition, s3Service } from '@shumai/core/src/s3/s3'
import { serveStatic } from 'hono/bun'
const route = new Hono()
.get(
'/*',
serveStatic({
root: './data',
rewriteRequestPath: (path) => path.replace(/^\/files\//, ''),
onFound: (_path, c) => {
if (c.req.query('download') === '1') {
c.header('Content-Disposition', buildContentDisposition(c.req.query('filename')))
}
},
}),
)
.put('/:bucket/:key{.+}', async (c) => {
const bucket = c.req.param('bucket')
const key = c.req.param('key')
const contentLength = parseInt(c.req.header('content-length') || '0', 10)
try {
const body = c.req.raw.body ?? (await c.req.arrayBuffer())
await s3Service.putObject(bucket, key, body, contentLength)
return c.text('OK')
} catch (e: unknown) {
const error = e as Error
return c.text(error.message || 'Internal Server Error', 500)
}
})
export default route