mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-12-03 06:24:30 +00:00
84 lines
2.4 KiB
TypeScript
84 lines
2.4 KiB
TypeScript
import { basename, extname } from 'node:path'
|
|
import { Hono } from 'hono'
|
|
import {
|
|
buildContentDisposition,
|
|
getStorageBackend,
|
|
verifyLocalGetUrlSignature,
|
|
} from '@shumai/core/src/s3/s3'
|
|
import { serveStatic } from 'hono/bun'
|
|
|
|
// Only serve formats used by preview and media clients inline on the app origin.
|
|
const inlineFileTypes = new Map([
|
|
['.aac', 'audio/aac'],
|
|
['.avif', 'image/avif'],
|
|
['.bmp', 'image/bmp'],
|
|
['.gif', 'image/gif'],
|
|
['.glb', 'model/gltf-binary'],
|
|
['.gltf', 'model/gltf+json'],
|
|
['.ico', 'image/x-icon'],
|
|
['.jpeg', 'image/jpeg'],
|
|
['.jpg', 'image/jpeg'],
|
|
['.m3u8', 'application/vnd.apple.mpegurl'],
|
|
['.m4a', 'audio/mp4'],
|
|
['.m4s', 'video/iso.segment'],
|
|
['.mp3', 'audio/mpeg'],
|
|
['.mp4', 'video/mp4'],
|
|
['.ogg', 'audio/ogg'],
|
|
['.opus', 'audio/opus'],
|
|
['.pdf', 'application/pdf'],
|
|
['.png', 'image/png'],
|
|
['.ts', 'video/mp2t'],
|
|
['.wav', 'audio/wav'],
|
|
['.webm', 'video/webm'],
|
|
['.webp', 'image/webp'],
|
|
])
|
|
|
|
const route = new Hono()
|
|
.use('*', async (c, next) => {
|
|
if (getStorageBackend() !== 'local') {
|
|
return c.notFound()
|
|
}
|
|
return next()
|
|
})
|
|
.get(
|
|
'/*',
|
|
async (c, next) => {
|
|
const fullPath = c.req.path.replace(/^\/files\//, '').replace(/^\//, '')
|
|
const slashIdx = fullPath.indexOf('/')
|
|
if (slashIdx === -1) {
|
|
return c.notFound()
|
|
}
|
|
const bucket = fullPath.slice(0, slashIdx)
|
|
const key = fullPath.slice(slashIdx + 1)
|
|
|
|
const signature = c.req.query('Signature')
|
|
const expires = c.req.query('Expires')
|
|
|
|
if (!verifyLocalGetUrlSignature(bucket, key, signature, expires)) {
|
|
return c.json({ error: 'Forbidden: invalid or expired signature' }, 403)
|
|
}
|
|
|
|
return next()
|
|
},
|
|
serveStatic({
|
|
root: './data',
|
|
rewriteRequestPath: (path) => path.replace(/^\/files\//, ''),
|
|
onFound: (path, c) => {
|
|
const inlineType = inlineFileTypes.get(extname(path).toLowerCase())
|
|
c.header('Content-Type', inlineType ?? 'application/octet-stream')
|
|
c.header('X-Content-Type-Options', 'nosniff')
|
|
|
|
if (!inlineType) {
|
|
c.header('Content-Security-Policy', 'sandbox')
|
|
}
|
|
|
|
if (!inlineType || c.req.query('download') === '1') {
|
|
const filename = c.req.query('filename') ?? (inlineType ? undefined : basename(path))
|
|
c.header('Content-Disposition', buildContentDisposition(filename))
|
|
}
|
|
},
|
|
}),
|
|
)
|
|
|
|
export default route
|