refactor(authz): move to domain-based authz and flatten routes

This commit is contained in:
yiling
2026-05-25 23:51:37 +08:00
parent 35fd5c78ce
commit 9f9549255d
61 changed files with 1646 additions and 1147 deletions
+9 -8
View File
@@ -96,7 +96,7 @@ describe('Agent API', () => {
}) })
}) })
describe('PUT /teams/:teamId/agents/:agentId', () => { describe('PUT /agents/:agentId', () => {
it('updates an agent', async () => { it('updates an agent', async () => {
const mockAgent = { const mockAgent = {
id: 'agent1', id: 'agent1',
@@ -111,7 +111,7 @@ describe('Agent API', () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
vi.mocked(agentService.updateAgent).mockResolvedValue(mockAgent as any) vi.mocked(agentService.updateAgent).mockResolvedValue(mockAgent as any)
const res = await app.request('/teams/team1/agents/agent1', { const res = await app.request('/agents/agent1', {
method: 'PUT', method: 'PUT',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ body: JSON.stringify({
@@ -131,9 +131,9 @@ describe('Agent API', () => {
}) })
}) })
describe('DELETE /teams/:teamId/agents/:agentId', () => { describe('DELETE /agents/:agentId', () => {
it('deletes an agent', async () => { it('deletes an agent', async () => {
const res = await app.request('/teams/team1/agents/agent1', { const res = await app.request('/agents/agent1', {
method: 'DELETE', method: 'DELETE',
}) })
@@ -142,7 +142,7 @@ describe('Agent API', () => {
}) })
}) })
describe('GET /teams/:teamId/agent-sessions/:sessionId/entries', () => { describe('GET /agent-sessions/:sessionId/entries', () => {
it('returns entries of agent session if user is admin', async () => { it('returns entries of agent session if user is admin', async () => {
const mockEntries = [ const mockEntries = [
{ {
@@ -154,7 +154,7 @@ describe('Agent API', () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
vi.mocked(agentService.getSessionEntries).mockResolvedValue(mockEntries as any) vi.mocked(agentService.getSessionEntries).mockResolvedValue(mockEntries as any)
const res = await app.request('/teams/team1/agent-sessions/session1/entries', { const res = await app.request('/agent-sessions/session1/entries', {
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
}) })
@@ -164,16 +164,17 @@ describe('Agent API', () => {
expect(data[0].id).toBe('entry1') expect(data[0].id).toBe('entry1')
expect(data[0].entry.step).toBe(1) expect(data[0].entry.step).toBe(1)
expect(authzService.hasPermission).toHaveBeenCalledWith({ expect(authzService.hasPermission).toHaveBeenCalledWith({
teamId: 'team1',
user: undefined, user: undefined,
permission: 'Admin', permission: 'Admin',
type: 'agentSession',
id: 'session1',
}) })
}) })
it('denies access if user is not admin', async () => { it('denies access if user is not admin', async () => {
vi.mocked(authzService.hasPermission).mockRejectedValue(new Error('Forbidden')) vi.mocked(authzService.hasPermission).mockRejectedValue(new Error('Forbidden'))
const res = await app.request('/teams/team1/agent-sessions/session1/entries', { const res = await app.request('/agent-sessions/session1/entries', {
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
}) })
+45 -47
View File
@@ -1,7 +1,7 @@
import { Hono } from 'hono' import { Hono } from 'hono'
import { zValidator } from '@hono/zod-validator' import { zValidator } from '@hono/zod-validator'
import { agentService } from '@/services/agent/agent' import { agentService } from '@/services/agent/agent'
import { authzService, Permission } from '@/services/authz/authz' import { authzService, Permission, ResourceType } from '@/services/authz/authz'
import { import {
createAgentRequestSchema, createAgentRequestSchema,
updateAgentRequestSchema, updateAgentRequestSchema,
@@ -19,9 +19,10 @@ const route = new Hono<{ Variables: { user: User } }>()
const userReq = c.get('user') const userReq = c.get('user')
await authzService.hasPermission({ await authzService.hasPermission({
teamId,
user: userReq, user: userReq,
permission: Permission.Read, permission: Permission.Read,
type: ResourceType.Team,
id: teamId,
}) })
const agents = await agentService.listAgents({ teamId }) const agents = await agentService.listAgents({ teamId })
@@ -55,9 +56,10 @@ const route = new Hono<{ Variables: { user: User } }>()
const req = c.req.valid('json') const req = c.req.valid('json')
await authzService.hasPermission({ await authzService.hasPermission({
teamId,
user: userReq, user: userReq,
permission: Permission.Admin, permission: Permission.Admin,
type: ResourceType.Team,
id: teamId,
}) })
const agent = await agentService.createAgent({ const agent = await agentService.createAgent({
@@ -88,57 +90,53 @@ const route = new Hono<{ Variables: { user: User } }>()
return c.json(info, 200) return c.json(info, 200)
}) })
.put( .put('/agents/:agentId', zValidator('json', updateAgentRequestSchema), async (c) => {
'/teams/:teamId/agents/:agentId', const agentId = c.req.param('agentId')
zValidator('json', updateAgentRequestSchema), const userReq = c.get('user')
async (c) => { const req = c.req.valid('json')
const teamId = c.req.param('teamId')
const agentId = c.req.param('agentId')
const userReq = c.get('user')
const req = c.req.valid('json')
await authzService.hasPermission({ await authzService.hasPermission({
teamId, user: userReq,
user: userReq, permission: Permission.Admin,
permission: Permission.Admin, type: ResourceType.Agent,
}) id: agentId,
})
const agent = await agentService.updateAgent({ const agent = await agentService.updateAgent({
agentId, agentId,
...req, ...req,
}) })
const config = agent.config as unknown as PrismaJson.AgentConfig const config = agent.config as unknown as PrismaJson.AgentConfig
const info: AgentInfo = { const info: AgentInfo = {
id: agent.id, id: agent.id,
name: agent.user.name, name: agent.user.name,
type: agent.type as AgentType, type: agent.type as AgentType,
enabled: agent.enabled, enabled: agent.enabled,
avatar: agent.user.image || undefined, avatar: agent.user.image || undefined,
providerId: agent.providerId || undefined, providerId: agent.providerId || undefined,
modelId: agent.modelId || undefined, modelId: agent.modelId || undefined,
thinkingLevel: config.thinkingLevel || '', thinkingLevel: config.thinkingLevel || '',
systemPrompt: config.systemPrompt, systemPrompt: config.systemPrompt,
soul: agent.soul || undefined, soul: agent.soul || undefined,
skills: agent.skills.map((s) => ({ skills: agent.skills.map((s) => ({
id: s.id, id: s.id,
skillId: s.skillId, skillId: s.skillId,
skill: s.skill, skill: s.skill,
})), })),
} }
return c.json(info, 200) return c.json(info, 200)
}, })
) .delete('/agents/:agentId', async (c) => {
.delete('/teams/:teamId/agents/:agentId', async (c) => {
const teamId = c.req.param('teamId')
const agentId = c.req.param('agentId') const agentId = c.req.param('agentId')
const userReq = c.get('user') const userReq = c.get('user')
await authzService.hasPermission({ await authzService.hasPermission({
teamId,
user: userReq, user: userReq,
permission: Permission.Admin, permission: Permission.Admin,
type: ResourceType.Agent,
id: agentId,
}) })
await agentService.deleteAgent({ await agentService.deleteAgent({
@@ -147,15 +145,15 @@ const route = new Hono<{ Variables: { user: User } }>()
return new Response(null, { status: 204 }) return new Response(null, { status: 204 })
}) })
.get('/teams/:teamId/agent-sessions/:sessionId/entries', async (c) => { .get('/agent-sessions/:sessionId/entries', async (c) => {
const teamId = c.req.param('teamId')
const sessionId = c.req.param('sessionId') const sessionId = c.req.param('sessionId')
const userReq = c.get('user') const userReq = c.get('user')
await authzService.hasPermission({ await authzService.hasPermission({
teamId,
user: userReq, user: userReq,
permission: Permission.Admin, permission: Permission.Admin,
type: ResourceType.AgentSession,
id: sessionId,
}) })
const entries = await agentService.getSessionEntries({ sessionId }) const entries = await agentService.getSessionEntries({ sessionId })
+11 -11
View File
@@ -4,6 +4,7 @@ import attachmentRoute from './attachment'
import { assetService } from '@/services/asset/asset' import { assetService } from '@/services/asset/asset'
import { AssetType } from '@/generated/prisma/client' import { AssetType } from '@/generated/prisma/client'
import { authMiddleware } from '@/api/middleware/auth' import { authMiddleware } from '@/api/middleware/auth'
import { authzService, Permission, ResourceType } from '@/services/authz/authz'
vi.mock('@/api/middleware/auth', () => ({ vi.mock('@/api/middleware/auth', () => ({
// any is used here because Hono's Context and Next types are complex to mock in vitest.mock // any is used here because Hono's Context and Next types are complex to mock in vitest.mock
@@ -15,16 +16,8 @@ vi.mock('@/api/middleware/auth', () => ({
}, },
})) }))
vi.mock('@/services/authz/authz', () => ({ vi.mock('@/services/authz/authz')
authzService: { vi.mock('@/services/asset/asset')
hasPermission: vi.fn(),
},
Permission: {
Read: 'Read',
Edit: 'Edit',
Admin: 'Admin',
},
}))
vi.mock('@/services/s3/s3', () => ({ vi.mock('@/services/s3/s3', () => ({
s3Service: { s3Service: {
@@ -37,12 +30,13 @@ describe('Attachment API', () => {
beforeEach(() => { beforeEach(() => {
vi.restoreAllMocks() vi.restoreAllMocks()
vi.mocked(authzService.hasPermission).mockResolvedValue(undefined)
}) })
it('POST /projects/:projectId/attachments', async () => { it('POST /projects/:projectId/attachments', async () => {
// We only need the id for this test // We only need the id for this test
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
vi.spyOn(assetService, 'createAsset').mockResolvedValue({ id: 'asset1' } as any) vi.mocked(assetService.createAsset).mockResolvedValue({ id: 'asset1' } as any)
const res = await app.request('/projects/project1/attachments', { const res = await app.request('/projects/project1/attachments', {
method: 'POST', method: 'POST',
@@ -58,6 +52,12 @@ describe('Attachment API', () => {
const json = await res.json() const json = await res.json()
expect(json.id).toBe('asset1') expect(json.id).toBe('asset1')
expect(json.uploadUrl).toBe('http://mock-s3-url') expect(json.uploadUrl).toBe('http://mock-s3-url')
expect(authzService.hasPermission).toHaveBeenCalledWith({
user: expect.anything(),
permission: Permission.Edit,
type: ResourceType.Project,
id: 'project1',
})
expect(assetService.createAsset).toHaveBeenCalledWith( expect(assetService.createAsset).toHaveBeenCalledWith(
expect.objectContaining({ expect.objectContaining({
name: 'test.txt', name: 'test.txt',
+3 -2
View File
@@ -5,7 +5,7 @@ import { assetService } from '@/services/asset/asset'
import { s3Service } from '@/services/s3/s3' import { s3Service } from '@/services/s3/s3'
import { AssetType } from '@/generated/prisma/client' import { AssetType } from '@/generated/prisma/client'
import { ulid } from 'ulid' import { ulid } from 'ulid'
import { authzService, Permission } from '@/services/authz/authz' import { authzService, Permission, ResourceType } from '@/services/authz/authz'
import type { Prisma } from '@/generated/prisma/client' import type { Prisma } from '@/generated/prisma/client'
type User = Prisma.UserGetPayload<Record<string, never>> type User = Prisma.UserGetPayload<Record<string, never>>
@@ -19,9 +19,10 @@ const route = new Hono<{ Variables: { user: User } }>().post(
const req = c.req.valid('json') const req = c.req.valid('json')
await authzService.hasPermission({ await authzService.hasPermission({
projectId,
user, user,
permission: Permission.Edit, permission: Permission.Edit,
type: ResourceType.Project,
id: projectId,
}) })
const key = `attachments/${ulid()}/${req.fileName}` const key = `attachments/${ulid()}/${req.fileName}`
+83 -62
View File
@@ -1,26 +1,46 @@
import { describe, it, expect, vi, beforeEach } from 'vitest' import { describe, it, expect, vi, beforeEach } from 'vitest'
import { collectionService } from '@/services/collection/collection' import { collectionService } from '@/services/collection/collection'
import { authzService } from '@/services/authz/authz' import { authzService, Permission, ResourceType } from '@/services/authz/authz'
import app from './collection' import { Hono, Context, Next } from 'hono'
import collectionRoute from './collection'
vi.mock('@/api/middleware/auth', () => ({ vi.mock('@/api/middleware/auth', () => ({
authMiddleware: vi.fn(async (c, next) => { authMiddleware: async (c: Context, next: Next) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any c.set('user', { id: 'user-1', name: 'Test User' })
c.set('user', { id: 'user-1', name: 'Test User' } as any)
await next() await next()
}), },
}))
vi.mock('@/services/authz/authz', () => ({
authzService: {
hasPermission: vi.fn().mockResolvedValue(undefined),
},
Permission: {
Read: 'Read',
Edit: 'Edit',
Admin: 'Admin',
},
ResourceType: {
Project: 'project',
Collection: 'collection',
},
})) }))
describe('Collection API', () => { describe('Collection API', () => {
const teamId = 'team-1'
const projectId = 'project-1' const projectId = 'project-1'
const collectionId = 'col-1' const collectionId = 'col-1'
const authMiddleware = async (c: Context, next: Next) => {
c.set('user', { id: 'user-1', name: 'Test User' })
await next()
}
const app = new Hono().use('*', authMiddleware).route('/', collectionRoute)
beforeEach(() => { beforeEach(() => {
vi.restoreAllMocks() vi.restoreAllMocks()
vi.mocked(authzService.hasPermission).mockResolvedValue(undefined)
}) })
it('POST /teams/:teamId/projects/:projectId/collections', async () => { it('POST /projects/:projectId/collections', async () => {
const mockCreate = vi.spyOn(collectionService, 'createCollection').mockResolvedValue({ const mockCreate = vi.spyOn(collectionService, 'createCollection').mockResolvedValue({
id: collectionId, id: collectionId,
name: 'New Collection', name: 'New Collection',
@@ -34,33 +54,29 @@ describe('Collection API', () => {
updatedAt: new Date(), updatedAt: new Date(),
}) })
const mockAuthz = vi.spyOn(authzService, 'hasPermission').mockResolvedValue(undefined) const res = await app.request(`/projects/${projectId}/collections`, {
method: 'POST',
const res = await app.request( headers: { 'Content-Type': 'application/json' },
`/teams/${teamId}/projects/${projectId}/collections`, body: JSON.stringify({
{ name: 'New Collection',
method: 'POST', filter: {
headers: { 'Content-Type': 'application/json' }, sourceFolderId: 'root-1',
body: JSON.stringify({ searchFilter: { conditions: [], operator: 'AND', recursively: true },
name: 'New Collection', },
filter: { }),
sourceFolderId: 'root-1', })
searchFilter: { conditions: [], operator: 'AND', recursively: true },
},
}),
},
{
user: { id: 'user-1' },
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} as any,
)
expect(res.status).toBe(200) expect(res.status).toBe(200)
expect(mockCreate).toHaveBeenCalledWith(projectId, expect.any(Object)) expect(mockCreate).toHaveBeenCalledWith(projectId, expect.any(Object))
expect(mockAuthz).toHaveBeenCalled() expect(authzService.hasPermission).toHaveBeenCalledWith({
user: expect.any(Object),
permission: Permission.Edit,
type: ResourceType.Project,
id: projectId,
})
}) })
it('GET /teams/:teamId/projects/:projectId/collections', async () => { it('GET /projects/:projectId/collections', async () => {
const mockList = vi.spyOn(collectionService, 'listCollections').mockResolvedValue({ const mockList = vi.spyOn(collectionService, 'listCollections').mockResolvedValue({
data: [ data: [
{ {
@@ -79,18 +95,21 @@ describe('Collection API', () => {
pageInfo: { total: 1 }, pageInfo: { total: 1 },
}) })
const mockAuthz = vi.spyOn(authzService, 'hasPermission').mockResolvedValue(undefined) const res = await app.request(`/projects/${projectId}/collections`)
const res = await app.request(`/teams/${teamId}/projects/${projectId}/collections`)
expect(res.status).toBe(200) expect(res.status).toBe(200)
const json = await res.json() const json = await res.json()
expect(json.data).toHaveLength(1) expect(json.data).toHaveLength(1)
expect(mockList).toHaveBeenCalled() expect(mockList).toHaveBeenCalled()
expect(mockAuthz).toHaveBeenCalled() expect(authzService.hasPermission).toHaveBeenCalledWith({
user: expect.any(Object),
permission: Permission.Read,
type: ResourceType.Project,
id: projectId,
})
}) })
it('GET /teams/:teamId/projects/:projectId/collections/:collectionId', async () => { it('GET /collections/:collectionId', async () => {
const mockGet = vi.spyOn(collectionService, 'getCollection').mockResolvedValue({ const mockGet = vi.spyOn(collectionService, 'getCollection').mockResolvedValue({
id: collectionId, id: collectionId,
name: 'Col 1', name: 'Col 1',
@@ -104,18 +123,19 @@ describe('Collection API', () => {
updatedAt: new Date(), updatedAt: new Date(),
}) })
const mockAuthz = vi.spyOn(authzService, 'hasPermission').mockResolvedValue(undefined) const res = await app.request(`/collections/${collectionId}`)
const res = await app.request(
`/teams/${teamId}/projects/${projectId}/collections/${collectionId}`,
)
expect(res.status).toBe(200) expect(res.status).toBe(200)
expect(mockGet).toHaveBeenCalledWith(collectionId) expect(mockGet).toHaveBeenCalledWith(collectionId)
expect(mockAuthz).toHaveBeenCalled() expect(authzService.hasPermission).toHaveBeenCalledWith({
user: expect.any(Object),
permission: Permission.Read,
type: ResourceType.Collection,
id: collectionId,
})
}) })
it('PATCH /teams/:teamId/projects/:projectId/collections/:collectionId', async () => { it('PATCH /collections/:collectionId', async () => {
const mockUpdate = vi.spyOn(collectionService, 'updateCollection').mockResolvedValue({ const mockUpdate = vi.spyOn(collectionService, 'updateCollection').mockResolvedValue({
id: collectionId, id: collectionId,
name: 'Updated Name', name: 'Updated Name',
@@ -129,36 +149,37 @@ describe('Collection API', () => {
updatedAt: new Date(), updatedAt: new Date(),
}) })
const mockAuthz = vi.spyOn(authzService, 'hasPermission').mockResolvedValue(undefined) const res = await app.request(`/collections/${collectionId}`, {
method: 'PATCH',
const res = await app.request( headers: { 'Content-Type': 'application/json' },
`/teams/${teamId}/projects/${projectId}/collections/${collectionId}`, body: JSON.stringify({ name: 'Updated Name' }),
{ })
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'Updated Name' }),
},
)
expect(res.status).toBe(200) expect(res.status).toBe(200)
expect(mockUpdate).toHaveBeenCalledWith(collectionId, { name: 'Updated Name' }) expect(mockUpdate).toHaveBeenCalledWith(collectionId, { name: 'Updated Name' })
expect(mockAuthz).toHaveBeenCalled() expect(authzService.hasPermission).toHaveBeenCalledWith({
user: expect.any(Object),
permission: Permission.Edit,
type: ResourceType.Collection,
id: collectionId,
})
}) })
it('DELETE /teams/:teamId/projects/:projectId/collections/:collectionId', async () => { it('DELETE /collections/:collectionId', async () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
const mockDelete = vi.spyOn(collectionService, 'deleteCollection').mockResolvedValue({} as any) const mockDelete = vi.spyOn(collectionService, 'deleteCollection').mockResolvedValue({} as any)
const mockAuthz = vi.spyOn(authzService, 'hasPermission').mockResolvedValue(undefined)
const res = await app.request( const res = await app.request(`/collections/${collectionId}`, {
`/teams/${teamId}/projects/${projectId}/collections/${collectionId}`, method: 'DELETE',
{ })
method: 'DELETE',
},
)
expect(res.status).toBe(200) expect(res.status).toBe(200)
expect(mockDelete).toHaveBeenCalledWith(collectionId) expect(mockDelete).toHaveBeenCalledWith(collectionId)
expect(mockAuthz).toHaveBeenCalled() expect(authzService.hasPermission).toHaveBeenCalledWith({
user: expect.any(Object),
permission: Permission.Edit,
type: ResourceType.Collection,
id: collectionId,
})
}) })
}) })
+21 -21
View File
@@ -1,7 +1,7 @@
import { zValidator } from '@hono/zod-validator' import { zValidator } from '@hono/zod-validator'
import { Hono } from 'hono' import { Hono } from 'hono'
import { collectionService } from '@/services/collection/collection' import { collectionService } from '@/services/collection/collection'
import { authzService, Permission } from '@/services/authz/authz' import { authzService, Permission, ResourceType } from '@/services/authz/authz'
import { import {
createCollectionRequestSchema, createCollectionRequestSchema,
updateCollectionRequestSchema, updateCollectionRequestSchema,
@@ -26,18 +26,18 @@ function toCollectionInfo(c: Prisma.CollectionGetPayload<Record<string, never>>)
const route = new Hono<{ Variables: { user: User } }>() const route = new Hono<{ Variables: { user: User } }>()
.post( .post(
'/teams/:teamId/projects/:projectId/collections', '/projects/:projectId/collections',
zValidator('json', createCollectionRequestSchema), zValidator('json', createCollectionRequestSchema),
async (c) => { async (c) => {
const { teamId, projectId } = c.req.param() const { projectId } = c.req.param()
const req = c.req.valid('json') const req = c.req.valid('json')
const user = c.get('user') const user = c.get('user')
await authzService.hasPermission({ await authzService.hasPermission({
teamId,
projectId,
user, user,
permission: Permission.Edit, permission: Permission.Edit,
type: ResourceType.Project,
id: projectId,
}) })
const collection = await collectionService.createCollection(projectId, req) const collection = await collectionService.createCollection(projectId, req)
@@ -45,18 +45,18 @@ const route = new Hono<{ Variables: { user: User } }>()
}, },
) )
.get( .get(
'/teams/:teamId/projects/:projectId/collections', '/projects/:projectId/collections',
zValidator('query', listCollectionsRequestSchema), zValidator('query', listCollectionsRequestSchema),
async (c) => { async (c) => {
const { teamId, projectId } = c.req.param() const { projectId } = c.req.param()
const req = c.req.valid('query') const req = c.req.valid('query')
const user = c.get('user') const user = c.get('user')
await authzService.hasPermission({ await authzService.hasPermission({
teamId,
projectId,
user, user,
permission: Permission.Read, permission: Permission.Read,
type: ResourceType.Project,
id: projectId,
}) })
const collections = await collectionService.listCollections(projectId, req) const collections = await collectionService.listCollections(projectId, req)
@@ -67,15 +67,15 @@ const route = new Hono<{ Variables: { user: User } }>()
}) })
}, },
) )
.get('/teams/:teamId/projects/:projectId/collections/:collectionId', async (c) => { .get('/collections/:collectionId', async (c) => {
const { teamId, projectId, collectionId } = c.req.param() const { collectionId } = c.req.param()
const user = c.get('user') const user = c.get('user')
await authzService.hasPermission({ await authzService.hasPermission({
teamId,
projectId,
user, user,
permission: Permission.Read, permission: Permission.Read,
type: ResourceType.Collection,
id: collectionId,
}) })
const collection = await collectionService.getCollection(collectionId) const collection = await collectionService.getCollection(collectionId)
@@ -86,33 +86,33 @@ const route = new Hono<{ Variables: { user: User } }>()
return c.json(toCollectionInfo(collection)) return c.json(toCollectionInfo(collection))
}) })
.patch( .patch(
'/teams/:teamId/projects/:projectId/collections/:collectionId', '/collections/:collectionId',
zValidator('json', updateCollectionRequestSchema), zValidator('json', updateCollectionRequestSchema),
async (c) => { async (c) => {
const { teamId, projectId, collectionId } = c.req.param() const { collectionId } = c.req.param()
const req = c.req.valid('json') const req = c.req.valid('json')
const user = c.get('user') const user = c.get('user')
await authzService.hasPermission({ await authzService.hasPermission({
teamId,
projectId,
user, user,
permission: Permission.Edit, permission: Permission.Edit,
type: ResourceType.Collection,
id: collectionId,
}) })
const collection = await collectionService.updateCollection(collectionId, req) const collection = await collectionService.updateCollection(collectionId, req)
return c.json(toCollectionInfo(collection)) return c.json(toCollectionInfo(collection))
}, },
) )
.delete('/teams/:teamId/projects/:projectId/collections/:collectionId', async (c) => { .delete('/collections/:collectionId', async (c) => {
const { teamId, projectId, collectionId } = c.req.param() const { collectionId } = c.req.param()
const user = c.get('user') const user = c.get('user')
await authzService.hasPermission({ await authzService.hasPermission({
teamId,
projectId,
user, user,
permission: Permission.Edit, permission: Permission.Edit,
type: ResourceType.Collection,
id: collectionId,
}) })
await collectionService.deleteCollection(collectionId) await collectionService.deleteCollection(collectionId)
+64 -39
View File
@@ -1,27 +1,30 @@
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest' import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'
import { Hono } from 'hono' import { Hono, type Context, type Next } from 'hono'
import fileRoute from './file' import fileRoute from './file'
import { assetService } from '@/services/asset/asset' import { assetService } from '@/services/asset/asset'
import { metadataService } from '@/services/metadata/metadata' import { metadataService } from '@/services/metadata/metadata'
import { notificationService } from '@/services/notification/notification' import { notificationService } from '@/services/notification/notification'
import { s3Service } from '@/services/s3/s3' import { s3Service } from '@/services/s3/s3'
import { authzService } from '@/services/authz/authz'
import { authMiddleware } from '@/api/middleware/auth' import { authMiddleware } from '@/api/middleware/auth'
import { authzService, ResourceType, Permission } from '@/services/authz/authz'
vi.mock('@/services/authz/authz', () => ({ vi.mock('@/services/authz/authz', () => ({
authzService: { authzService: {
hasPermission: vi.fn(), hasPermission: vi.fn().mockResolvedValue(undefined),
}, },
Permission: { Permission: {
Read: 'Read', Read: 'Read',
Edit: 'Edit', Edit: 'Edit',
Admin: 'Admin', Admin: 'Admin',
}, },
ResourceType: {
Asset: 'asset',
Team: 'team',
},
})) }))
vi.mock('@/api/middleware/auth', () => ({ vi.mock('@/api/middleware/auth', () => ({
// eslint-disable-next-line @typescript-eslint/no-explicit-any authMiddleware: async (c: Context, next: Next) => {
authMiddleware: async (c: any, next: any) => {
c.set('user', { id: 'user1', name: 'Test User' }) c.set('user', { id: 'user1', name: 'Test User' })
await next() await next()
}, },
@@ -32,6 +35,7 @@ describe('file api', () => {
vi.mocked(authzService.hasPermission).mockClear() vi.mocked(authzService.hasPermission).mockClear()
vi.spyOn(assetService, 'getAsset').mockImplementation(vi.fn()) vi.spyOn(assetService, 'getAsset').mockImplementation(vi.fn())
vi.spyOn(assetService, 'getAssetContext').mockResolvedValue({ teamId: 'test-team' })
vi.spyOn(assetService, 'updateAssetName').mockImplementation(vi.fn()) vi.spyOn(assetService, 'updateAssetName').mockImplementation(vi.fn())
vi.spyOn(assetService, 'deleteAssets').mockImplementation(vi.fn()) vi.spyOn(assetService, 'deleteAssets').mockImplementation(vi.fn())
vi.spyOn(assetService, 'createComment').mockImplementation(vi.fn()) vi.spyOn(assetService, 'createComment').mockImplementation(vi.fn())
@@ -41,13 +45,14 @@ describe('file api', () => {
vi.spyOn(metadataService, 'updateAssetMetadata').mockImplementation(vi.fn()) vi.spyOn(metadataService, 'updateAssetMetadata').mockImplementation(vi.fn())
vi.spyOn(notificationService, 'create').mockImplementation(vi.fn()) vi.spyOn(notificationService, 'create').mockImplementation(vi.fn())
vi.spyOn(s3Service, 'putObject').mockImplementation(vi.fn()) vi.spyOn(s3Service, 'putObject').mockImplementation(vi.fn())
vi.mocked(authzService.hasPermission).mockResolvedValue(undefined)
}) })
afterEach(() => { afterEach(() => {
vi.restoreAllMocks() vi.restoreAllMocks()
}) })
it('GET /teams/:teamId/files/:fileId', async () => { it('GET /files/:fileId', async () => {
vi.mocked(assetService.getAsset).mockResolvedValue({ vi.mocked(assetService.getAsset).mockResolvedValue({
id: 'test-id', id: 'test-id',
name: 'test-file', name: 'test-file',
@@ -61,20 +66,21 @@ describe('file api', () => {
}) })
const app = new Hono().use('*', authMiddleware).route('/', fileRoute) const app = new Hono().use('*', authMiddleware).route('/', fileRoute)
const res = await app.request('/teams/test-team/files/test-id') const res = await app.request('/files/test-id')
expect(res.status).toBe(200) expect(res.status).toBe(200)
const json = await res.json() const json = await res.json()
expect(json.name).toBe('test-file') expect(json.name).toBe('test-file')
expect(authzService.hasPermission).toHaveBeenCalledWith({ expect(authzService.hasPermission).toHaveBeenCalledWith({
assetId: 'test-id',
user: { id: 'user1', name: 'Test User' }, user: { id: 'user1', name: 'Test User' },
permission: 'Read', permission: Permission.Read,
type: ResourceType.Asset,
id: 'test-id',
}) })
}) })
it('PUT /teams/:teamId/files/:fileId', async () => { it('PUT /files/:fileId', async () => {
vi.mocked(assetService.updateAssetName).mockResolvedValue({ vi.mocked(assetService.updateAssetName).mockResolvedValue({
id: 'test-id', id: 'test-id',
name: 'new-name', name: 'new-name',
@@ -88,7 +94,7 @@ describe('file api', () => {
}) })
const app = new Hono().use('*', authMiddleware).route('/', fileRoute) const app = new Hono().use('*', authMiddleware).route('/', fileRoute)
const res = await app.request('/teams/test-team/files/test-id', { const res = await app.request('/files/test-id', {
method: 'PUT', method: 'PUT',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'new-name' }), body: JSON.stringify({ name: 'new-name' }),
@@ -99,17 +105,18 @@ describe('file api', () => {
expect(json.name).toBe('new-name') expect(json.name).toBe('new-name')
expect(authzService.hasPermission).toHaveBeenCalledWith({ expect(authzService.hasPermission).toHaveBeenCalledWith({
assetId: 'test-id',
user: { id: 'user1', name: 'Test User' }, user: { id: 'user1', name: 'Test User' },
permission: 'Edit', permission: Permission.Edit,
type: ResourceType.Asset,
id: 'test-id',
}) })
}) })
it('DELETE /teams/:teamId/files', async () => { it('DELETE /files', async () => {
vi.mocked(assetService.deleteAssets).mockResolvedValue(undefined) vi.mocked(assetService.deleteAssets).mockResolvedValue(undefined)
const app = new Hono().use('*', authMiddleware).route('/', fileRoute) const app = new Hono().use('*', authMiddleware).route('/', fileRoute)
const res = await app.request('/teams/test-team/files', { const res = await app.request('/files', {
method: 'DELETE', method: 'DELETE',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ ids: ['test-id'] }), body: JSON.stringify({ ids: ['test-id'] }),
@@ -118,18 +125,19 @@ describe('file api', () => {
expect(res.status).toBe(204) expect(res.status).toBe(204)
expect(authzService.hasPermission).toHaveBeenCalledWith({ expect(authzService.hasPermission).toHaveBeenCalledWith({
assetId: 'test-id',
user: { id: 'user1', name: 'Test User' }, user: { id: 'user1', name: 'Test User' },
permission: 'Edit', permission: Permission.Edit,
type: ResourceType.Asset,
id: 'test-id',
}) })
expect(assetService.deleteAssets).toHaveBeenCalledWith(['test-id']) expect(assetService.deleteAssets).toHaveBeenCalledWith(['test-id'])
}) })
it('POST /teams/:teamId/files/restore', async () => { it('POST /files/restore', async () => {
vi.mocked(assetService.restoreAssets).mockResolvedValue(undefined) vi.mocked(assetService.restoreAssets).mockResolvedValue(undefined)
const app = new Hono().use('*', authMiddleware).route('/', fileRoute) const app = new Hono().use('*', authMiddleware).route('/', fileRoute)
const res = await app.request('/teams/test-team/files/restore', { const res = await app.request('/files/restore', {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ ids: ['test-id'] }), body: JSON.stringify({ ids: ['test-id'] }),
@@ -138,14 +146,15 @@ describe('file api', () => {
expect(res.status).toBe(204) expect(res.status).toBe(204)
expect(authzService.hasPermission).toHaveBeenCalledWith({ expect(authzService.hasPermission).toHaveBeenCalledWith({
assetId: 'test-id',
user: { id: 'user1', name: 'Test User' }, user: { id: 'user1', name: 'Test User' },
permission: 'Edit', permission: Permission.Edit,
type: ResourceType.Asset,
id: 'test-id',
}) })
expect(assetService.restoreAssets).toHaveBeenCalledWith(['test-id']) expect(assetService.restoreAssets).toHaveBeenCalledWith(['test-id'])
}) })
it('POST /teams/:teamId/files/:fileId/comments', async () => { it('POST /files/:fileId/comments', async () => {
vi.mocked(assetService.createComment).mockResolvedValue({ vi.mocked(assetService.createComment).mockResolvedValue({
id: 'comment-id', id: 'comment-id',
assetId: 'test-id', assetId: 'test-id',
@@ -160,8 +169,14 @@ describe('file api', () => {
sessionId: null, sessionId: null,
}) })
// Mock assetService.getAsset to return teamId for notification
vi.mocked(assetService.getAsset).mockResolvedValue({
id: 'test-id',
project: { teamId: 'test-team' },
} as any) // eslint-disable-line @typescript-eslint/no-explicit-any
const app = new Hono().use('*', authMiddleware).route('/', fileRoute) const app = new Hono().use('*', authMiddleware).route('/', fileRoute)
const res = await app.request('/teams/test-team/files/test-id/comments', { const res = await app.request('/files/test-id/comments', {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ message: 'hello', attachmentIds: [] }), body: JSON.stringify({ message: 'hello', attachmentIds: [] }),
@@ -172,9 +187,10 @@ describe('file api', () => {
expect(json.message).toBe('hello') expect(json.message).toBe('hello')
expect(authzService.hasPermission).toHaveBeenCalledWith({ expect(authzService.hasPermission).toHaveBeenCalledWith({
assetId: 'test-id',
user: { id: 'user1', name: 'Test User' }, user: { id: 'user1', name: 'Test User' },
permission: 'Read', permission: Permission.Read,
type: ResourceType.Asset,
id: 'test-id',
}) })
expect(notificationService.create).toHaveBeenCalledWith({ expect(notificationService.create).toHaveBeenCalledWith({
@@ -186,7 +202,7 @@ describe('file api', () => {
}) })
}) })
it('GET /teams/:teamId/files/:fileId/comments', async () => { it('GET /files/:fileId/comments', async () => {
vi.mocked(assetService.listComments).mockResolvedValue({ vi.mocked(assetService.listComments).mockResolvedValue({
data: [ data: [
{ {
@@ -207,7 +223,7 @@ describe('file api', () => {
}) })
const app = new Hono().use('*', authMiddleware).route('/', fileRoute) const app = new Hono().use('*', authMiddleware).route('/', fileRoute)
const res = await app.request('/teams/test-team/files/test-id/comments') const res = await app.request('/files/test-id/comments')
expect(res.status).toBe(200) expect(res.status).toBe(200)
const json = await res.json() const json = await res.json()
@@ -215,9 +231,10 @@ describe('file api', () => {
expect(json.data[0].message).toBe('hello') expect(json.data[0].message).toBe('hello')
expect(authzService.hasPermission).toHaveBeenCalledWith({ expect(authzService.hasPermission).toHaveBeenCalledWith({
assetId: 'test-id',
user: { id: 'user1', name: 'Test User' }, user: { id: 'user1', name: 'Test User' },
permission: 'Read', permission: Permission.Read,
type: ResourceType.Asset,
id: 'test-id',
}) })
}) })
@@ -239,18 +256,24 @@ describe('file api', () => {
expect(json.key).toMatch(/^files\//) expect(json.key).toMatch(/^files\//)
expect(authzService.hasPermission).toHaveBeenCalledWith({ expect(authzService.hasPermission).toHaveBeenCalledWith({
teamId: 'test-team',
user: { id: 'user1', name: 'Test User' }, user: { id: 'user1', name: 'Test User' },
permission: 'Read', permission: Permission.Read,
type: ResourceType.Team,
id: 'test-team',
}) })
expect(s3Service.putObject).toHaveBeenCalled() expect(s3Service.putObject).toHaveBeenCalled()
}) })
it('PATCH /teams/:teamId/files/:fileId/metadata', async () => { it('PATCH /files/:fileId/metadata', async () => {
vi.mocked(metadataService.updateAssetMetadata).mockResolvedValue(undefined) vi.mocked(metadataService.updateAssetMetadata).mockResolvedValue(undefined)
// Mock assetService.getAsset to return teamId for notification
vi.mocked(assetService.getAsset).mockResolvedValue({
id: 'test-id',
project: { teamId: 'test-team' },
} as any) // eslint-disable-line @typescript-eslint/no-explicit-any
const app = new Hono().use('*', authMiddleware).route('/', fileRoute) const app = new Hono().use('*', authMiddleware).route('/', fileRoute)
const res = await app.request('/teams/test-team/files/test-id/metadata', { const res = await app.request('/files/test-id/metadata', {
method: 'PATCH', method: 'PATCH',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify([{ key: 'status', value: 'approved' }]), body: JSON.stringify([{ key: 'status', value: 'approved' }]),
@@ -259,9 +282,10 @@ describe('file api', () => {
expect(res.status).toBe(200) expect(res.status).toBe(200)
expect(authzService.hasPermission).toHaveBeenCalledWith({ expect(authzService.hasPermission).toHaveBeenCalledWith({
assetId: 'test-id',
user: { id: 'user1', name: 'Test User' }, user: { id: 'user1', name: 'Test User' },
permission: 'Edit', permission: Permission.Edit,
type: ResourceType.Asset,
id: 'test-id',
}) })
expect(notificationService.create).toHaveBeenCalledWith({ expect(notificationService.create).toHaveBeenCalledWith({
@@ -272,7 +296,7 @@ describe('file api', () => {
}) })
}) })
it('PATCH /teams/:teamId/files/:fileId/order', async () => { it('PATCH /files/:fileId/order', async () => {
vi.spyOn(assetService, 'updateAssetOrder').mockResolvedValue({ vi.spyOn(assetService, 'updateAssetOrder').mockResolvedValue({
id: 'test-id', id: 'test-id',
name: 'test-file', name: 'test-file',
@@ -286,7 +310,7 @@ describe('file api', () => {
}) })
const app = new Hono().use('*', authMiddleware).route('/', fileRoute) const app = new Hono().use('*', authMiddleware).route('/', fileRoute)
const res = await app.request('/teams/test-team/files/test-id/order', { const res = await app.request('/files/test-id/order', {
method: 'PATCH', method: 'PATCH',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ beforeIndex: 'index-1' }), body: JSON.stringify({ beforeIndex: 'index-1' }),
@@ -295,9 +319,10 @@ describe('file api', () => {
expect(res.status).toBe(200) expect(res.status).toBe(200)
expect(authzService.hasPermission).toHaveBeenCalledWith({ expect(authzService.hasPermission).toHaveBeenCalledWith({
assetId: 'test-id',
user: { id: 'user1', name: 'Test User' }, user: { id: 'user1', name: 'Test User' },
permission: 'Edit', permission: Permission.Edit,
type: ResourceType.Asset,
id: 'test-id',
}) })
expect(assetService.updateAssetOrder).toHaveBeenCalledWith('test-id', { expect(assetService.updateAssetOrder).toHaveBeenCalledWith('test-id', {
+51 -37
View File
@@ -1,6 +1,6 @@
import { Hono } from 'hono' import { Hono } from 'hono'
import { zValidator } from '@hono/zod-validator' import { zValidator } from '@hono/zod-validator'
import { authzService, Permission } from '@/services/authz/authz' import { authzService, Permission, ResourceType } from '@/services/authz/authz'
import { assetService } from '@/services/asset/asset' import { assetService } from '@/services/asset/asset'
import { metadataService } from '@/services/metadata/metadata' import { metadataService } from '@/services/metadata/metadata'
import { notificationService } from '@/services/notification/notification' import { notificationService } from '@/services/notification/notification'
@@ -22,21 +22,22 @@ import type { Prisma } from '@/generated/prisma/client'
type User = Prisma.UserGetPayload<Record<string, never>> type User = Prisma.UserGetPayload<Record<string, never>>
const route = new Hono<{ Variables: { user: User } }>() const route = new Hono<{ Variables: { user: User } }>()
.get('/teams/:teamId/files/:fileId', async (c) => { .get('/files/:fileId', async (c) => {
const fileId = c.req.param('fileId') const fileId = c.req.param('fileId')
const user = c.get('user') const user = c.get('user')
await authzService.hasPermission({ await authzService.hasPermission({
assetId: fileId,
user, user,
permission: Permission.Read, permission: Permission.Read,
type: ResourceType.Asset,
id: fileId,
}) })
const asset = await assetService.getAsset({ assetId: fileId }) const asset = await assetService.getAsset({ assetId: fileId })
return c.json(asset) return c.json(asset)
}) })
.patch( .patch(
'/teams/:teamId/files/:fileId/order', '/files/:fileId/order',
zValidator('json', updateAssetOrderRequestSchema), zValidator('json', updateAssetOrderRequestSchema),
async (c) => { async (c) => {
const fileId = c.req.param('fileId') const fileId = c.req.param('fileId')
@@ -44,24 +45,26 @@ const route = new Hono<{ Variables: { user: User } }>()
const req = c.req.valid('json') const req = c.req.valid('json')
await authzService.hasPermission({ await authzService.hasPermission({
assetId: fileId,
user, user,
permission: Permission.Edit, permission: Permission.Edit,
type: ResourceType.Asset,
id: fileId,
}) })
const updated = await assetService.updateAssetOrder(fileId, req) const updated = await assetService.updateAssetOrder(fileId, req)
return c.json(updated) return c.json(updated)
}, },
) )
.put('/teams/:teamId/files/:fileId', zValidator('json', updateFileRequestSchema), async (c) => { .put('/files/:fileId', zValidator('json', updateFileRequestSchema), async (c) => {
const fileId = c.req.param('fileId') const fileId = c.req.param('fileId')
const user = c.get('user') const user = c.get('user')
const req = c.req.valid('json') const req = c.req.valid('json')
await authzService.hasPermission({ await authzService.hasPermission({
assetId: fileId,
user, user,
permission: Permission.Edit, permission: Permission.Edit,
type: ResourceType.Asset,
id: fileId,
}) })
const updatedAsset = await assetService.updateAssetName({ const updatedAsset = await assetService.updateAssetName({
@@ -71,15 +74,16 @@ const route = new Hono<{ Variables: { user: User } }>()
return c.json(updatedAsset) return c.json(updatedAsset)
}) })
.delete('/teams/:teamId/files', zValidator('json', deleteFilesRequestSchema), async (c) => { .delete('/files', zValidator('json', deleteFilesRequestSchema), async (c) => {
const user = c.get('user') const user = c.get('user')
const req = c.req.valid('json') const req = c.req.valid('json')
for (const id of req.ids) { for (const id of req.ids) {
await authzService.hasPermission({ await authzService.hasPermission({
assetId: id,
user, user,
permission: Permission.Edit, permission: Permission.Edit,
type: ResourceType.Asset,
id,
}) })
} }
@@ -87,48 +91,51 @@ const route = new Hono<{ Variables: { user: User } }>()
return c.body(null, 204) return c.body(null, 204)
}) })
.patch( .patch(
'/teams/:teamId/files/:fileId/metadata', '/files/:fileId/metadata',
zValidator('json', z.array(updateAssetMetadataRequestSchema)), zValidator('json', z.array(updateAssetMetadataRequestSchema)),
async (c) => { async (c) => {
const teamId = c.req.param('teamId')
const fileId = c.req.param('fileId') const fileId = c.req.param('fileId')
const user = c.get('user') const user = c.get('user')
const req = c.req.valid('json') const req = c.req.valid('json')
await authzService.hasPermission({ await authzService.hasPermission({
assetId: fileId,
user, user,
permission: Permission.Edit, permission: Permission.Edit,
type: ResourceType.Asset,
id: fileId,
}) })
await metadataService.updateAssetMetadata(fileId, req) await metadataService.updateAssetMetadata(fileId, req)
const hasStatus = req.some((m) => m.key === 'status') const hasStatus = req.some((m) => m.key === 'status')
if (hasStatus) { if (hasStatus) {
notificationService.create({ const context = await assetService.getAssetContext(fileId)
type: 'metadata_field_updated_status', if (context?.teamId) {
teamId, notificationService.create({
creatorId: user.id, type: 'metadata_field_updated_status',
assetId: fileId, teamId: context.teamId,
}) creatorId: user.id,
assetId: fileId,
})
}
} }
return c.json('') return c.json('')
}, },
) )
.post( .post(
'/teams/:teamId/files/:fileId/comments', '/files/:fileId/comments',
zValidator('json', createCommentRequestSchema.omit({ assetId: true, userId: true })), zValidator('json', createCommentRequestSchema.omit({ assetId: true, userId: true })),
async (c) => { async (c) => {
const teamId = c.req.param('teamId')
const fileId = c.req.param('fileId') const fileId = c.req.param('fileId')
const user = c.get('user') const user = c.get('user')
const req = c.req.valid('json') const req = c.req.valid('json')
await authzService.hasPermission({ await authzService.hasPermission({
assetId: fileId,
user, user,
permission: Permission.Read, permission: Permission.Read,
type: ResourceType.Asset,
id: fileId,
}) })
const comment = await assetService.createComment({ const comment = await assetService.createComment({
@@ -143,19 +150,23 @@ const route = new Hono<{ Variables: { user: User } }>()
const notifType = req.replyToId ? 'reply_created' : 'comment_created' const notifType = req.replyToId ? 'reply_created' : 'comment_created'
notificationService.create({ const context = await assetService.getAssetContext(fileId)
type: notifType,
teamId, if (context?.teamId) {
creatorId: user.id, notificationService.create({
assetId: fileId, type: notifType,
commentMessage: req.message, teamId: context.teamId,
}) creatorId: user.id,
assetId: fileId,
commentMessage: req.message,
})
}
return c.json(comment, 201) return c.json(comment, 201)
}, },
) )
.get( .get(
'/teams/:teamId/files/:fileId/comments', '/files/:fileId/comments',
zValidator('query', paginationParamsSchema), zValidator('query', paginationParamsSchema),
async (c) => { async (c) => {
const fileId = c.req.param('fileId') const fileId = c.req.param('fileId')
@@ -163,31 +174,32 @@ const route = new Hono<{ Variables: { user: User } }>()
const req = c.req.valid('query') const req = c.req.valid('query')
await authzService.hasPermission({ await authzService.hasPermission({
assetId: fileId,
user, user,
permission: Permission.Read, permission: Permission.Read,
type: ResourceType.Asset,
id: fileId,
}) })
const comments = await assetService.listComments(fileId, req) const comments = await assetService.listComments(fileId, req)
return c.json(comments) return c.json(comments)
}, },
) )
.get('/teams/:teamId/comments/:commentId', async (c) => { .get('/comments/:commentId', async (c) => {
const commentId = c.req.param('commentId') const commentId = c.req.param('commentId')
const user = c.get('user') const user = c.get('user')
const comment = await assetService.getComment(commentId)
await authzService.hasPermission({ await authzService.hasPermission({
assetId: comment.assetId,
user, user,
permission: Permission.Read, permission: Permission.Read,
type: ResourceType.Comment,
id: commentId,
}) })
const comment = await assetService.getComment(commentId)
return c.json(comment) return c.json(comment)
}) })
.post( .post(
'/teams/:teamId/files/restore', '/files/restore',
zValidator('json', restoreFilesRequestSchema), zValidator('json', restoreFilesRequestSchema),
async (c) => { async (c) => {
const user = c.get('user') const user = c.get('user')
@@ -195,9 +207,10 @@ const route = new Hono<{ Variables: { user: User } }>()
for (const id of req.ids) { for (const id of req.ids) {
await authzService.hasPermission({ await authzService.hasPermission({
assetId: id,
user, user,
permission: Permission.Edit, permission: Permission.Edit,
type: ResourceType.Asset,
id,
}) })
} }
@@ -211,9 +224,10 @@ const route = new Hono<{ Variables: { user: User } }>()
const { file } = c.req.valid('form') const { file } = c.req.valid('form')
await authzService.hasPermission({ await authzService.hasPermission({
teamId,
user, user,
permission: Permission.Read, permission: Permission.Read,
type: ResourceType.Team,
id: teamId,
}) })
if (file.size > 10 * 1024 * 1024) { if (file.size > 10 * 1024 * 1024) {
+45 -34
View File
@@ -3,18 +3,21 @@ import { Hono } from 'hono'
import folderRoute from './folder' import folderRoute from './folder'
import { assetService } from '@/services/asset/asset' import { assetService } from '@/services/asset/asset'
import { searchService } from '@/services/search/search' import { searchService } from '@/services/search/search'
import { authzService } from '@/services/authz/authz' import { authzService, ResourceType, Permission } from '@/services/authz/authz'
import { authMiddleware } from '@/api/middleware/auth' import { authMiddleware } from '@/api/middleware/auth'
vi.mock('@/services/authz/authz', () => ({ vi.mock('@/services/authz/authz', () => ({
authzService: { authzService: {
hasPermission: vi.fn(), hasPermission: vi.fn().mockResolvedValue(undefined),
}, },
Permission: { Permission: {
Read: 'Read', Read: 'Read',
Edit: 'Edit', Edit: 'Edit',
Admin: 'Admin', Admin: 'Admin',
}, },
ResourceType: {
Asset: 'asset',
},
})) }))
vi.mock('@/api/middleware/auth', () => ({ vi.mock('@/api/middleware/auth', () => ({
@@ -42,7 +45,7 @@ describe('folder api', () => {
vi.restoreAllMocks() vi.restoreAllMocks()
}) })
it('GET /teams/:teamId/folders/:folderId', async () => { it('GET /folders/:folderId', async () => {
vi.mocked(assetService.getAsset).mockResolvedValue({ vi.mocked(assetService.getAsset).mockResolvedValue({
id: 'test-id', id: 'test-id',
name: 'test-folder', name: 'test-folder',
@@ -56,20 +59,21 @@ describe('folder api', () => {
}) })
const app = new Hono().use('*', authMiddleware).route('/', folderRoute) const app = new Hono().use('*', authMiddleware).route('/', folderRoute)
const res = await app.request('/teams/test-team/folders/test-id') const res = await app.request('/folders/test-id')
expect(res.status).toBe(200) expect(res.status).toBe(200)
const json = await res.json() const json = await res.json()
expect(json.name).toBe('test-folder') expect(json.name).toBe('test-folder')
expect(authzService.hasPermission).toHaveBeenCalledWith({ expect(authzService.hasPermission).toHaveBeenCalledWith({
assetId: 'test-id',
user: { id: 'user1', name: 'Test User' }, user: { id: 'user1', name: 'Test User' },
permission: 'Read', permission: Permission.Read,
type: ResourceType.Asset,
id: 'test-id',
}) })
}) })
it('PUT /teams/:teamId/folders/:folderId', async () => { it('PUT /folders/:folderId', async () => {
vi.mocked(assetService.updateAssetName).mockResolvedValue({ vi.mocked(assetService.updateAssetName).mockResolvedValue({
id: 'test-id', id: 'test-id',
name: 'new-name', name: 'new-name',
@@ -83,7 +87,7 @@ describe('folder api', () => {
}) })
const app = new Hono().use('*', authMiddleware).route('/', folderRoute) const app = new Hono().use('*', authMiddleware).route('/', folderRoute)
const res = await app.request('/teams/test-team/folders/test-id', { const res = await app.request('/folders/test-id', {
method: 'PUT', method: 'PUT',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'new-name' }), body: JSON.stringify({ name: 'new-name' }),
@@ -94,13 +98,14 @@ describe('folder api', () => {
expect(json.name).toBe('new-name') expect(json.name).toBe('new-name')
expect(authzService.hasPermission).toHaveBeenCalledWith({ expect(authzService.hasPermission).toHaveBeenCalledWith({
assetId: 'test-id',
user: { id: 'user1', name: 'Test User' }, user: { id: 'user1', name: 'Test User' },
permission: 'Edit', permission: Permission.Edit,
type: ResourceType.Asset,
id: 'test-id',
}) })
}) })
it('POST /teams/:teamId/folders', async () => { it('POST /folders', async () => {
vi.mocked(assetService.createAsset).mockResolvedValue({ vi.mocked(assetService.createAsset).mockResolvedValue({
id: 'new-id', id: 'new-id',
name: 'new-folder', name: 'new-folder',
@@ -114,7 +119,7 @@ describe('folder api', () => {
}) })
const app = new Hono().use('*', authMiddleware).route('/', folderRoute) const app = new Hono().use('*', authMiddleware).route('/', folderRoute)
const res = await app.request('/teams/test-team/folders', { const res = await app.request('/folders', {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'new-folder', parentId: 'parent-id' }), body: JSON.stringify({ name: 'new-folder', parentId: 'parent-id' }),
@@ -125,13 +130,14 @@ describe('folder api', () => {
expect(json.name).toBe('new-folder') expect(json.name).toBe('new-folder')
expect(authzService.hasPermission).toHaveBeenCalledWith({ expect(authzService.hasPermission).toHaveBeenCalledWith({
assetId: 'parent-id',
user: { id: 'user1', name: 'Test User' }, user: { id: 'user1', name: 'Test User' },
permission: 'Edit', permission: Permission.Edit,
type: ResourceType.Asset,
id: 'parent-id',
}) })
}) })
it('GET /teams/:teamId/folders/:folderId/children', async () => { it('GET /folders/:folderId/children', async () => {
vi.mocked(assetService.listChildren).mockResolvedValue({ vi.mocked(assetService.listChildren).mockResolvedValue({
data: [ data: [
{ {
@@ -150,7 +156,7 @@ describe('folder api', () => {
}) })
const app = new Hono().use('*', authMiddleware).route('/', folderRoute) const app = new Hono().use('*', authMiddleware).route('/', folderRoute)
const res = await app.request('/teams/test-team/folders/test-id/children?assetType=folder') const res = await app.request('/folders/test-id/children?assetType=folder')
expect(res.status).toBe(200) expect(res.status).toBe(200)
const json = await res.json() const json = await res.json()
@@ -158,17 +164,18 @@ describe('folder api', () => {
expect(json.data[0].name).toBe('child-folder') expect(json.data[0].name).toBe('child-folder')
expect(authzService.hasPermission).toHaveBeenCalledWith({ expect(authzService.hasPermission).toHaveBeenCalledWith({
assetId: 'test-id',
user: { id: 'user1', name: 'Test User' }, user: { id: 'user1', name: 'Test User' },
permission: 'Read', permission: Permission.Read,
type: ResourceType.Asset,
id: 'test-id',
}) })
}) })
it('DELETE /teams/:teamId/folders', async () => { it('DELETE /folders', async () => {
vi.mocked(assetService.deleteAssets).mockResolvedValue(undefined) vi.mocked(assetService.deleteAssets).mockResolvedValue(undefined)
const app = new Hono().use('*', authMiddleware).route('/', folderRoute) const app = new Hono().use('*', authMiddleware).route('/', folderRoute)
const res = await app.request('/teams/test-team/folders', { const res = await app.request('/folders', {
method: 'DELETE', method: 'DELETE',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ ids: ['test-id'] }), body: JSON.stringify({ ids: ['test-id'] }),
@@ -177,18 +184,19 @@ describe('folder api', () => {
expect(res.status).toBe(204) expect(res.status).toBe(204)
expect(authzService.hasPermission).toHaveBeenCalledWith({ expect(authzService.hasPermission).toHaveBeenCalledWith({
assetId: 'test-id',
user: { id: 'user1', name: 'Test User' }, user: { id: 'user1', name: 'Test User' },
permission: 'Edit', permission: Permission.Edit,
type: ResourceType.Asset,
id: 'test-id',
}) })
expect(assetService.deleteAssets).toHaveBeenCalledWith(['test-id']) expect(assetService.deleteAssets).toHaveBeenCalledWith(['test-id'])
}) })
it('POST /teams/:teamId/folders/restore', async () => { it('POST /folders/restore', async () => {
vi.mocked(assetService.restoreAssets).mockResolvedValue(undefined) vi.mocked(assetService.restoreAssets).mockResolvedValue(undefined)
const app = new Hono().use('*', authMiddleware).route('/', folderRoute) const app = new Hono().use('*', authMiddleware).route('/', folderRoute)
const res = await app.request('/teams/test-team/folders/restore', { const res = await app.request('/folders/restore', {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ ids: ['test-id'] }), body: JSON.stringify({ ids: ['test-id'] }),
@@ -197,14 +205,15 @@ describe('folder api', () => {
expect(res.status).toBe(204) expect(res.status).toBe(204)
expect(authzService.hasPermission).toHaveBeenCalledWith({ expect(authzService.hasPermission).toHaveBeenCalledWith({
assetId: 'test-id',
user: { id: 'user1', name: 'Test User' }, user: { id: 'user1', name: 'Test User' },
permission: 'Edit', permission: Permission.Edit,
type: ResourceType.Asset,
id: 'test-id',
}) })
expect(assetService.restoreAssets).toHaveBeenCalledWith(['test-id']) expect(assetService.restoreAssets).toHaveBeenCalledWith(['test-id'])
}) })
it('POST /teams/:teamId/folders/:folderId/search', async () => { it('POST /folders/:folderId/search', async () => {
vi.mocked(searchService.search).mockResolvedValue({ vi.mocked(searchService.search).mockResolvedValue({
data: [ data: [
{ {
@@ -223,7 +232,7 @@ describe('folder api', () => {
}) })
const app = new Hono().use('*', authMiddleware).route('/', folderRoute) const app = new Hono().use('*', authMiddleware).route('/', folderRoute)
const res = await app.request('/teams/test-team/folders/test-id/search', { const res = await app.request('/folders/test-id/search', {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ body: JSON.stringify({
@@ -237,13 +246,14 @@ describe('folder api', () => {
expect(json.data[0].name).toBe('result-folder') expect(json.data[0].name).toBe('result-folder')
expect(authzService.hasPermission).toHaveBeenCalledWith({ expect(authzService.hasPermission).toHaveBeenCalledWith({
assetId: 'test-id',
user: { id: 'user1', name: 'Test User' }, user: { id: 'user1', name: 'Test User' },
permission: 'Read', permission: Permission.Read,
type: ResourceType.Asset,
id: 'test-id',
}) })
}) })
it('PATCH /teams/:teamId/folders/:folderId/order', async () => { it('PATCH /folders/:folderId/order', async () => {
vi.spyOn(assetService, 'updateAssetOrder').mockResolvedValue({ vi.spyOn(assetService, 'updateAssetOrder').mockResolvedValue({
id: 'test-id', id: 'test-id',
name: 'test-folder', name: 'test-folder',
@@ -257,7 +267,7 @@ describe('folder api', () => {
}) })
const app = new Hono().use('*', authMiddleware).route('/', folderRoute) const app = new Hono().use('*', authMiddleware).route('/', folderRoute)
const res = await app.request('/teams/test-team/folders/test-id/order', { const res = await app.request('/folders/test-id/order', {
method: 'PATCH', method: 'PATCH',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ beforeIndex: 'index-1' }), body: JSON.stringify({ beforeIndex: 'index-1' }),
@@ -266,9 +276,10 @@ describe('folder api', () => {
expect(res.status).toBe(200) expect(res.status).toBe(200)
expect(authzService.hasPermission).toHaveBeenCalledWith({ expect(authzService.hasPermission).toHaveBeenCalledWith({
assetId: 'test-id',
user: { id: 'user1', name: 'Test User' }, user: { id: 'user1', name: 'Test User' },
permission: 'Edit', permission: Permission.Edit,
type: ResourceType.Asset,
id: 'test-id',
}) })
expect(assetService.updateAssetOrder).toHaveBeenCalledWith('test-id', { expect(assetService.updateAssetOrder).toHaveBeenCalledWith('test-id', {
+75 -83
View File
@@ -1,6 +1,6 @@
import { Hono } from 'hono' import { Hono } from 'hono'
import { zValidator } from '@hono/zod-validator' import { zValidator } from '@hono/zod-validator'
import { authzService, Permission } from '@/services/authz/authz' import { authzService, Permission, ResourceType } from '@/services/authz/authz'
import { assetService } from '@/services/asset/asset' import { assetService } from '@/services/asset/asset'
import { searchService } from '@/services/search/search' import { searchService } from '@/services/search/search'
import { import {
@@ -16,14 +16,15 @@ import type { Prisma } from '@/generated/prisma/client'
type User = Prisma.UserGetPayload<Record<string, never>> type User = Prisma.UserGetPayload<Record<string, never>>
const route = new Hono<{ Variables: { user: User } }>() const route = new Hono<{ Variables: { user: User } }>()
.post('/teams/:teamId/folders', zValidator('json', createFolderRequestSchema), async (c) => { .post('/folders', zValidator('json', createFolderRequestSchema), async (c) => {
const user = c.get('user') const user = c.get('user')
const req = c.req.valid('json') const req = c.req.valid('json')
await authzService.hasPermission({ await authzService.hasPermission({
assetId: req.parentId,
user, user,
permission: Permission.Edit, permission: Permission.Edit,
type: ResourceType.Asset,
id: req.parentId,
}) })
const newAsset = await assetService.createAsset({ const newAsset = await assetService.createAsset({
@@ -35,7 +36,7 @@ const route = new Hono<{ Variables: { user: User } }>()
return c.json(newAsset) return c.json(newAsset)
}) })
.patch( .patch(
'/teams/:teamId/folders/:folderId/order', '/folders/:folderId/order',
zValidator('json', updateAssetOrderRequestSchema), zValidator('json', updateAssetOrderRequestSchema),
async (c) => { async (c) => {
const folderId = c.req.param('folderId') const folderId = c.req.param('folderId')
@@ -43,126 +44,117 @@ const route = new Hono<{ Variables: { user: User } }>()
const req = c.req.valid('json') const req = c.req.valid('json')
await authzService.hasPermission({ await authzService.hasPermission({
assetId: folderId,
user, user,
permission: Permission.Edit, permission: Permission.Edit,
type: ResourceType.Asset,
id: folderId,
}) })
const updated = await assetService.updateAssetOrder(folderId, req) const updated = await assetService.updateAssetOrder(folderId, req)
return c.json(updated) return c.json(updated)
}, },
) )
.put( .put('/folders/:folderId', zValidator('json', updateFolderRequestSchema), async (c) => {
'/teams/:teamId/folders/:folderId', const folderId = c.req.param('folderId')
zValidator('json', updateFolderRequestSchema), const user = c.get('user')
async (c) => { const req = c.req.valid('json')
const folderId = c.req.param('folderId')
const user = c.get('user')
const req = c.req.valid('json')
await authzService.hasPermission({ await authzService.hasPermission({
assetId: folderId, user,
user, permission: Permission.Edit,
permission: Permission.Edit, type: ResourceType.Asset,
}) id: folderId,
})
const updatedAsset = await assetService.updateAssetName({ const updatedAsset = await assetService.updateAssetName({
id: folderId, id: folderId,
name: req.name, name: req.name,
}) })
return c.json(updatedAsset) return c.json(updatedAsset)
}, })
) .get('/folders/:folderId', async (c) => {
.get('/teams/:teamId/folders/:folderId', async (c) => {
const folderId = c.req.param('folderId') const folderId = c.req.param('folderId')
const user = c.get('user') const user = c.get('user')
await authzService.hasPermission({ await authzService.hasPermission({
assetId: folderId,
user, user,
permission: Permission.Read, permission: Permission.Read,
type: ResourceType.Asset,
id: folderId,
}) })
const assetInfo = await assetService.getAsset({ assetId: folderId }) const assetInfo = await assetService.getAsset({ assetId: folderId })
return c.json(assetInfo) return c.json(assetInfo)
}) })
.get( .get('/folders/:folderId/children', zValidator('query', listChildrenRequestSchema), async (c) => {
'/teams/:teamId/folders/:folderId/children', const folderId = c.req.param('folderId')
zValidator('query', listChildrenRequestSchema), const user = c.get('user')
async (c) => { const req = c.req.valid('query')
const folderId = c.req.param('folderId')
const user = c.get('user')
const req = c.req.valid('query')
await authzService.hasPermission({ await authzService.hasPermission({
assetId: folderId, user,
user, permission: Permission.Read,
permission: Permission.Read, type: ResourceType.Asset,
}) id: folderId,
})
const resp = await assetService.listChildren({ const resp = await assetService.listChildren({
assetId: folderId, assetId: folderId,
assetType: req.assetType, assetType: req.assetType,
projectId: req.projectId, projectId: req.projectId,
showDeleted: req.showDeleted, showDeleted: req.showDeleted,
sort: req.sort, sort: req.sort,
order: req.order, order: req.order,
}) })
return c.json(resp) return c.json(resp)
}, })
) .delete('/folders', zValidator('json', deleteFoldersRequestSchema), async (c) => {
.delete('/teams/:teamId/folders', zValidator('json', deleteFoldersRequestSchema), async (c) => {
const user = c.get('user') const user = c.get('user')
const req = c.req.valid('json') const req = c.req.valid('json')
for (const id of req.ids) { for (const id of req.ids) {
await authzService.hasPermission({ await authzService.hasPermission({
assetId: id,
user, user,
permission: Permission.Edit, permission: Permission.Edit,
type: ResourceType.Asset,
id,
}) })
} }
await assetService.deleteAssets(req.ids) await assetService.deleteAssets(req.ids)
return c.body(null, 204) return c.body(null, 204)
}) })
.post( .post('/folders/restore', zValidator('json', restoreFoldersRequestSchema), async (c) => {
'/teams/:teamId/folders/restore', const user = c.get('user')
zValidator('json', restoreFoldersRequestSchema), const req = c.req.valid('json')
async (c) => {
const user = c.get('user')
const req = c.req.valid('json')
for (const id of req.ids) {
await authzService.hasPermission({
assetId: id,
user,
permission: Permission.Edit,
})
}
await assetService.restoreAssets(req.ids)
return c.body(null, 204)
},
)
.post(
'/teams/:teamId/folders/:folderId/search',
zValidator('json', searchRequestSchema),
async (c) => {
const folderId = c.req.param('folderId')
const user = c.get('user')
const req = c.req.valid('json')
for (const id of req.ids) {
await authzService.hasPermission({ await authzService.hasPermission({
assetId: folderId,
user, user,
permission: Permission.Read, permission: Permission.Edit,
type: ResourceType.Asset,
id,
}) })
}
const result = await searchService.search(folderId, req) await assetService.restoreAssets(req.ids)
return c.json(result) return c.body(null, 204)
}, })
) .post('/folders/:folderId/search', zValidator('json', searchRequestSchema), async (c) => {
const folderId = c.req.param('folderId')
const user = c.get('user')
const req = c.req.valid('json')
await authzService.hasPermission({
user,
permission: Permission.Read,
type: ResourceType.Asset,
id: folderId,
})
const result = await searchService.search(folderId, req)
return c.json(result)
})
export default route export default route
+48 -50
View File
@@ -1,41 +1,18 @@
import { describe, expect, it, vi } from 'vitest' import { describe, expect, it, vi, beforeEach } from 'vitest'
import { Hono } from 'hono' import { Hono, type Context, type Next } from 'hono'
import inviteRoute from './invite' import inviteRoute from './invite'
import publicInviteRoute from './public-invite' import publicInviteRoute from './public-invite'
import { authMiddleware } from '@/api/middleware/auth' import { authzService, Permission, ResourceType } from '@/services/authz/authz'
import { inviteService } from '@/services/invite/invite'
import { notificationService } from '@/services/notification/notification'
vi.mock('@/services/invite/invite', () => ({ vi.mock('@/services/invite/invite')
inviteService: { vi.mock('@/services/notification/notification')
createTeamInvite: vi.fn(), vi.mock('@/services/authz/authz')
createProjectInvite: vi.fn(),
getInvite: vi.fn(),
consumeInvite: vi.fn(),
},
}))
vi.mock('@/services/notification/notification', () => ({
notificationService: {
create: vi.fn(),
},
}))
vi.mock('@/services/authz/authz', () => ({
authzService: {
hasPermission: vi.fn(),
},
Permission: {
Read: 'Read',
Edit: 'Edit',
Admin: 'Admin',
},
}))
vi.mock('@/api/middleware/auth', () => ({ vi.mock('@/api/middleware/auth', () => ({
// any is used here because Hono's Context and Next types are complex to mock in vitest.mock authMiddleware: async (c: Context, next: Next) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any c.set('user', { id: 'u1', name: 'Test User' })
authMiddleware: async (c: any, next: any) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
c.set('user', { id: 'u1', name: 'Test User' } as any)
await next() await next()
}, },
})) }))
@@ -43,15 +20,24 @@ vi.mock('@/api/middleware/auth', () => ({
const getApp = () => { const getApp = () => {
const app = new Hono() const app = new Hono()
.route('/', publicInviteRoute) .route('/', publicInviteRoute)
.use('*', authMiddleware) .use('*', async (c, next) => {
c.set('user', { id: 'u1', name: 'Test User' })
await next()
})
.route('/', inviteRoute) .route('/', inviteRoute)
return app return app
} }
describe('Invite API', () => { describe('Invite API', () => {
beforeEach(() => {
vi.clearAllMocks()
vi.mocked(authzService.hasPermission).mockResolvedValue(undefined)
})
it('GET /invite/:code', async () => { it('GET /invite/:code', async () => {
const app = getApp() const app = getApp()
const { inviteService } = await import('@/services/invite/invite')
// Using any here because mocking complex service return types or Hono context is overly verbose for this test.
vi.mocked(inviteService.getInvite).mockResolvedValue({ vi.mocked(inviteService.getInvite).mockResolvedValue({
code: 'code123', code: 'code123',
teamId: 't1', teamId: 't1',
@@ -59,7 +45,7 @@ describe('Invite API', () => {
inviter: { name: 'Inviter' }, inviter: { name: 'Inviter' },
role: 'editor', role: 'editor',
used: false, used: false,
} as never) } as any) // eslint-disable-line @typescript-eslint/no-explicit-any
const res = await app.request('/invite/code123') const res = await app.request('/invite/code123')
expect(res.status).toBe(200) expect(res.status).toBe(200)
@@ -75,9 +61,8 @@ describe('Invite API', () => {
it('POST /teams/:teamId/invite', async () => { it('POST /teams/:teamId/invite', async () => {
const app = getApp() const app = getApp()
const { authzService } = await import('@/services/authz/authz')
const { inviteService } = await import('@/services/invite/invite') // Using any here because mocking complex service return types or Hono context is overly verbose for this test.
vi.mocked(authzService.hasPermission).mockResolvedValue(undefined as never)
vi.mocked(inviteService.createTeamInvite).mockResolvedValue({ vi.mocked(inviteService.createTeamInvite).mockResolvedValue({
code: 'test-code', code: 'test-code',
role: 'editor', role: 'editor',
@@ -85,7 +70,7 @@ describe('Invite API', () => {
team: { name: 'Team A' }, team: { name: 'Team A' },
inviter: { name: 'Inviter' }, inviter: { name: 'Inviter' },
used: false, used: false,
} as never) } as any) // eslint-disable-line @typescript-eslint/no-explicit-any
const res = await app.request('/teams/t1/invite', { const res = await app.request('/teams/t1/invite', {
method: 'POST', method: 'POST',
@@ -105,6 +90,12 @@ describe('Invite API', () => {
inviterName: 'Inviter', inviterName: 'Inviter',
isUsed: false, isUsed: false,
}) })
expect(authzService.hasPermission).toHaveBeenCalledWith({
user: expect.anything(),
permission: Permission.Admin,
type: ResourceType.Team,
id: 't1',
})
expect(inviteService.createTeamInvite).toHaveBeenCalledWith({ expect(inviteService.createTeamInvite).toHaveBeenCalledWith({
teamId: 't1', teamId: 't1',
role: 'editor', role: 'editor',
@@ -114,9 +105,8 @@ describe('Invite API', () => {
it('POST /projects/:projectId/invite', async () => { it('POST /projects/:projectId/invite', async () => {
const app = getApp() const app = getApp()
const { authzService } = await import('@/services/authz/authz')
const { inviteService } = await import('@/services/invite/invite') // Using any here because mocking complex service return types or Hono context is overly verbose for this test.
vi.mocked(authzService.hasPermission).mockResolvedValue(undefined as never)
vi.mocked(inviteService.createProjectInvite).mockResolvedValue({ vi.mocked(inviteService.createProjectInvite).mockResolvedValue({
code: 'proj-code', code: 'proj-code',
role: 'reviewer', role: 'reviewer',
@@ -125,7 +115,7 @@ describe('Invite API', () => {
project: { id: 'p1', name: 'Project A' }, project: { id: 'p1', name: 'Project A' },
inviter: { name: 'Inviter' }, inviter: { name: 'Inviter' },
used: false, used: false,
} as never) } as any) // eslint-disable-line @typescript-eslint/no-explicit-any
const res = await app.request('/projects/p1/invite', { const res = await app.request('/projects/p1/invite', {
method: 'POST', method: 'POST',
@@ -147,6 +137,12 @@ describe('Invite API', () => {
inviterName: 'Inviter', inviterName: 'Inviter',
isUsed: false, isUsed: false,
}) })
expect(authzService.hasPermission).toHaveBeenCalledWith({
user: expect.anything(),
permission: Permission.Admin,
type: ResourceType.Project,
id: 'p1',
})
expect(inviteService.createProjectInvite).toHaveBeenCalledWith({ expect(inviteService.createProjectInvite).toHaveBeenCalledWith({
projectId: 'p1', projectId: 'p1',
role: 'reviewer', role: 'reviewer',
@@ -156,19 +152,21 @@ describe('Invite API', () => {
it('POST /join (Team)', async () => { it('POST /join (Team)', async () => {
const app = getApp() const app = getApp()
const { inviteService } = await import('@/services/invite/invite') // Using any here because mocking complex service return types or Hono context is overly verbose for this test.
const { notificationService } = await import('@/services/notification/notification') // eslint-disable-next-line @typescript-eslint/no-explicit-any
vi.mocked(notificationService.create).mockResolvedValue(undefined as any)
vi.mocked(notificationService.create).mockResolvedValue(undefined as never)
// Using any here because mocking complex service return types or Hono context is overly verbose for this test.
vi.mocked(inviteService.getInvite).mockResolvedValue({ vi.mocked(inviteService.getInvite).mockResolvedValue({
code: 'code123', code: 'code123',
teamId: 't1', teamId: 't1',
team: { name: 'Team A' }, team: { name: 'Team A' },
inviter: { name: 'Inviter' }, inviter: { name: 'Inviter' },
used: false, used: false,
} as never) } as any) // eslint-disable-line @typescript-eslint/no-explicit-any
vi.mocked(inviteService.consumeInvite).mockResolvedValue(undefined as never) // Using any here because mocking complex service return types or Hono context is overly verbose for this test.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
vi.mocked(inviteService.consumeInvite).mockResolvedValue(undefined as any)
const res = await app.request('/join', { const res = await app.request('/join', {
method: 'POST', method: 'POST',
+5 -3
View File
@@ -6,7 +6,7 @@ import {
joinRequestSchema, joinRequestSchema,
InviteInfo, InviteInfo,
} from '@/dtos/invite' } from '@/dtos/invite'
import { authzService, Permission } from '@/services/authz/authz' import { authzService, Permission, ResourceType } from '@/services/authz/authz'
import { inviteService } from '@/services/invite/invite' import { inviteService } from '@/services/invite/invite'
import { notificationService } from '@/services/notification/notification' import { notificationService } from '@/services/notification/notification'
import { NotificationType } from '@/generated/prisma/client' import { NotificationType } from '@/generated/prisma/client'
@@ -40,9 +40,10 @@ const route = new Hono<{ Variables: { user: User } }>()
const user = c.get('user') const user = c.get('user')
await authzService.hasPermission({ await authzService.hasPermission({
teamId,
user, user,
permission: Permission.Admin, permission: Permission.Admin,
type: ResourceType.Team,
id: teamId,
}) })
const inv = await inviteService.createTeamInvite({ const inv = await inviteService.createTeamInvite({
@@ -63,9 +64,10 @@ const route = new Hono<{ Variables: { user: User } }>()
const user = c.get('user') const user = c.get('user')
await authzService.hasPermission({ await authzService.hasPermission({
projectId,
user, user,
permission: Permission.Admin, permission: Permission.Admin,
type: ResourceType.Project,
id: projectId,
}) })
const inv = await inviteService.createProjectInvite({ const inv = await inviteService.createProjectInvite({
+98 -47
View File
@@ -1,36 +1,30 @@
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest' import { describe, expect, it, vi, beforeEach } from 'vitest'
import { Hono } from 'hono' import { Hono, type Context, type Next } from 'hono'
import metadataRoute from './metadata' import metadataRoute from './metadata'
import { metadataService } from '@/services/metadata/metadata' import { metadataService } from '@/services/metadata/metadata'
import { Prisma } from '@/generated/prisma/client.ts' import { authzService, Permission, ResourceType } from '@/services/authz/authz'
import { authMiddleware } from '@/api/middleware/auth'
vi.mock('@/services/authz/authz', () => ({
authzService: {
hasPermission: vi.fn(),
},
Permission: {
Read: 'Read',
Edit: 'Edit',
Admin: 'Admin',
},
}))
vi.mock('@/api/middleware/auth', () => ({ vi.mock('@/api/middleware/auth', () => ({
// eslint-disable-next-line @typescript-eslint/no-explicit-any authMiddleware: async (c: Context, next: Next) => {
authMiddleware: async (c: any, next: any) => {
c.set('user', { id: 'user1', name: 'Test User' }) c.set('user', { id: 'user1', name: 'Test User' })
await next() await next()
}, },
})) }))
vi.mock('@/services/authz/authz')
vi.mock('@/services/metadata/metadata')
describe('metadata api', () => { describe('metadata api', () => {
const app = new Hono()
.use('*', async (c, next) => {
c.set('user', { id: 'user1', name: 'Test User' })
await next()
})
.route('/', metadataRoute)
beforeEach(() => { beforeEach(() => {
vi.restoreAllMocks() vi.restoreAllMocks()
}) vi.mocked(authzService.hasPermission).mockResolvedValue(undefined)
afterEach(() => {
vi.restoreAllMocks()
}) })
it('GET /teams/:teamId/fields', async () => { it('GET /teams/:teamId/fields', async () => {
@@ -41,11 +35,11 @@ describe('metadata api', () => {
readOnly: false, readOnly: false,
description: 'desc', description: 'desc',
aiAutofill: true, aiAutofill: true,
} as Prisma.MetadataFieldGetPayload<Record<string, never>> }
vi.spyOn(metadataService, 'listTeamFields').mockResolvedValue([mockField]) // Using any here because mocking complex service return types or Hono context is overly verbose for this test.
vi.mocked(metadataService.listTeamFields).mockResolvedValue([mockField as any]) // eslint-disable-line @typescript-eslint/no-explicit-any
const app = new Hono().use('*', authMiddleware).route('/', metadataRoute)
const res = await app.request('/teams/t1/fields') const res = await app.request('/teams/t1/fields')
expect(res.status).toBe(200) expect(res.status).toBe(200)
@@ -54,6 +48,12 @@ describe('metadata api', () => {
expect(json[0].id).toBe('field1') expect(json[0].id).toBe('field1')
expect(json[0].config.name).toBe('Test Field') expect(json[0].config.name).toBe('Test Field')
expect(json[0].aiAutofill).toBe(true) expect(json[0].aiAutofill).toBe(true)
expect(authzService.hasPermission).toHaveBeenCalledWith({
user: expect.anything(),
permission: Permission.Read,
type: ResourceType.Team,
id: 't1',
})
}) })
it('POST /teams/:teamId/fields', async () => { it('POST /teams/:teamId/fields', async () => {
@@ -64,11 +64,11 @@ describe('metadata api', () => {
readOnly: false, readOnly: false,
description: 'desc', description: 'desc',
aiAutofill: true, aiAutofill: true,
} as Prisma.MetadataFieldGetPayload<Record<string, never>> }
vi.spyOn(metadataService, 'createTeamField').mockResolvedValue(mockField) // Using any here because mocking complex service return types or Hono context is overly verbose for this test.
vi.mocked(metadataService.createTeamField).mockResolvedValue(mockField as any) // eslint-disable-line @typescript-eslint/no-explicit-any
const app = new Hono().use('*', authMiddleware).route('/', metadataRoute)
const res = await app.request('/teams/t1/fields', { const res = await app.request('/teams/t1/fields', {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
@@ -82,6 +82,12 @@ describe('metadata api', () => {
expect(res.status).toBe(200) expect(res.status).toBe(200)
const json = await res.json() const json = await res.json()
expect(json.id).toBe('newfield') expect(json.id).toBe('newfield')
expect(authzService.hasPermission).toHaveBeenCalledWith({
user: expect.anything(),
permission: Permission.Admin,
type: ResourceType.Team,
id: 't1',
})
}) })
it('GET /projects/:projectId/fields', async () => { it('GET /projects/:projectId/fields', async () => {
@@ -92,13 +98,12 @@ describe('metadata api', () => {
readOnly: false, readOnly: false,
description: 'desc', description: 'desc',
aiAutofill: false, aiAutofill: false,
} as Prisma.MetadataFieldGetPayload<Record<string, never>> }
vi.spyOn(metadataService, 'listProjectFields').mockResolvedValue([ vi.mocked(metadataService.listProjectFields).mockResolvedValue([
{ field: mockField, visible: true }, { field: mockField, visible: true } as any, // eslint-disable-line @typescript-eslint/no-explicit-any
]) ])
const app = new Hono().use('*', authMiddleware).route('/', metadataRoute)
const res = await app.request('/projects/p1/fields') const res = await app.request('/projects/p1/fields')
expect(res.status).toBe(200) expect(res.status).toBe(200)
@@ -106,12 +111,19 @@ describe('metadata api', () => {
expect(json).toHaveLength(1) expect(json).toHaveLength(1)
expect(json[0].id).toBe('field1') expect(json[0].id).toBe('field1')
expect(json[0].visible).toBe(true) expect(json[0].visible).toBe(true)
expect(authzService.hasPermission).toHaveBeenCalledWith({
user: expect.anything(),
permission: Permission.Read,
type: ResourceType.Project,
id: 'p1',
})
}) })
it('PATCH /projects/:projectId/fields/order', async () => { it('PATCH /projects/:projectId/fields/order', async () => {
vi.spyOn(metadataService, 'updateProjectFieldsOrder').mockResolvedValue(undefined) // Using any here because mocking complex service return types or Hono context is overly verbose for this test.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
vi.mocked(metadataService.updateProjectFieldsOrder).mockResolvedValue(undefined as any)
const app = new Hono().use('*', authMiddleware).route('/', metadataRoute)
const res = await app.request('/projects/p1/fields/order', { const res = await app.request('/projects/p1/fields/order', {
method: 'PATCH', method: 'PATCH',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
@@ -122,33 +134,72 @@ describe('metadata api', () => {
expect(metadataService.updateProjectFieldsOrder).toHaveBeenCalledWith('user1', 'p1', [ expect(metadataService.updateProjectFieldsOrder).toHaveBeenCalledWith('user1', 'p1', [
{ fieldId: 'field1', visible: true }, { fieldId: 'field1', visible: true },
]) ])
expect(authzService.hasPermission).toHaveBeenCalledWith({
user: expect.anything(),
permission: Permission.Admin,
type: ResourceType.Project,
id: 'p1',
})
}) })
it('DELETE /teams/:teamId/fields/:fieldId', async () => { it('DELETE /fields/:fieldId', async () => {
vi.spyOn(metadataService, 'deleteTeamField').mockResolvedValue(undefined) // Using any here because mocking complex service return types or Hono context is overly verbose for this test.
vi.mocked(metadataService.getFieldByKey).mockResolvedValue({
key: 'f1',
teamId: 't1',
} as any) // eslint-disable-line @typescript-eslint/no-explicit-any
// Using any here because mocking complex service return types or Hono context is overly verbose for this test.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
vi.mocked(metadataService.deleteTeamField).mockResolvedValue(undefined as any)
const app = new Hono().use('*', authMiddleware).route('/', metadataRoute) const res = await app.request('/fields/f1', {
const res = await app.request('/teams/t1/fields/f1', {
method: 'DELETE', method: 'DELETE',
}) })
expect(res.status).toBe(204) expect(res.status).toBe(204)
expect(metadataService.deleteTeamField).toHaveBeenCalledWith('t1', 'f1') expect(metadataService.deleteTeamField).toHaveBeenCalledWith('t1', 'f1')
expect(authzService.hasPermission).toHaveBeenCalledWith({
user: expect.anything(),
permission: Permission.Admin,
type: ResourceType.MetadataField,
id: 'f1',
})
}) })
it('PATCH /teams/:teamId/files/:fileId/metadata', async () => { it('PUT /fields/:fieldId', async () => {
vi.spyOn(metadataService, 'updateAssetMetadata').mockResolvedValue(undefined) const mockField = {
key: 'f1',
scope: 'TEAM',
config: { name: 'Updated Field', type: 'text' },
readOnly: false,
description: 'desc',
aiAutofill: true,
teamId: 't1',
}
const app = new Hono().use('*', authMiddleware).route('/', metadataRoute) // Using any here because mocking complex service return types or Hono context is overly verbose for this test.
const res = await app.request('/teams/t1/files/f1/metadata', { vi.mocked(metadataService.getFieldByKey).mockResolvedValue(mockField as any) // eslint-disable-line @typescript-eslint/no-explicit-any
method: 'PATCH', // Using any here because mocking complex service return types or Hono context is overly verbose for this test.
vi.mocked(metadataService.updateTeamField).mockResolvedValue(mockField as any) // eslint-disable-line @typescript-eslint/no-explicit-any
const res = await app.request('/fields/f1', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify([{ key: 'resolution_width', value: 1920 }]), body: JSON.stringify({
config: { name: 'Updated Field', type: 'text' },
aiAutofill: true,
description: 'desc',
}),
}) })
expect(res.status).toBe(204) expect(res.status).toBe(200)
expect(metadataService.updateAssetMetadata).toHaveBeenCalledWith('f1', [ const json = await res.json()
{ key: 'resolution_width', value: 1920 }, expect(json.id).toBe('f1')
]) expect(authzService.hasPermission).toHaveBeenCalledWith({
user: expect.anything(),
permission: Permission.Admin,
type: ResourceType.MetadataField,
id: 'f1',
})
}) })
}) })
+52 -83
View File
@@ -1,13 +1,11 @@
import { zValidator } from '@hono/zod-validator' import { zValidator } from '@hono/zod-validator'
import { z } from 'zod'
import { Hono } from 'hono' import { Hono } from 'hono'
import { metadataService } from '@/services/metadata/metadata' import { metadataService } from '@/services/metadata/metadata'
import { authzService, Permission } from '@/services/authz/authz' import { authzService, Permission, ResourceType } from '@/services/authz/authz'
import { import {
createFieldRequestSchema, createFieldRequestSchema,
updateFieldRequestSchema, updateFieldRequestSchema,
updateProjectFieldsOrderRequestSchema, updateProjectFieldsOrderRequestSchema,
updateAssetMetadataRequestSchema,
FieldInfo, FieldInfo,
} from '@/dtos/metadata' } from '@/dtos/metadata'
import type { Prisma } from '@/generated/prisma/client' import type { Prisma } from '@/generated/prisma/client'
@@ -37,9 +35,10 @@ const route = new Hono<{ Variables: { user: User } }>()
const user = c.get('user') const user = c.get('user')
await authzService.hasPermission({ await authzService.hasPermission({
teamId,
user, user,
permission: Permission.Admin, permission: Permission.Admin,
type: ResourceType.Team,
id: teamId,
}) })
const field = await metadataService.createTeamField(teamId, req) const field = await metadataService.createTeamField(teamId, req)
@@ -50,45 +49,66 @@ const route = new Hono<{ Variables: { user: User } }>()
const user = c.get('user') const user = c.get('user')
await authzService.hasPermission({ await authzService.hasPermission({
teamId,
user, user,
permission: Permission.Read, permission: Permission.Read,
type: ResourceType.Team,
id: teamId,
}) })
const fields = await metadataService.listTeamFields(teamId) const fields = await metadataService.listTeamFields(teamId)
return c.json(fields.map((f) => toFieldInfo(f))) return c.json(fields.map((f) => toFieldInfo(f)))
}) })
.put( .put('/fields/:fieldId', zValidator('json', updateFieldRequestSchema), async (c) => {
'/teams/:teamId/fields/:fieldId', const fieldId = c.req.param('fieldId')
zValidator('json', updateFieldRequestSchema), const req = c.req.valid('json')
async (c) => { const user = c.get('user')
const teamId = c.req.param('teamId')
const fieldId = c.req.param('fieldId')
const req = c.req.valid('json')
const user = c.get('user')
await authzService.hasPermission({ await authzService.hasPermission({
teamId, user,
user, permission: Permission.Admin,
permission: Permission.Admin, type: ResourceType.MetadataField,
}) id: fieldId,
})
const field = await metadataService.updateTeamField(teamId, fieldId, req) // We need teamId/projectId for metadataService. But we can get them from the field itself.
return c.json(toFieldInfo(field)) // Or we can refactor metadataService to not require them if we already have the field.
}, // For now, let's just fetch it once to get the context for the service call.
) const field = await metadataService.getFieldByKey(fieldId)
.delete('/teams/:teamId/fields/:fieldId', async (c) => { if (!field) throw new Error('Field not found')
const teamId = c.req.param('teamId')
let updated
if (field.projectId) {
updated = await metadataService.updateProjectField(field.projectId, fieldId, req)
} else if (field.teamId) {
updated = await metadataService.updateTeamField(field.teamId, fieldId, req)
} else {
throw new Error('Field has no context')
}
return c.json(toFieldInfo(updated))
})
.delete('/fields/:fieldId', async (c) => {
const fieldId = c.req.param('fieldId') const fieldId = c.req.param('fieldId')
const user = c.get('user') const user = c.get('user')
await authzService.hasPermission({ await authzService.hasPermission({
teamId,
user, user,
permission: Permission.Admin, permission: Permission.Admin,
type: ResourceType.MetadataField,
id: fieldId,
}) })
await metadataService.deleteTeamField(teamId, fieldId) const field = await metadataService.getFieldByKey(fieldId)
if (!field) throw new Error('Field not found')
if (field.projectId) {
await metadataService.deleteProjectField(field.projectId, fieldId)
} else if (field.teamId) {
await metadataService.deleteTeamField(field.teamId, fieldId)
} else {
throw new Error('Field has no context')
}
return new Response(null, { status: 204 }) return new Response(null, { status: 204 })
}) })
.post('/projects/:projectId/fields', zValidator('json', createFieldRequestSchema), async (c) => { .post('/projects/:projectId/fields', zValidator('json', createFieldRequestSchema), async (c) => {
@@ -97,9 +117,10 @@ const route = new Hono<{ Variables: { user: User } }>()
const user = c.get('user') const user = c.get('user')
await authzService.hasPermission({ await authzService.hasPermission({
projectId,
user, user,
permission: Permission.Admin, permission: Permission.Admin,
type: ResourceType.Project,
id: projectId,
}) })
const field = await metadataService.createProjectField(projectId, req) const field = await metadataService.createProjectField(projectId, req)
@@ -110,9 +131,10 @@ const route = new Hono<{ Variables: { user: User } }>()
const user = c.get('user') const user = c.get('user')
await authzService.hasPermission({ await authzService.hasPermission({
projectId,
user, user,
permission: Permission.Read, permission: Permission.Read,
type: ResourceType.Project,
id: projectId,
}) })
const fields = await metadataService.listProjectFields(user.id, projectId) const fields = await metadataService.listProjectFields(user.id, projectId)
@@ -127,68 +149,15 @@ const route = new Hono<{ Variables: { user: User } }>()
const user = c.get('user') const user = c.get('user')
await authzService.hasPermission({ await authzService.hasPermission({
projectId,
user, user,
permission: Permission.Admin, permission: Permission.Admin,
type: ResourceType.Project,
id: projectId,
}) })
await metadataService.updateProjectFieldsOrder(user.id, projectId, req) await metadataService.updateProjectFieldsOrder(user.id, projectId, req)
return new Response(null, { status: 204 }) return new Response(null, { status: 204 })
}, },
) )
.put(
'/projects/:projectId/fields/:fieldId',
zValidator('json', updateFieldRequestSchema),
async (c) => {
const projectId = c.req.param('projectId')
const fieldId = c.req.param('fieldId')
const req = c.req.valid('json')
const user = c.get('user')
await authzService.hasPermission({
projectId,
user,
permission: Permission.Admin,
})
const field = await metadataService.updateProjectField(projectId, fieldId, req)
return c.json(toFieldInfo(field))
},
)
.delete('/projects/:projectId/fields/:fieldId', async (c) => {
const projectId = c.req.param('projectId')
const fieldId = c.req.param('fieldId')
const user = c.get('user')
await authzService.hasPermission({
projectId,
user,
permission: Permission.Admin,
})
await metadataService.deleteProjectField(projectId, fieldId)
return new Response(null, { status: 204 })
})
.patch(
'/teams/:teamId/files/:fileId/metadata',
zValidator('json', z.array(updateAssetMetadataRequestSchema)),
async (c) => {
const teamId = c.req.param('teamId')
const fileId = c.req.param('fileId') // Actually maps to assetId
const req = c.req.valid('json')
const user = c.get('user')
await authzService.hasPermission({
teamId,
assetId: fileId,
user,
permission: Permission.Edit,
})
await metadataService.updateAssetMetadata(fileId, req)
return new Response(null, { status: 204 })
},
)
export default route export default route
+33 -34
View File
@@ -1,52 +1,38 @@
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest' import { describe, expect, it, vi, beforeEach } from 'vitest'
import { Hono } from 'hono' import { Hono, type Context, type Next } from 'hono'
import notificationRoute from './notification' import notificationRoute from './notification'
import { notificationService } from '@/services/notification/notification' import { notificationService } from '@/services/notification/notification'
import { authMiddleware } from '@/api/middleware/auth' import { authzService, Permission, ResourceType } from '@/services/authz/authz'
vi.mock('@/services/authz/authz', () => ({
authzService: {
hasPermission: vi.fn(),
},
Permission: {
Read: 'Read',
Edit: 'Edit',
Admin: 'Admin',
},
}))
vi.mock('@/api/middleware/auth', () => ({ vi.mock('@/api/middleware/auth', () => ({
// eslint-disable-next-line @typescript-eslint/no-explicit-any authMiddleware: async (c: Context, next: Next) => {
authMiddleware: async (c: any, next: any) => {
c.set('user', { id: 'user1', name: 'Test User' }) c.set('user', { id: 'user1', name: 'Test User' })
await next() await next()
}, },
})) }))
vi.mock('@/services/authz/authz')
vi.mock('@/services/notification/notification')
describe('notification api', () => { describe('notification api', () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any const app = new Hono()
let mockList: any .use('*', async (c, next) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any c.set('user', { id: 'user1', name: 'Test User' })
let mockMarkRead: any await next()
})
.route('/', notificationRoute)
beforeEach(() => { beforeEach(() => {
mockList = vi.fn()
mockMarkRead = vi.fn()
vi.spyOn(notificationService, 'list').mockImplementation(mockList)
vi.spyOn(notificationService, 'markRead').mockImplementation(mockMarkRead)
})
afterEach(() => {
vi.restoreAllMocks() vi.restoreAllMocks()
vi.mocked(authzService.hasPermission).mockResolvedValue(undefined)
}) })
it('GET /teams/:teamId/notifications', async () => { it('GET /teams/:teamId/notifications', async () => {
mockList.mockResolvedValue({ vi.mocked(notificationService.list).mockResolvedValue({
data: [{ id: 'n1', type: 'comment_created' }], data: [{ id: 'n1', type: 'comment_created' }] as any, // eslint-disable-line @typescript-eslint/no-explicit-any
pageInfo: { total: 1, cursor: 'abc' }, pageInfo: { total: 1, cursor: 'abc' },
}) })
const app = new Hono().use('*', authMiddleware).route('/', notificationRoute)
const res = await app.request('/teams/t1/notifications?unreadOnly=true&pageSize=10') const res = await app.request('/teams/t1/notifications?unreadOnly=true&pageSize=10')
expect(res.status).toBe(200) expect(res.status).toBe(200)
@@ -55,17 +41,24 @@ describe('notification api', () => {
expect(json.pageInfo.total).toBe(1) expect(json.pageInfo.total).toBe(1)
expect(json.pageInfo.cursor).toBe('abc') expect(json.pageInfo.cursor).toBe('abc')
expect(mockList).toHaveBeenCalledWith('t1', 'user1', { expect(notificationService.list).toHaveBeenCalledWith('t1', 'user1', {
unreadOnly: true, unreadOnly: true,
after: undefined, after: undefined,
pageSize: 10, pageSize: 10,
}) })
expect(authzService.hasPermission).toHaveBeenCalledWith({
user: expect.anything(),
permission: Permission.Read,
type: ResourceType.Team,
id: 't1',
})
}) })
it('POST /teams/:teamId/notifications/read', async () => { it('POST /teams/:teamId/notifications/read', async () => {
mockMarkRead.mockResolvedValue(undefined) // Using any here because mocking complex service return types or Hono context is overly verbose for this test.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
vi.mocked(notificationService.markRead).mockResolvedValue(undefined as any)
const app = new Hono().use('*', authMiddleware).route('/', notificationRoute)
const res = await app.request('/teams/t1/notifications/read', { const res = await app.request('/teams/t1/notifications/read', {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
@@ -73,6 +66,12 @@ describe('notification api', () => {
}) })
expect(res.status).toBe(204) expect(res.status).toBe(204)
expect(mockMarkRead).toHaveBeenCalledWith('t1', 'user1', 'n1') expect(notificationService.markRead).toHaveBeenCalledWith('t1', 'user1', 'n1')
expect(authzService.hasPermission).toHaveBeenCalledWith({
user: expect.anything(),
permission: Permission.Read,
type: ResourceType.Team,
id: 't1',
})
}) })
}) })
+5 -3
View File
@@ -1,7 +1,7 @@
import { zValidator } from '@hono/zod-validator' import { zValidator } from '@hono/zod-validator'
import { Hono } from 'hono' import { Hono } from 'hono'
import { notificationService } from '@/services/notification/notification' import { notificationService } from '@/services/notification/notification'
import { authzService, Permission } from '@/services/authz/authz' import { authzService, Permission, ResourceType } from '@/services/authz/authz'
import { import {
listNotificationsRequestSchema, listNotificationsRequestSchema,
markNotificationReadRequestSchema, markNotificationReadRequestSchema,
@@ -20,9 +20,10 @@ const route = new Hono<{ Variables: { user: User } }>()
const user = c.get('user') const user = c.get('user')
await authzService.hasPermission({ await authzService.hasPermission({
teamId,
user, user,
permission: Permission.Read, permission: Permission.Read,
type: ResourceType.Team,
id: teamId,
}) })
const res = await notificationService.list(teamId, user.id, { const res = await notificationService.list(teamId, user.id, {
@@ -50,9 +51,10 @@ const route = new Hono<{ Variables: { user: User } }>()
const user = c.get('user') const user = c.get('user')
await authzService.hasPermission({ await authzService.hasPermission({
teamId,
user, user,
permission: Permission.Read, permission: Permission.Read,
type: ResourceType.Team,
id: teamId,
}) })
await notificationService.markRead(teamId, user.id, req.notificationId) await notificationService.markRead(teamId, user.id, req.notificationId)
+73 -74
View File
@@ -1,69 +1,40 @@
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest' import { describe, expect, it, vi, beforeEach } from 'vitest'
import { Hono } from 'hono' import { Hono, type Context, type Next } from 'hono'
import projectRoute from './project' import projectRoute from './project'
import { authMiddleware } from '@/api/middleware/auth' import { authzService, Permission, ResourceType } from '@/services/authz/authz'
import { projectService } from '@/services/project/project' import { projectService } from '@/services/project/project'
import { assetService } from '@/services/asset/asset' import { assetService } from '@/services/asset/asset'
import { authzService } from '@/services/authz/authz'
vi.mock('@/services/authz/authz', () => ({
authzService: {
hasPermission: vi.fn(),
},
Permission: {
Read: 'Read',
Edit: 'Edit',
Admin: 'Admin',
},
}))
vi.mock('@/api/middleware/auth', () => ({ vi.mock('@/api/middleware/auth', () => ({
// eslint-disable-next-line @typescript-eslint/no-explicit-any authMiddleware: async (c: Context, next: Next) => {
authMiddleware: async (c: any, next: any) => {
c.set('user', { id: 'user1', name: 'Test User' }) c.set('user', { id: 'user1', name: 'Test User' })
await next() await next()
}, },
})) }))
vi.mock('@/services/authz/authz')
vi.mock('@/services/project/project')
vi.mock('@/services/asset/asset')
describe('project api', () => { describe('project api', () => {
let mockListProjects: any // eslint-disable-line @typescript-eslint/no-explicit-any const app = new Hono()
let mockCreateProject: any // eslint-disable-line @typescript-eslint/no-explicit-any .use('*', async (c, next) => {
let mockUpdateProject: any // eslint-disable-line @typescript-eslint/no-explicit-any c.set('user', { id: 'user1', name: 'Test User' })
let mockGetProject: any // eslint-disable-line @typescript-eslint/no-explicit-any await next()
let mockGetProjectTeam: any // eslint-disable-line @typescript-eslint/no-explicit-any })
let mockListProjectMembers: any // eslint-disable-line @typescript-eslint/no-explicit-any .route('/', projectRoute)
let mockReparentAssets: any // eslint-disable-line @typescript-eslint/no-explicit-any
beforeEach(() => { beforeEach(() => {
mockListProjects = vi.fn()
mockCreateProject = vi.fn()
mockUpdateProject = vi.fn()
mockGetProject = vi.fn()
mockGetProjectTeam = vi.fn()
mockListProjectMembers = vi.fn()
mockReparentAssets = vi.fn()
vi.mocked(authzService.hasPermission).mockClear()
vi.spyOn(projectService, 'listProjects').mockImplementation(mockListProjects)
vi.spyOn(projectService, 'createProject').mockImplementation(mockCreateProject)
vi.spyOn(projectService, 'updateProject').mockImplementation(mockUpdateProject)
vi.spyOn(projectService, 'getProject').mockImplementation(mockGetProject)
vi.spyOn(projectService, 'getProjectTeam').mockImplementation(mockGetProjectTeam)
vi.spyOn(projectService, 'listProjectMembers').mockImplementation(mockListProjectMembers)
vi.spyOn(assetService, 'reparentAssets').mockImplementation(mockReparentAssets)
})
afterEach(() => {
vi.restoreAllMocks() vi.restoreAllMocks()
vi.mocked(authzService.hasPermission).mockResolvedValue(undefined)
}) })
it('GET /teams/:teamId/projects', async () => { it('GET /teams/:teamId/projects', async () => {
mockListProjects.mockResolvedValue({ vi.mocked(projectService.listProjects).mockResolvedValue({
data: [{ id: 'foo', name: 'foo.png', rootFolder: 'uid' }], data: [{ id: 'foo', name: 'foo.png', rootFolder: 'uid' }] as any, // eslint-disable-line @typescript-eslint/no-explicit-any
pageInfo: { total: 100, cursor: 'abc' }, pageInfo: { total: 100, cursor: 'abc' },
}) })
const app = new Hono().use('*', authMiddleware).route('/', projectRoute)
const res = await app.request('/teams/t/projects?page_size=10') const res = await app.request('/teams/t/projects?page_size=10')
expect(res.status).toBe(200) expect(res.status).toBe(200)
@@ -71,16 +42,21 @@ describe('project api', () => {
expect(json.data).toHaveLength(1) expect(json.data).toHaveLength(1)
expect(json.pageInfo.total).toBe(100) expect(json.pageInfo.total).toBe(100)
expect(json.data[0].id).toBe('foo') expect(json.data[0].id).toBe('foo')
expect(authzService.hasPermission).toHaveBeenCalledWith({
user: expect.anything(),
permission: Permission.Read,
type: ResourceType.Team,
id: 't',
})
}) })
it('POST /teams/:teamId/projects', async () => { it('POST /teams/:teamId/projects', async () => {
mockCreateProject.mockResolvedValue({ vi.mocked(projectService.createProject).mockResolvedValue({
id: 'foo', id: 'foo',
name: 'foo.png', name: 'foo.png',
coverImage: 'http://s3/bucket/key', coverImage: 'http://s3/bucket/key',
}) } as any) // eslint-disable-line @typescript-eslint/no-explicit-any
const app = new Hono().use('*', authMiddleware).route('/', projectRoute)
const res = await app.request('/teams/t/projects', { const res = await app.request('/teams/t/projects', {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
@@ -92,17 +68,22 @@ describe('project api', () => {
expect(json.id).toBe('foo') expect(json.id).toBe('foo')
expect(json.name).toBe('foo.png') expect(json.name).toBe('foo.png')
expect(json.coverImage).toBe('http://s3/bucket/key') expect(json.coverImage).toBe('http://s3/bucket/key')
expect(authzService.hasPermission).toHaveBeenCalledWith({
user: expect.anything(),
permission: Permission.Edit,
type: ResourceType.Team,
id: 't',
})
}) })
it('PUT /teams/:teamId/projects/:projectId', async () => { it('PUT /projects/:projectId', async () => {
mockUpdateProject.mockResolvedValue({ vi.mocked(projectService.updateProject).mockResolvedValue({
id: 'foo', id: 'foo',
name: 'updated', name: 'updated',
coverImage: 'http://s3/bucket/key', coverImage: 'http://s3/bucket/key',
}) } as any) // eslint-disable-line @typescript-eslint/no-explicit-any
const app = new Hono().use('*', authMiddleware).route('/', projectRoute) const res = await app.request('/projects/foo', {
const res = await app.request('/teams/t/projects/foo', {
method: 'PUT', method: 'PUT',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'updated' }), body: JSON.stringify({ name: 'updated' }),
@@ -111,39 +92,54 @@ describe('project api', () => {
expect(res.status).toBe(200) expect(res.status).toBe(200)
const json = await res.json() const json = await res.json()
expect(json.name).toBe('updated') expect(json.name).toBe('updated')
expect(authzService.hasPermission).toHaveBeenCalledWith({
user: expect.anything(),
permission: Permission.Edit,
type: ResourceType.Project,
id: 'foo',
})
}) })
it('GET /projects/:projectId', async () => { it('GET /projects/:projectId', async () => {
mockGetProject.mockResolvedValue({ vi.mocked(projectService.getProject).mockResolvedValue({
id: 'p', id: 'p',
name: 'foo.png', name: 'foo.png',
rootFolder: 'root_folder_id', rootFolder: 'root_folder_id',
}) } as any) // eslint-disable-line @typescript-eslint/no-explicit-any
const app = new Hono().use('*', authMiddleware).route('/', projectRoute)
const res = await app.request('/projects/p') const res = await app.request('/projects/p')
expect(res.status).toBe(200) expect(res.status).toBe(200)
const json = await res.json() const json = await res.json()
expect(json.rootFolder).toBe('root_folder_id') expect(json.rootFolder).toBe('root_folder_id')
expect(json.id).toBe('p') expect(json.id).toBe('p')
expect(authzService.hasPermission).toHaveBeenCalledWith({
user: expect.anything(),
permission: Permission.Read,
type: ResourceType.Project,
id: 'p',
})
}) })
it('GET /projects/:projectId/team', async () => { it('GET /projects/:projectId/team', async () => {
mockGetProjectTeam.mockResolvedValue('teamId') vi.mocked(projectService.getProjectTeam).mockResolvedValue('teamId')
const app = new Hono().use('*', authMiddleware).route('/', projectRoute)
const res = await app.request('/projects/p/team') const res = await app.request('/projects/p/team')
expect(res.status).toBe(200) expect(res.status).toBe(200)
const json = await res.json() const json = await res.json()
expect(json.teamId).toBe('teamId') expect(json.teamId).toBe('teamId')
expect(authzService.hasPermission).toHaveBeenCalledWith({
user: expect.anything(),
permission: Permission.Read,
type: ResourceType.Project,
id: 'p',
})
}) })
it('POST /projects/:projectId/reparent', async () => { it('POST /projects/:projectId/reparent', async () => {
mockReparentAssets.mockResolvedValue(undefined) vi.mocked(assetService.reparentAssets).mockResolvedValue(undefined)
const app = new Hono().use('*', authMiddleware).route('/', projectRoute)
const res = await app.request('/projects/p/reparent', { const res = await app.request('/projects/p/reparent', {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
@@ -154,22 +150,25 @@ describe('project api', () => {
}) })
expect(res.status).toBe(204) expect(res.status).toBe(204)
expect(authzService.hasPermission).toHaveBeenNthCalledWith(1, { expect(authzService.hasPermission).toHaveBeenCalledWith({
assetId: 'new_parent_id', user: expect.anything(),
user: { id: 'user1', name: 'Test User' }, permission: Permission.Edit,
permission: 'Edit', type: ResourceType.Asset,
id: 'new_parent_id',
}) })
expect(authzService.hasPermission).toHaveBeenNthCalledWith(2, { expect(authzService.hasPermission).toHaveBeenCalledWith({
assetId: 'asset_1', user: expect.anything(),
user: { id: 'user1', name: 'Test User' }, permission: Permission.Edit,
permission: 'Edit', type: ResourceType.Asset,
id: 'asset_1',
}) })
expect(authzService.hasPermission).toHaveBeenNthCalledWith(3, { expect(authzService.hasPermission).toHaveBeenCalledWith({
assetId: 'asset_2', user: expect.anything(),
user: { id: 'user1', name: 'Test User' }, permission: Permission.Edit,
permission: 'Edit', type: ResourceType.Asset,
id: 'asset_2',
}) })
expect(mockReparentAssets).toHaveBeenCalledWith({ expect(assetService.reparentAssets).toHaveBeenCalledWith({
newParentId: 'new_parent_id', newParentId: 'new_parent_id',
assetIds: ['asset_1', 'asset_2'], assetIds: ['asset_1', 'asset_2'],
creatorId: 'user1', creatorId: 'user1',
+41 -32
View File
@@ -1,6 +1,6 @@
import { Hono } from 'hono' import { Hono } from 'hono'
import { zValidator } from '@hono/zod-validator' import { zValidator } from '@hono/zod-validator'
import { authzService, Permission } from '@/services/authz/authz' import { authzService, Permission, ResourceType } from '@/services/authz/authz'
import { projectService } from '@/services/project/project' import { projectService } from '@/services/project/project'
import { assetService } from '@/services/asset/asset' import { assetService } from '@/services/asset/asset'
import { reparentAssetsRequestSchema, copyAssetsRequestSchema } from '@/dtos/asset' import { reparentAssetsRequestSchema, copyAssetsRequestSchema } from '@/dtos/asset'
@@ -22,9 +22,10 @@ const route = new Hono<{ Variables: { user: User } }>()
const req = c.req.valid('json') const req = c.req.valid('json')
await authzService.hasPermission({ await authzService.hasPermission({
teamId,
user, user,
permission: Permission.Edit, permission: Permission.Edit,
type: ResourceType.Team,
id: teamId,
}) })
const newProject = await projectService.createProject(user, { const newProject = await projectService.createProject(user, {
@@ -34,28 +35,25 @@ const route = new Hono<{ Variables: { user: User } }>()
return c.json(newProject) return c.json(newProject)
}) })
.put( .put('/projects/:projectId', zValidator('json', updateProjectRequestSchema), async (c) => {
'/teams/:teamId/projects/:projectId', const projectId = c.req.param('projectId')
zValidator('json', updateProjectRequestSchema), const user = c.get('user')
async (c) => { const req = c.req.valid('json')
const projectId = c.req.param('projectId')
const user = c.get('user')
const req = c.req.valid('json')
await authzService.hasPermission({ await authzService.hasPermission({
projectId, user,
user, permission: Permission.Edit,
permission: Permission.Edit, type: ResourceType.Project,
}) id: projectId,
})
const updatedProject = await projectService.updateProject({ const updatedProject = await projectService.updateProject({
projectId, projectId,
...req, ...req,
}) })
return c.json(updatedProject) return c.json(updatedProject)
}, })
)
.get( .get(
'/projects/:projectId/recently-deleted', '/projects/:projectId/recently-deleted',
zValidator('query', recentlyDeletedRequestSchema), zValidator('query', recentlyDeletedRequestSchema),
@@ -65,9 +63,10 @@ const route = new Hono<{ Variables: { user: User } }>()
const req = c.req.valid('query') const req = c.req.valid('query')
await authzService.hasPermission({ await authzService.hasPermission({
projectId,
user, user,
permission: Permission.Read, permission: Permission.Read,
type: ResourceType.Project,
id: projectId,
}) })
const resp = await assetService.listChildren({ const resp = await assetService.listChildren({
@@ -86,9 +85,10 @@ const route = new Hono<{ Variables: { user: User } }>()
const req = c.req.valid('query') const req = c.req.valid('query')
await authzService.hasPermission({ await authzService.hasPermission({
teamId,
user, user,
permission: Permission.Read, permission: Permission.Read,
type: ResourceType.Team,
id: teamId,
}) })
const res = await projectService.listProjects({ const res = await projectService.listProjects({
@@ -112,9 +112,10 @@ const route = new Hono<{ Variables: { user: User } }>()
const user = c.get('user') const user = c.get('user')
await authzService.hasPermission({ await authzService.hasPermission({
projectId,
user, user,
permission: Permission.Read, permission: Permission.Read,
type: ResourceType.Project,
id: projectId,
}) })
const p = await projectService.getProject(projectId) const p = await projectService.getProject(projectId)
@@ -125,9 +126,10 @@ const route = new Hono<{ Variables: { user: User } }>()
const user = c.get('user') const user = c.get('user')
await authzService.hasPermission({ await authzService.hasPermission({
projectId,
user, user,
permission: Permission.Admin, permission: Permission.Admin,
type: ResourceType.Project,
id: projectId,
}) })
await projectService.deleteProject(projectId) await projectService.deleteProject(projectId)
@@ -138,9 +140,10 @@ const route = new Hono<{ Variables: { user: User } }>()
const user = c.get('user') const user = c.get('user')
await authzService.hasPermission({ await authzService.hasPermission({
projectId,
user, user,
permission: Permission.Read, permission: Permission.Read,
type: ResourceType.Project,
id: projectId,
}) })
const teamId = await projectService.getProjectTeam(projectId) const teamId = await projectService.getProjectTeam(projectId)
@@ -152,9 +155,10 @@ const route = new Hono<{ Variables: { user: User } }>()
const { includeAgents } = c.req.valid('query') const { includeAgents } = c.req.valid('query')
await authzService.hasPermission({ await authzService.hasPermission({
projectId,
user, user,
permission: Permission.Read, permission: Permission.Read,
type: ResourceType.Project,
id: projectId,
}) })
const members = await projectService.listProjectMembers({ const members = await projectService.listProjectMembers({
@@ -168,9 +172,10 @@ const route = new Hono<{ Variables: { user: User } }>()
const user = c.get('user') const user = c.get('user')
await authzService.hasPermission({ await authzService.hasPermission({
projectId,
user, user,
permission: Permission.Read, permission: Permission.Read,
type: ResourceType.Project,
id: projectId,
}) })
// STUB: AgentService is not migrated yet. // STUB: AgentService is not migrated yet.
@@ -186,17 +191,19 @@ const route = new Hono<{ Variables: { user: User } }>()
// Check Edit permission on target folder/project // Check Edit permission on target folder/project
await authzService.hasPermission({ await authzService.hasPermission({
assetId: req.newParentId,
user, user,
permission: Permission.Edit, permission: Permission.Edit,
type: ResourceType.Asset,
id: req.newParentId,
}) })
// Check Edit permission on all source assets // Check Edit permission on all source assets
for (const assetId of req.assetIds) { for (const assetId of req.assetIds) {
await authzService.hasPermission({ await authzService.hasPermission({
assetId,
user, user,
permission: Permission.Edit, permission: Permission.Edit,
type: ResourceType.Asset,
id: assetId,
}) })
} }
@@ -214,17 +221,19 @@ const route = new Hono<{ Variables: { user: User } }>()
// Check Edit permission on target folder/project // Check Edit permission on target folder/project
await authzService.hasPermission({ await authzService.hasPermission({
assetId: req.newParentId,
user, user,
permission: Permission.Edit, permission: Permission.Edit,
type: ResourceType.Asset,
id: req.newParentId,
}) })
// Check Read permission on all source assets // Check Read permission on all source assets
for (const assetId of req.assetIds) { for (const assetId of req.assetIds) {
await authzService.hasPermission({ await authzService.hasPermission({
assetId,
user, user,
permission: Permission.Read, permission: Permission.Read,
type: ResourceType.Asset,
id: assetId,
}) })
} }
+91 -55
View File
@@ -1,53 +1,38 @@
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest' import { describe, expect, it, vi, beforeEach } from 'vitest'
import { Hono } from 'hono' import { Hono, type Context, type Next } from 'hono'
import providerRoute from './provider' import providerRoute from './provider'
import { authMiddleware } from '@/api/middleware/auth'
import { providerService } from '@/services/provider/provider' import { providerService } from '@/services/provider/provider'
import { authzService } from '@/services/authz/authz' import { authzService, Permission, ResourceType } from '@/services/authz/authz'
vi.mock('@/services/authz/authz', () => ({
authzService: {
hasPermission: vi.fn(),
},
Permission: {
Read: 'Read',
Edit: 'Edit',
Admin: 'Admin',
},
}))
vi.mock('@/api/middleware/auth', () => ({ vi.mock('@/api/middleware/auth', () => ({
// eslint-disable-next-line @typescript-eslint/no-explicit-any authMiddleware: async (c: Context, next: Next) => {
authMiddleware: async (c: any, next: any) => {
c.set('user', { id: 'user1', name: 'Test User' }) c.set('user', { id: 'user1', name: 'Test User' })
await next() await next()
}, },
})) }))
describe('provider api', () => { vi.mock('@/services/authz/authz')
const app = new Hono().use('*', authMiddleware).route('/', providerRoute) vi.mock('@/services/provider/provider')
let mockListByTeam: any // eslint-disable-line @typescript-eslint/no-explicit-any describe('provider api', () => {
let mockCreate: any // eslint-disable-line @typescript-eslint/no-explicit-any const app = new Hono()
let mockUpdate: any // eslint-disable-line @typescript-eslint/no-explicit-any .use('*', async (c, next) => {
let mockDelete: any // eslint-disable-line @typescript-eslint/no-explicit-any c.set('user', { id: 'user1', name: 'Test User' })
await next()
})
.route('/', providerRoute)
beforeEach(() => { beforeEach(() => {
mockListByTeam = vi.spyOn(providerService, 'listByTeam') vi.restoreAllMocks()
mockCreate = vi.spyOn(providerService, 'create')
mockUpdate = vi.spyOn(providerService, 'update')
mockDelete = vi.spyOn(providerService, 'delete')
// Default to admin permission granted
vi.mocked(authzService.hasPermission).mockResolvedValue(undefined) vi.mocked(authzService.hasPermission).mockResolvedValue(undefined)
}) })
afterEach(() => {
vi.restoreAllMocks()
})
it('GET /teams/:teamId/providers returns providers', async () => { it('GET /teams/:teamId/providers returns providers', async () => {
mockListByTeam.mockResolvedValue([{ id: 'p1', name: 'openai', config: {} }]) // Using any here because mocking complex service return types or Hono context is overly verbose for this test.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
vi.mocked(providerService.listByTeam).mockResolvedValue([
{ id: 'p1', name: 'openai', config: {} },
] as any)
const res = await app.request('/teams/t1/providers') const res = await app.request('/teams/t1/providers')
@@ -55,26 +40,37 @@ describe('provider api', () => {
const data = await res.json() const data = await res.json()
expect(data).toHaveLength(1) expect(data).toHaveLength(1)
expect(data[0].id).toBe('p1') expect(data[0].id).toBe('p1')
expect(authzService.hasPermission).toHaveBeenCalledWith( expect(authzService.hasPermission).toHaveBeenCalledWith({
expect.objectContaining({ user: expect.anything(),
teamId: 't1', permission: Permission.Admin,
permission: 'Admin', type: ResourceType.Team,
}), id: 't1',
) })
}) })
it('GET /teams/:teamId/providers/:id/models returns models', async () => { it('GET /providers/:id/models returns models', async () => {
const mockListModelsByProvider = vi.spyOn(providerService, 'listModelsByProvider') // Using any here because mocking complex service return types or Hono context is overly verbose for this test.
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
mockListModelsByProvider.mockResolvedValue([{ modelId: 'm1', name: 'model1' } as any]) vi.mocked(providerService.getById).mockResolvedValue({ id: 'p1', teamId: 't1' } as any)
// Using any here because mocking complex service return types or Hono context is overly verbose for this test.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
vi.mocked(providerService.listModelsByProvider).mockResolvedValue([
{ modelId: 'm1', name: 'model1' },
] as any)
const res = await app.request('/teams/t1/providers/p1/models') const res = await app.request('/providers/p1/models')
expect(res.status).toBe(200) expect(res.status).toBe(200)
const data = await res.json() const data = await res.json()
expect(data).toHaveLength(1) expect(data).toHaveLength(1)
expect(data[0].modelId).toBe('m1') expect(data[0].modelId).toBe('m1')
expect(mockListModelsByProvider).toHaveBeenCalledWith('t1', 'p1') expect(providerService.listModelsByProvider).toHaveBeenCalledWith('t1', 'p1')
expect(authzService.hasPermission).toHaveBeenCalledWith({
user: expect.anything(),
permission: Permission.Admin,
type: ResourceType.Provider,
id: 'p1',
})
}) })
it('POST /teams/:teamId/providers creates provider', async () => { it('POST /teams/:teamId/providers creates provider', async () => {
@@ -96,7 +92,14 @@ describe('provider api', () => {
}, },
}, },
] ]
mockCreate.mockResolvedValue({ id: 'p1', name: 'openai', config, models }) // Using any here because mocking complex service return types or Hono context is overly verbose for this test.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
vi.mocked(providerService.create).mockResolvedValue({
id: 'p1',
name: 'openai',
config,
models,
} as any)
const res = await app.request('/teams/t1/providers', { const res = await app.request('/teams/t1/providers', {
method: 'POST', method: 'POST',
@@ -107,10 +110,16 @@ describe('provider api', () => {
expect(res.status).toBe(200) expect(res.status).toBe(200)
const data = await res.json() const data = await res.json()
expect(data.name).toBe('openai') expect(data.name).toBe('openai')
expect(mockCreate).toHaveBeenCalledWith('t1', 'openai', config, models) expect(providerService.create).toHaveBeenCalledWith('t1', 'openai', config, models)
expect(authzService.hasPermission).toHaveBeenCalledWith({
user: expect.anything(),
permission: Permission.Admin,
type: ResourceType.Team,
id: 't1',
})
}) })
it('PUT /teams/:teamId/providers/:id updates provider', async () => { it('PUT /providers/:id updates provider', async () => {
const config = { const config = {
baseUrl: 'https://new-url.com', baseUrl: 'https://new-url.com',
api: 'openai-completions', api: 'openai-completions',
@@ -129,9 +138,19 @@ describe('provider api', () => {
}, },
}, },
] ]
mockUpdate.mockResolvedValue({ id: 'p1', name: 'openai', config, models }) // Using any here because mocking complex service return types or Hono context is overly verbose for this test.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
vi.mocked(providerService.getById).mockResolvedValue({ id: 'p1', teamId: 't1' } as any)
// Using any here because mocking complex service return types or Hono context is overly verbose for this test.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
vi.mocked(providerService.update).mockResolvedValue({
id: 'p1',
name: 'openai',
config,
models,
} as any)
const res = await app.request('/teams/t1/providers/p1', { const res = await app.request('/providers/p1', {
method: 'PUT', method: 'PUT',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ config, models }), body: JSON.stringify({ config, models }),
@@ -140,19 +159,36 @@ describe('provider api', () => {
expect(res.status).toBe(200) expect(res.status).toBe(200)
const data = await res.json() const data = await res.json()
expect(data.config.baseUrl).toBe('https://new-url.com') expect(data.config.baseUrl).toBe('https://new-url.com')
expect(mockUpdate).toHaveBeenCalledWith('t1', 'p1', config, models) expect(providerService.update).toHaveBeenCalledWith('t1', 'p1', config, models)
expect(authzService.hasPermission).toHaveBeenCalledWith({
user: expect.anything(),
permission: Permission.Admin,
type: ResourceType.Provider,
id: 'p1',
})
}) })
it('DELETE /teams/:teamId/providers/:id deletes provider', async () => { it('DELETE /providers/:id deletes provider', async () => {
mockDelete.mockResolvedValue({ id: 'p1' }) // Using any here because mocking complex service return types or Hono context is overly verbose for this test.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
vi.mocked(providerService.getById).mockResolvedValue({ id: 'p1', teamId: 't1' } as any)
// Using any here because mocking complex service return types or Hono context is overly verbose for this test.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
vi.mocked(providerService.delete).mockResolvedValue({ id: 'p1' } as any)
const res = await app.request('/teams/t1/providers/p1', { const res = await app.request('/providers/p1', {
method: 'DELETE', method: 'DELETE',
}) })
expect(res.status).toBe(200) expect(res.status).toBe(200)
const data = await res.json() const data = await res.json()
expect(data.success).toBe(true) expect(data.success).toBe(true)
expect(mockDelete).toHaveBeenCalledWith('t1', 'p1') expect(providerService.delete).toHaveBeenCalledWith('t1', 'p1')
expect(authzService.hasPermission).toHaveBeenCalledWith({
user: expect.anything(),
permission: Permission.Admin,
type: ResourceType.Provider,
id: 'p1',
})
}) })
}) })
+35 -28
View File
@@ -1,6 +1,6 @@
import { zValidator } from '@hono/zod-validator' import { zValidator } from '@hono/zod-validator'
import { Hono } from 'hono' import { Hono } from 'hono'
import { authzService, Permission } from '@/services/authz/authz' import { authzService, Permission, ResourceType } from '@/services/authz/authz'
import { providerService } from '@/services/provider/provider' import { providerService } from '@/services/provider/provider'
import { createProviderRequestSchema, updateProviderRequestSchema } from '@/dtos/provider' import { createProviderRequestSchema, updateProviderRequestSchema } from '@/dtos/provider'
import type { Prisma } from '@/generated/prisma/client' import type { Prisma } from '@/generated/prisma/client'
@@ -13,27 +13,31 @@ const route = new Hono<{ Variables: { user: User } }>()
const user = c.get('user') const user = c.get('user')
await authzService.hasPermission({ await authzService.hasPermission({
teamId,
user, user,
permission: Permission.Admin, permission: Permission.Admin,
type: ResourceType.Team,
id: teamId,
}) })
const providers = await providerService.listByTeam(teamId) const providers = await providerService.listByTeam(teamId)
return c.json(providers) return c.json(providers)
}) })
.get('/teams/:teamId/providers/:id/models', async (c) => { .get('/providers/:id/models', async (c) => {
const teamId = c.req.param('teamId')
const id = c.req.param('id') const id = c.req.param('id')
const user = c.get('user') const user = c.get('user')
await authzService.hasPermission({ await authzService.hasPermission({
teamId,
user, user,
permission: Permission.Admin, permission: Permission.Admin,
type: ResourceType.Provider,
id,
}) })
const models = await providerService.listModelsByProvider(teamId, id) const provider = await providerService.getById(id)
if (!provider) throw new Error('Provider not found')
const models = await providerService.listModelsByProvider(provider.teamId, id)
return c.json(models) return c.json(models)
}) })
@@ -43,47 +47,50 @@ const route = new Hono<{ Variables: { user: User } }>()
const { name, config, models } = c.req.valid('json') const { name, config, models } = c.req.valid('json')
await authzService.hasPermission({ await authzService.hasPermission({
teamId,
user, user,
permission: Permission.Admin, permission: Permission.Admin,
type: ResourceType.Team,
id: teamId,
}) })
const provider = await providerService.create(teamId, name, config, models) const provider = await providerService.create(teamId, name, config, models)
return c.json(provider) return c.json(provider)
}) })
.put( .put('/providers/:id', zValidator('json', updateProviderRequestSchema), async (c) => {
'/teams/:teamId/providers/:id', const id = c.req.param('id')
zValidator('json', updateProviderRequestSchema), const user = c.get('user')
async (c) => { const { config, models } = c.req.valid('json')
const teamId = c.req.param('teamId')
const id = c.req.param('id')
const user = c.get('user')
const { config, models } = c.req.valid('json')
await authzService.hasPermission({ await authzService.hasPermission({
teamId, user,
user, permission: Permission.Admin,
permission: Permission.Admin, type: ResourceType.Provider,
}) id,
})
const provider = await providerService.update(teamId, id, config, models) const providerBefore = await providerService.getById(id)
return c.json(provider) if (!providerBefore) throw new Error('Provider not found')
},
)
.delete('/teams/:teamId/providers/:id', async (c) => { const provider = await providerService.update(providerBefore.teamId, id, config, models)
const teamId = c.req.param('teamId') return c.json(provider)
})
.delete('/providers/:id', async (c) => {
const id = c.req.param('id') const id = c.req.param('id')
const user = c.get('user') const user = c.get('user')
await authzService.hasPermission({ await authzService.hasPermission({
teamId,
user, user,
permission: Permission.Admin, permission: Permission.Admin,
type: ResourceType.Provider,
id,
}) })
await providerService.delete(teamId, id) const providerBefore = await providerService.getById(id)
if (!providerBefore) throw new Error('Provider not found')
await providerService.delete(providerBefore.teamId, id)
return c.json({ success: true }) return c.json({ success: true })
}) })
+53 -11
View File
@@ -5,6 +5,7 @@ import publicShareRoute from './public-share'
import { authMiddleware } from '@/api/middleware/auth' import { authMiddleware } from '@/api/middleware/auth'
import { shareService } from '@/services/share/share' import { shareService } from '@/services/share/share'
import { assetService } from '@/services/asset/asset' import { assetService } from '@/services/asset/asset'
import { authzService, Permission, ResourceType } from '@/services/authz/authz'
vi.mock('@/api/middleware/auth', () => ({ vi.mock('@/api/middleware/auth', () => ({
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -20,9 +21,14 @@ vi.mock('@/services/authz/authz', () => ({
hasPermission: vi.fn().mockResolvedValue(undefined), hasPermission: vi.fn().mockResolvedValue(undefined),
}, },
Permission: { Permission: {
Read: 'read', Read: 'Read',
Edit: 'edit', Edit: 'Edit',
Admin: 'admin', Admin: 'Admin',
},
ResourceType: {
Project: 'project',
Share: 'share',
Asset: 'asset',
}, },
})) }))
@@ -34,6 +40,7 @@ describe('Share API', () => {
beforeEach(() => { beforeEach(() => {
vi.restoreAllMocks() vi.restoreAllMocks()
vi.mocked(authzService.hasPermission).mockResolvedValue(undefined)
}) })
// Public Routes // Public Routes
@@ -102,7 +109,7 @@ describe('Share API', () => {
}) })
// Protected Routes // Protected Routes
describe('POST /teams/:teamId/projects/:projectId/shares', () => { describe('POST /projects/:projectId/shares', () => {
test('Success', async () => { test('Success', async () => {
vi.spyOn(shareService, 'createShareLink').mockResolvedValue({ vi.spyOn(shareService, 'createShareLink').mockResolvedValue({
id: 'share1', id: 'share1',
@@ -116,7 +123,7 @@ describe('Share API', () => {
updatedAt: new Date().toISOString(), updatedAt: new Date().toISOString(),
}) })
const res = await app.request('/teams/team1/projects/project1/shares', { const res = await app.request('/projects/project1/shares', {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'My Share' }), body: JSON.stringify({ name: 'My Share' }),
@@ -125,22 +132,36 @@ describe('Share API', () => {
expect(res.status).toBe(200) expect(res.status).toBe(200)
const body = await res.json() const body = await res.json()
expect(body.id).toBe('share1') expect(body.id).toBe('share1')
expect(authzService.hasPermission).toHaveBeenCalledWith(
expect.objectContaining({
type: ResourceType.Project,
id: 'project1',
permission: Permission.Edit,
}),
)
expect(shareService.createShareLink).toHaveBeenCalledWith('project1', { name: 'My Share' }) expect(shareService.createShareLink).toHaveBeenCalledWith('project1', { name: 'My Share' })
}) })
}) })
describe('GET /teams/:teamId/projects/:projectId/shares', () => { describe('GET /projects/:projectId/shares', () => {
test('Success', async () => { test('Success', async () => {
vi.spyOn(shareService, 'listProjectShareLinks').mockResolvedValue({ vi.spyOn(shareService, 'listProjectShareLinks').mockResolvedValue({
data: [], data: [],
pageInfo: { total: 0, cursor: undefined }, pageInfo: { total: 0, cursor: undefined },
}) })
const res = await app.request('/teams/team1/projects/project1/shares', { const res = await app.request('/projects/project1/shares', {
method: 'GET', method: 'GET',
}) })
expect(res.status).toBe(200) expect(res.status).toBe(200)
expect(authzService.hasPermission).toHaveBeenCalledWith(
expect.objectContaining({
type: ResourceType.Project,
id: 'project1',
permission: Permission.Read,
}),
)
expect(shareService.listProjectShareLinks).toHaveBeenCalledWith( expect(shareService.listProjectShareLinks).toHaveBeenCalledWith(
expect.objectContaining({ expect.objectContaining({
projectId: 'project1', projectId: 'project1',
@@ -149,7 +170,7 @@ describe('Share API', () => {
}) })
}) })
describe('GET /teams/:teamId/shares/:shareId', () => { describe('GET /shares/:shareId', () => {
test('Success', async () => { test('Success', async () => {
vi.spyOn(shareService, 'getShareLink').mockResolvedValue({ vi.spyOn(shareService, 'getShareLink').mockResolvedValue({
id: 'share1', id: 'share1',
@@ -163,16 +184,23 @@ describe('Share API', () => {
updatedAt: new Date().toISOString(), updatedAt: new Date().toISOString(),
}) })
const res = await app.request('/teams/team1/shares/share1', { const res = await app.request('/shares/share1', {
method: 'GET', method: 'GET',
}) })
expect(res.status).toBe(200) expect(res.status).toBe(200)
expect(authzService.hasPermission).toHaveBeenCalledWith(
expect.objectContaining({
type: ResourceType.Share,
id: 'share1',
permission: Permission.Read,
}),
)
expect(shareService.getShareLink).toHaveBeenCalledWith('share1') expect(shareService.getShareLink).toHaveBeenCalledWith('share1')
}) })
}) })
describe('POST /teams/:teamId/shares/:shareId/assets', () => { describe('POST /shares/:shareId/assets', () => {
test('Success', async () => { test('Success', async () => {
vi.spyOn(shareService, 'getShareLink').mockResolvedValue({ vi.spyOn(shareService, 'getShareLink').mockResolvedValue({
id: 'share1', id: 'share1',
@@ -187,7 +215,7 @@ describe('Share API', () => {
}) })
vi.spyOn(shareService, 'addAssetToShare').mockResolvedValue(1) vi.spyOn(shareService, 'addAssetToShare').mockResolvedValue(1)
const res = await app.request('/teams/team1/shares/share1/assets', { const res = await app.request('/shares/share1/assets', {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ assetIds: ['asset1'] }), body: JSON.stringify({ assetIds: ['asset1'] }),
@@ -196,6 +224,20 @@ describe('Share API', () => {
expect(res.status).toBe(200) expect(res.status).toBe(200)
const body = await res.json() const body = await res.json()
expect(body.addedCount).toBe(1) expect(body.addedCount).toBe(1)
expect(authzService.hasPermission).toHaveBeenCalledWith(
expect.objectContaining({
type: ResourceType.Share,
id: 'share1',
permission: Permission.Edit,
}),
)
expect(authzService.hasPermission).toHaveBeenCalledWith(
expect.objectContaining({
type: ResourceType.Asset,
id: 'asset1',
permission: Permission.Read,
}),
)
expect(shareService.addAssetToShare).toHaveBeenCalledWith('share1', { assetIds: ['asset1'] }) expect(shareService.addAssetToShare).toHaveBeenCalledWith('share1', { assetIds: ['asset1'] })
}) })
}) })
+50 -55
View File
@@ -1,6 +1,6 @@
import { Hono } from 'hono' import { Hono } from 'hono'
import { zValidator } from '@hono/zod-validator' import { zValidator } from '@hono/zod-validator'
import { authzService, Permission } from '@/services/authz/authz' import { authzService, Permission, ResourceType } from '@/services/authz/authz'
import { shareService } from '@/services/share/share' import { shareService } from '@/services/share/share'
import { import {
createShareLinkRequestSchema, createShareLinkRequestSchema,
@@ -14,7 +14,7 @@ type User = Prisma.UserGetPayload<Record<string, never>>
const route = new Hono<{ Variables: { user: User } }>() const route = new Hono<{ Variables: { user: User } }>()
.post( .post(
'/teams/:teamId/projects/:projectId/shares', '/projects/:projectId/shares',
zValidator('json', createShareLinkRequestSchema), zValidator('json', createShareLinkRequestSchema),
async (c) => { async (c) => {
const projectId = c.req.param('projectId') const projectId = c.req.param('projectId')
@@ -22,9 +22,10 @@ const route = new Hono<{ Variables: { user: User } }>()
const req = c.req.valid('json') const req = c.req.valid('json')
await authzService.hasPermission({ await authzService.hasPermission({
projectId,
user, user,
permission: Permission.Edit, permission: Permission.Edit,
type: ResourceType.Project,
id: projectId,
}) })
const shareLink = await shareService.createShareLink(projectId, req) const shareLink = await shareService.createShareLink(projectId, req)
@@ -32,7 +33,7 @@ const route = new Hono<{ Variables: { user: User } }>()
}, },
) )
.get( .get(
'/teams/:teamId/projects/:projectId/shares', '/projects/:projectId/shares',
zValidator('query', listShareLinksRequestSchema), zValidator('query', listShareLinksRequestSchema),
async (c) => { async (c) => {
const projectId = c.req.param('projectId') const projectId = c.req.param('projectId')
@@ -40,9 +41,10 @@ const route = new Hono<{ Variables: { user: User } }>()
const req = c.req.valid('query') const req = c.req.valid('query')
await authzService.hasPermission({ await authzService.hasPermission({
projectId,
user, user,
permission: Permission.Read, permission: Permission.Read,
type: ResourceType.Project,
id: projectId,
}) })
const res = await shareService.listProjectShareLinks({ const res = await shareService.listProjectShareLinks({
@@ -53,91 +55,84 @@ const route = new Hono<{ Variables: { user: User } }>()
return c.json(res) return c.json(res)
}, },
) )
.get('/teams/:teamId/shares/:shareId', async (c) => { .get('/shares/:shareId', async (c) => {
const shareId = c.req.param('shareId') const shareId = c.req.param('shareId')
const user = c.get('user') const user = c.get('user')
const shareLink = await shareService.getShareLink(shareId)
await authzService.hasPermission({ await authzService.hasPermission({
projectId: shareLink.projectId,
user, user,
permission: Permission.Read, permission: Permission.Read,
type: ResourceType.Share,
id: shareId,
}) })
const shareLink = await shareService.getShareLink(shareId)
return c.json(shareLink) return c.json(shareLink)
}) })
.put( .put('/shares/:shareId', zValidator('json', updateShareLinkRequestSchema), async (c) => {
'/teams/:teamId/shares/:shareId', const shareId = c.req.param('shareId')
zValidator('json', updateShareLinkRequestSchema), const user = c.get('user')
async (c) => { const req = c.req.valid('json')
const shareId = c.req.param('shareId')
const user = c.get('user')
const req = c.req.valid('json')
const shareLink = await shareService.getShareLink(shareId) await authzService.hasPermission({
await authzService.hasPermission({ user,
projectId: shareLink.projectId, permission: Permission.Edit,
user, type: ResourceType.Share,
permission: Permission.Edit, id: shareId,
}) })
const updated = await shareService.updateShareLink(shareId, req) const updated = await shareService.updateShareLink(shareId, req)
return c.json(updated) return c.json(updated)
}, })
) .delete('/shares/:shareId', async (c) => {
.delete('/teams/:teamId/shares/:shareId', async (c) => {
const shareId = c.req.param('shareId') const shareId = c.req.param('shareId')
const user = c.get('user') const user = c.get('user')
const shareLink = await shareService.getShareLink(shareId)
await authzService.hasPermission({ await authzService.hasPermission({
projectId: shareLink.projectId,
user, user,
permission: Permission.Edit, permission: Permission.Edit,
type: ResourceType.Share,
id: shareId,
}) })
await shareService.deleteShareLink(shareId) await shareService.deleteShareLink(shareId)
return c.body(null, 204) return c.body(null, 204)
}) })
.post( .post('/shares/:shareId/assets', zValidator('json', addAssetToShareRequestSchema), async (c) => {
'/teams/:teamId/shares/:shareId/assets', const shareId = c.req.param('shareId')
zValidator('json', addAssetToShareRequestSchema), const user = c.get('user')
async (c) => { const req = c.req.valid('json')
const shareId = c.req.param('shareId')
const user = c.get('user')
const req = c.req.valid('json')
const shareLink = await shareService.getShareLink(shareId) await authzService.hasPermission({
user,
permission: Permission.Edit,
type: ResourceType.Share,
id: shareId,
})
// Also check if user has read permission on the source assets
for (const assetId of req.assetIds) {
await authzService.hasPermission({ await authzService.hasPermission({
projectId: shareLink.projectId,
user, user,
permission: Permission.Edit, permission: Permission.Read,
type: ResourceType.Asset,
id: assetId,
}) })
}
// Also check if user has read permission on the source assets const addedCount = await shareService.addAssetToShare(shareId, req)
for (const assetId of req.assetIds) { return c.json({ addedCount })
await authzService.hasPermission({ })
assetId, .delete('/shares/:shareId/assets/:assetId', async (c) => {
user,
permission: Permission.Read,
})
}
const addedCount = await shareService.addAssetToShare(shareId, req)
return c.json({ addedCount })
},
)
.delete('/teams/:teamId/shares/:shareId/assets/:assetId', async (c) => {
const shareId = c.req.param('shareId') const shareId = c.req.param('shareId')
const assetId = c.req.param('assetId') // symlink asset id const assetId = c.req.param('assetId') // symlink asset id
const user = c.get('user') const user = c.get('user')
const shareLink = await shareService.getShareLink(shareId)
await authzService.hasPermission({ await authzService.hasPermission({
projectId: shareLink.projectId,
user, user,
permission: Permission.Edit, permission: Permission.Edit,
type: ResourceType.Share,
id: shareId,
}) })
await shareService.removeAssetFromShare(shareId, assetId) await shareService.removeAssetFromShare(shareId, assetId)
+41 -11
View File
@@ -3,7 +3,7 @@ import { Hono } from 'hono'
import skillRoute from './skill' import skillRoute from './skill'
import { skillService } from '@/services/skill/skill' import { skillService } from '@/services/skill/skill'
import { authMiddleware } from '@/api/middleware/auth' import { authMiddleware } from '@/api/middleware/auth'
import { authzService } from '@/services/authz/authz' import { authzService, ResourceType, Permission } from '@/services/authz/authz'
vi.mock('@/api/middleware/auth', () => ({ vi.mock('@/api/middleware/auth', () => ({
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -16,12 +16,16 @@ vi.mock('@/api/middleware/auth', () => ({
vi.mock('@/services/authz/authz', () => ({ vi.mock('@/services/authz/authz', () => ({
authzService: { authzService: {
hasPermission: vi.fn(), hasPermission: vi.fn().mockResolvedValue(undefined),
}, },
Permission: { Permission: {
Read: 'read', Read: 'Read',
Edit: 'edit', Edit: 'Edit',
Admin: 'admin', Admin: 'Admin',
},
ResourceType: {
Team: 'team',
Skill: 'skill',
}, },
})) }))
@@ -30,6 +34,7 @@ describe('Skill API', () => {
beforeEach(() => { beforeEach(() => {
vi.restoreAllMocks() vi.restoreAllMocks()
vi.mocked(authzService.hasPermission).mockResolvedValue(undefined)
}) })
describe('GET /teams/:teamId/skills', () => { describe('GET /teams/:teamId/skills', () => {
@@ -56,7 +61,11 @@ describe('Skill API', () => {
expect(res.status).toBe(200) expect(res.status).toBe(200)
expect(await res.json()).toEqual({ skills: mockSkills }) expect(await res.json()).toEqual({ skills: mockSkills })
expect(authzService.hasPermission).toHaveBeenCalledWith( expect(authzService.hasPermission).toHaveBeenCalledWith(
expect.objectContaining({ permission: 'admin' }), expect.objectContaining({
type: ResourceType.Team,
id: 'team1',
permission: Permission.Admin,
}),
) )
}) })
}) })
@@ -83,6 +92,13 @@ describe('Skill API', () => {
expect(res.status).toBe(200) expect(res.status).toBe(200)
expect(await res.json()).toEqual(mockSkill) expect(await res.json()).toEqual(mockSkill)
expect(authzService.hasPermission).toHaveBeenCalledWith(
expect.objectContaining({
type: ResourceType.Team,
id: 'team1',
permission: Permission.Admin,
}),
)
expect(skillService.upsertSkill).toHaveBeenCalledWith('team1', { assetId: 'asset1' }) expect(skillService.upsertSkill).toHaveBeenCalledWith('team1', { assetId: 'asset1' })
}) })
@@ -113,7 +129,7 @@ describe('Skill API', () => {
}) })
test('Forbidden without Admin permission', async () => { test('Forbidden without Admin permission', async () => {
vi.spyOn(authzService, 'hasPermission').mockRejectedValueOnce(new Error('Forbidden')) vi.mocked(authzService.hasPermission).mockRejectedValueOnce(new Error('Forbidden'))
const res = await app.request('/teams/team1/skills', { const res = await app.request('/teams/team1/skills', {
method: 'POST', method: 'POST',
@@ -125,21 +141,28 @@ describe('Skill API', () => {
}) })
}) })
describe('DELETE /teams/:teamId/skills/:id', () => { describe('DELETE /skills/:id', () => {
test('Success', async () => { test('Success', async () => {
vi.spyOn(skillService, 'deleteSkill').mockResolvedValue(undefined) vi.spyOn(skillService, 'deleteSkill').mockResolvedValue(undefined)
const res = await app.request('/teams/team1/skills/skill1', { const res = await app.request('/skills/skill1', {
method: 'DELETE', method: 'DELETE',
headers: { Authorization: 'Bearer test' }, headers: { Authorization: 'Bearer test' },
}) })
expect(res.status).toBe(204) expect(res.status).toBe(204)
expect(authzService.hasPermission).toHaveBeenCalledWith(
expect.objectContaining({
type: ResourceType.Skill,
id: 'skill1',
permission: Permission.Admin,
}),
)
expect(skillService.deleteSkill).toHaveBeenCalledWith('skill1') expect(skillService.deleteSkill).toHaveBeenCalledWith('skill1')
}) })
}) })
describe('PATCH /teams/:teamId/skills/:id/config', () => { describe('PATCH /skills/:id/config', () => {
test('Success', async () => { test('Success', async () => {
const mockConfig = { const mockConfig = {
environmentVariables: [{ name: 'TEST_VAR', default: 'test_val' }], environmentVariables: [{ name: 'TEST_VAR', default: 'test_val' }],
@@ -156,7 +179,7 @@ describe('Skill API', () => {
} }
vi.spyOn(skillService, 'updateSkillConfig').mockResolvedValue(mockSkill) vi.spyOn(skillService, 'updateSkillConfig').mockResolvedValue(mockSkill)
const res = await app.request('/teams/team1/skills/skill1/config', { const res = await app.request('/skills/skill1/config', {
method: 'PATCH', method: 'PATCH',
headers: { 'Content-Type': 'application/json', Authorization: 'Bearer test' }, headers: { 'Content-Type': 'application/json', Authorization: 'Bearer test' },
body: JSON.stringify({ config: mockConfig }), body: JSON.stringify({ config: mockConfig }),
@@ -164,6 +187,13 @@ describe('Skill API', () => {
expect(res.status).toBe(200) expect(res.status).toBe(200)
expect(await res.json()).toEqual(mockSkill) expect(await res.json()).toEqual(mockSkill)
expect(authzService.hasPermission).toHaveBeenCalledWith(
expect.objectContaining({
type: ResourceType.Skill,
id: 'skill1',
permission: Permission.Admin,
}),
)
expect(skillService.updateSkillConfig).toHaveBeenCalledWith('skill1', mockConfig) expect(skillService.updateSkillConfig).toHaveBeenCalledWith('skill1', mockConfig)
}) })
}) })
+21 -23
View File
@@ -1,6 +1,6 @@
import { Hono } from 'hono' import { Hono } from 'hono'
import { zValidator } from '@hono/zod-validator' import { zValidator } from '@hono/zod-validator'
import { authzService, Permission } from '@/services/authz/authz' import { authzService, Permission, ResourceType } from '@/services/authz/authz'
import { skillService } from '@/services/skill/skill' import { skillService } from '@/services/skill/skill'
import { upsertSkillRequestSchema, updateSkillConfigRequestSchema } from '@/dtos/skill' import { upsertSkillRequestSchema, updateSkillConfigRequestSchema } from '@/dtos/skill'
import type { Prisma } from '@/generated/prisma/client' import type { Prisma } from '@/generated/prisma/client'
@@ -13,9 +13,10 @@ const route = new Hono<{ Variables: { user: User } }>()
const teamId = c.req.param('teamId') const teamId = c.req.param('teamId')
await authzService.hasPermission({ await authzService.hasPermission({
teamId,
user, user,
permission: Permission.Admin, permission: Permission.Admin,
type: ResourceType.Team,
id: teamId,
}) })
const skills = await skillService.listSkills(teamId) const skills = await skillService.listSkills(teamId)
@@ -27,9 +28,10 @@ const route = new Hono<{ Variables: { user: User } }>()
const req = c.req.valid('json') const req = c.req.valid('json')
await authzService.hasPermission({ await authzService.hasPermission({
teamId,
user, user,
permission: Permission.Admin, permission: Permission.Admin,
type: ResourceType.Team,
id: teamId,
}) })
try { try {
@@ -42,38 +44,34 @@ const route = new Hono<{ Variables: { user: User } }>()
throw err throw err
} }
}) })
.delete('/teams/:teamId/skills/:id', async (c) => { .delete('/skills/:id', async (c) => {
const user = c.get('user') const user = c.get('user')
const teamId = c.req.param('teamId')
const id = c.req.param('id') const id = c.req.param('id')
await authzService.hasPermission({ await authzService.hasPermission({
teamId,
user, user,
permission: Permission.Admin, permission: Permission.Admin,
type: ResourceType.Skill,
id,
}) })
await skillService.deleteSkill(id) await skillService.deleteSkill(id)
return new Response(null, { status: 204 }) return new Response(null, { status: 204 })
}) })
.patch( .patch('/skills/:id/config', zValidator('json', updateSkillConfigRequestSchema), async (c) => {
'/teams/:teamId/skills/:id/config', const user = c.get('user')
zValidator('json', updateSkillConfigRequestSchema), const id = c.req.param('id')
async (c) => { const req = c.req.valid('json')
const user = c.get('user')
const teamId = c.req.param('teamId')
const id = c.req.param('id')
const req = c.req.valid('json')
await authzService.hasPermission({ await authzService.hasPermission({
teamId, user,
user, permission: Permission.Admin,
permission: Permission.Admin, type: ResourceType.Skill,
}) id,
})
const skill = await skillService.updateSkillConfig(id, req.config) const skill = await skillService.updateSkillConfig(id, req.config)
return c.json(skill) return c.json(skill)
}, })
)
export default route export default route
+62 -1
View File
@@ -5,16 +5,20 @@ import { authMiddleware } from '@/api/middleware/auth'
import { teamService } from '@/services/team/team' import { teamService } from '@/services/team/team'
import { userMetadataService } from '@/services/user-metadata/user-metadata' import { userMetadataService } from '@/services/user-metadata/user-metadata'
import { notificationService } from '@/services/notification/notification' import { notificationService } from '@/services/notification/notification'
import { authzService, ResourceType, Permission } from '@/services/authz/authz'
vi.mock('@/services/authz/authz', () => ({ vi.mock('@/services/authz/authz', () => ({
authzService: { authzService: {
hasPermission: vi.fn(), hasPermission: vi.fn().mockResolvedValue(undefined),
}, },
Permission: { Permission: {
Read: 'Read', Read: 'Read',
Edit: 'Edit', Edit: 'Edit',
Admin: 'Admin', Admin: 'Admin',
}, },
ResourceType: {
Team: 'team',
},
})) }))
vi.mock('@/api/middleware/auth', () => ({ vi.mock('@/api/middleware/auth', () => ({
@@ -53,6 +57,7 @@ describe('team api', () => {
mockCreateNotification = vi.spyOn(notificationService, 'create').mockResolvedValue() mockCreateNotification = vi.spyOn(notificationService, 'create').mockResolvedValue()
mockGetSandboxSettings = vi.spyOn(teamService, 'getSandboxSettings') mockGetSandboxSettings = vi.spyOn(teamService, 'getSandboxSettings')
mockUpdateSandboxSettings = vi.spyOn(teamService, 'updateSandboxSettings') mockUpdateSandboxSettings = vi.spyOn(teamService, 'updateSandboxSettings')
vi.mocked(authzService.hasPermission).mockResolvedValue(undefined)
}) })
afterEach(() => { afterEach(() => {
@@ -118,6 +123,13 @@ describe('team api', () => {
expect(res.status).toBe(200) expect(res.status).toBe(200)
const data = await res.json() const data = await res.json()
expect(data.role).toBe('owner') expect(data.role).toBe('owner')
expect(authzService.hasPermission).toHaveBeenCalledWith(
expect.objectContaining({
type: ResourceType.Team,
id: 't1',
permission: Permission.Read,
}),
)
expect(mockGetMe).toHaveBeenCalledWith({ teamId: 't1', user: expect.any(Object) }) expect(mockGetMe).toHaveBeenCalledWith({ teamId: 't1', user: expect.any(Object) })
}) })
@@ -129,6 +141,13 @@ describe('team api', () => {
expect(res.status).toBe(200) expect(res.status).toBe(200)
const data = await res.json() const data = await res.json()
expect(data).toHaveLength(1) expect(data).toHaveLength(1)
expect(authzService.hasPermission).toHaveBeenCalledWith(
expect.objectContaining({
type: ResourceType.Team,
id: 't1',
permission: Permission.Read,
}),
)
expect(mockGetTeamMembers).toHaveBeenCalledWith({ teamId: 't1', includeAgents: false }) expect(mockGetTeamMembers).toHaveBeenCalledWith({ teamId: 't1', includeAgents: false })
}) })
@@ -140,6 +159,13 @@ describe('team api', () => {
expect(res.status).toBe(200) expect(res.status).toBe(200)
const data = await res.json() const data = await res.json()
expect(data.someKey).toBe('some_value') expect(data.someKey).toBe('some_value')
expect(authzService.hasPermission).toHaveBeenCalledWith(
expect.objectContaining({
type: ResourceType.Team,
id: 't1',
permission: Permission.Read,
}),
)
expect(mockGetSettings).toHaveBeenCalledWith('t1') expect(mockGetSettings).toHaveBeenCalledWith('t1')
}) })
@@ -155,6 +181,13 @@ describe('team api', () => {
expect(res.status).toBe(200) expect(res.status).toBe(200)
const data = await res.json() const data = await res.json()
expect(data.someKey).toBe('new_value') expect(data.someKey).toBe('new_value')
expect(authzService.hasPermission).toHaveBeenCalledWith(
expect.objectContaining({
type: ResourceType.Team,
id: 't1',
permission: Permission.Admin,
}),
)
expect(mockUpdateSettings).toHaveBeenCalledWith('t1', 'someKey', 'new_value') expect(mockUpdateSettings).toHaveBeenCalledWith('t1', 'someKey', 'new_value')
}) })
@@ -170,6 +203,13 @@ describe('team api', () => {
const data = await res.json() const data = await res.json()
expect(data).toHaveLength(2) expect(data).toHaveLength(2)
expect(data[0].key).toBe('key1') expect(data[0].key).toBe('key1')
expect(authzService.hasPermission).toHaveBeenCalledWith(
expect.objectContaining({
type: ResourceType.Team,
id: 't1',
permission: Permission.Read,
}),
)
expect(mockListUserMetadata).toHaveBeenCalledWith('user1', 't1') expect(mockListUserMetadata).toHaveBeenCalledWith('user1', 't1')
}) })
@@ -186,6 +226,13 @@ describe('team api', () => {
const data = await res.json() const data = await res.json()
expect(data.key).toBe('key1') expect(data.key).toBe('key1')
expect(data.value).toBe('value1') expect(data.value).toBe('value1')
expect(authzService.hasPermission).toHaveBeenCalledWith(
expect.objectContaining({
type: ResourceType.Team,
id: 't1',
permission: Permission.Read,
}),
)
expect(mockUpsertUserMetadata).toHaveBeenCalledWith('user1', 't1', 'key1', 'value1') expect(mockUpsertUserMetadata).toHaveBeenCalledWith('user1', 't1', 'key1', 'value1')
}) })
@@ -197,6 +244,13 @@ describe('team api', () => {
expect(res.status).toBe(200) expect(res.status).toBe(200)
const data = await res.json() const data = await res.json()
expect(data.allowedDomains).toEqual(['example.com']) expect(data.allowedDomains).toEqual(['example.com'])
expect(authzService.hasPermission).toHaveBeenCalledWith(
expect.objectContaining({
type: ResourceType.Team,
id: 't1',
permission: Permission.Read,
}),
)
expect(mockGetSandboxSettings).toHaveBeenCalledWith('t1') expect(mockGetSandboxSettings).toHaveBeenCalledWith('t1')
}) })
@@ -212,6 +266,13 @@ describe('team api', () => {
expect(res.status).toBe(200) expect(res.status).toBe(200)
const data = await res.json() const data = await res.json()
expect(data.allowedDomains).toEqual(['new.com']) expect(data.allowedDomains).toEqual(['new.com'])
expect(authzService.hasPermission).toHaveBeenCalledWith(
expect.objectContaining({
type: ResourceType.Team,
id: 't1',
permission: Permission.Admin,
}),
)
expect(mockUpdateSandboxSettings).toHaveBeenCalledWith('t1', { allowedDomains: ['new.com'] }) expect(mockUpdateSandboxSettings).toHaveBeenCalledWith('t1', { allowedDomains: ['new.com'] })
}) })
}) })
+17 -9
View File
@@ -1,6 +1,6 @@
import { Hono } from 'hono' import { Hono } from 'hono'
import { zValidator } from '@hono/zod-validator' import { zValidator } from '@hono/zod-validator'
import { authzService, Permission } from '@/services/authz/authz' import { authzService, Permission, ResourceType } from '@/services/authz/authz'
import { teamService } from '@/services/team/team' import { teamService } from '@/services/team/team'
import { userMetadataService } from '@/services/user-metadata/user-metadata' import { userMetadataService } from '@/services/user-metadata/user-metadata'
import { notificationService } from '@/services/notification/notification' import { notificationService } from '@/services/notification/notification'
@@ -64,9 +64,10 @@ const route = new Hono<{ Variables: { user: User } }>()
const teamId = c.req.param('teamId') const teamId = c.req.param('teamId')
await authzService.hasPermission({ await authzService.hasPermission({
teamId,
user, user,
permission: Permission.Read, permission: Permission.Read,
type: ResourceType.Team,
id: teamId,
}) })
const me = await teamService.getMe({ const me = await teamService.getMe({
@@ -82,9 +83,10 @@ const route = new Hono<{ Variables: { user: User } }>()
const { includeAgents } = c.req.valid('query') const { includeAgents } = c.req.valid('query')
await authzService.hasPermission({ await authzService.hasPermission({
teamId,
user, user,
permission: Permission.Read, permission: Permission.Read,
type: ResourceType.Team,
id: teamId,
}) })
const members = await teamService.getTeamMembers({ const members = await teamService.getTeamMembers({
@@ -99,9 +101,10 @@ const route = new Hono<{ Variables: { user: User } }>()
const teamId = c.req.param('teamId') const teamId = c.req.param('teamId')
await authzService.hasPermission({ await authzService.hasPermission({
teamId,
user, user,
permission: Permission.Read, permission: Permission.Read,
type: ResourceType.Team,
id: teamId,
}) })
const settings = await teamService.getSettings(teamId) const settings = await teamService.getSettings(teamId)
@@ -116,9 +119,10 @@ const route = new Hono<{ Variables: { user: User } }>()
const req = c.req.valid('json') const req = c.req.valid('json')
await authzService.hasPermission({ await authzService.hasPermission({
teamId,
user, user,
permission: Permission.Admin, permission: Permission.Admin,
type: ResourceType.Team,
id: teamId,
}) })
const settings = await teamService.updateSettings(teamId, req.key, req.value) const settings = await teamService.updateSettings(teamId, req.key, req.value)
@@ -130,9 +134,10 @@ const route = new Hono<{ Variables: { user: User } }>()
const teamId = c.req.param('teamId') const teamId = c.req.param('teamId')
await authzService.hasPermission({ await authzService.hasPermission({
teamId,
user, user,
permission: Permission.Read, permission: Permission.Read,
type: ResourceType.Team,
id: teamId,
}) })
const sandbox = await teamService.getSandboxSettings(teamId) const sandbox = await teamService.getSandboxSettings(teamId)
@@ -147,9 +152,10 @@ const route = new Hono<{ Variables: { user: User } }>()
const req = c.req.valid('json') const req = c.req.valid('json')
await authzService.hasPermission({ await authzService.hasPermission({
teamId,
user, user,
permission: Permission.Admin, permission: Permission.Admin,
type: ResourceType.Team,
id: teamId,
}) })
const sandbox = await teamService.updateSandboxSettings(teamId, req) const sandbox = await teamService.updateSandboxSettings(teamId, req)
@@ -161,9 +167,10 @@ const route = new Hono<{ Variables: { user: User } }>()
const teamId = c.req.param('teamId') const teamId = c.req.param('teamId')
await authzService.hasPermission({ await authzService.hasPermission({
teamId,
user, user,
permission: Permission.Read, permission: Permission.Read,
type: ResourceType.Team,
id: teamId,
}) })
const metadata = await userMetadataService.listMetadata(user.id, teamId) const metadata = await userMetadataService.listMetadata(user.id, teamId)
@@ -179,9 +186,10 @@ const route = new Hono<{ Variables: { user: User } }>()
const req = c.req.valid('json') const req = c.req.valid('json')
await authzService.hasPermission({ await authzService.hasPermission({
teamId,
user, user,
permission: Permission.Read, permission: Permission.Read,
type: ResourceType.Team,
id: teamId,
}) })
const metadata = await userMetadataService.upsertMetadata(user.id, teamId, key, req.value) const metadata = await userMetadataService.upsertMetadata(user.id, teamId, key, req.value)
+28 -1
View File
@@ -5,6 +5,7 @@ import { authMiddleware } from '@/api/middleware/auth'
import { uploadService } from '@/services/upload/upload' import { uploadService } from '@/services/upload/upload'
import type { CreateUploadTaskResponse, TaskInfo } from '@/dtos/upload' import type { CreateUploadTaskResponse, TaskInfo } from '@/dtos/upload'
import type { PaginatedData } from '@/services/pagination' import type { PaginatedData } from '@/services/pagination'
import { authzService, ResourceType, Permission } from '@/services/authz/authz'
vi.mock('@/api/middleware/auth', () => ({ vi.mock('@/api/middleware/auth', () => ({
// We use any here because mocking Hono context and middleware // We use any here because mocking Hono context and middleware
@@ -19,13 +20,17 @@ vi.mock('@/api/middleware/auth', () => ({
vi.mock('@/services/authz/authz', () => ({ vi.mock('@/services/authz/authz', () => ({
authzService: { authzService: {
hasPermission: vi.fn(), hasPermission: vi.fn().mockResolvedValue(undefined),
}, },
Permission: { Permission: {
Read: 'Read', Read: 'Read',
Edit: 'Edit', Edit: 'Edit',
Admin: 'Admin', Admin: 'Admin',
}, },
ResourceType: {
Team: 'team',
Asset: 'asset',
},
})) }))
vi.mock('@/services/notification/notification', () => ({ vi.mock('@/services/notification/notification', () => ({
@@ -39,6 +44,7 @@ describe('Upload API', () => {
beforeEach(() => { beforeEach(() => {
vi.restoreAllMocks() vi.restoreAllMocks()
vi.mocked(authzService.hasPermission).mockResolvedValue(undefined)
}) })
it('GET /teams/:teamId/upload/tasks', async () => { it('GET /teams/:teamId/upload/tasks', async () => {
@@ -53,6 +59,13 @@ describe('Upload API', () => {
}) })
expect(res.status).toBe(200) expect(res.status).toBe(200)
expect(authzService.hasPermission).toHaveBeenCalledWith(
expect.objectContaining({
type: ResourceType.Team,
id: 'team1',
permission: Permission.Read,
}),
)
expect(uploadService.listUploadTasks).toHaveBeenCalled() expect(uploadService.listUploadTasks).toHaveBeenCalled()
}) })
@@ -73,6 +86,13 @@ describe('Upload API', () => {
}) })
expect(res.status).toBe(200) expect(res.status).toBe(200)
expect(authzService.hasPermission).toHaveBeenCalledWith(
expect.objectContaining({
type: ResourceType.Asset,
id: 'parent1',
permission: Permission.Edit,
}),
)
expect(uploadService.createUploadTask).toHaveBeenCalled() expect(uploadService.createUploadTask).toHaveBeenCalled()
}) })
@@ -88,6 +108,13 @@ describe('Upload API', () => {
}) })
expect(res.status).toBe(200) expect(res.status).toBe(200)
expect(authzService.hasPermission).toHaveBeenCalledWith(
expect.objectContaining({
type: ResourceType.Team,
id: 'team1',
permission: Permission.Edit,
}),
)
expect(uploadService.confirmFileUpload).toHaveBeenCalledWith('user1', 'task1', { expect(uploadService.confirmFileUpload).toHaveBeenCalledWith('user1', 'task1', {
fileId: 'file1', fileId: 'file1',
}) })
+18 -4
View File
@@ -7,7 +7,7 @@ import {
localUploadQuerySchema, localUploadQuerySchema,
} from '@/dtos/upload' } from '@/dtos/upload'
import { paginationParamsSchema } from '@/dtos/pagination' import { paginationParamsSchema } from '@/dtos/pagination'
import { authzService, Permission } from '@/services/authz/authz' import { authzService, Permission, ResourceType } from '@/services/authz/authz'
import { notificationService } from '@/services/notification/notification' import { notificationService } from '@/services/notification/notification'
import { NotificationType } from '@/generated/prisma/client' import { NotificationType } from '@/generated/prisma/client'
import { s3Service, verifyLocalUrlSignature } from '@/services/s3/s3' import { s3Service, verifyLocalUrlSignature } from '@/services/s3/s3'
@@ -48,9 +48,17 @@ const route = new Hono<{ Variables: { user: User } }>()
return c.json({ success: true }) return c.json({ success: true })
}) })
.get('/teams/:teamId/upload/tasks', zValidator('query', paginationParamsSchema), async (c) => { .get('/teams/:teamId/upload/tasks', zValidator('query', paginationParamsSchema), async (c) => {
const teamId = c.req.param('teamId')
const user = c.get('user') const user = c.get('user')
const params = c.req.valid('query') const params = c.req.valid('query')
await authzService.hasPermission({
user,
permission: Permission.Read,
type: ResourceType.Team,
id: teamId,
})
const tasks = await uploadService.listUploadTasks(user.id, params) const tasks = await uploadService.listUploadTasks(user.id, params)
return c.json(tasks) return c.json(tasks)
}) })
@@ -58,15 +66,14 @@ const route = new Hono<{ Variables: { user: User } }>()
'/teams/:teamId/upload/tasks', '/teams/:teamId/upload/tasks',
zValidator('json', createUploadTaskRequestSchema), zValidator('json', createUploadTaskRequestSchema),
async (c) => { async (c) => {
const teamId = c.req.param('teamId')
const user = c.get('user') const user = c.get('user')
const req = c.req.valid('json') const req = c.req.valid('json')
await authzService.hasPermission({ await authzService.hasPermission({
teamId,
assetId: req.parentId,
user, user,
permission: Permission.Edit, permission: Permission.Edit,
type: ResourceType.Asset,
id: req.parentId,
}) })
const resp = await uploadService.createUploadTask(user.id, req) const resp = await uploadService.createUploadTask(user.id, req)
@@ -82,6 +89,13 @@ const route = new Hono<{ Variables: { user: User } }>()
const user = c.get('user') const user = c.get('user')
const req = c.req.valid('json') const req = c.req.valid('json')
await authzService.hasPermission({
user,
permission: Permission.Edit,
type: ResourceType.Team,
id: teamId,
})
await uploadService.confirmFileUpload(user.id, taskId, req) await uploadService.confirmFileUpload(user.id, taskId, req)
if (!req.errorMessage) { if (!req.errorMessage) {
+32 -31
View File
@@ -4,16 +4,21 @@ import versionStackRoute from './versionStack'
import { authMiddleware } from '@/api/middleware/auth' import { authMiddleware } from '@/api/middleware/auth'
import { versionStackService } from '@/services/versionStack/versionStack' import { versionStackService } from '@/services/versionStack/versionStack'
import { assetService } from '@/services/asset/asset' import { assetService } from '@/services/asset/asset'
import { authzService, ResourceType, Permission } from '@/services/authz/authz'
vi.mock('@/services/authz/authz', () => ({ vi.mock('@/services/authz/authz', () => ({
authzService: { authzService: {
hasPermission: vi.fn(), hasPermission: vi.fn().mockResolvedValue(undefined),
}, },
Permission: { Permission: {
Read: 'Read', Read: 'Read',
Edit: 'Edit', Edit: 'Edit',
Admin: 'Admin', Admin: 'Admin',
}, },
ResourceType: {
Project: 'project',
Asset: 'asset',
},
})) }))
vi.mock('@/api/middleware/auth', () => ({ vi.mock('@/api/middleware/auth', () => ({
@@ -35,6 +40,7 @@ describe('versionStack api', () => {
mockChangeStackFileVersion = vi.spyOn(versionStackService, 'changeStackFileVersion') mockChangeStackFileVersion = vi.spyOn(versionStackService, 'changeStackFileVersion')
mockGetAsset = vi.spyOn(assetService, 'getAsset') mockGetAsset = vi.spyOn(assetService, 'getAsset')
mockGetStackVersions = vi.spyOn(assetService, 'getStackVersions') mockGetStackVersions = vi.spyOn(assetService, 'getStackVersions')
vi.mocked(authzService.hasPermission).mockResolvedValue(undefined)
}) })
afterEach(() => { afterEach(() => {
@@ -61,6 +67,13 @@ describe('versionStack api', () => {
const data = await res.json() const data = await res.json()
expect(data).toEqual(mockAssetInfo) expect(data).toEqual(mockAssetInfo)
expect(authzService.hasPermission).toHaveBeenCalledWith(
expect.objectContaining({
type: ResourceType.Project,
id: 'p1',
permission: Permission.Edit,
}),
)
expect(mockCreateVersionStack).toHaveBeenCalledWith({ expect(mockCreateVersionStack).toHaveBeenCalledWith({
projectId: 'p1', projectId: 'p1',
creatorId: 'user1', creatorId: 'user1',
@@ -68,28 +81,15 @@ describe('versionStack api', () => {
}) })
expect(mockGetAsset).toHaveBeenCalledWith({ assetId: 'stack1' }) expect(mockGetAsset).toHaveBeenCalledWith({ assetId: 'stack1' })
}) })
it('should fail with validation error for invalid body', async () => {
const app = new Hono().use('*', authMiddleware).route('/', versionStackRoute)
const res = await app.request('/projects/p1/version_stacks', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ wrongField: [] }),
})
expect(res.status).toBe(400)
expect(mockCreateVersionStack).not.toHaveBeenCalled()
})
}) })
describe('POST /projects/:projectID/version_stacks/:stackID/order', () => { describe('POST /version_stacks/:stackID/order', () => {
it('should change order and return 200', async () => { it('should change order and return 200', async () => {
mockChangeStackFileVersion.mockResolvedValue() mockChangeStackFileVersion.mockResolvedValue()
const app = new Hono().use('*', authMiddleware).route('/', versionStackRoute) const app = new Hono().use('*', authMiddleware).route('/', versionStackRoute)
const res = await app.request('/projects/p1/version_stacks/stack1/order', { const res = await app.request('/version_stacks/stack1/order', {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ fileId: 'f1', beforeId: 'f2' }), body: JSON.stringify({ fileId: 'f1', beforeId: 'f2' }),
@@ -97,28 +97,22 @@ describe('versionStack api', () => {
expect(res.status).toBe(200) expect(res.status).toBe(200)
expect(authzService.hasPermission).toHaveBeenCalledWith(
expect.objectContaining({
type: ResourceType.Asset,
id: 'stack1',
permission: Permission.Edit,
}),
)
expect(mockChangeStackFileVersion).toHaveBeenCalledWith({ expect(mockChangeStackFileVersion).toHaveBeenCalledWith({
stackId: 'stack1', stackId: 'stack1',
fileId: 'f1', fileId: 'f1',
beforeId: 'f2', beforeId: 'f2',
}) })
}) })
it('should fail with validation error for invalid body', async () => {
const app = new Hono().use('*', authMiddleware).route('/', versionStackRoute)
const res = await app.request('/projects/p1/version_stacks/stack1/order', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ fileId: 'f1' }), // missing beforeId
})
expect(res.status).toBe(400)
expect(mockChangeStackFileVersion).not.toHaveBeenCalled()
})
}) })
describe('GET /projects/:projectID/version_stacks/:stackID/versions', () => { describe('GET /version_stacks/:stackID/versions', () => {
it('should return stack versions', async () => { it('should return stack versions', async () => {
const mockVersions = [ const mockVersions = [
{ {
@@ -134,7 +128,7 @@ describe('versionStack api', () => {
const app = new Hono().use('*', authMiddleware).route('/', versionStackRoute) const app = new Hono().use('*', authMiddleware).route('/', versionStackRoute)
const res = await app.request('/projects/p1/version_stacks/stack1/versions', { const res = await app.request('/version_stacks/stack1/versions', {
method: 'GET', method: 'GET',
}) })
@@ -142,6 +136,13 @@ describe('versionStack api', () => {
const data = await res.json() const data = await res.json()
expect(data).toEqual(mockVersions) expect(data).toEqual(mockVersions)
expect(authzService.hasPermission).toHaveBeenCalledWith(
expect.objectContaining({
type: ResourceType.Asset,
id: 'stack1',
permission: Permission.Read,
}),
)
expect(mockGetStackVersions).toHaveBeenCalledWith('stack1') expect(mockGetStackVersions).toHaveBeenCalledWith('stack1')
}) })
}) })
+9 -8
View File
@@ -2,7 +2,7 @@ import { Hono } from 'hono'
import { zValidator } from '@hono/zod-validator' import { zValidator } from '@hono/zod-validator'
import { versionStackService } from '@/services/versionStack/versionStack' import { versionStackService } from '@/services/versionStack/versionStack'
import { assetService } from '@/services/asset/asset' import { assetService } from '@/services/asset/asset'
import { authzService, Permission } from '@/services/authz/authz' import { authzService, Permission, ResourceType } from '@/services/authz/authz'
import { import {
createVersionStackRequestSchema, createVersionStackRequestSchema,
changeStackFileVersionRequestSchema, changeStackFileVersionRequestSchema,
@@ -23,9 +23,10 @@ const route = app
const req = c.req.valid('json') const req = c.req.valid('json')
await authzService.hasPermission({ await authzService.hasPermission({
projectId,
user, user,
permission: Permission.Edit, permission: Permission.Edit,
type: ResourceType.Project,
id: projectId,
}) })
const stack = await versionStackService.createVersionStack({ const stack = await versionStackService.createVersionStack({
@@ -40,18 +41,18 @@ const route = app
}, },
) )
.post( .post(
'/projects/:projectId/version_stacks/:stackId/order', '/version_stacks/:stackId/order',
zValidator('json', changeStackFileVersionRequestSchema), zValidator('json', changeStackFileVersionRequestSchema),
async (c) => { async (c) => {
const projectId = c.req.param('projectId')
const stackId = c.req.param('stackId') const stackId = c.req.param('stackId')
const user = c.get('user') const user = c.get('user')
const req = c.req.valid('json') const req = c.req.valid('json')
await authzService.hasPermission({ await authzService.hasPermission({
projectId,
user, user,
permission: Permission.Edit, permission: Permission.Edit,
type: ResourceType.Asset,
id: stackId,
}) })
await versionStackService.changeStackFileVersion({ await versionStackService.changeStackFileVersion({
@@ -63,15 +64,15 @@ const route = app
return new Response(null, { status: 200 }) return new Response(null, { status: 200 })
}, },
) )
.get('/projects/:projectId/version_stacks/:stackId/versions', async (c) => { .get('/version_stacks/:stackId/versions', async (c) => {
const projectId = c.req.param('projectId')
const stackId = c.req.param('stackId') const stackId = c.req.param('stackId')
const user = c.get('user') const user = c.get('user')
await authzService.hasPermission({ await authzService.hasPermission({
projectId,
user, user,
permission: Permission.Read, permission: Permission.Read,
type: ResourceType.Asset,
id: stackId,
}) })
const versions = await assetService.getStackVersions(stackId) const versions = await assetService.getStackVersions(stackId)
+39 -16
View File
@@ -1,21 +1,21 @@
import { prisma } from '@/db' import { prisma } from '@/db'
import { import {
AncestorFolder, AncestorFolder,
AssetInfo, AssetInfo,
AttachmentInfo, AttachmentInfo,
ChildPreview, ChildPreview,
CommentInfo, CommentInfo,
CopyAssetsRequest, CopyAssetsRequest,
CreateAssetRequest, CreateAssetRequest,
CreateCommentRequest, CreateCommentRequest,
FieldValueInfo, FieldValueInfo,
GetAssetRequest, GetAssetRequest,
ListChildrenRequest, ListChildrenRequest,
PreviewInfo, PreviewInfo,
ReparentAssetsRequest, ReparentAssetsRequest,
UpdateAssetNameRequest, UpdateAssetNameRequest,
UpdateAssetOrderRequest, UpdateAssetOrderRequest,
UserInfo, UserInfo,
} from '@/dtos/asset' } from '@/dtos/asset'
import { Asset, AssetStatus, AssetType, Prisma, StorageKey } from '@/generated/prisma/client.ts' import { Asset, AssetStatus, AssetType, Prisma, StorageKey } from '@/generated/prisma/client.ts'
import { logger } from '@/logger' import { logger } from '@/logger'
@@ -830,6 +830,29 @@ export class AssetService {
return info return info
} }
async getAssetContext(assetId: string): Promise<{ teamId: string; projectId?: string } | null> {
const asset = await this.prismaClient.asset.findUnique({
where: { id: assetId },
select: {
projectId: true,
project: { select: { teamId: true } },
teamRootFolder: { select: { id: true } },
},
})
if (!asset) return null
if (asset.project) {
return { teamId: asset.project.teamId, projectId: asset.projectId ?? undefined }
}
if (asset.teamRootFolder) {
return { teamId: asset.teamRootFolder.id }
}
return null
}
async resolveTargetAssetId(assetId: string): Promise<string> { async resolveTargetAssetId(assetId: string): Promise<string> {
const asset = await this.prismaClient.asset.findUnique({ const asset = await this.prismaClient.asset.findUnique({
where: { id: assetId }, where: { id: assetId },
+52 -17
View File
@@ -2,7 +2,7 @@ import { setupTestDbHooks } from '@/db-test-hooks'
import { describe, expect, it } from 'vitest' import { describe, expect, it } from 'vitest'
import { prisma } from '@/db' import { prisma } from '@/db'
import { authzService, Permission } from '@/services/authz/authz' import { authzService, Permission, ResourceType } from '@/services/authz/authz'
describe('AuthzService', () => { describe('AuthzService', () => {
setupTestDbHooks() setupTestDbHooks()
@@ -52,6 +52,18 @@ describe('AuthzService', () => {
}, },
}) })
// Collection
const collection = await prisma.collection.create({
data: {
name: 'Collection A',
projectId: project.id,
filter: {
sourceFolderId: 'root',
searchFilter: { conditions: [], operator: 'AND', recursively: true },
},
},
})
// Project Scope User // Project Scope User
const userProjectEditor = await prisma.user.create({ const userProjectEditor = await prisma.user.create({
data: { name: 'p_editor', email: 'p_editor@example.com', password: 'pass' }, data: { name: 'p_editor', email: 'p_editor@example.com', password: 'pass' },
@@ -72,7 +84,8 @@ describe('AuthzService', () => {
{ {
name: 'Owner can Admin Project', name: 'Owner can Admin Project',
req: { req: {
projectId: project.id, type: ResourceType.Project,
id: project.id,
user: userOwner, user: userOwner,
permission: Permission.Admin, permission: Permission.Admin,
}, },
@@ -81,7 +94,8 @@ describe('AuthzService', () => {
{ {
name: 'Editor cannot Admin Project', name: 'Editor cannot Admin Project',
req: { req: {
projectId: project.id, type: ResourceType.Project,
id: project.id,
user: userEditor, user: userEditor,
permission: Permission.Admin, permission: Permission.Admin,
}, },
@@ -90,7 +104,8 @@ describe('AuthzService', () => {
{ {
name: 'Editor can Edit Project', name: 'Editor can Edit Project',
req: { req: {
projectId: project.id, type: ResourceType.Project,
id: project.id,
user: userEditor, user: userEditor,
permission: Permission.Edit, permission: Permission.Edit,
}, },
@@ -99,7 +114,8 @@ describe('AuthzService', () => {
{ {
name: 'Reviewer cannot Edit Project', name: 'Reviewer cannot Edit Project',
req: { req: {
projectId: project.id, type: ResourceType.Project,
id: project.id,
user: userReviewer, user: userReviewer,
permission: Permission.Edit, permission: Permission.Edit,
}, },
@@ -108,7 +124,8 @@ describe('AuthzService', () => {
{ {
name: 'Reviewer can Read Project', name: 'Reviewer can Read Project',
req: { req: {
projectId: project.id, type: ResourceType.Project,
id: project.id,
user: userReviewer, user: userReviewer,
permission: Permission.Read, permission: Permission.Read,
}, },
@@ -117,7 +134,8 @@ describe('AuthzService', () => {
{ {
name: 'Non-member cannot Read Project', name: 'Non-member cannot Read Project',
req: { req: {
projectId: project.id, type: ResourceType.Project,
id: project.id,
user: userOther, user: userOther,
permission: Permission.Read, permission: Permission.Read,
}, },
@@ -127,7 +145,8 @@ describe('AuthzService', () => {
{ {
name: 'Project Editor can Edit Project', name: 'Project Editor can Edit Project',
req: { req: {
projectId: project.id, type: ResourceType.Project,
id: project.id,
user: userProjectEditor, user: userProjectEditor,
permission: Permission.Edit, permission: Permission.Edit,
}, },
@@ -136,7 +155,8 @@ describe('AuthzService', () => {
{ {
name: 'Project Editor cannot Admin Project', name: 'Project Editor cannot Admin Project',
req: { req: {
projectId: project.id, type: ResourceType.Project,
id: project.id,
user: userProjectEditor, user: userProjectEditor,
permission: Permission.Admin, permission: Permission.Admin,
}, },
@@ -145,7 +165,8 @@ describe('AuthzService', () => {
{ {
name: 'Project Scope User can Read Team', name: 'Project Scope User can Read Team',
req: { req: {
teamId: team.id, type: ResourceType.Team,
id: team.id,
user: userProjectEditor, user: userProjectEditor,
permission: Permission.Read, permission: Permission.Read,
}, },
@@ -154,7 +175,8 @@ describe('AuthzService', () => {
{ {
name: 'Project Scope User cannot Edit Team', name: 'Project Scope User cannot Edit Team',
req: { req: {
teamId: team.id, type: ResourceType.Team,
id: team.id,
user: userProjectEditor, user: userProjectEditor,
permission: Permission.Edit, permission: Permission.Edit,
}, },
@@ -162,22 +184,35 @@ describe('AuthzService', () => {
errMessage: 'User has only project scope', errMessage: 'User has only project scope',
}, },
{ {
name: 'Resolve Team from Asset ID', name: 'Resolve Context from Asset',
req: { req: {
assetId: asset.id, type: ResourceType.Asset,
id: asset.id,
user: userOwner, user: userOwner,
permission: Permission.Edit, permission: Permission.Edit,
}, },
wantErr: false, wantErr: false,
}, },
{ {
name: 'Asset without Project', name: 'Resolve Context from Collection',
req: { req: {
assetId: '01HJXXW6A61234567890ABCDEF', type: ResourceType.Collection,
id: collection.id,
user: userOwner,
permission: Permission.Edit,
},
wantErr: false,
},
{
name: 'Asset Not Found',
req: {
type: ResourceType.Asset,
id: '01HJXXW6A61234567890ABCDEF',
user: userOwner, user: userOwner,
permission: Permission.Read, permission: Permission.Read,
}, },
wantErr: true, wantErr: true,
errMessage: 'Asset not found',
}, },
] ]
@@ -191,13 +226,13 @@ describe('AuthzService', () => {
} catch (e: any) { } catch (e: any) {
err = e err = e
} }
expect(err).toBeDefined() expect(err, tt.name).toBeDefined()
if (tt.errMessage) { if (tt.errMessage) {
expect(err.message).include(tt.errMessage) expect(err.message).include(tt.errMessage)
} }
} else { } else {
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
await expect(authzService.hasPermission(tt.req as any)).resolves.toBeUndefined() await expect(authzService.hasPermission(tt.req as any), tt.name).resolves.toBeUndefined()
} }
} }
}) })
+163 -34
View File
@@ -8,46 +8,35 @@ export enum Permission {
Admin = 'Admin', Admin = 'Admin',
} }
export enum ResourceType {
Team = 'team',
Project = 'project',
Asset = 'asset',
Collection = 'collection',
Agent = 'agent',
Share = 'share',
MetadataField = 'metadataField',
Skill = 'skill',
Provider = 'provider',
Invite = 'invite',
Comment = 'comment',
AgentSession = 'agentSession',
}
export interface AuthzRequest { export interface AuthzRequest {
teamId?: string
projectId?: string
assetId?: string
user: User user: User
permission: Permission permission: Permission
type: ResourceType
id: string
} }
export class AuthzService { export class AuthzService {
async hasPermission(req: AuthzRequest): Promise<void> { async hasPermission(req: AuthzRequest): Promise<void> {
if (!req.user) throw new Error('User is required') if (!req.user) throw new Error('User is required')
let projectId = req.projectId const { teamId, projectId } = await this.resolveContext(req.type, req.id)
let teamId: string | undefined
// 1. Resolve ProjectID and TeamID // 1. Check Team Membership
if (req.assetId) {
const asset = await prisma.asset.findUnique({
where: { id: req.assetId },
select: { projectId: true },
})
if (!asset) throw new Error('Asset not found')
if (!asset.projectId) throw new Error(`Asset ${req.assetId} does not belong to a project`)
projectId = asset.projectId
}
if (projectId) {
const proj = await prisma.project.findUnique({
where: { id: projectId },
select: { teamId: true },
})
if (!proj) throw new Error('Project not found')
teamId = proj.teamId
} else {
if (!req.teamId) throw new Error('Project ID or Team ID is required')
teamId = req.teamId
}
// 2. Check Team Membership
const member = await prisma.teamMember.findUnique({ const member = await prisma.teamMember.findUnique({
where: { where: {
teamIdUserId: { teamIdUserId: {
@@ -59,15 +48,17 @@ export class AuthzService {
if (!member) throw new Error('User is not a member of the team') if (!member) throw new Error('User is not a member of the team')
// 3. Check Scope // 2. Check Scope
if (member.scope === 'team') { if (member.scope === 'team') {
return this.checkRole(member.role, req.permission) return this.checkRole(member.role, req.permission)
} }
// 4. Scope is Project // 3. Scope is Project
if (!projectId) { if (!projectId) {
// User has project scope but no project context provided. // User has project scope but no project context provided (e.g. Team-level resource)
// Allow Read access to team context (e.g. ListProjects) // If it's a team-level resource, project-scoped users shouldn't have access except for Read maybe?
// But usually team resources like Skills/Providers are managed by Team Owners/Editors.
// For now, let's keep the logic: project-scoped users can't access team-level resources unless it's Read (like ListProjects).
if (req.permission === Permission.Read) { if (req.permission === Permission.Read) {
return return
} }
@@ -89,6 +80,144 @@ export class AuthzService {
return this.checkRole(pm.role, req.permission) return this.checkRole(pm.role, req.permission)
} }
private async resolveContext(
type: ResourceType,
id: string,
): Promise<{ teamId: string; projectId?: string }> {
switch (type) {
case ResourceType.Team:
return { teamId: id }
case ResourceType.Project: {
const proj = await prisma.project.findUnique({
where: { id },
select: { teamId: true },
})
if (!proj) throw new Error('Project not found')
return { teamId: proj.teamId, projectId: id }
}
case ResourceType.Asset: {
const asset = await prisma.asset.findUnique({
where: { id },
select: {
parentId: true,
teamRootFolder: { select: { id: true } },
project: { select: { id: true, teamId: true } },
},
})
if (!asset) throw new Error('Asset not found')
if (asset.project) {
return { teamId: asset.project.teamId, projectId: asset.project.id }
}
if (asset.teamRootFolder) {
return { teamId: asset.teamRootFolder.id }
}
if (asset.parentId) {
// If it's a nested asset, we might need recursive lookup.
// However, in this project, assets typically have projectId if they are in a project.
// If parentId is set but no project, it might be in a team root folder.
// For now, let's try to get context from parent.
return this.resolveContext(ResourceType.Asset, asset.parentId)
}
throw new Error('Could not resolve context for asset')
}
case ResourceType.Collection: {
const coll = await prisma.collection.findUnique({
where: { id },
include: { project: true },
})
if (!coll) throw new Error('Collection not found')
return { teamId: coll.project.teamId, projectId: coll.projectId }
}
case ResourceType.Agent: {
const agent = await prisma.agent.findUnique({
where: { id },
select: { teamId: true },
})
if (!agent) throw new Error('Agent not found')
return { teamId: agent.teamId }
}
case ResourceType.AgentSession: {
const session = await prisma.agentSession.findUnique({
where: { id },
include: { agent: true },
})
if (!session) throw new Error('Agent session not found')
return { teamId: session.agent.teamId }
}
case ResourceType.Share: {
const share = await prisma.shareLink.findUnique({
where: { id },
include: { project: true },
})
if (!share) throw new Error('Share not found')
return { teamId: share.project.teamId, projectId: share.projectId }
}
case ResourceType.MetadataField: {
const field = await prisma.metadataField.findUnique({
where: { key: id },
select: { teamId: true, projectId: true },
})
if (!field) throw new Error('Metadata field not found')
if (field.projectId) {
const proj = await prisma.project.findUnique({
where: { id: field.projectId },
select: { teamId: true },
})
return { teamId: proj!.teamId, projectId: field.projectId }
}
if (!field.teamId) throw new Error('Metadata field has no context')
return { teamId: field.teamId }
}
case ResourceType.Skill: {
const skill = await prisma.skill.findUnique({
where: { id },
select: { teamId: true },
})
if (!skill) throw new Error('Skill not found')
return { teamId: skill.teamId }
}
case ResourceType.Provider: {
const provider = await prisma.provider.findUnique({
where: { id },
select: { teamId: true },
})
if (!provider) throw new Error('Provider not found')
return { teamId: provider.teamId }
}
case ResourceType.Invite: {
const invite = await prisma.invite.findUnique({
where: { id },
select: { teamId: true, projectId: true },
})
if (!invite) throw new Error('Invite not found')
return { teamId: invite.teamId, projectId: invite.projectId ?? undefined }
}
case ResourceType.Comment: {
const comment = await prisma.assetComment.findUnique({
where: { id },
include: { asset: { include: { project: true } } },
})
if (!comment) throw new Error('Comment not found')
if (!comment.asset.project) throw new Error('Comment asset has no project')
return { teamId: comment.asset.project.teamId, projectId: comment.asset.projectId! }
}
default:
throw new Error(`Unsupported resource type: ${type}`)
}
}
private checkRole(role: string, permission: Permission): void { private checkRole(role: string, permission: Permission): void {
switch (permission) { switch (permission) {
case Permission.Read: case Permission.Read:
+8
View File
@@ -67,6 +67,14 @@ export class MetadataService {
return fields return fields
} }
async getFieldByKey(
key: string,
): Promise<Prisma.MetadataFieldGetPayload<Record<string, never>> | null> {
return this.client.metadataField.findUnique({
where: { key },
})
}
async updateTeamField( async updateTeamField(
teamId: string, teamId: string,
fieldId: string, fieldId: string,
+6
View File
@@ -65,6 +65,12 @@ export class ProviderService {
})) }))
} }
async getById(id: string) {
return this.prismaClient.provider.findUnique({
where: { id },
})
}
async listModelsByProvider(teamId: string, providerId: string) { async listModelsByProvider(teamId: string, providerId: string) {
return this.prismaClient.model.findMany({ return this.prismaClient.model.findMany({
where: { where: {
+8 -8
View File
@@ -55,15 +55,15 @@ export const MessageCard: React.FC<MessageCardProps> = ({
initialMessage.message in AI_PLACEHOLDERS initialMessage.message in AI_PLACEHOLDERS
const { data: polledMessage } = useQuery({ const { data: polledMessage } = useQuery({
queryKey: ['teams', teamId, 'comments', initialMessage.id], queryKey: ['comments', initialMessage.id],
queryFn: async () => { queryFn: async () => {
const res = await client.api.teams[':teamId'].comments[':commentId'].$get({ const res = await client.api.comments[':commentId'].$get({
param: { teamId: teamId!, commentId: initialMessage.id! }, param: { commentId: initialMessage.id! },
}) })
if (!res.ok) throw new Error('Failed to fetch comment') if (!res.ok) throw new Error('Failed to fetch comment')
return (await res.json()) as CommentInfo return (await res.json()) as CommentInfo
}, },
enabled: !!teamId && isRunning, enabled: isRunning,
refetchInterval: (query) => { refetchInterval: (query) => {
const data = query.state.data as CommentInfo const data = query.state.data as CommentInfo
if (data && (!data.message || !(data.message in AI_PLACEHOLDERS))) { if (data && (!data.message || !(data.message in AI_PLACEHOLDERS))) {
@@ -97,15 +97,15 @@ export const MessageCard: React.FC<MessageCardProps> = ({
const isAdmin = me?.role === 'owner' const isAdmin = me?.role === 'owner'
const { data: logs, isLoading: isLogsLoading } = useQuery({ const { data: logs, isLoading: isLogsLoading } = useQuery({
queryKey: ['teams', teamId, 'agent-sessions', message.sessionId, 'entries'], queryKey: ['agent-sessions', message.sessionId, 'entries'],
queryFn: async () => { queryFn: async () => {
const res = await client.api.teams[':teamId']['agent-sessions'][':sessionId'].entries.$get({ const res = await client.api['agent-sessions'][':sessionId'].entries.$get({
param: { teamId: teamId!, sessionId: message.sessionId! }, param: { sessionId: message.sessionId! },
}) })
if (!res.ok) throw new Error('Failed to fetch session logs') if (!res.ok) throw new Error('Failed to fetch session logs')
return await res.json() return await res.json()
}, },
enabled: isLogsOpen && !!message.sessionId && !!teamId, enabled: isLogsOpen && !!message.sessionId,
}) })
const renderFormattedMessage = (text: string) => { const renderFormattedMessage = (text: string) => {
@@ -128,8 +128,8 @@ export function FileBrowser({
const { data: shareLinksData } = useQuery({ const { data: shareLinksData } = useQuery({
queryKey: ['shares', teamId, projectId], queryKey: ['shares', teamId, projectId],
queryFn: async () => { queryFn: async () => {
const res = await client.api.teams[':teamId'].projects[':projectId'].shares.$get({ const res = await client.api.projects[':projectId'].shares.$get({
param: { teamId, projectId }, param: { projectId },
query: { first: '100' }, query: { first: '100' },
}) })
if (!res.ok) throw new Error('Failed to fetch share links') if (!res.ok) throw new Error('Failed to fetch share links')
@@ -240,16 +240,16 @@ export function FileBrowser({
day: 'numeric', day: 'numeric',
}) })
const res = await client.api.teams[':teamId'].projects[':projectId'].shares.$post({ const res = await client.api.projects[':projectId'].shares.$post({
param: { teamId, projectId }, param: { projectId },
json: { name }, json: { name },
}) })
if (!res.ok) throw new Error('Failed to create share link') if (!res.ok) throw new Error('Failed to create share link')
const share = await res.json() const share = await res.json()
// Add assets to the new share link // Add assets to the new share link
const assetsRes = await client.api.teams[':teamId'].shares[':shareId'].assets.$post({ const assetsRes = await client.api.shares[':shareId'].assets.$post({
param: { teamId, shareId: share.id }, param: { shareId: share.id },
json: { assetIds: items.map((i) => i.id!) }, json: { assetIds: items.map((i) => i.id!) },
}) })
if (!assetsRes.ok) throw new Error('Failed to add assets to share link') if (!assetsRes.ok) throw new Error('Failed to add assets to share link')
@@ -273,8 +273,8 @@ export function FileBrowser({
const { mutate: addToShareLink } = useMutation({ const { mutate: addToShareLink } = useMutation({
mutationFn: async ({ shareId, items }: { shareId: string; items: AssetInfo[] }) => { mutationFn: async ({ shareId, items }: { shareId: string; items: AssetInfo[] }) => {
const res = await client.api.teams[':teamId'].shares[':shareId'].assets.$post({ const res = await client.api.shares[':shareId'].assets.$post({
param: { teamId, shareId }, param: { shareId },
json: { assetIds: items.map((i) => i.id!) }, json: { assetIds: items.map((i) => i.id!) },
}) })
if (!res.ok) throw new Error('Failed to add assets') if (!res.ok) throw new Error('Failed to add assets')
+2 -2
View File
@@ -87,8 +87,8 @@ export function FileCard({
const { data: polledItem } = useQuery({ const { data: polledItem } = useQuery({
queryKey: ['file', teamId, item.id], queryKey: ['file', teamId, item.id],
queryFn: async () => { queryFn: async () => {
const res = await client.api.teams[':teamId'].files[':fileId'].$get({ const res = await client.api.files[':fileId'].$get({
param: { teamId: teamId || '', fileId: item.id || '' }, param: { fileId: item.id || '' },
}) })
if (!res.ok) throw new Error('failed to fetch file') if (!res.ok) throw new Error('failed to fetch file')
return (await res.json()) as unknown as AssetInfo return (await res.json()) as unknown as AssetInfo
@@ -66,8 +66,8 @@ export function FileListItem({
const { data: polledItem } = useQuery({ const { data: polledItem } = useQuery({
queryKey: ['file', teamId, item.id], queryKey: ['file', teamId, item.id],
queryFn: async () => { queryFn: async () => {
const res = await client.api.teams[':teamId'].files[':fileId'].$get({ const res = await client.api.files[':fileId'].$get({
param: { teamId: teamId || '', fileId: item.id || '' }, param: { fileId: item.id || '' },
}) })
if (!res.ok) throw new Error('failed to fetch file') if (!res.ok) throw new Error('failed to fetch file')
return (await res.json()) as unknown as AssetInfo return (await res.json()) as unknown as AssetInfo
+4 -4
View File
@@ -58,15 +58,15 @@ export function FileBrowserToolbar({
const isCollection = !!collection const isCollection = !!collection
const { data: folderInfo } = useQuery({ const { data: folderInfo } = useQuery({
queryKey: ['folders', teamId, assetId], queryKey: ['folders', assetId],
queryFn: async () => { queryFn: async () => {
const res = await client.api.teams[':teamId'].folders[':folderId'].$get({ const res = await client.api.folders[':folderId'].$get({
param: { teamId: teamId, folderId: assetId }, param: { folderId: assetId },
}) })
if (!res.ok) throw new Error('failed to fetch folder') if (!res.ok) throw new Error('failed to fetch folder')
return (await res.json()) as unknown as AssetInfo return (await res.json()) as unknown as AssetInfo
}, },
enabled: isCollection && !!teamId && !!assetId, enabled: isCollection && !!assetId,
}) })
const { data: members } = useQuery({ const { data: members } = useQuery({
@@ -28,7 +28,7 @@ export function useFileActions({
const [itemsToDelete, setItemsToDelete] = useState<AssetInfo[]>([]) const [itemsToDelete, setItemsToDelete] = useState<AssetInfo[]>([])
const queryClient = useQueryClient() const queryClient = useQueryClient()
const $createFolder = client.api.teams[':teamId'].folders.$post const $createFolder = client.api.folders.$post
const { mutate: createFolder } = useMutation< const { mutate: createFolder } = useMutation<
InferResponseType<typeof $createFolder, 200>, InferResponseType<typeof $createFolder, 200>,
Error, Error,
@@ -41,7 +41,7 @@ export function useFileActions({
}, },
}) })
const $renameFolder = client.api.teams[':teamId'].folders[':folderId'].$put const $renameFolder = client.api.folders[':folderId'].$put
const { mutate: renameFolder } = useMutation< const { mutate: renameFolder } = useMutation<
InferResponseType<typeof $renameFolder, 200>, InferResponseType<typeof $renameFolder, 200>,
Error, Error,
@@ -54,7 +54,7 @@ export function useFileActions({
}, },
}) })
const $renameFile = client.api.teams[':teamId'].files[':fileId'].$put const $renameFile = client.api.files[':fileId'].$put
const { mutate: renameFile } = useMutation< const { mutate: renameFile } = useMutation<
InferResponseType<typeof $renameFile, 200>, InferResponseType<typeof $renameFile, 200>,
Error, Error,
@@ -67,7 +67,7 @@ export function useFileActions({
}, },
}) })
const $deleteFiles = client.api.teams[':teamId'].files.$delete const $deleteFiles = client.api.files.$delete
const { mutate: deleteFiles } = useMutation<void, Error, InferRequestType<typeof $deleteFiles>>({ const { mutate: deleteFiles } = useMutation<void, Error, InferRequestType<typeof $deleteFiles>>({
mutationFn: async (request) => { mutationFn: async (request) => {
const res = await $deleteFiles(request) const res = await $deleteFiles(request)
@@ -75,7 +75,7 @@ export function useFileActions({
}, },
}) })
const $deleteFolders = client.api.teams[':teamId'].folders.$delete const $deleteFolders = client.api.folders.$delete
const { mutate: deleteFolders } = useMutation< const { mutate: deleteFolders } = useMutation<
InferResponseType<typeof $deleteFolders>, InferResponseType<typeof $deleteFolders>,
Error, Error,
@@ -88,7 +88,7 @@ export function useFileActions({
}, },
}) })
const $restoreFiles = client.api.teams[':teamId'].files.restore.$post const $restoreFiles = client.api.files.restore.$post
const { mutate: restoreFiles } = useMutation<void, Error, InferRequestType<typeof $restoreFiles>>( const { mutate: restoreFiles } = useMutation<void, Error, InferRequestType<typeof $restoreFiles>>(
{ {
mutationFn: async (request) => { mutationFn: async (request) => {
@@ -98,7 +98,7 @@ export function useFileActions({
}, },
) )
const $restoreFolders = client.api.teams[':teamId'].folders.restore.$post const $restoreFolders = client.api.folders.restore.$post
const { mutate: restoreFolders } = useMutation< const { mutate: restoreFolders } = useMutation<
InferResponseType<typeof $restoreFolders>, InferResponseType<typeof $restoreFolders>,
Error, Error,
@@ -121,7 +121,7 @@ export function useFileActions({
if (fileIds.length > 0) { if (fileIds.length > 0) {
deleteFiles( deleteFiles(
{ param: { teamId: teamId }, json: { ids: fileIds } }, { json: { ids: fileIds } },
{ {
onSuccess: () => { onSuccess: () => {
queryClient.invalidateQueries({ queryClient.invalidateQueries({
@@ -134,7 +134,7 @@ export function useFileActions({
if (folderIds.length > 0) { if (folderIds.length > 0) {
deleteFolders( deleteFolders(
{ param: { teamId: teamId }, json: { ids: folderIds } }, { json: { ids: folderIds } },
{ {
onSuccess: () => { onSuccess: () => {
queryClient.invalidateQueries({ queryClient.invalidateQueries({
@@ -160,7 +160,7 @@ export function useFileActions({
if (fileIds.length > 0) { if (fileIds.length > 0) {
restoreFiles( restoreFiles(
{ param: { teamId: teamId }, json: { ids: fileIds } }, { json: { ids: fileIds } },
{ {
onSuccess: () => { onSuccess: () => {
queryClient.invalidateQueries({ queryClient.invalidateQueries({
@@ -173,7 +173,7 @@ export function useFileActions({
if (folderIds.length > 0) { if (folderIds.length > 0) {
restoreFolders( restoreFolders(
{ param: { teamId: teamId }, json: { ids: folderIds } }, { json: { ids: folderIds } },
{ {
onSuccess: () => { onSuccess: () => {
queryClient.invalidateQueries({ queryClient.invalidateQueries({
@@ -195,7 +195,7 @@ export function useFileActions({
const handleNewFolder = (name: string) => { const handleNewFolder = (name: string) => {
createFolder( createFolder(
{ param: { teamId: teamId }, json: { name, parentId: assetId } }, { json: { name, parentId: assetId } },
{ {
onSuccess: (data) => { onSuccess: (data) => {
queryClient.invalidateQueries({ queryClient.invalidateQueries({
@@ -215,7 +215,7 @@ export function useFileActions({
const onRenameSubmit = (item: AssetInfo, newName: string) => { const onRenameSubmit = (item: AssetInfo, newName: string) => {
if (item.type === 'folder') { if (item.type === 'folder') {
renameFolder( renameFolder(
{ param: { teamId: teamId, folderId: item.id! }, json: { name: newName } }, { param: { folderId: item.id! }, json: { name: newName } },
{ {
onSuccess: () => { onSuccess: () => {
queryClient.invalidateQueries({ queryClient.invalidateQueries({
@@ -230,7 +230,7 @@ export function useFileActions({
} else { } else {
renameFile( renameFile(
{ {
param: { teamId: teamId, fileId: item.id! }, param: { fileId: item.id! },
json: { name: newName }, json: { name: newName },
}, },
{ {
+9 -10
View File
@@ -47,7 +47,7 @@ export default function FileSystemManager({
const navigate = useNavigate() const navigate = useNavigate()
const queryClient = useQueryClient() const queryClient = useQueryClient()
const { loadedProjectId, setFields } = useFieldStore() const { loadedProjectId, setFields } = useFieldStore()
const $patchMetadata = client.api.teams[':teamId'].files[':fileId'].metadata.$patch const $patchMetadata = client.api.files[':fileId'].metadata.$patch
const { mutate: patchMetadata } = useMutation< const { mutate: patchMetadata } = useMutation<
InferResponseType<typeof $patchMetadata>, InferResponseType<typeof $patchMetadata>,
Error, Error,
@@ -132,10 +132,10 @@ export default function FileSystemManager({
const { data: folderInfo } = isRecentlyDeleted const { data: folderInfo } = isRecentlyDeleted
? { data: undefined } ? { data: undefined }
: useQuery({ : useQuery({
queryKey: ['folders', teamId, assetId], queryKey: ['folders', assetId],
queryFn: async () => { queryFn: async () => {
const res = await client.api.teams[':teamId'].folders[':folderId'].$get({ const res = await client.api.folders[':folderId'].$get({
param: { teamId: teamId, folderId: assetId }, param: { folderId: assetId },
}) })
if (!res.ok) throw new Error('failed to fetch folder') if (!res.ok) throw new Error('failed to fetch folder')
return (await res.json()) as unknown as AssetInfo return (await res.json()) as unknown as AssetInfo
@@ -206,8 +206,8 @@ export default function FileSystemManager({
return { data: [], pageInfo: { total: 0 } } return { data: [], pageInfo: { total: 0 } }
} }
const res = await client.api.teams[':teamId'].folders[':folderId'].search.$post({ const res = await client.api.folders[':folderId'].search.$post({
param: { teamId: teamId, folderId: assetId }, param: { folderId: assetId },
json: { json: {
assetType: 'folder', assetType: 'folder',
after: pageParam as string, after: pageParam as string,
@@ -248,8 +248,8 @@ export default function FileSystemManager({
return (await res.json()) as unknown as AssetInfoPaginatedList return (await res.json()) as unknown as AssetInfoPaginatedList
} }
const res = await client.api.teams[':teamId'].folders[':folderId'].search.$post({ const res = await client.api.folders[':folderId'].search.$post({
param: { teamId: teamId, folderId: assetId }, param: { folderId: assetId },
json: { json: {
assetType: 'file', assetType: 'file',
after: pageParam as string, after: pageParam as string,
@@ -370,7 +370,7 @@ export default function FileSystemManager({
const handleSaveField = (fileId: string, fieldId: string, value: unknown) => { const handleSaveField = (fileId: string, fieldId: string, value: unknown) => {
patchMetadata( patchMetadata(
{ {
param: { teamId: teamId, fileId: fileId }, param: { fileId: fileId },
json: [{ key: fieldId, value }] as InferRequestType<typeof $patchMetadata>['json'], json: [{ key: fieldId, value }] as InferRequestType<typeof $patchMetadata>['json'],
}, },
{ {
@@ -378,7 +378,6 @@ export default function FileSystemManager({
queryClient.invalidateQueries({ queryClient.invalidateQueries({
queryKey: [ queryKey: [
'folders', 'folders',
teamId,
assetId, assetId,
'children', 'children',
{ {
@@ -10,7 +10,6 @@ import { Button } from './ui/button'
import { ScrollArea } from './ui/scroll-area' import { ScrollArea } from './ui/scroll-area'
interface FileViewerLeftSidebarProps { interface FileViewerLeftSidebarProps {
teamId: string
projectId: string projectId: string
currentAssetId: string currentAssetId: string
parentFolderId: string parentFolderId: string
@@ -18,7 +17,6 @@ interface FileViewerLeftSidebarProps {
} }
export const FileViewerLeftSidebar: FC<FileViewerLeftSidebarProps> = ({ export const FileViewerLeftSidebar: FC<FileViewerLeftSidebarProps> = ({
teamId,
projectId, projectId,
currentAssetId, currentAssetId,
parentFolderId, parentFolderId,
@@ -34,7 +32,6 @@ export const FileViewerLeftSidebar: FC<FileViewerLeftSidebarProps> = ({
const { data, fetchNextPage, hasNextPage, isFetchingNextPage, isLoading } = useInfiniteQuery({ const { data, fetchNextPage, hasNextPage, isFetchingNextPage, isLoading } = useInfiniteQuery({
queryKey: [ queryKey: [
'folders', 'folders',
teamId,
parentFolderId, parentFolderId,
'children', 'children',
{ {
@@ -42,8 +39,8 @@ export const FileViewerLeftSidebar: FC<FileViewerLeftSidebarProps> = ({
}, },
], ],
queryFn: async ({ pageParam }) => { queryFn: async ({ pageParam }) => {
const res = await client.api.teams[':teamId'].folders[':folderId'].children.$get({ const res = await client.api.folders[':folderId'].children.$get({
param: { teamId: teamId, folderId: parentFolderId }, param: { folderId: parentFolderId },
query: { query: {
assetType: 'file', assetType: 'file',
after: pageParam, after: pageParam,
@@ -99,7 +99,7 @@ export function FileViewerRightSidebar({
} = useInfiniteQuery({ } = useInfiniteQuery({
queryKey: isPublic queryKey: isPublic
? ['shares', shareId, 'files', file?.id, 'comments'] ? ['shares', shareId, 'files', file?.id, 'comments']
: ['teams', teamId, 'files', file?.id, 'comments'], : ['files', file?.id, 'comments'],
queryFn: async ({ pageParam }) => { queryFn: async ({ pageParam }) => {
if (isPublic) { if (isPublic) {
const password = localStorage.getItem(`share_pwd_${shareId}`) || '' const password = localStorage.getItem(`share_pwd_${shareId}`) || ''
@@ -117,8 +117,8 @@ export function FileViewerRightSidebar({
if (!res.ok) throw new Error('Failed to fetch comments') if (!res.ok) throw new Error('Failed to fetch comments')
return await res.json() return await res.json()
} else { } else {
const res = await client.api.teams[':teamId'].files[':fileId'].comments.$get({ const res = await client.api.files[':fileId'].comments.$get({
param: { teamId: teamId, fileId: file!.id! }, param: { fileId: file!.id! },
query: { after: pageParam as string }, query: { after: pageParam as string },
}) })
if (!res.ok) throw new Error('Failed to fetch comments') if (!res.ok) throw new Error('Failed to fetch comments')
@@ -168,8 +168,8 @@ export function FileViewerRightSidebar({
if (!res.ok) throw new Error('Failed to create comment') if (!res.ok) throw new Error('Failed to create comment')
return await res.json() return await res.json()
} else { } else {
const res = await client.api.teams[':teamId'].files[':fileId'].comments.$post({ const res = await client.api.files[':fileId'].comments.$post({
param: { teamId: teamId, fileId: file!.id! }, param: { fileId: file!.id! },
json: { json: {
message: text, message: text,
attachmentIds: attachmentIds, attachmentIds: attachmentIds,
@@ -185,7 +185,7 @@ export function FileViewerRightSidebar({
queryClient.invalidateQueries({ queryClient.invalidateQueries({
queryKey: isPublic queryKey: isPublic
? ['shares', shareId, 'files', file?.id, 'comments'] ? ['shares', shareId, 'files', file?.id, 'comments']
: ['teams', teamId, 'files', file?.id, 'comments'], : ['files', file?.id, 'comments'],
}) })
}, },
}) })
+16 -17
View File
@@ -54,35 +54,35 @@ export function FolderTree({
}) })
const { data: shareLinksData } = useQuery({ const { data: shareLinksData } = useQuery({
queryKey: ['shares', teamId, projectId], queryKey: ['shares', projectId],
queryFn: async () => { queryFn: async () => {
const res = await client.api.teams[':teamId'].projects[':projectId'].shares.$get({ const res = await client.api.projects[':projectId'].shares.$get({
param: { teamId, projectId }, param: { projectId },
query: { first: '100' }, query: { first: '100' },
}) })
if (!res.ok) throw new Error('Failed to fetch share links') if (!res.ok) throw new Error('Failed to fetch share links')
return (await res.json()) as unknown as { data: ShareLinkInfo[] } return (await res.json()) as unknown as { data: ShareLinkInfo[] }
}, },
enabled: !!teamId && !!projectId, enabled: !!projectId,
}) })
const { data: collectionsData } = useQuery({ const { data: collectionsData } = useQuery({
queryKey: ['collections', teamId, projectId], queryKey: ['collections', projectId],
queryFn: async () => { queryFn: async () => {
const res = await client.api.teams[':teamId'].projects[':projectId'].collections.$get({ const res = await client.api.projects[':projectId'].collections.$get({
param: { teamId, projectId }, param: { projectId },
query: { first: '100' }, query: { first: '100' },
}) })
if (!res.ok) throw new Error('Failed to fetch collections') if (!res.ok) throw new Error('Failed to fetch collections')
return (await res.json()) as unknown as { data: CollectionInfo[] } return (await res.json()) as unknown as { data: CollectionInfo[] }
}, },
enabled: !!teamId && !!projectId, enabled: !!projectId,
}) })
const { mutate: createCollection } = useMutation({ const { mutate: createCollection } = useMutation({
mutationFn: async () => { mutationFn: async () => {
const res = await client.api.teams[':teamId'].projects[':projectId'].collections.$post({ const res = await client.api.projects[':projectId'].collections.$post({
param: { teamId, projectId }, param: { projectId },
json: { json: {
name: 'Untitled Collection', name: 'Untitled Collection',
filter: { filter: {
@@ -98,7 +98,7 @@ export function FolderTree({
return await res.json() return await res.json()
}, },
onSuccess: (data) => { onSuccess: (data) => {
queryClient.invalidateQueries({ queryKey: ['collections', teamId, projectId] }) queryClient.invalidateQueries({ queryKey: ['collections', projectId] })
toast.success('Collection created') toast.success('Collection created')
navigate({ navigate({
to: '/projects/$projectId/collections/$collectionId', to: '/projects/$projectId/collections/$collectionId',
@@ -112,8 +112,8 @@ export function FolderTree({
const { mutate: createShareLink } = useMutation({ const { mutate: createShareLink } = useMutation({
mutationFn: async () => { mutationFn: async () => {
const res = await client.api.teams[':teamId'].projects[':projectId'].shares.$post({ const res = await client.api.projects[':projectId'].shares.$post({
param: { teamId, projectId }, param: { projectId },
json: { json: {
name: new Date().toLocaleDateString('en-US', { name: new Date().toLocaleDateString('en-US', {
year: 'numeric', year: 'numeric',
@@ -126,7 +126,7 @@ export function FolderTree({
return await res.json() return await res.json()
}, },
onSuccess: (data) => { onSuccess: (data) => {
queryClient.invalidateQueries({ queryKey: ['shares', teamId, projectId] }) queryClient.invalidateQueries({ queryKey: ['shares', projectId] })
toast.success('Share link created') toast.success('Share link created')
navigate({ navigate({
to: '/projects/$projectId/shares/$shareId', to: '/projects/$projectId/shares/$shareId',
@@ -362,7 +362,6 @@ function FolderTreeItem({
} = useInfiniteQuery<AssetInfoPaginatedList>({ } = useInfiniteQuery<AssetInfoPaginatedList>({
queryKey: [ queryKey: [
'folders', 'folders',
teamId,
folder.id, folder.id,
'children', 'children',
{ {
@@ -370,8 +369,8 @@ function FolderTreeItem({
}, },
], ],
queryFn: async ({ pageParam }) => { queryFn: async ({ pageParam }) => {
const res = await client.api.teams[':teamId'].folders[':folderId'].children.$get({ const res = await client.api.folders[':folderId'].children.$get({
param: { teamId: teamId, folderId: folder.id }, param: { folderId: folder.id },
query: { query: {
assetType: 'folder', assetType: 'folder',
after: pageParam as string, after: pageParam as string,
+4 -4
View File
@@ -161,7 +161,7 @@ export function ManageFieldsDialog({ projectId, open, onOpenChange }: ManageFiel
resetEditor(data) resetEditor(data)
}, },
}) })
const $put = client.api.projects[':projectId'].fields[':fieldId'].$put const $put = client.api.fields[':fieldId'].$put
const { mutate: updateField } = useMutation< const { mutate: updateField } = useMutation<
InferResponseType<typeof $put>, InferResponseType<typeof $put>,
Error, Error,
@@ -179,7 +179,7 @@ export function ManageFieldsDialog({ projectId, open, onOpenChange }: ManageFiel
updateFields(newFields) updateFields(newFields)
}, },
}) })
const $delete = client.api.projects[':projectId'].fields[':fieldId'].$delete const $delete = client.api.fields[':fieldId'].$delete
const { mutate: deleteField } = useMutation< const { mutate: deleteField } = useMutation<
InferResponseType<typeof $delete>, InferResponseType<typeof $delete>,
Error, Error,
@@ -287,7 +287,7 @@ export function ManageFieldsDialog({ projectId, open, onOpenChange }: ManageFiel
const handleSaveEdit = () => { const handleSaveEdit = () => {
if (!selectedField) return if (!selectedField) return
updateField({ updateField({
param: { projectId: projectId, fieldId: selectedField.id! }, param: { fieldId: selectedField.id! },
json: { json: {
config: { config: {
...selectedField.config, ...selectedField.config,
@@ -303,7 +303,7 @@ export function ManageFieldsDialog({ projectId, open, onOpenChange }: ManageFiel
const handleDelete = () => { const handleDelete = () => {
if (!selectedField) return if (!selectedField) return
if (confirm('Are you sure you want to delete this field?')) { if (confirm('Are you sure you want to delete this field?')) {
deleteField({ param: { projectId: projectId, fieldId: selectedField.id! } }) deleteField({ param: { fieldId: selectedField.id! } })
} }
} }
+2 -2
View File
@@ -73,7 +73,7 @@ export function ProjectDialog({ open, onOpenChange, mode, teamId, project }: Pro
}, },
}) })
const $put = client.api.teams[':teamId'].projects[':projectId'].$put const $put = client.api.projects[':projectId'].$put
const { mutate: updateProject } = useMutation< const { mutate: updateProject } = useMutation<
InferResponseType<typeof $put>, InferResponseType<typeof $put>,
Error, Error,
@@ -81,7 +81,7 @@ export function ProjectDialog({ open, onOpenChange, mode, teamId, project }: Pro
>({ >({
mutationFn: async (payload) => { mutationFn: async (payload) => {
const res = await $put({ const res = await $put({
param: { teamId: teamId, projectId: project!.id! }, param: { projectId: project!.id! },
json: payload, json: payload,
}) })
if (!res.ok) throw new Error('Failed to update project') if (!res.ok) throw new Error('Failed to update project')
@@ -108,8 +108,8 @@ export function SearchFilterDialog({
} }
if (!name) name = 'Untitled Collection' if (!name) name = 'Untitled Collection'
const res = await client.api.teams[':teamId'].projects[':projectId'].collections.$post({ const res = await client.api.projects[':projectId'].collections.$post({
param: { teamId, projectId }, param: { projectId },
json: { json: {
name, name,
filter: { filter: {
@@ -125,7 +125,7 @@ export function SearchFilterDialog({
return await res.json() return await res.json()
}, },
onSuccess: (data) => { onSuccess: (data) => {
queryClient.invalidateQueries({ queryKey: ['collections', teamId, projectId] }) queryClient.invalidateQueries({ queryKey: ['collections', projectId] })
toast.success('Collection saved') toast.success('Collection saved')
onOpenChange(false) onOpenChange(false)
navigate({ navigate({
@@ -141,8 +141,8 @@ export function SearchFilterDialog({
const { data: searchResults, isLoading } = useQuery({ const { data: searchResults, isLoading } = useQuery({
queryKey: ['search-preview', teamId, assetId, combinedConditions], queryKey: ['search-preview', teamId, assetId, combinedConditions],
queryFn: async () => { queryFn: async () => {
const res = await client.api.teams[':teamId'].folders[':folderId'].search.$post({ const res = await client.api.folders[':folderId'].search.$post({
param: { teamId, folderId: assetId }, param: { folderId: assetId },
json: { json: {
assetType: undefined, assetType: undefined,
conditions: combinedConditions, conditions: combinedConditions,
@@ -144,8 +144,8 @@ export function AgentFormDialog({
const { data: models, isLoading: isModelsLoading } = useQuery({ const { data: models, isLoading: isModelsLoading } = useQuery({
queryKey: ['teams', teamId, 'providers', selectedProviderId, 'models'], queryKey: ['teams', teamId, 'providers', selectedProviderId, 'models'],
queryFn: async () => { queryFn: async () => {
const res = await client.api.teams[':teamId'].providers[':id'].models.$get({ const res = await client.api.providers[':id'].models.$get({
param: { teamId, id: selectedProviderId! }, param: { id: selectedProviderId! },
}) })
if (!res.ok) throw new Error('Failed to fetch models') if (!res.ok) throw new Error('Failed to fetch models')
return await res.json() return await res.json()
@@ -174,8 +174,8 @@ export function AgentFormDialog({
const updateMutation = useMutation({ const updateMutation = useMutation({
mutationFn: async ({ id, values }: { id: string; values: AgentFormValues }) => { mutationFn: async ({ id, values }: { id: string; values: AgentFormValues }) => {
const res = await client.api.teams[':teamId'].agents[':agentId'].$put({ const res = await client.api.agents[':agentId'].$put({
param: { teamId, agentId: id }, param: { agentId: id },
json: values, json: values,
}) })
if (!res.ok) throw new Error('Failed to update agent') if (!res.ok) throw new Error('Failed to update agent')
@@ -82,8 +82,8 @@ export function AgentsSettings({ teamId }: AgentsSettingsProps) {
const deleteAgentMutation = useMutation({ const deleteAgentMutation = useMutation({
mutationFn: async (agentId: string) => { mutationFn: async (agentId: string) => {
const res = await client.api.teams[':teamId'].agents[':agentId'].$delete({ const res = await client.api.agents[':agentId'].$delete({
param: { teamId, agentId }, param: { agentId },
}) })
if (!res.ok) throw new Error('failed to delete agent') if (!res.ok) throw new Error('failed to delete agent')
}, },
@@ -112,8 +112,8 @@ export function AgentsSettings({ teamId }: AgentsSettingsProps) {
soul?: string soul?: string
skills?: string[] skills?: string[]
}) => { }) => {
const res = await client.api.teams[':teamId'].agents[':agentId'].$put({ const res = await client.api.agents[':agentId'].$put({
param: { teamId: params.teamId, agentId: params.agentId }, param: { agentId: params.agentId },
json: { json: {
name: params.name, name: params.name,
type: params.type, type: params.type,
@@ -105,8 +105,8 @@ export function ProvidersSettings({ teamId }: ProvidersSettingsProps) {
const { data: editingModels, isLoading: isModelsLoading } = useQuery({ const { data: editingModels, isLoading: isModelsLoading } = useQuery({
queryKey: ['teams', teamId, 'providers', editingProviderId, 'models'], queryKey: ['teams', teamId, 'providers', editingProviderId, 'models'],
queryFn: async () => { queryFn: async () => {
const res = await client.api.teams[':teamId'].providers[':id'].models.$get({ const res = await client.api.providers[':id'].models.$get({
param: { teamId, id: editingProviderId! }, param: { id: editingProviderId! },
}) })
if (!res.ok) throw new Error('Failed to fetch models') if (!res.ok) throw new Error('Failed to fetch models')
return await res.json() return await res.json()
@@ -150,8 +150,8 @@ export function ProvidersSettings({ teamId }: ProvidersSettingsProps) {
// Update Mutation // Update Mutation
const updateMutation = useMutation({ const updateMutation = useMutation({
mutationFn: async ({ id, values }: { id: string; values: ProviderFormValues }) => { mutationFn: async ({ id, values }: { id: string; values: ProviderFormValues }) => {
const res = await client.api.teams[':teamId'].providers[':id'].$put({ const res = await client.api.providers[':id'].$put({
param: { teamId, id }, param: { id },
json: { json: {
config: values.config, config: values.config,
models: values.models, models: values.models,
@@ -173,8 +173,8 @@ export function ProvidersSettings({ teamId }: ProvidersSettingsProps) {
// Delete Mutation // Delete Mutation
const deleteMutation = useMutation({ const deleteMutation = useMutation({
mutationFn: async (id: string) => { mutationFn: async (id: string) => {
const res = await client.api.teams[':teamId'].providers[':id'].$delete({ const res = await client.api.providers[':id'].$delete({
param: { teamId, id }, param: { id },
}) })
if (!res.ok) throw new Error('Failed to delete provider') if (!res.ok) throw new Error('Failed to delete provider')
return await res.json() return await res.json()
@@ -57,8 +57,8 @@ export const SkillsConfigCard: React.FC<SkillsConfigCardProps> = ({ teamId }) =>
// Delete Skill // Delete Skill
const deleteMutation = useMutation({ const deleteMutation = useMutation({
mutationFn: async (id: string) => { mutationFn: async (id: string) => {
const res = await client.api.teams[':teamId'].skills[':id'].$delete({ const res = await client.api.skills[':id'].$delete({
param: { teamId, id }, param: { id },
}) })
if (!res.ok) throw new Error('Failed to delete skill') if (!res.ok) throw new Error('Failed to delete skill')
}, },
@@ -499,8 +499,8 @@ const ConfigSkillDialog = ({
setIsSaving(true) setIsSaving(true)
try { try {
const res = await client.api.teams[':teamId'].skills[':id'].config.$patch({ const res = await client.api.skills[':id'].config.$patch({
param: { teamId, id: skill.id }, param: { id: skill.id },
json: { config: finalConfig }, json: { config: finalConfig },
}) })
if (!res.ok) { if (!res.ok) {
+9 -9
View File
@@ -43,8 +43,8 @@ export default function ShareManager({
const { data: shareLink } = useQuery({ const { data: shareLink } = useQuery({
queryKey: ['share', shareId], queryKey: ['share', shareId],
queryFn: async () => { queryFn: async () => {
const res = await client.api.teams[':teamId'].shares[':shareId'].$get({ const res = await client.api.shares[':shareId'].$get({
param: { teamId, shareId }, param: { shareId },
}) })
if (!res.ok) throw new Error('Failed to fetch share link') if (!res.ok) throw new Error('Failed to fetch share link')
return (await res.json()) as unknown as ShareLinkInfo return (await res.json()) as unknown as ShareLinkInfo
@@ -101,8 +101,8 @@ export default function ShareManager({
} = useInfiniteQuery<AssetInfoPaginatedList>({ } = useInfiniteQuery<AssetInfoPaginatedList>({
queryKey: ['folder-children', teamId, currentFolderId, 'folder'], queryKey: ['folder-children', teamId, currentFolderId, 'folder'],
queryFn: async ({ pageParam }) => { queryFn: async ({ pageParam }) => {
const res = await client.api.teams[':teamId'].folders[':folderId'].children.$get({ const res = await client.api.folders[':folderId'].children.$get({
param: { teamId, folderId: currentFolderId! }, param: { folderId: currentFolderId! },
query: { query: {
assetType: 'folder', assetType: 'folder',
after: pageParam as string, after: pageParam as string,
@@ -124,8 +124,8 @@ export default function ShareManager({
} = useInfiniteQuery<AssetInfoPaginatedList>({ } = useInfiniteQuery<AssetInfoPaginatedList>({
queryKey: ['folder-children', teamId, currentFolderId, 'file'], queryKey: ['folder-children', teamId, currentFolderId, 'file'],
queryFn: async ({ pageParam }) => { queryFn: async ({ pageParam }) => {
const res = await client.api.teams[':teamId'].folders[':folderId'].children.$get({ const res = await client.api.folders[':folderId'].children.$get({
param: { teamId, folderId: currentFolderId! }, param: { folderId: currentFolderId! },
query: { query: {
assetType: 'file', assetType: 'file',
after: pageParam as string, after: pageParam as string,
@@ -198,11 +198,11 @@ export default function ShareManager({
onClearSelection: handleClearSelection, onClearSelection: handleClearSelection,
}) })
const $removeFromShare = client.api.teams[':teamId'].shares[':shareId'].assets[':assetId'].$delete const $removeFromShare = client.api.shares[':shareId'].assets[':assetId'].$delete
const { mutate: removeFromShare } = useMutation({ const { mutate: removeFromShare } = useMutation({
mutationFn: async (assetId: string) => { mutationFn: async (assetId: string) => {
const res = await $removeFromShare({ const res = await $removeFromShare({
param: { teamId, shareId, assetId }, param: { shareId, assetId },
}) })
if (!res.ok) throw new Error('Failed to remove') if (!res.ok) throw new Error('Failed to remove')
}, },
@@ -306,7 +306,7 @@ export default function ShareManager({
} }
/> />
<div style={{ width: rightSidebarWidth }} className="flex-shrink-0"> <div style={{ width: rightSidebarWidth }} className="flex-shrink-0">
<ShareSettingsSidebar teamId={teamId} shareLink={shareLink} /> <ShareSettingsSidebar shareLink={shareLink} />
</div> </div>
</> </>
)} )}
+4 -5
View File
@@ -20,11 +20,10 @@ import React, { useState } from 'react'
import { toast } from 'sonner' import { toast } from 'sonner'
import { DateTimePicker } from '@/ui/components/datetime-picker' import { DateTimePicker } from '@/ui/components/datetime-picker'
interface ShareSettingsSidebarProps { interface ShareSettingsSidebarProps {
teamId: string
shareLink: ShareLinkInfo shareLink: ShareLinkInfo
} }
export function ShareSettingsSidebar({ teamId, shareLink }: ShareSettingsSidebarProps) { export function ShareSettingsSidebar({ shareLink }: ShareSettingsSidebarProps) {
const queryClient = useQueryClient() const queryClient = useQueryClient()
const [password, setPassword] = useState('') const [password, setPassword] = useState('')
const [expireAt, setExpireAt] = useState<Date | undefined>( const [expireAt, setExpireAt] = useState<Date | undefined>(
@@ -45,18 +44,18 @@ export function ShareSettingsSidebar({ teamId, shareLink }: ShareSettingsSidebar
enabled: !!shareLink.projectId, enabled: !!shareLink.projectId,
}) })
const $updateShare = client.api.teams[':teamId'].shares[':shareId'].$put const $updateShare = client.api.shares[':shareId'].$put
const { mutate: updateShare } = useMutation({ const { mutate: updateShare } = useMutation({
mutationFn: async (json: UpdateShareLinkRequest) => { mutationFn: async (json: UpdateShareLinkRequest) => {
const res = await $updateShare({ const res = await $updateShare({
param: { teamId, shareId: shareLink.id }, param: { shareId: shareLink.id },
json, json,
}) })
if (!res.ok) throw new Error('Failed to update') if (!res.ok) throw new Error('Failed to update')
return await res.json() return await res.json()
}, },
onSuccess: () => { onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['shares', teamId, shareLink.projectId] }) queryClient.invalidateQueries({ queryKey: ['shares', shareLink.projectId] })
queryClient.invalidateQueries({ queryKey: ['share', shareLink.id] }) queryClient.invalidateQueries({ queryKey: ['share', shareLink.id] })
toast.success('Settings updated') toast.success('Settings updated')
}, },
+7 -9
View File
@@ -44,7 +44,7 @@ export function useFileSystemDnd({
}, },
}) })
const $reorderFolder = client.api.teams[':teamId'].folders[':folderId'].order.$patch const $reorderFolder = client.api.folders[':folderId'].order.$patch
const { mutate: reorderFolder } = useMutation< const { mutate: reorderFolder } = useMutation<
InferResponseType<typeof $reorderFolder, 200>, InferResponseType<typeof $reorderFolder, 200>,
Error, Error,
@@ -57,7 +57,7 @@ export function useFileSystemDnd({
}, },
}) })
const $reorderFile = client.api.teams[':teamId'].files[':fileId'].order.$patch const $reorderFile = client.api.files[':fileId'].order.$patch
const { mutate: reorderFile } = useMutation< const { mutate: reorderFile } = useMutation<
InferResponseType<typeof $reorderFile, 200>, InferResponseType<typeof $reorderFile, 200>,
Error, Error,
@@ -70,7 +70,7 @@ export function useFileSystemDnd({
}, },
}) })
const $addAssetToShare = client.api.teams[':teamId'].shares[':shareId'].assets.$post const $addAssetToShare = client.api.shares[':shareId'].assets.$post
const { mutate: addAssetToShare } = useMutation< const { mutate: addAssetToShare } = useMutation<
{ addedCount: number }, { addedCount: number },
Error, Error,
@@ -128,7 +128,7 @@ export function useFileSystemDnd({
addAssetToShare( addAssetToShare(
{ {
param: { teamId, shareId }, param: { shareId },
json: { assetIds }, json: { assetIds },
}, },
{ {
@@ -139,7 +139,7 @@ export function useFileSystemDnd({
toast.success(`Added ${data.addedCount} item(s) to share link`) toast.success(`Added ${data.addedCount} item(s) to share link`)
} }
queryClient.invalidateQueries({ queryClient.invalidateQueries({
queryKey: ['shares', teamId, projectId], queryKey: ['shares', projectId],
}) })
onClearSelection() onClearSelection()
}, },
@@ -178,8 +178,7 @@ export function useFileSystemDnd({
if (isFolder) { if (isFolder) {
reorderFolder( reorderFolder(
{ {
// eslint-disable-next-line @typescript-eslint/no-explicit-any param: { folderId: draggedId },
param: { teamId: teamId, folderId: draggedId } as any,
json: json:
position === 'before' position === 'before'
? { beforeIndex: targetItem.sortIndex ?? undefined } ? { beforeIndex: targetItem.sortIndex ?? undefined }
@@ -201,8 +200,7 @@ export function useFileSystemDnd({
} else { } else {
reorderFile( reorderFile(
{ {
// eslint-disable-next-line @typescript-eslint/no-explicit-any param: { fileId: draggedId },
param: { teamId: teamId, fileId: draggedId } as any,
json: json:
position === 'before' position === 'before'
? { beforeIndex: targetItem.sortIndex ?? undefined } ? { beforeIndex: targetItem.sortIndex ?? undefined }
@@ -16,13 +16,11 @@ const projectInfoQueryOptions = (projectId: string) => ({
}, },
}) })
const collectionInfoQueryOptions = (teamId: string, projectId: string, collectionId: string) => ({ const collectionInfoQueryOptions = (collectionId: string) => ({
queryKey: ['collections', teamId, projectId, collectionId], queryKey: ['collections', collectionId],
queryFn: async () => { queryFn: async () => {
const res = await client.api.teams[':teamId'].projects[':projectId'].collections[ const res = await client.api.collections[':collectionId'].$get({
':collectionId' param: { collectionId },
].$get({
param: { teamId, projectId, collectionId },
}) })
if (!res.ok) throw new Error('Failed to fetch collection') if (!res.ok) throw new Error('Failed to fetch collection')
return await res.json() return await res.json()
@@ -40,17 +38,14 @@ function CollectionPage() {
const { data: projectInfo } = useSuspenseQuery(projectInfoQueryOptions(projectId)) const { data: projectInfo } = useSuspenseQuery(projectInfoQueryOptions(projectId))
const { data: collection, refetch: refetchCollection } = useQuery({ const { data: collection, refetch: refetchCollection } = useQuery({
...collectionInfoQueryOptions(teamId || '', projectId, collectionId), ...collectionInfoQueryOptions(collectionId),
enabled: !!teamId,
}) })
const { mutate: updateCollection } = useMutation({ const { mutate: updateCollection } = useMutation({
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
mutationFn: async (updates: { name?: string; filter?: any }) => { mutationFn: async (updates: { name?: string; filter?: any }) => {
const res = await client.api.teams[':teamId'].projects[':projectId'].collections[ const res = await client.api.collections[':collectionId'].$patch({
':collectionId' param: { collectionId },
].$patch({
param: { teamId: teamId!, projectId, collectionId },
json: updates, json: updates,
}) })
if (!res.ok) throw new Error('Failed to update collection') if (!res.ok) throw new Error('Failed to update collection')
@@ -64,15 +59,15 @@ function CollectionPage() {
const rootFolderId = projectInfo?.rootFolder const rootFolderId = projectInfo?.rootFolder
const { data: rootFolder } = useQuery({ const { data: rootFolder } = useQuery({
queryKey: ['folders', teamId!, rootFolderId!], queryKey: ['folders', rootFolderId!],
queryFn: async () => { queryFn: async () => {
const res = await client.api.teams[':teamId'].folders[':folderId'].$get({ const res = await client.api.folders[':folderId'].$get({
param: { teamId: teamId!, folderId: rootFolderId! }, param: { folderId: rootFolderId! },
}) })
if (!res.ok) throw new Error('Failed to fetch folder') if (!res.ok) throw new Error('Failed to fetch folder')
return await res.json() return await res.json()
}, },
enabled: !!teamId && !!rootFolderId, enabled: !!rootFolderId,
}) })
if (!teamId || !rootFolderId || !rootFolder || !collection) { if (!teamId || !rootFolderId || !rootFolder || !collection) {
@@ -34,7 +34,7 @@ function FileViewPage() {
const [leftSidebarWidth, setLeftSidebarWidth] = useState(280) const [leftSidebarWidth, setLeftSidebarWidth] = useState(280)
const [rightSidebarWidth, setRightSidebarWidth] = useState(360) const [rightSidebarWidth, setRightSidebarWidth] = useState(360)
const [annotations, setAnnotations] = useState<Annotation[]>([]) const [annotations, setAnnotations] = useState<Annotation[]>([])
const $patchMetadata = client.api.teams[':teamId'].files[':fileId'].metadata.$patch const $patchMetadata = client.api.files[':fileId'].metadata.$patch
const { mutate: patchMetadata } = useMutation< const { mutate: patchMetadata } = useMutation<
InferResponseType<typeof $patchMetadata>, InferResponseType<typeof $patchMetadata>,
Error, Error,
@@ -65,10 +65,10 @@ function FileViewPage() {
isError: isStackError, isError: isStackError,
isFetching: isStackFetching, isFetching: isStackFetching,
} = useQuery({ } = useQuery({
queryKey: ['teams', teamId, 'files', fileId], queryKey: ['files', fileId],
queryFn: async () => { queryFn: async () => {
const res = await client.api.teams[':teamId'].files[':fileId'].$get({ const res = await client.api.files[':fileId'].$get({
param: { teamId: teamId!, fileId: fileId }, param: { fileId: fileId },
}) })
if (!res.ok) throw new Error('Failed to fetch stack') if (!res.ok) throw new Error('Failed to fetch stack')
return await res.json() return await res.json()
@@ -83,10 +83,10 @@ function FileViewPage() {
isError: isVersionError, isError: isVersionError,
isFetching: isVersionFetching, isFetching: isVersionFetching,
} = useQuery({ } = useQuery({
queryKey: ['teams', teamId, 'files', versionAssetId], queryKey: ['files', versionAssetId],
queryFn: async () => { queryFn: async () => {
const res = await client.api.teams[':teamId'].files[':fileId'].$get({ const res = await client.api.files[':fileId'].$get({
param: { teamId: teamId!, fileId: versionAssetId! }, param: { fileId: versionAssetId! },
}) })
if (!res.ok) throw new Error('Failed to fetch version') if (!res.ok) throw new Error('Failed to fetch version')
return await res.json() return await res.json()
@@ -96,10 +96,10 @@ function FileViewPage() {
}) })
const { data: versionsList } = useQuery({ const { data: versionsList } = useQuery({
queryKey: ['projects', projectId, 'version_stacks', fileId, 'versions'], queryKey: ['version_stacks', fileId, 'versions'],
queryFn: async () => { queryFn: async () => {
const res = await client.api.projects[':projectId'].version_stacks[':stackId'].versions.$get({ const res = await client.api.version_stacks[':stackId'].versions.$get({
param: { projectId: projectId, stackId: fileId }, param: { stackId: fileId },
}) })
if (!res.ok) throw new Error('Failed to fetch versions') if (!res.ok) throw new Error('Failed to fetch versions')
return await res.json() return await res.json()
@@ -180,13 +180,13 @@ function FileViewPage() {
if (!teamId) return if (!teamId) return
patchMetadata( patchMetadata(
{ {
param: { teamId: teamId, fileId: activeFileId }, param: { fileId: activeFileId },
json: [{ key: fieldId, value }] as InferRequestType<typeof $patchMetadata>['json'], json: [{ key: fieldId, value }] as InferRequestType<typeof $patchMetadata>['json'],
}, },
{ {
onSuccess: () => { onSuccess: () => {
queryClient.invalidateQueries({ queryClient.invalidateQueries({
queryKey: ['teams', teamId, 'files', activeFileId], queryKey: ['files', activeFileId],
}) })
}, },
}, },
@@ -216,7 +216,6 @@ function FileViewPage() {
<> <>
<div style={{ width: leftSidebarWidth }} className="flex-shrink-0"> <div style={{ width: leftSidebarWidth }} className="flex-shrink-0">
<FileViewerLeftSidebar <FileViewerLeftSidebar
teamId={teamId!}
projectId={projectId} projectId={projectId}
currentAssetId={activeFileId} currentAssetId={activeFileId}
parentFolderId={ parentFolderId={
@@ -29,15 +29,15 @@ function FolderPage() {
const rootFolderId = projectInfo?.rootFolder const rootFolderId = projectInfo?.rootFolder
const { data: rootFolder } = useQuery({ const { data: rootFolder } = useQuery({
queryKey: ['folders', teamId!, rootFolderId!], queryKey: ['folders', rootFolderId!],
queryFn: () => queryFn: () =>
(async () => { (async () => {
const res = await client.api.teams[':teamId'].folders[':folderId'].$get({ const res = await client.api.folders[':folderId'].$get({
param: { teamId: teamId!, folderId: rootFolderId! }, param: { folderId: rootFolderId! },
}) })
return await res.json() return await res.json()
})(), })(),
enabled: !!teamId && !!rootFolderId, enabled: !!rootFolderId,
}) })
if (!teamId || !rootFolderId || !rootFolder) { if (!teamId || !rootFolderId || !rootFolder) {
+4 -4
View File
@@ -29,15 +29,15 @@ function ProjectPage() {
const rootFolderId = projectInfo?.rootFolder const rootFolderId = projectInfo?.rootFolder
const { data: rootFolder } = useQuery({ const { data: rootFolder } = useQuery({
queryKey: ['folders', teamId!, rootFolderId!], queryKey: ['folders', rootFolderId!],
queryFn: async () => { queryFn: async () => {
const res = await client.api.teams[':teamId'].folders[':folderId'].$get({ const res = await client.api.folders[':folderId'].$get({
param: { teamId: teamId!, folderId: rootFolderId! }, param: { folderId: rootFolderId! },
}) })
if (!res.ok) throw new Error('failed to fetch folder') if (!res.ok) throw new Error('failed to fetch folder')
return await res.json() return await res.json()
}, },
enabled: !!teamId && !!rootFolderId, enabled: !!rootFolderId,
}) })
if (!teamId || !rootFolderId || !rootFolder) { if (!teamId || !rootFolderId || !rootFolder) {
@@ -29,15 +29,15 @@ function RecentlyDeletedPage() {
const rootFolderId = projectInfo?.rootFolder const rootFolderId = projectInfo?.rootFolder
const { data: rootFolder } = useQuery({ const { data: rootFolder } = useQuery({
queryKey: ['folders', teamId!, rootFolderId!], queryKey: ['folders', rootFolderId!],
queryFn: () => queryFn: () =>
(async () => { (async () => {
const res = await client.api.teams[':teamId'].folders[':folderId'].$get({ const res = await client.api.folders[':folderId'].$get({
param: { teamId: teamId!, folderId: rootFolderId! }, param: { folderId: rootFolderId! },
}) })
return await res.json() return await res.json()
})(), })(),
enabled: !!teamId && !!rootFolderId, enabled: !!rootFolderId,
}) })
if (!teamId || !rootFolderId || !rootFolder) { if (!teamId || !rootFolderId || !rootFolder) {
@@ -29,15 +29,15 @@ function SharePage() {
const rootFolderId = projectInfo?.rootFolder const rootFolderId = projectInfo?.rootFolder
const { data: rootFolder } = useQuery({ const { data: rootFolder } = useQuery({
queryKey: ['folders', teamId!, rootFolderId!], queryKey: ['folders', rootFolderId!],
queryFn: async () => { queryFn: async () => {
const res = await client.api.teams[':teamId'].folders[':folderId'].$get({ const res = await client.api.folders[':folderId'].$get({
param: { teamId: teamId!, folderId: rootFolderId! }, param: { folderId: rootFolderId! },
}) })
if (!res.ok) throw new Error('Failed to fetch folder') if (!res.ok) throw new Error('Failed to fetch folder')
return await res.json() return await res.json()
}, },
enabled: !!teamId && !!rootFolderId, enabled: !!rootFolderId,
}) })
if (!teamId || !rootFolderId || !rootFolder) { if (!teamId || !rootFolderId || !rootFolder) {