fix(api): enforce SHUMAI_DEMO_MODE for API token and CLI requests (#413)

This commit is contained in:
Yiling-J
2026-09-17 21:47:07 +08:00
committed by GitHub
parent d8621a53b6
commit ca94e51424
2 changed files with 88 additions and 31 deletions
+31 -31
View File
@@ -11,44 +11,44 @@ export const authMiddleware = createMiddleware<{
user: User
}
}>(async (c, next) => {
if (c.get('user')) {
await next()
return
}
let user = c.get('user')
const session = await auth.api.getSession({
headers: c.req.raw.headers,
})
if (!user) {
const session = await auth.api.getSession({
headers: c.req.raw.headers,
})
if (!session) {
return c.json({ error: 'Unauthorized' }, 401)
}
try {
const user = await userService.getUserById(session.user.id)
if (!user) {
return c.json({ error: 'User not found' }, 401)
if (!session) {
return c.json({ error: 'Unauthorized' }, 401)
}
c.set('user', user)
try {
const fetchedUser = await userService.getUserById(session.user.id)
if (process.env.SHUMAI_DEMO_MODE === '1') {
const method = c.req.method.toUpperCase()
const path = c.req.path
const isAllowedDemoWrite =
method === 'POST' && (path.endsWith('/search') || path.endsWith('/recents/view'))
if (['POST', 'PUT', 'PATCH', 'DELETE'].includes(method) && !isAllowedDemoWrite) {
const hasWritable = await teamService.hasWritableRoleInAnyTeam(user.id)
if (!fetchedUser) {
return c.json({ error: 'User not found' }, 401)
}
if (!hasWritable) {
return c.json({ error: 'System is in read-only mode' }, 403)
}
user = fetchedUser
c.set('user', user)
} catch {
return c.json({ error: 'Authentication failed' }, 401)
}
}
if (process.env.SHUMAI_DEMO_MODE === '1') {
const method = c.req.method.toUpperCase()
const path = c.req.path
const isAllowedDemoWrite =
method === 'POST' && (path.endsWith('/search') || path.endsWith('/recents/view'))
if (['POST', 'PUT', 'PATCH', 'DELETE'].includes(method) && !isAllowedDemoWrite) {
const hasWritable = await teamService.hasWritableRoleInAnyTeam(user.id)
if (!hasWritable) {
return c.json({ error: 'System is in read-only mode' }, 403)
}
}
await next()
} catch {
return c.json({ error: 'Authentication failed' }, 401)
}
await next()
})