Files
shumai/packages/api/src/s3.ts
T
Yiling-J 65e2ac1383 fix(security): improve access control and storage security (#518)
* fix(security): improve access control and storage security

* fix(security): set NODE_ENV in dockerfiles and sign local storage get urls with lru cache
2026-11-05 20:49:38 +08:00

48 lines
1.3 KiB
TypeScript

import { Hono } from 'hono'
import {
buildContentDisposition,
getStorageBackend,
verifyLocalGetUrlSignature,
} from '@shumai/core/src/s3/s3'
import { serveStatic } from 'hono/bun'
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) => {
if (c.req.query('download') === '1') {
c.header('Content-Disposition', buildContentDisposition(c.req.query('filename')))
}
},
}),
)
export default route