diff --git a/packages/api/src/middleware/auth.test.ts b/packages/api/src/middleware/auth.test.ts index 809ed604..c73e7b4a 100644 --- a/packages/api/src/middleware/auth.test.ts +++ b/packages/api/src/middleware/auth.test.ts @@ -1,10 +1,13 @@ import { describe, expect, it, vi, beforeEach } from 'vitest' import { Hono } from 'hono' +import type { Prisma } from '@shumai/db' import { authMiddleware } from './auth' import { auth } from '@shumai/core/src/auth/auth' import { userService } from '@shumai/core/src/user/user' import { teamService } from '@shumai/core/src/team/team' +type User = Prisma.UserGetPayload> + vi.mock('@shumai/core/src/auth/auth', () => ({ auth: { api: { @@ -124,5 +127,59 @@ describe('authMiddleware', () => { const res = await app.request('/test', { method: 'POST' }) expect(res.status).toBe(200) }) + + const createTokenApp = () => + new Hono<{ Variables: { user: User } }>() + .use('*', async (c, next) => { + c.set('user', { id: 'token-user' } as unknown as User) + await next() + }) + .use('*', authMiddleware) + .get('/test', (c) => c.text('ok')) + .post('/test', (c) => c.text('ok')) + .post('/test/search', (c) => c.text('ok')) + .post('/test/recents/view', (c) => c.text('ok')) + .put('/test', (c) => c.text('ok')) + .delete('/test', (c) => c.text('ok')) + + it('rejects POST for token-authenticated user without writable role in demo mode', async () => { + const tokenApp = createTokenApp() + vi.mocked(teamService.hasWritableRoleInAnyTeam).mockResolvedValue(false) + + const res = await tokenApp.request('/test', { method: 'POST' }) + expect(res.status).toBe(403) + expect(await res.json()).toEqual({ error: 'System is in read-only mode' }) + }) + + it('allows GET for token-authenticated user in demo mode', async () => { + const tokenApp = createTokenApp() + const res = await tokenApp.request('/test', { method: 'GET' }) + expect(res.status).toBe(200) + }) + + it('allows allowed demo write paths for token-authenticated user in demo mode', async () => { + const tokenApp = createTokenApp() + vi.mocked(teamService.hasWritableRoleInAnyTeam).mockResolvedValue(false) + + const searchRes = await tokenApp.request('/test/search', { method: 'POST' }) + expect(searchRes.status).toBe(200) + + const recentsRes = await tokenApp.request('/test/recents/view', { method: 'POST' }) + expect(recentsRes.status).toBe(200) + }) + + it('allows write operations for token-authenticated user with writable role in demo mode', async () => { + const tokenApp = createTokenApp() + vi.mocked(teamService.hasWritableRoleInAnyTeam).mockResolvedValue(true) + + const postRes = await tokenApp.request('/test', { method: 'POST' }) + expect(postRes.status).toBe(200) + + const putRes = await tokenApp.request('/test', { method: 'PUT' }) + expect(putRes.status).toBe(200) + + const delRes = await tokenApp.request('/test', { method: 'DELETE' }) + expect(delRes.status).toBe(200) + }) }) }) diff --git a/packages/api/src/middleware/auth.ts b/packages/api/src/middleware/auth.ts index 8c57aaaf..8338d0e9 100644 --- a/packages/api/src/middleware/auth.ts +++ b/packages/api/src/middleware/auth.ts @@ -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() })