mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-25 09:50:25 +00:00
refactor(monorepo): decouple api and webui into workspaces packages
This commit is contained in:
@@ -0,0 +1,184 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { agentService } from '@shumai/core/src/agent/agent'
|
||||
import { authzService } from '@shumai/core/src/authz/authz'
|
||||
import app from './agent'
|
||||
|
||||
vi.mock('@shumai/core/src/agent/agent')
|
||||
vi.mock('@shumai/core/src/authz/authz')
|
||||
|
||||
describe('Agent API', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
vi.mocked(authzService.hasPermission).mockResolvedValue(undefined)
|
||||
})
|
||||
|
||||
describe('GET /teams/:teamId/agents', () => {
|
||||
it('returns list of agents', async () => {
|
||||
const mockAgents = [
|
||||
{
|
||||
id: 'agent1',
|
||||
user: { name: 'Bot 1', image: 'avatar1' },
|
||||
type: 'chat',
|
||||
providerId: 'prov1',
|
||||
modelId: 'model1',
|
||||
soul: 'Soul',
|
||||
config: {
|
||||
provider: 'prov1',
|
||||
model: 'model1',
|
||||
thinkingLevel: 'high',
|
||||
systemPrompt: 'prompt',
|
||||
},
|
||||
skills: [],
|
||||
},
|
||||
]
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.mocked(agentService.listAgents).mockResolvedValue(mockAgents as any)
|
||||
|
||||
const res = await app.request('/teams/team1/agents', {
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data).toHaveLength(1)
|
||||
expect(data[0].name).toBe('Bot 1')
|
||||
expect(data[0].providerId).toBe('prov1')
|
||||
})
|
||||
})
|
||||
|
||||
describe('POST /teams/:teamId/agents', () => {
|
||||
it('creates an agent', async () => {
|
||||
const mockAgent = {
|
||||
id: 'agent2',
|
||||
user: { name: 'New Agent', image: 'avatar2' },
|
||||
type: 'chat',
|
||||
providerId: 'prov1',
|
||||
modelId: 'model1',
|
||||
soul: 'New Soul',
|
||||
config: { provider: 'prov1', model: 'model1', thinkingLevel: 'low', systemPrompt: 'p' },
|
||||
skills: [],
|
||||
}
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.mocked(agentService.createAgent).mockResolvedValue(mockAgent as any)
|
||||
|
||||
const res = await app.request('/teams/team1/agents', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
name: 'New Agent',
|
||||
type: 'chat',
|
||||
providerId: 'prov1',
|
||||
modelId: 'model1',
|
||||
thinkingLevel: 'low',
|
||||
systemPrompt: 'p',
|
||||
soul: 'New Soul',
|
||||
skills: ['skill1'],
|
||||
}),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data.name).toBe('New Agent')
|
||||
expect(data.soul).toBe('New Soul')
|
||||
})
|
||||
|
||||
it('validates request', async () => {
|
||||
const res = await app.request('/teams/team1/agents', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
name: '',
|
||||
type: 'chat',
|
||||
}),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(400)
|
||||
})
|
||||
})
|
||||
|
||||
describe('PUT /agents/:agentId', () => {
|
||||
it('updates an agent', async () => {
|
||||
const mockAgent = {
|
||||
id: 'agent1',
|
||||
user: { name: 'Updated Agent', image: 'avatar1' },
|
||||
type: 'autofill',
|
||||
providerId: 'prov1',
|
||||
modelId: 'model1',
|
||||
soul: 'Updated Soul',
|
||||
config: { provider: 'prov1', model: 'model1' },
|
||||
skills: [],
|
||||
}
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.mocked(agentService.updateAgent).mockResolvedValue(mockAgent as any)
|
||||
|
||||
const res = await app.request('/agents/agent1', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
name: 'Updated Agent',
|
||||
type: 'autofill',
|
||||
providerId: 'prov1',
|
||||
modelId: 'model1',
|
||||
soul: 'Updated Soul',
|
||||
skills: [],
|
||||
}),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data.name).toBe('Updated Agent')
|
||||
expect(data.soul).toBe('Updated Soul')
|
||||
})
|
||||
})
|
||||
|
||||
describe('DELETE /agents/:agentId', () => {
|
||||
it('deletes an agent', async () => {
|
||||
const res = await app.request('/agents/agent1', {
|
||||
method: 'DELETE',
|
||||
})
|
||||
|
||||
expect(res.status).toBe(204)
|
||||
expect(agentService.deleteAgent).toHaveBeenCalledWith({ agentId: 'agent1' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('GET /agent-sessions/:sessionId/entries', () => {
|
||||
it('returns entries of agent session if user is admin', async () => {
|
||||
const mockEntries = [
|
||||
{
|
||||
id: 'entry1',
|
||||
sessionId: 'session1',
|
||||
entry: { step: 1, message: 'Step 1' },
|
||||
},
|
||||
]
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.mocked(agentService.getSessionEntries).mockResolvedValue(mockEntries as any)
|
||||
|
||||
const res = await app.request('/agent-sessions/session1/entries', {
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data).toHaveLength(1)
|
||||
expect(data[0].id).toBe('entry1')
|
||||
expect(data[0].entry.step).toBe(1)
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: undefined,
|
||||
permission: 'Admin',
|
||||
type: 'agentSession',
|
||||
id: 'session1',
|
||||
})
|
||||
})
|
||||
|
||||
it('denies access if user is not admin', async () => {
|
||||
vi.mocked(authzService.hasPermission).mockRejectedValue(new Error('Forbidden'))
|
||||
|
||||
const res = await app.request('/agent-sessions/session1/entries', {
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
|
||||
expect(res.status).toBe(500)
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,169 @@
|
||||
import { Hono } from 'hono'
|
||||
import { zValidator } from '@hono/zod-validator'
|
||||
import { agentService } from '@shumai/core/src/agent/agent'
|
||||
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
import {
|
||||
createAgentRequestSchema,
|
||||
updateAgentRequestSchema,
|
||||
AgentInfo,
|
||||
AgentType,
|
||||
} from '@shumai/dtos'
|
||||
|
||||
import type { Prisma } from '@shumai/db'
|
||||
|
||||
type User = Prisma.UserGetPayload<Record<string, never>>
|
||||
|
||||
const route = new Hono<{ Variables: { user: User } }>()
|
||||
.get('/teams/:teamId/agents', async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
const userReq = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user: userReq,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const agents = await agentService.listAgents({ teamId })
|
||||
|
||||
const res: AgentInfo[] = agents.map((agent) => {
|
||||
const config = agent.config as unknown as PrismaJson.AgentConfig
|
||||
return {
|
||||
id: agent.id,
|
||||
name: agent.user.name,
|
||||
type: agent.type as AgentType,
|
||||
enabled: agent.enabled,
|
||||
avatar: agent.user.image || undefined,
|
||||
providerId: agent.providerId || undefined,
|
||||
modelId: agent.modelId || undefined,
|
||||
thinkingLevel: config.thinkingLevel || '',
|
||||
systemPrompt: config.systemPrompt,
|
||||
soul: agent.soul || undefined,
|
||||
skills: agent.skills.map((s) => ({
|
||||
id: s.id,
|
||||
skillId: s.skillId,
|
||||
skill: s.skill,
|
||||
})),
|
||||
}
|
||||
})
|
||||
|
||||
return c.json(res, 200)
|
||||
})
|
||||
.post('/teams/:teamId/agents', zValidator('json', createAgentRequestSchema), async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
const userReq = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user: userReq,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const agent = await agentService.createAgent({
|
||||
teamId,
|
||||
...req,
|
||||
})
|
||||
|
||||
if (!agent) throw new Error('failed to create agent')
|
||||
|
||||
const config = agent.config as unknown as PrismaJson.AgentConfig
|
||||
const info: AgentInfo = {
|
||||
id: agent.id,
|
||||
name: agent.user.name,
|
||||
type: agent.type as AgentType,
|
||||
enabled: agent.enabled,
|
||||
avatar: agent.user.image || undefined,
|
||||
providerId: agent.providerId || undefined,
|
||||
modelId: agent.modelId || undefined,
|
||||
thinkingLevel: config.thinkingLevel || '',
|
||||
systemPrompt: config.systemPrompt,
|
||||
soul: agent.soul || undefined,
|
||||
skills: agent.skills.map((s) => ({
|
||||
id: s.id,
|
||||
skillId: s.skillId,
|
||||
skill: s.skill,
|
||||
})),
|
||||
}
|
||||
|
||||
return c.json(info, 200)
|
||||
})
|
||||
.put('/agents/:agentId', zValidator('json', updateAgentRequestSchema), async (c) => {
|
||||
const agentId = c.req.param('agentId')
|
||||
const userReq = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user: userReq,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Agent,
|
||||
id: agentId,
|
||||
})
|
||||
|
||||
const agent = await agentService.updateAgent({
|
||||
agentId,
|
||||
...req,
|
||||
})
|
||||
|
||||
const config = agent.config as unknown as PrismaJson.AgentConfig
|
||||
const info: AgentInfo = {
|
||||
id: agent.id,
|
||||
name: agent.user.name,
|
||||
type: agent.type as AgentType,
|
||||
enabled: agent.enabled,
|
||||
avatar: agent.user.image || undefined,
|
||||
providerId: agent.providerId || undefined,
|
||||
modelId: agent.modelId || undefined,
|
||||
thinkingLevel: config.thinkingLevel || '',
|
||||
systemPrompt: config.systemPrompt,
|
||||
soul: agent.soul || undefined,
|
||||
skills: agent.skills.map((s) => ({
|
||||
id: s.id,
|
||||
skillId: s.skillId,
|
||||
skill: s.skill,
|
||||
})),
|
||||
}
|
||||
|
||||
return c.json(info, 200)
|
||||
})
|
||||
.delete('/agents/:agentId', async (c) => {
|
||||
const agentId = c.req.param('agentId')
|
||||
const userReq = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user: userReq,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Agent,
|
||||
id: agentId,
|
||||
})
|
||||
|
||||
await agentService.deleteAgent({
|
||||
agentId,
|
||||
})
|
||||
|
||||
return new Response(null, { status: 204 })
|
||||
})
|
||||
.get('/agent-sessions/:sessionId/entries', async (c) => {
|
||||
const sessionId = c.req.param('sessionId')
|
||||
const userReq = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user: userReq,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.AgentSession,
|
||||
id: sessionId,
|
||||
})
|
||||
|
||||
const entries = await agentService.getSessionEntries({ sessionId })
|
||||
const infos = entries.map((entry) => ({
|
||||
id: entry.id,
|
||||
sessionId: entry.sessionId,
|
||||
entry: entry.entry,
|
||||
}))
|
||||
|
||||
return c.json(infos, 200)
|
||||
})
|
||||
|
||||
export default route
|
||||
@@ -0,0 +1,69 @@
|
||||
import { describe, expect, it, vi, beforeEach } from 'vitest'
|
||||
import { Hono } from 'hono'
|
||||
import attachmentRoute from './attachment'
|
||||
import { assetService } from '@shumai/core/src/asset/asset'
|
||||
import { AssetType } from '@shumai/db'
|
||||
import { authMiddleware } from './middleware/auth'
|
||||
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
|
||||
vi.mock('./middleware/auth', () => ({
|
||||
// any is used here because Hono's Context and Next types are complex to mock in vitest.mock
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
authMiddleware: async (c: any, next: any) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
c.set('user', { id: 'user1', name: 'Test User' } as any)
|
||||
await next()
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@shumai/core/src/authz/authz')
|
||||
vi.mock('@shumai/core/src/asset/asset')
|
||||
|
||||
vi.mock('@shumai/core/src/s3/s3', () => ({
|
||||
s3Service: {
|
||||
presign: vi.fn().mockResolvedValue('http://mock-s3-url'),
|
||||
},
|
||||
}))
|
||||
|
||||
describe('Attachment API', () => {
|
||||
const app = new Hono().use('*', authMiddleware).route('/', attachmentRoute)
|
||||
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
vi.mocked(authzService.hasPermission).mockResolvedValue(undefined)
|
||||
})
|
||||
|
||||
it('POST /projects/:projectId/attachments', async () => {
|
||||
// We only need the id for this test
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.mocked(assetService.createAsset).mockResolvedValue({ id: 'asset1' } as any)
|
||||
|
||||
const res = await app.request('/projects/project1/attachments', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Authorization: 'Bearer test' },
|
||||
body: JSON.stringify({
|
||||
fileName: 'test.txt',
|
||||
contentType: 'text/plain',
|
||||
size: 100,
|
||||
}),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.id).toBe('asset1')
|
||||
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.objectContaining({
|
||||
name: 'test.txt',
|
||||
type: AssetType.attachment,
|
||||
projectId: 'project1',
|
||||
}),
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,49 @@
|
||||
import { Hono } from 'hono'
|
||||
import { zValidator } from '@hono/zod-validator'
|
||||
import { postAttachmentRequestSchema } from '@shumai/dtos'
|
||||
import { assetService } from '@shumai/core/src/asset/asset'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { AssetType } from '@shumai/db'
|
||||
import { ulid } from 'ulid'
|
||||
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
import type { Prisma } from '@shumai/db'
|
||||
|
||||
type User = Prisma.UserGetPayload<Record<string, never>>
|
||||
|
||||
const route = new Hono<{ Variables: { user: User } }>().post(
|
||||
'/projects/:projectId/attachments',
|
||||
zValidator('json', postAttachmentRequestSchema),
|
||||
async (c) => {
|
||||
const projectId = c.req.param('projectId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Project,
|
||||
id: projectId,
|
||||
})
|
||||
|
||||
const key = `attachments/${ulid()}/${req.fileName}`
|
||||
|
||||
const assetInfo = await assetService.createAsset({
|
||||
name: req.fileName,
|
||||
type: AssetType.attachment,
|
||||
projectId: projectId,
|
||||
key: key,
|
||||
sizeByte: req.size,
|
||||
contentType: req.contentType,
|
||||
creatorId: user.id,
|
||||
})
|
||||
|
||||
const uploadUrl = await s3Service.presign(process.env.S3_BUCKET || 'shumai', key, 'PUT')
|
||||
|
||||
return c.json({
|
||||
id: assetInfo.id,
|
||||
uploadUrl: uploadUrl,
|
||||
})
|
||||
},
|
||||
)
|
||||
|
||||
export default route
|
||||
@@ -0,0 +1,33 @@
|
||||
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { Hono } from 'hono'
|
||||
import authnRoute from './authn'
|
||||
import { teamService } from '@shumai/core/src/team/team'
|
||||
|
||||
describe('authn api', () => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
let mockGetSignupInfo: any
|
||||
|
||||
beforeEach(() => {
|
||||
mockGetSignupInfo = vi.spyOn(teamService, 'getSignupInfo')
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('GET /signup-info', async () => {
|
||||
mockGetSignupInfo.mockResolvedValue({
|
||||
userCount: 5,
|
||||
enablePublicSignup: true,
|
||||
})
|
||||
|
||||
const app = new Hono().route('/', authnRoute)
|
||||
const res = await app.request('/signup-info')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({
|
||||
userCount: 5,
|
||||
enablePublicSignup: true,
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,49 @@
|
||||
import { Hono } from 'hono'
|
||||
import { teamService } from '@shumai/core/src/team/team'
|
||||
import { auth } from '@shumai/core/src/auth/auth'
|
||||
import { z } from 'zod'
|
||||
import { zValidator } from '@hono/zod-validator'
|
||||
import { prisma } from '@shumai/db'
|
||||
import { ulid } from 'ulid'
|
||||
|
||||
const app = new Hono()
|
||||
|
||||
const identifySchema = z.object({
|
||||
username: z.string().min(1),
|
||||
email: z.string().email(),
|
||||
})
|
||||
|
||||
const route = app
|
||||
.get('/signup-info', async (c) => {
|
||||
const info = await teamService.getSignupInfo()
|
||||
return c.json({
|
||||
userCount: info.userCount,
|
||||
enablePublicSignup: info.enablePublicSignup,
|
||||
})
|
||||
})
|
||||
.get('/me', async (c) => {
|
||||
const session = await auth.api.getSession({
|
||||
headers: c.req.raw.headers,
|
||||
})
|
||||
return c.json({ id: session?.user?.id ?? null })
|
||||
})
|
||||
.post('/identify', zValidator('json', identifySchema), async (c) => {
|
||||
const { username, email } = c.req.valid('json')
|
||||
|
||||
const dummyEmail = `guest_${ulid()}@guest.local`
|
||||
const user = await prisma.user.create({
|
||||
data: {
|
||||
name: username,
|
||||
email: dummyEmail,
|
||||
guestEmail: email,
|
||||
type: 'human',
|
||||
},
|
||||
})
|
||||
|
||||
return c.json({ id: user.id })
|
||||
})
|
||||
.all('/auth/*', (c) => {
|
||||
return auth.handler(c.req.raw)
|
||||
})
|
||||
|
||||
export default route
|
||||
@@ -0,0 +1,185 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { collectionService } from '@shumai/core/src/collection/collection'
|
||||
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
import { Hono, Context, Next } from 'hono'
|
||||
import collectionRoute from './collection'
|
||||
|
||||
vi.mock('./middleware/auth', () => ({
|
||||
authMiddleware: async (c: Context, next: Next) => {
|
||||
c.set('user', { id: 'user-1', name: 'Test User' })
|
||||
await next()
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@shumai/core/src/authz/authz', () => ({
|
||||
authzService: {
|
||||
hasPermission: vi.fn().mockResolvedValue(undefined),
|
||||
},
|
||||
Permission: {
|
||||
Read: 'Read',
|
||||
Edit: 'Edit',
|
||||
Admin: 'Admin',
|
||||
},
|
||||
ResourceType: {
|
||||
Project: 'project',
|
||||
Collection: 'collection',
|
||||
},
|
||||
}))
|
||||
|
||||
describe('Collection API', () => {
|
||||
const projectId = 'project-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(() => {
|
||||
vi.restoreAllMocks()
|
||||
vi.mocked(authzService.hasPermission).mockResolvedValue(undefined)
|
||||
})
|
||||
|
||||
it('POST /projects/:projectId/collections', async () => {
|
||||
const mockCreate = vi.spyOn(collectionService, 'createCollection').mockResolvedValue({
|
||||
id: collectionId,
|
||||
name: 'New Collection',
|
||||
filter: {
|
||||
sourceFolderId: 'root-1',
|
||||
searchFilter: { conditions: [], operator: 'AND', recursively: true },
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} as any,
|
||||
projectId,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
})
|
||||
|
||||
const res = await app.request(`/projects/${projectId}/collections`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
name: 'New Collection',
|
||||
filter: {
|
||||
sourceFolderId: 'root-1',
|
||||
searchFilter: { conditions: [], operator: 'AND', recursively: true },
|
||||
},
|
||||
}),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(mockCreate).toHaveBeenCalledWith(projectId, expect.any(Object))
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: expect.any(Object),
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Project,
|
||||
id: projectId,
|
||||
})
|
||||
})
|
||||
|
||||
it('GET /projects/:projectId/collections', async () => {
|
||||
const mockList = vi.spyOn(collectionService, 'listCollections').mockResolvedValue({
|
||||
data: [
|
||||
{
|
||||
id: collectionId,
|
||||
name: 'Col 1',
|
||||
filter: {
|
||||
sourceFolderId: 'root-1',
|
||||
searchFilter: { conditions: [], operator: 'AND', recursively: true },
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} as any,
|
||||
projectId,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
},
|
||||
],
|
||||
pageInfo: { total: 1 },
|
||||
})
|
||||
|
||||
const res = await app.request(`/projects/${projectId}/collections`)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.data).toHaveLength(1)
|
||||
expect(mockList).toHaveBeenCalled()
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: expect.any(Object),
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Project,
|
||||
id: projectId,
|
||||
})
|
||||
})
|
||||
|
||||
it('GET /collections/:collectionId', async () => {
|
||||
const mockGet = vi.spyOn(collectionService, 'getCollection').mockResolvedValue({
|
||||
id: collectionId,
|
||||
name: 'Col 1',
|
||||
filter: {
|
||||
sourceFolderId: 'root-1',
|
||||
searchFilter: { conditions: [], operator: 'AND', recursively: true },
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} as any,
|
||||
projectId,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
})
|
||||
|
||||
const res = await app.request(`/collections/${collectionId}`)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(mockGet).toHaveBeenCalledWith(collectionId)
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: expect.any(Object),
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Collection,
|
||||
id: collectionId,
|
||||
})
|
||||
})
|
||||
|
||||
it('PATCH /collections/:collectionId', async () => {
|
||||
const mockUpdate = vi.spyOn(collectionService, 'updateCollection').mockResolvedValue({
|
||||
id: collectionId,
|
||||
name: 'Updated Name',
|
||||
filter: {
|
||||
sourceFolderId: 'root-1',
|
||||
searchFilter: { conditions: [], operator: 'AND', recursively: true },
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} as any,
|
||||
projectId,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
})
|
||||
|
||||
const res = await app.request(`/collections/${collectionId}`, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name: 'Updated Name' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(mockUpdate).toHaveBeenCalledWith(collectionId, { name: 'Updated Name' })
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: expect.any(Object),
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Collection,
|
||||
id: collectionId,
|
||||
})
|
||||
})
|
||||
|
||||
it('DELETE /collections/:collectionId', async () => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const mockDelete = vi.spyOn(collectionService, 'deleteCollection').mockResolvedValue({} as any)
|
||||
|
||||
const res = await app.request(`/collections/${collectionId}`, {
|
||||
method: 'DELETE',
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(mockDelete).toHaveBeenCalledWith(collectionId)
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: expect.any(Object),
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Collection,
|
||||
id: collectionId,
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,122 @@
|
||||
import { zValidator } from '@hono/zod-validator'
|
||||
import { Hono } from 'hono'
|
||||
import { collectionService } from '@shumai/core/src/collection/collection'
|
||||
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
import {
|
||||
createCollectionRequestSchema,
|
||||
updateCollectionRequestSchema,
|
||||
listCollectionsRequestSchema,
|
||||
CollectionInfo,
|
||||
CollectionFilter,
|
||||
} from '@shumai/dtos'
|
||||
import type { Prisma } from '@shumai/db'
|
||||
|
||||
type User = Prisma.UserGetPayload<Record<string, never>>
|
||||
|
||||
function toCollectionInfo(c: Prisma.CollectionGetPayload<Record<string, never>>): CollectionInfo {
|
||||
return {
|
||||
id: c.id,
|
||||
name: c.name,
|
||||
filter: c.filter as unknown as CollectionFilter,
|
||||
projectId: c.projectId,
|
||||
createdAt: c.createdAt.toISOString(),
|
||||
updatedAt: c.updatedAt.toISOString(),
|
||||
}
|
||||
}
|
||||
|
||||
const route = new Hono<{ Variables: { user: User } }>()
|
||||
.post(
|
||||
'/projects/:projectId/collections',
|
||||
zValidator('json', createCollectionRequestSchema),
|
||||
async (c) => {
|
||||
const { projectId } = c.req.param()
|
||||
const req = c.req.valid('json')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Project,
|
||||
id: projectId,
|
||||
})
|
||||
|
||||
const collection = await collectionService.createCollection(projectId, req)
|
||||
return c.json(toCollectionInfo(collection))
|
||||
},
|
||||
)
|
||||
.get(
|
||||
'/projects/:projectId/collections',
|
||||
zValidator('query', listCollectionsRequestSchema),
|
||||
async (c) => {
|
||||
const { projectId } = c.req.param()
|
||||
const req = c.req.valid('query')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Project,
|
||||
id: projectId,
|
||||
})
|
||||
|
||||
const collections = await collectionService.listCollections(projectId, req)
|
||||
return c.json({
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
data: collections.data.map((c: any) => toCollectionInfo(c)),
|
||||
pageInfo: collections.pageInfo,
|
||||
})
|
||||
},
|
||||
)
|
||||
.get('/collections/:collectionId', async (c) => {
|
||||
const { collectionId } = c.req.param()
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Collection,
|
||||
id: collectionId,
|
||||
})
|
||||
|
||||
const collection = await collectionService.getCollection(collectionId)
|
||||
if (!collection) {
|
||||
return c.json({ error: 'Collection not found' }, 404)
|
||||
}
|
||||
|
||||
return c.json(toCollectionInfo(collection))
|
||||
})
|
||||
.patch(
|
||||
'/collections/:collectionId',
|
||||
zValidator('json', updateCollectionRequestSchema),
|
||||
async (c) => {
|
||||
const { collectionId } = c.req.param()
|
||||
const req = c.req.valid('json')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Collection,
|
||||
id: collectionId,
|
||||
})
|
||||
|
||||
const collection = await collectionService.updateCollection(collectionId, req)
|
||||
return c.json(toCollectionInfo(collection))
|
||||
},
|
||||
)
|
||||
.delete('/collections/:collectionId', async (c) => {
|
||||
const { collectionId } = c.req.param()
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Collection,
|
||||
id: collectionId,
|
||||
})
|
||||
|
||||
await collectionService.deleteCollection(collectionId)
|
||||
return c.json({ success: true })
|
||||
})
|
||||
|
||||
export default route
|
||||
@@ -0,0 +1,405 @@
|
||||
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { Hono, type Context, type Next } from 'hono'
|
||||
import { prisma } from '@shumai/db'
|
||||
import fileRoute from './file'
|
||||
import { assetService } from '@shumai/core/src/asset/asset'
|
||||
import { metadataService } from '@shumai/core/src/metadata/metadata'
|
||||
import { notificationService } from '@shumai/core/src/notification/notification'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { authMiddleware } from './middleware/auth'
|
||||
import { authzService, ResourceType, Permission } from '@shumai/core/src/authz/authz'
|
||||
|
||||
vi.mock('@shumai/core/src/authz/authz', () => ({
|
||||
authzService: {
|
||||
hasPermission: vi.fn().mockResolvedValue(undefined),
|
||||
},
|
||||
Permission: {
|
||||
Read: 'Read',
|
||||
Edit: 'Edit',
|
||||
Admin: 'Admin',
|
||||
},
|
||||
ResourceType: {
|
||||
Asset: 'asset',
|
||||
Team: 'team',
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('./middleware/auth', () => ({
|
||||
authMiddleware: async (c: Context, next: Next) => {
|
||||
c.set('user', { id: 'user1', name: 'Test User' })
|
||||
await next()
|
||||
},
|
||||
}))
|
||||
|
||||
describe('file api', () => {
|
||||
beforeEach(() => {
|
||||
vi.mocked(authzService.hasPermission).mockClear()
|
||||
|
||||
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, 'deleteAssets').mockImplementation(vi.fn())
|
||||
vi.spyOn(assetService, 'createComment').mockImplementation(vi.fn())
|
||||
vi.spyOn(assetService, 'listComments').mockImplementation(vi.fn())
|
||||
vi.spyOn(assetService, 'restoreAssets').mockImplementation(vi.fn())
|
||||
vi.spyOn(metadataService, 'updateAssetMetadata').mockImplementation(vi.fn())
|
||||
vi.spyOn(notificationService, 'create').mockImplementation(vi.fn())
|
||||
vi.spyOn(s3Service, 'putObject').mockImplementation(vi.fn())
|
||||
vi.mocked(authzService.hasPermission).mockResolvedValue(undefined)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('GET /files/:fileId', async () => {
|
||||
vi.mocked(assetService.getAsset).mockResolvedValue({
|
||||
id: 'test-id',
|
||||
name: 'test-file',
|
||||
sizeByte: 10,
|
||||
fileCount: 1,
|
||||
type: 'file',
|
||||
status: 'active',
|
||||
mediaType: 'image/jpeg',
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
})
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', fileRoute)
|
||||
const res = await app.request('/files/test-id')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.name).toBe('test-file')
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Asset,
|
||||
id: 'test-id',
|
||||
})
|
||||
})
|
||||
|
||||
it('PUT /files/:fileId', async () => {
|
||||
vi.mocked(assetService.updateAssetName).mockResolvedValue({
|
||||
id: 'test-id',
|
||||
name: 'new-name',
|
||||
sizeByte: 10,
|
||||
fileCount: 1,
|
||||
type: 'file',
|
||||
status: 'active',
|
||||
mediaType: 'image/jpeg',
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
})
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', fileRoute)
|
||||
const res = await app.request('/files/test-id', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name: 'new-name' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.name).toBe('new-name')
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id: 'test-id',
|
||||
})
|
||||
})
|
||||
|
||||
it('DELETE /files', async () => {
|
||||
vi.mocked(assetService.deleteAssets).mockResolvedValue(undefined)
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', fileRoute)
|
||||
const res = await app.request('/files', {
|
||||
method: 'DELETE',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ ids: ['test-id'] }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(204)
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id: 'test-id',
|
||||
})
|
||||
expect(assetService.deleteAssets).toHaveBeenCalledWith(['test-id'])
|
||||
})
|
||||
|
||||
it('POST /files/restore', async () => {
|
||||
vi.mocked(assetService.restoreAssets).mockResolvedValue(undefined)
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', fileRoute)
|
||||
const res = await app.request('/files/restore', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ ids: ['test-id'] }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(204)
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id: 'test-id',
|
||||
})
|
||||
expect(assetService.restoreAssets).toHaveBeenCalledWith(['test-id'])
|
||||
})
|
||||
|
||||
it('POST /files/:fileId/comments', async () => {
|
||||
vi.mocked(assetService.createComment).mockResolvedValue({
|
||||
id: 'comment-id',
|
||||
assetId: 'file-id',
|
||||
message: 'hello',
|
||||
annotations: null,
|
||||
second: null,
|
||||
creator: { id: 'user-id', name: 'Test User' },
|
||||
replies: [],
|
||||
attachments: [],
|
||||
mentions: [],
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
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 res = await app.request('/files/test-id/comments', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ message: 'hello', attachmentIds: [] }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(201)
|
||||
const json = await res.json()
|
||||
expect(json.message).toBe('hello')
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Asset,
|
||||
id: 'test-id',
|
||||
})
|
||||
|
||||
expect(notificationService.create).toHaveBeenCalledWith({
|
||||
type: 'comment_created',
|
||||
teamId: 'test-team',
|
||||
creatorId: 'user1',
|
||||
assetId: 'test-id',
|
||||
commentMessage: 'hello',
|
||||
})
|
||||
})
|
||||
|
||||
it('POST /files/:fileId/comments - reply_created targets parent comment creator', async () => {
|
||||
vi.mocked(assetService.createComment).mockResolvedValue({
|
||||
id: 'comment-id',
|
||||
assetId: 'file-id',
|
||||
message: 'hello reply',
|
||||
annotations: null,
|
||||
second: null,
|
||||
creator: { id: 'user-id', name: 'Test User' },
|
||||
replies: [],
|
||||
attachments: [],
|
||||
mentions: [],
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
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 mockFindUnique = vi.spyOn(prisma.assetComment, 'findUnique').mockResolvedValue({
|
||||
id: 'parent-comment-id',
|
||||
creatorId: 'parent-comment-creator-id',
|
||||
} as any) // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', fileRoute)
|
||||
const res = await app.request('/files/test-id/comments', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
message: 'hello reply',
|
||||
replyToId: 'parent-comment-id',
|
||||
attachmentIds: [],
|
||||
}),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(201)
|
||||
const json = await res.json()
|
||||
expect(json.message).toBe('hello reply')
|
||||
|
||||
expect(notificationService.create).toHaveBeenCalledWith({
|
||||
type: 'reply_created',
|
||||
teamId: 'test-team',
|
||||
creatorId: 'user1',
|
||||
assetId: 'test-id',
|
||||
userId: 'parent-comment-creator-id',
|
||||
commentMessage: 'hello reply',
|
||||
})
|
||||
|
||||
mockFindUnique.mockRestore()
|
||||
})
|
||||
|
||||
it('GET /files/:fileId/comments', async () => {
|
||||
vi.mocked(assetService.listComments).mockResolvedValue({
|
||||
data: [
|
||||
{
|
||||
id: 'comment-id',
|
||||
assetId: 'file-id',
|
||||
message: 'hello',
|
||||
annotations: null,
|
||||
second: null,
|
||||
creator: { id: 'user-id', name: 'Test User' },
|
||||
replies: [],
|
||||
attachments: [],
|
||||
mentions: [],
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
sessionId: null,
|
||||
},
|
||||
],
|
||||
pageInfo: { cursor: 'cursor', total: 1 },
|
||||
})
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', fileRoute)
|
||||
const res = await app.request('/files/test-id/comments')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.data).toHaveLength(1)
|
||||
expect(json.data[0].message).toBe('hello')
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Asset,
|
||||
id: 'test-id',
|
||||
})
|
||||
})
|
||||
|
||||
it('POST /teams/:teamId/files', async () => {
|
||||
vi.mocked(s3Service.putObject).mockResolvedValue(undefined)
|
||||
|
||||
const formData = new FormData()
|
||||
const file = new File(['test content'], 'test.jpg', { type: 'image/jpeg' })
|
||||
formData.append('file', file)
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', fileRoute)
|
||||
const res = await app.request('/teams/test-team/files', {
|
||||
method: 'POST',
|
||||
body: formData,
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.key).toMatch(/^files\//)
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Team,
|
||||
id: 'test-team',
|
||||
})
|
||||
expect(s3Service.putObject).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('PATCH /files/:fileId/metadata', async () => {
|
||||
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 res = await app.request('/files/test-id/metadata', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify([{ key: 'status', value: 'approved' }]),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id: 'test-id',
|
||||
})
|
||||
|
||||
expect(notificationService.create).toHaveBeenCalledWith({
|
||||
type: 'metadata_field_updated_status',
|
||||
teamId: 'test-team',
|
||||
creatorId: 'user1',
|
||||
assetId: 'test-id',
|
||||
})
|
||||
})
|
||||
|
||||
it('PATCH /files/:fileId/metadata rejects readonly fields with 422', async () => {
|
||||
vi.mocked(metadataService.updateAssetMetadata).mockRejectedValue(
|
||||
new Error('Field some-key is read-only'),
|
||||
)
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', fileRoute)
|
||||
const res = await app.request('/files/test-id/metadata', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify([{ key: 'some-key', value: 'approved' }]),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(422)
|
||||
const body = await res.json()
|
||||
expect(body.error).toContain('Field some-key is read-only')
|
||||
})
|
||||
|
||||
it('PATCH /files/:fileId/order', async () => {
|
||||
vi.spyOn(assetService, 'updateAssetOrder').mockResolvedValue({
|
||||
id: 'test-id',
|
||||
name: 'test-file',
|
||||
sizeByte: 10,
|
||||
fileCount: 1,
|
||||
type: 'file',
|
||||
status: 'active',
|
||||
mediaType: 'image/jpeg',
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
})
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', fileRoute)
|
||||
const res = await app.request('/files/test-id/order', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ beforeIndex: 'index-1' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id: 'test-id',
|
||||
})
|
||||
|
||||
expect(assetService.updateAssetOrder).toHaveBeenCalledWith('test-id', {
|
||||
beforeIndex: 'index-1',
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,238 @@
|
||||
import { Hono } from 'hono'
|
||||
import { zValidator } from '@hono/zod-validator'
|
||||
import { prisma } from '@shumai/db'
|
||||
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
import { assetService } from '@shumai/core/src/asset/asset'
|
||||
import { metadataService } from '@shumai/core/src/metadata/metadata'
|
||||
import { notificationService } from '@shumai/core/src/notification/notification'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import {
|
||||
updateFileRequestSchema,
|
||||
updateAssetOrderRequestSchema,
|
||||
deleteFilesRequestSchema,
|
||||
restoreFilesRequestSchema,
|
||||
createCommentRequestSchema,
|
||||
uploadFileRequestSchema,
|
||||
} from '@shumai/dtos'
|
||||
import { updateAssetMetadataRequestSchema } from '@shumai/dtos'
|
||||
import { paginationParamsSchema } from '@shumai/dtos'
|
||||
import { ulid } from 'ulid'
|
||||
import { z } from 'zod'
|
||||
import type { Prisma } from '@shumai/db'
|
||||
|
||||
type User = Prisma.UserGetPayload<Record<string, never>>
|
||||
|
||||
const route = new Hono<{ Variables: { user: User } }>()
|
||||
.get('/files/:fileId', async (c) => {
|
||||
const fileId = c.req.param('fileId')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Asset,
|
||||
id: fileId,
|
||||
})
|
||||
|
||||
const asset = await assetService.getAsset({ assetId: fileId })
|
||||
return c.json(asset)
|
||||
})
|
||||
.patch('/files/:fileId/order', zValidator('json', updateAssetOrderRequestSchema), async (c) => {
|
||||
const fileId = c.req.param('fileId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id: fileId,
|
||||
})
|
||||
|
||||
const updated = await assetService.updateAssetOrder(fileId, req)
|
||||
return c.json(updated)
|
||||
})
|
||||
.put('/files/:fileId', zValidator('json', updateFileRequestSchema), async (c) => {
|
||||
const fileId = c.req.param('fileId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id: fileId,
|
||||
})
|
||||
|
||||
const updatedAsset = await assetService.updateAssetName({
|
||||
id: fileId,
|
||||
name: req.name,
|
||||
})
|
||||
|
||||
return c.json(updatedAsset)
|
||||
})
|
||||
.delete('/files', zValidator('json', deleteFilesRequestSchema), async (c) => {
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
for (const id of req.ids) {
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id,
|
||||
})
|
||||
}
|
||||
|
||||
await assetService.deleteAssets(req.ids)
|
||||
return c.body(null, 204)
|
||||
})
|
||||
.patch(
|
||||
'/files/:fileId/metadata',
|
||||
zValidator('json', z.array(updateAssetMetadataRequestSchema)),
|
||||
async (c) => {
|
||||
const fileId = c.req.param('fileId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id: fileId,
|
||||
})
|
||||
|
||||
try {
|
||||
await metadataService.updateAssetMetadata(fileId, req)
|
||||
} catch (err) {
|
||||
if (err instanceof Error && err.message.includes('is read-only')) {
|
||||
return c.json({ error: err.message }, 422)
|
||||
}
|
||||
throw err
|
||||
}
|
||||
|
||||
const hasStatus = req.some((m) => m.key === 'status')
|
||||
if (hasStatus) {
|
||||
const context = await assetService.getAssetContext(fileId)
|
||||
if (context?.teamId) {
|
||||
notificationService.create({
|
||||
type: 'metadata_field_updated_status',
|
||||
teamId: context.teamId,
|
||||
creatorId: user.id,
|
||||
assetId: fileId,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return c.json('')
|
||||
},
|
||||
)
|
||||
.post(
|
||||
'/files/:fileId/comments',
|
||||
zValidator('json', createCommentRequestSchema.omit({ assetId: true, userId: true })),
|
||||
async (c) => {
|
||||
const fileId = c.req.param('fileId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Asset,
|
||||
id: fileId,
|
||||
})
|
||||
|
||||
const comment = await assetService.createComment({
|
||||
assetId: fileId,
|
||||
userId: user.id,
|
||||
replyToId: req.replyToId,
|
||||
message: req.message,
|
||||
annotations: req.annotations,
|
||||
second: req.second,
|
||||
attachmentIds: req.attachmentIds,
|
||||
})
|
||||
|
||||
const notifType = req.replyToId ? 'reply_created' : 'comment_created'
|
||||
|
||||
const context = await assetService.getAssetContext(fileId)
|
||||
|
||||
if (context?.teamId) {
|
||||
let targetUserId: string | undefined
|
||||
if (req.replyToId) {
|
||||
const parentComment = await prisma.assetComment.findUnique({
|
||||
where: { id: req.replyToId },
|
||||
})
|
||||
if (parentComment?.creatorId) {
|
||||
targetUserId = parentComment.creatorId
|
||||
}
|
||||
}
|
||||
|
||||
notificationService.create({
|
||||
type: notifType,
|
||||
teamId: context.teamId,
|
||||
creatorId: user.id,
|
||||
assetId: fileId,
|
||||
userId: targetUserId,
|
||||
commentMessage: req.message,
|
||||
})
|
||||
}
|
||||
|
||||
return c.json(comment, 201)
|
||||
},
|
||||
)
|
||||
.get('/files/:fileId/comments', zValidator('query', paginationParamsSchema), async (c) => {
|
||||
const fileId = c.req.param('fileId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('query')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Asset,
|
||||
id: fileId,
|
||||
})
|
||||
|
||||
const comments = await assetService.listComments(fileId, req)
|
||||
return c.json(comments)
|
||||
})
|
||||
.post('/files/restore', zValidator('json', restoreFilesRequestSchema), async (c) => {
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
for (const id of req.ids) {
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id,
|
||||
})
|
||||
}
|
||||
|
||||
await assetService.restoreAssets(req.ids)
|
||||
return c.body(null, 204)
|
||||
})
|
||||
.post('/teams/:teamId/files', zValidator('form', uploadFileRequestSchema), async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
const user = c.get('user')
|
||||
const { file } = c.req.valid('form')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
if (file.size > 10 * 1024 * 1024) {
|
||||
return c.json('file too large, max 10MB', 400)
|
||||
}
|
||||
|
||||
const key = `files/${ulid()}`
|
||||
const buffer = Buffer.from(await file.arrayBuffer())
|
||||
|
||||
await s3Service.putObject(process.env.S3_BUCKET || 'shumai', key, buffer, file.size, file.type)
|
||||
|
||||
return c.json({ key })
|
||||
})
|
||||
|
||||
export default route
|
||||
@@ -0,0 +1,289 @@
|
||||
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { Hono } from 'hono'
|
||||
import folderRoute from './folder'
|
||||
import { assetService } from '@shumai/core/src/asset/asset'
|
||||
import { searchService } from '@shumai/core/src/search/search'
|
||||
import { authzService, ResourceType, Permission } from '@shumai/core/src/authz/authz'
|
||||
import { authMiddleware } from './middleware/auth'
|
||||
|
||||
vi.mock('@shumai/core/src/authz/authz', () => ({
|
||||
authzService: {
|
||||
hasPermission: vi.fn().mockResolvedValue(undefined),
|
||||
},
|
||||
Permission: {
|
||||
Read: 'Read',
|
||||
Edit: 'Edit',
|
||||
Admin: 'Admin',
|
||||
},
|
||||
ResourceType: {
|
||||
Asset: 'asset',
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('./middleware/auth', () => ({
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
authMiddleware: async (c: any, next: any) => {
|
||||
c.set('user', { id: 'user1', name: 'Test User' })
|
||||
await next()
|
||||
},
|
||||
}))
|
||||
|
||||
describe('folder api', () => {
|
||||
beforeEach(() => {
|
||||
vi.mocked(authzService.hasPermission).mockClear()
|
||||
|
||||
vi.spyOn(assetService, 'getAsset').mockImplementation(vi.fn())
|
||||
vi.spyOn(assetService, 'createAsset').mockImplementation(vi.fn())
|
||||
vi.spyOn(assetService, 'updateAssetName').mockImplementation(vi.fn())
|
||||
vi.spyOn(assetService, 'deleteAssets').mockImplementation(vi.fn())
|
||||
vi.spyOn(assetService, 'restoreAssets').mockImplementation(vi.fn())
|
||||
vi.spyOn(assetService, 'listChildren').mockImplementation(vi.fn())
|
||||
vi.spyOn(searchService, 'search').mockImplementation(vi.fn())
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('GET /folders/:folderId', async () => {
|
||||
vi.mocked(assetService.getAsset).mockResolvedValue({
|
||||
id: 'test-id',
|
||||
name: 'test-folder',
|
||||
sizeByte: 10,
|
||||
fileCount: 1,
|
||||
type: 'folder',
|
||||
status: 'active',
|
||||
mediaType: null,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
})
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', folderRoute)
|
||||
const res = await app.request('/folders/test-id')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.name).toBe('test-folder')
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Asset,
|
||||
id: 'test-id',
|
||||
})
|
||||
})
|
||||
|
||||
it('PUT /folders/:folderId', async () => {
|
||||
vi.mocked(assetService.updateAssetName).mockResolvedValue({
|
||||
id: 'test-id',
|
||||
name: 'new-name',
|
||||
sizeByte: 10,
|
||||
fileCount: 1,
|
||||
type: 'folder',
|
||||
status: 'active',
|
||||
mediaType: null,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
})
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', folderRoute)
|
||||
const res = await app.request('/folders/test-id', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name: 'new-name' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.name).toBe('new-name')
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id: 'test-id',
|
||||
})
|
||||
})
|
||||
|
||||
it('POST /folders', async () => {
|
||||
vi.mocked(assetService.createAsset).mockResolvedValue({
|
||||
id: 'new-id',
|
||||
name: 'new-folder',
|
||||
sizeByte: 0,
|
||||
fileCount: 0,
|
||||
type: 'folder',
|
||||
status: 'active',
|
||||
mediaType: null,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
})
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', folderRoute)
|
||||
const res = await app.request('/folders', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name: 'new-folder', parentId: 'parent-id' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.name).toBe('new-folder')
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id: 'parent-id',
|
||||
})
|
||||
})
|
||||
|
||||
it('GET /folders/:folderId/children', async () => {
|
||||
vi.mocked(assetService.listChildren).mockResolvedValue({
|
||||
data: [
|
||||
{
|
||||
id: 'child-id',
|
||||
name: 'child-folder',
|
||||
sizeByte: 0,
|
||||
fileCount: 0,
|
||||
type: 'folder',
|
||||
status: 'active',
|
||||
mediaType: null,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
},
|
||||
],
|
||||
pageInfo: { total: 1, cursor: '' },
|
||||
})
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', folderRoute)
|
||||
const res = await app.request('/folders/test-id/children?assetType=folder')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.data).toHaveLength(1)
|
||||
expect(json.data[0].name).toBe('child-folder')
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Asset,
|
||||
id: 'test-id',
|
||||
})
|
||||
})
|
||||
|
||||
it('DELETE /folders', async () => {
|
||||
vi.mocked(assetService.deleteAssets).mockResolvedValue(undefined)
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', folderRoute)
|
||||
const res = await app.request('/folders', {
|
||||
method: 'DELETE',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ ids: ['test-id'] }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(204)
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id: 'test-id',
|
||||
})
|
||||
expect(assetService.deleteAssets).toHaveBeenCalledWith(['test-id'])
|
||||
})
|
||||
|
||||
it('POST /folders/restore', async () => {
|
||||
vi.mocked(assetService.restoreAssets).mockResolvedValue(undefined)
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', folderRoute)
|
||||
const res = await app.request('/folders/restore', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ ids: ['test-id'] }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(204)
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id: 'test-id',
|
||||
})
|
||||
expect(assetService.restoreAssets).toHaveBeenCalledWith(['test-id'])
|
||||
})
|
||||
|
||||
it('POST /folders/:folderId/search', async () => {
|
||||
vi.mocked(searchService.search).mockResolvedValue({
|
||||
data: [
|
||||
{
|
||||
id: 'result-id',
|
||||
name: 'result-folder',
|
||||
sizeByte: 0,
|
||||
fileCount: 0,
|
||||
type: 'folder',
|
||||
status: 'active',
|
||||
mediaType: null,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
},
|
||||
],
|
||||
pageInfo: { total: 1, cursor: '' },
|
||||
})
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', folderRoute)
|
||||
const res = await app.request('/folders/test-id/search', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
conditions: [{ field: 'name', operator: 'eq', value: 'result-folder' }],
|
||||
}),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.data).toHaveLength(1)
|
||||
expect(json.data[0].name).toBe('result-folder')
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Asset,
|
||||
id: 'test-id',
|
||||
})
|
||||
})
|
||||
|
||||
it('PATCH /folders/:folderId/order', async () => {
|
||||
vi.spyOn(assetService, 'updateAssetOrder').mockResolvedValue({
|
||||
id: 'test-id',
|
||||
name: 'test-folder',
|
||||
sizeByte: 10,
|
||||
fileCount: 1,
|
||||
type: 'folder',
|
||||
status: 'active',
|
||||
mediaType: null,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
})
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', folderRoute)
|
||||
const res = await app.request('/folders/test-id/order', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ beforeIndex: 'index-1' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id: 'test-id',
|
||||
})
|
||||
|
||||
expect(assetService.updateAssetOrder).toHaveBeenCalledWith('test-id', {
|
||||
beforeIndex: 'index-1',
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,160 @@
|
||||
import { Hono } from 'hono'
|
||||
import { zValidator } from '@hono/zod-validator'
|
||||
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
import { assetService } from '@shumai/core/src/asset/asset'
|
||||
import { searchService } from '@shumai/core/src/search/search'
|
||||
import {
|
||||
createFolderRequestSchema,
|
||||
updateFolderRequestSchema,
|
||||
deleteFoldersRequestSchema,
|
||||
restoreFoldersRequestSchema,
|
||||
} from '@shumai/dtos'
|
||||
import { listChildrenRequestSchema, updateAssetOrderRequestSchema } from '@shumai/dtos'
|
||||
import { searchRequestSchema } from '@shumai/dtos'
|
||||
import type { Prisma } from '@shumai/db'
|
||||
|
||||
type User = Prisma.UserGetPayload<Record<string, never>>
|
||||
|
||||
const route = new Hono<{ Variables: { user: User } }>()
|
||||
.post('/folders', zValidator('json', createFolderRequestSchema), async (c) => {
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id: req.parentId,
|
||||
})
|
||||
|
||||
const newAsset = await assetService.createAsset({
|
||||
name: req.name,
|
||||
parentId: req.parentId,
|
||||
type: 'folder',
|
||||
})
|
||||
|
||||
return c.json(newAsset)
|
||||
})
|
||||
.patch(
|
||||
'/folders/:folderId/order',
|
||||
zValidator('json', updateAssetOrderRequestSchema),
|
||||
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.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id: folderId,
|
||||
})
|
||||
|
||||
const updated = await assetService.updateAssetOrder(folderId, req)
|
||||
return c.json(updated)
|
||||
},
|
||||
)
|
||||
.put('/folders/:folderId', zValidator('json', updateFolderRequestSchema), 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.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id: folderId,
|
||||
})
|
||||
|
||||
const updatedAsset = await assetService.updateAssetName({
|
||||
id: folderId,
|
||||
name: req.name,
|
||||
})
|
||||
|
||||
return c.json(updatedAsset)
|
||||
})
|
||||
.get('/folders/:folderId', async (c) => {
|
||||
const folderId = c.req.param('folderId')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Asset,
|
||||
id: folderId,
|
||||
})
|
||||
|
||||
const assetInfo = await assetService.getAsset({ assetId: folderId })
|
||||
return c.json(assetInfo)
|
||||
})
|
||||
.get('/folders/:folderId/children', zValidator('query', listChildrenRequestSchema), async (c) => {
|
||||
const folderId = c.req.param('folderId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('query')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Asset,
|
||||
id: folderId,
|
||||
})
|
||||
|
||||
const resp = await assetService.listChildren({
|
||||
assetId: folderId,
|
||||
assetType: req.assetType,
|
||||
projectId: req.projectId,
|
||||
showDeleted: req.showDeleted,
|
||||
sort: req.sort,
|
||||
order: req.order,
|
||||
})
|
||||
return c.json(resp)
|
||||
})
|
||||
.delete('/folders', zValidator('json', deleteFoldersRequestSchema), async (c) => {
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
for (const id of req.ids) {
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id,
|
||||
})
|
||||
}
|
||||
|
||||
await assetService.deleteAssets(req.ids)
|
||||
return c.body(null, 204)
|
||||
})
|
||||
.post('/folders/restore', zValidator('json', restoreFoldersRequestSchema), async (c) => {
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
for (const id of req.ids) {
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id,
|
||||
})
|
||||
}
|
||||
|
||||
await assetService.restoreAssets(req.ids)
|
||||
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
|
||||
@@ -0,0 +1,186 @@
|
||||
import { describe, expect, it, vi, beforeEach } from 'vitest'
|
||||
import { Hono, type Context, type Next } from 'hono'
|
||||
import inviteRoute from './invite'
|
||||
import publicInviteRoute from './public-invite'
|
||||
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
import { inviteService } from '@shumai/core/src/invite/invite'
|
||||
import { notificationService } from '@shumai/core/src/notification/notification'
|
||||
|
||||
vi.mock('@shumai/core/src/invite/invite')
|
||||
vi.mock('@shumai/core/src/notification/notification')
|
||||
vi.mock('@shumai/core/src/authz/authz')
|
||||
|
||||
vi.mock('./middleware/auth', () => ({
|
||||
authMiddleware: async (
|
||||
c: Context<{ Variables: { user: { id: string; name: string } } }>,
|
||||
next: Next,
|
||||
) => {
|
||||
c.set('user', { id: 'u1', name: 'Test User' })
|
||||
await next()
|
||||
},
|
||||
}))
|
||||
|
||||
const getApp = () => {
|
||||
const app = new Hono<{ Variables: { user: { id: string; name: string } } }>()
|
||||
.route('/', publicInviteRoute)
|
||||
.use('*', async (c, next) => {
|
||||
c.set('user', { id: 'u1', name: 'Test User' })
|
||||
await next()
|
||||
})
|
||||
.route('/', inviteRoute)
|
||||
return app
|
||||
}
|
||||
|
||||
describe('Invite API', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
vi.mocked(authzService.hasPermission).mockResolvedValue(undefined)
|
||||
})
|
||||
|
||||
it('GET /invite/:code', async () => {
|
||||
const app = getApp()
|
||||
|
||||
// Using any here because mocking complex service return types or Hono context is overly verbose for this test.
|
||||
vi.mocked(inviteService.getInvite).mockResolvedValue({
|
||||
code: 'code123',
|
||||
teamId: 't1',
|
||||
team: { name: 'My Team' },
|
||||
inviter: { name: 'Inviter' },
|
||||
role: 'editor',
|
||||
used: false,
|
||||
} as any) // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
|
||||
const res = await app.request('/invite/code123')
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({
|
||||
code: 'code123',
|
||||
role: 'editor',
|
||||
teamId: 't1',
|
||||
teamName: 'My Team',
|
||||
inviterName: 'Inviter',
|
||||
isUsed: false,
|
||||
})
|
||||
})
|
||||
|
||||
it('POST /teams/:teamId/invite', async () => {
|
||||
const app = getApp()
|
||||
|
||||
// Using any here because mocking complex service return types or Hono context is overly verbose for this test.
|
||||
vi.mocked(inviteService.createTeamInvite).mockResolvedValue({
|
||||
code: 'test-code',
|
||||
role: 'editor',
|
||||
teamId: 't1',
|
||||
team: { name: 'Team A' },
|
||||
inviter: { name: 'Inviter' },
|
||||
used: false,
|
||||
} as any) // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
|
||||
const res = await app.request('/teams/t1/invite', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: 'Bearer fake',
|
||||
},
|
||||
body: JSON.stringify({ role: 'editor' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({
|
||||
code: 'test-code',
|
||||
role: 'editor',
|
||||
teamId: 't1',
|
||||
teamName: 'Team A',
|
||||
inviterName: 'Inviter',
|
||||
isUsed: false,
|
||||
})
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: expect.anything(),
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Team,
|
||||
id: 't1',
|
||||
})
|
||||
expect(inviteService.createTeamInvite).toHaveBeenCalledWith({
|
||||
teamId: 't1',
|
||||
role: 'editor',
|
||||
inviterId: 'u1',
|
||||
})
|
||||
})
|
||||
|
||||
it('POST /projects/:projectId/invite', async () => {
|
||||
const app = getApp()
|
||||
|
||||
// Using any here because mocking complex service return types or Hono context is overly verbose for this test.
|
||||
vi.mocked(inviteService.createProjectInvite).mockResolvedValue({
|
||||
code: 'proj-code',
|
||||
role: 'reviewer',
|
||||
teamId: 't1',
|
||||
team: { name: 'Team A' },
|
||||
project: { id: 'p1', name: 'Project A' },
|
||||
inviter: { name: 'Inviter' },
|
||||
used: false,
|
||||
} as any) // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
|
||||
const res = await app.request('/projects/p1/invite', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: 'Bearer fake',
|
||||
},
|
||||
body: JSON.stringify({ role: 'reviewer' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({
|
||||
code: 'proj-code',
|
||||
role: 'reviewer',
|
||||
teamId: 't1',
|
||||
teamName: 'Team A',
|
||||
projectId: 'p1',
|
||||
projectName: 'Project A',
|
||||
inviterName: 'Inviter',
|
||||
isUsed: false,
|
||||
})
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: expect.anything(),
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Project,
|
||||
id: 'p1',
|
||||
})
|
||||
expect(inviteService.createProjectInvite).toHaveBeenCalledWith({
|
||||
projectId: 'p1',
|
||||
role: 'reviewer',
|
||||
inviterId: 'u1',
|
||||
})
|
||||
})
|
||||
|
||||
it('POST /join (Team)', async () => {
|
||||
const app = getApp()
|
||||
// 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.create).mockResolvedValue(undefined as any)
|
||||
|
||||
// Using any here because mocking complex service return types or Hono context is overly verbose for this test.
|
||||
vi.mocked(inviteService.getInvite).mockResolvedValue({
|
||||
code: 'code123',
|
||||
teamId: 't1',
|
||||
team: { name: 'Team A' },
|
||||
inviter: { name: 'Inviter' },
|
||||
used: false,
|
||||
} 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(inviteService.consumeInvite).mockResolvedValue(undefined as any)
|
||||
|
||||
const res = await app.request('/join', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: 'Bearer fake',
|
||||
},
|
||||
body: JSON.stringify({ code: 'code123' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(inviteService.consumeInvite).toHaveBeenCalledWith('code123', 'u1')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,113 @@
|
||||
import { zValidator } from '@hono/zod-validator'
|
||||
import { Hono } from 'hono'
|
||||
import {
|
||||
createProjectInviteRequestSchema,
|
||||
createTeamInviteRequestSchema,
|
||||
joinRequestSchema,
|
||||
InviteInfo,
|
||||
} from '@shumai/dtos'
|
||||
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
import { inviteService } from '@shumai/core/src/invite/invite'
|
||||
import { notificationService } from '@shumai/core/src/notification/notification'
|
||||
import { NotificationType } from '@shumai/db'
|
||||
import type { Prisma } from '@shumai/db'
|
||||
|
||||
type User = Prisma.UserGetPayload<Record<string, never>>
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const mapToInviteInfo = (inv: any): InviteInfo => {
|
||||
const info: InviteInfo = {
|
||||
code: inv.code,
|
||||
role: inv.role!,
|
||||
teamId: inv.teamId,
|
||||
teamName: inv.team.name,
|
||||
inviterName: inv.inviter.name,
|
||||
isUsed: inv.used,
|
||||
}
|
||||
|
||||
if (inv.project) {
|
||||
info.projectId = inv.project.id
|
||||
info.projectName = inv.project.name
|
||||
}
|
||||
|
||||
return info
|
||||
}
|
||||
|
||||
const route = new Hono<{ Variables: { user: User } }>()
|
||||
.post('/teams/:teamId/invite', zValidator('json', createTeamInviteRequestSchema), async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
const req = c.req.valid('json')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const inv = await inviteService.createTeamInvite({
|
||||
teamId,
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
role: req.role as any,
|
||||
inviterId: user.id,
|
||||
})
|
||||
|
||||
return c.json(mapToInviteInfo(inv))
|
||||
})
|
||||
.post(
|
||||
'/projects/:projectId/invite',
|
||||
zValidator('json', createProjectInviteRequestSchema),
|
||||
async (c) => {
|
||||
const projectId = c.req.param('projectId')
|
||||
const req = c.req.valid('json')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Project,
|
||||
id: projectId,
|
||||
})
|
||||
|
||||
const inv = await inviteService.createProjectInvite({
|
||||
projectId,
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
role: req.role as any,
|
||||
inviterId: user.id,
|
||||
})
|
||||
|
||||
return c.json(mapToInviteInfo(inv))
|
||||
},
|
||||
)
|
||||
.post('/join', zValidator('json', joinRequestSchema), async (c) => {
|
||||
const req = c.req.valid('json')
|
||||
const user = c.get('user')
|
||||
|
||||
try {
|
||||
const info = await inviteService.getInvite(req.code)
|
||||
|
||||
await inviteService.consumeInvite(req.code, user.id)
|
||||
|
||||
if (info.projectId) {
|
||||
await notificationService.create({
|
||||
type: NotificationType.new_user_join_project,
|
||||
teamId: info.teamId,
|
||||
projectId: info.projectId,
|
||||
userId: user.id,
|
||||
})
|
||||
} else {
|
||||
await notificationService.create({
|
||||
type: NotificationType.new_user_join_team,
|
||||
teamId: info.teamId,
|
||||
userId: user.id,
|
||||
})
|
||||
}
|
||||
|
||||
return new Response(null, { status: 200 })
|
||||
} catch {
|
||||
return c.json({ error: 'Bad Request' }, 400)
|
||||
}
|
||||
})
|
||||
|
||||
export default route
|
||||
@@ -0,0 +1,208 @@
|
||||
import { describe, expect, it, vi, beforeEach } from 'vitest'
|
||||
import { Hono, type Context, type Next } from 'hono'
|
||||
import metadataRoute from './metadata'
|
||||
import { metadataService } from '@shumai/core/src/metadata/metadata'
|
||||
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
|
||||
vi.mock('./middleware/auth', () => ({
|
||||
authMiddleware: async (
|
||||
c: Context<{ Variables: { user: { id: string; name: string } } }>,
|
||||
next: Next,
|
||||
) => {
|
||||
c.set('user', { id: 'user1', name: 'Test User' })
|
||||
await next()
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@shumai/core/src/authz/authz')
|
||||
vi.mock('@shumai/core/src/metadata/metadata')
|
||||
|
||||
describe('metadata api', () => {
|
||||
const app = new Hono<{ Variables: { user: { id: string; name: string } } }>()
|
||||
.use('*', async (c, next) => {
|
||||
c.set('user', { id: 'user1', name: 'Test User' })
|
||||
await next()
|
||||
})
|
||||
.route('/', metadataRoute)
|
||||
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
vi.mocked(authzService.hasPermission).mockResolvedValue(undefined)
|
||||
})
|
||||
|
||||
it('GET /teams/:teamId/fields', async () => {
|
||||
const mockField = {
|
||||
key: 'field1',
|
||||
scope: 'TEAM',
|
||||
config: { name: 'Test Field', type: 'text' },
|
||||
readOnly: false,
|
||||
description: 'desc',
|
||||
aiAutofill: true,
|
||||
}
|
||||
|
||||
// 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 res = await app.request('/teams/t1/fields')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json).toHaveLength(1)
|
||||
expect(json[0].id).toBe('field1')
|
||||
expect(json[0].config.name).toBe('Test Field')
|
||||
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 () => {
|
||||
const mockField = {
|
||||
key: 'newfield',
|
||||
scope: 'TEAM',
|
||||
config: { name: 'New Field', type: 'text' },
|
||||
readOnly: false,
|
||||
description: 'desc',
|
||||
aiAutofill: true,
|
||||
}
|
||||
|
||||
// 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 res = await app.request('/teams/t1/fields', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
config: { name: 'New Field', type: 'text' },
|
||||
aiAutofill: true,
|
||||
description: 'desc',
|
||||
}),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
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 () => {
|
||||
const mockField = {
|
||||
key: 'field1',
|
||||
scope: 'PROJECT',
|
||||
config: { name: 'Project Field', type: 'text' },
|
||||
readOnly: false,
|
||||
description: 'desc',
|
||||
aiAutofill: false,
|
||||
}
|
||||
|
||||
vi.mocked(metadataService.listProjectFields).mockResolvedValue([
|
||||
{ field: mockField, visible: true } as any, // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
])
|
||||
|
||||
const res = await app.request('/projects/p1/fields')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json).toHaveLength(1)
|
||||
expect(json[0].id).toBe('field1')
|
||||
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 () => {
|
||||
// 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 res = await app.request('/projects/p1/fields/order', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify([{ fieldId: 'field1', visible: true }]),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(204)
|
||||
expect(metadataService.updateProjectFieldsOrder).toHaveBeenCalledWith('user1', 'p1', [
|
||||
{ fieldId: 'field1', visible: true },
|
||||
])
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: expect.anything(),
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Project,
|
||||
id: 'p1',
|
||||
})
|
||||
})
|
||||
|
||||
it('DELETE /fields/:fieldId', async () => {
|
||||
// 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 res = await app.request('/fields/f1', {
|
||||
method: 'DELETE',
|
||||
})
|
||||
|
||||
expect(res.status).toBe(204)
|
||||
expect(metadataService.deleteTeamField).toHaveBeenCalledWith('t1', 'f1')
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: expect.anything(),
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.MetadataField,
|
||||
id: 'f1',
|
||||
})
|
||||
})
|
||||
|
||||
it('PUT /fields/:fieldId', async () => {
|
||||
const mockField = {
|
||||
key: 'f1',
|
||||
scope: 'TEAM',
|
||||
config: { name: 'Updated Field', type: 'text' },
|
||||
readOnly: false,
|
||||
description: 'desc',
|
||||
aiAutofill: true,
|
||||
teamId: 't1',
|
||||
}
|
||||
|
||||
// Using any here because mocking complex service return types or Hono context is overly verbose for this test.
|
||||
vi.mocked(metadataService.getFieldByKey).mockResolvedValue(mockField 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.
|
||||
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' },
|
||||
body: JSON.stringify({
|
||||
config: { name: 'Updated Field', type: 'text' },
|
||||
aiAutofill: true,
|
||||
description: 'desc',
|
||||
}),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.id).toBe('f1')
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: expect.anything(),
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.MetadataField,
|
||||
id: 'f1',
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,163 @@
|
||||
import { zValidator } from '@hono/zod-validator'
|
||||
import { Hono } from 'hono'
|
||||
import { metadataService } from '@shumai/core/src/metadata/metadata'
|
||||
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
import {
|
||||
createFieldRequestSchema,
|
||||
updateFieldRequestSchema,
|
||||
updateProjectFieldsOrderRequestSchema,
|
||||
FieldInfo,
|
||||
} from '@shumai/dtos'
|
||||
import type { Prisma } from '@shumai/db'
|
||||
|
||||
type User = Prisma.UserGetPayload<Record<string, never>>
|
||||
|
||||
function toFieldInfo(
|
||||
f: Prisma.MetadataFieldGetPayload<Record<string, never>>,
|
||||
visible = false,
|
||||
): FieldInfo {
|
||||
return {
|
||||
id: f.key,
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
config: f.config as any,
|
||||
scope: f.scope ?? '',
|
||||
readOnly: f.readOnly,
|
||||
visible: visible,
|
||||
description: f.description,
|
||||
aiAutofill: f.aiAutofill,
|
||||
}
|
||||
}
|
||||
|
||||
const route = new Hono<{ Variables: { user: User } }>()
|
||||
.post('/teams/:teamId/fields', zValidator('json', createFieldRequestSchema), async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
const req = c.req.valid('json')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const field = await metadataService.createTeamField(teamId, req)
|
||||
return c.json(toFieldInfo(field))
|
||||
})
|
||||
.get('/teams/:teamId/fields', async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const fields = await metadataService.listTeamFields(teamId)
|
||||
return c.json(fields.map((f) => toFieldInfo(f)))
|
||||
})
|
||||
.put('/fields/:fieldId', zValidator('json', updateFieldRequestSchema), async (c) => {
|
||||
const fieldId = c.req.param('fieldId')
|
||||
const req = c.req.valid('json')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.MetadataField,
|
||||
id: fieldId,
|
||||
})
|
||||
|
||||
// We need teamId/projectId for metadataService. But we can get them from the field itself.
|
||||
// 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)
|
||||
if (!field) throw new Error('Field not found')
|
||||
|
||||
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 user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.MetadataField,
|
||||
id: 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 })
|
||||
})
|
||||
.post('/projects/:projectId/fields', zValidator('json', createFieldRequestSchema), async (c) => {
|
||||
const projectId = c.req.param('projectId')
|
||||
const req = c.req.valid('json')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Project,
|
||||
id: projectId,
|
||||
})
|
||||
|
||||
const field = await metadataService.createProjectField(projectId, req)
|
||||
return c.json(toFieldInfo(field))
|
||||
})
|
||||
.get('/projects/:projectId/fields', async (c) => {
|
||||
const projectId = c.req.param('projectId')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Project,
|
||||
id: projectId,
|
||||
})
|
||||
|
||||
const fields = await metadataService.listProjectFields(user.id, projectId)
|
||||
return c.json(fields.map((f) => toFieldInfo(f.field, f.visible)))
|
||||
})
|
||||
.patch(
|
||||
'/projects/:projectId/fields/order',
|
||||
zValidator('json', updateProjectFieldsOrderRequestSchema),
|
||||
async (c) => {
|
||||
const projectId = c.req.param('projectId')
|
||||
const req = c.req.valid('json')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Project,
|
||||
id: projectId,
|
||||
})
|
||||
|
||||
await metadataService.updateProjectFieldsOrder(user.id, projectId, req)
|
||||
return new Response(null, { status: 204 })
|
||||
},
|
||||
)
|
||||
|
||||
export default route
|
||||
@@ -0,0 +1,35 @@
|
||||
import type { Prisma } from '@shumai/db'
|
||||
import { auth } from '@shumai/core/src/auth/auth'
|
||||
import { prisma } from '@shumai/db'
|
||||
import { createMiddleware } from 'hono/factory'
|
||||
|
||||
type User = Prisma.UserGetPayload<Record<string, never>>
|
||||
|
||||
export const authMiddleware = createMiddleware<{
|
||||
Variables: {
|
||||
user: User
|
||||
}
|
||||
}>(async (c, next) => {
|
||||
const session = await auth.api.getSession({
|
||||
headers: c.req.raw.headers,
|
||||
})
|
||||
|
||||
if (!session) {
|
||||
return c.json({ error: 'Unauthorized' }, 401)
|
||||
}
|
||||
|
||||
try {
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { id: session.user.id },
|
||||
})
|
||||
|
||||
if (!user) {
|
||||
return c.json({ error: 'User not found' }, 401)
|
||||
}
|
||||
|
||||
c.set('user', user)
|
||||
await next()
|
||||
} catch {
|
||||
return c.json({ error: 'Authentication failed' }, 401)
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,156 @@
|
||||
import { describe, expect, it, vi, beforeEach } from 'vitest'
|
||||
import { Hono, type Context, type Next } from 'hono'
|
||||
import notificationRoute from './notification'
|
||||
import { notificationService } from '@shumai/core/src/notification/notification'
|
||||
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
import { userMetadataService } from '@shumai/core/src/user-metadata/user-metadata'
|
||||
|
||||
vi.mock('./middleware/auth', () => ({
|
||||
authMiddleware: async (
|
||||
c: Context<{ Variables: { user: { id: string; name: string } } }>,
|
||||
next: Next,
|
||||
) => {
|
||||
c.set('user', { id: 'user1', name: 'Test User' })
|
||||
await next()
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@shumai/core/src/authz/authz')
|
||||
vi.mock('@shumai/core/src/notification/notification')
|
||||
vi.mock('@shumai/core/src/user-metadata/user-metadata')
|
||||
|
||||
describe('notification api', () => {
|
||||
const app = new Hono<{ Variables: { user: { id: string; name: string } } }>()
|
||||
.use('*', async (c, next) => {
|
||||
c.set('user', { id: 'user1', name: 'Test User' })
|
||||
await next()
|
||||
})
|
||||
.route('/', notificationRoute)
|
||||
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
vi.mocked(authzService.hasPermission).mockResolvedValue(undefined)
|
||||
})
|
||||
|
||||
it('GET /teams/:teamId/notifications', async () => {
|
||||
vi.mocked(notificationService.list).mockResolvedValue({
|
||||
data: [{ id: 'n1', type: 'comment_created' }] as any, // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
pageInfo: { total: 1, cursor: 'abc' },
|
||||
})
|
||||
|
||||
const res = await app.request('/teams/t1/notifications?unreadOnly=true&pageSize=10')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.data).toHaveLength(1)
|
||||
expect(json.pageInfo.total).toBe(1)
|
||||
expect(json.pageInfo.cursor).toBe('abc')
|
||||
|
||||
expect(notificationService.list).toHaveBeenCalledWith('t1', 'user1', {
|
||||
unreadOnly: true,
|
||||
after: undefined,
|
||||
pageSize: 10,
|
||||
})
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: expect.anything(),
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Team,
|
||||
id: 't1',
|
||||
})
|
||||
})
|
||||
|
||||
it('POST /teams/:teamId/notifications/read', async () => {
|
||||
// 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 res = await app.request('/teams/t1/notifications/read', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ notificationId: 'n1' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(204)
|
||||
expect(notificationService.markRead).toHaveBeenCalledWith('t1', 'user1', 'n1')
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: expect.anything(),
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Team,
|
||||
id: 't1',
|
||||
})
|
||||
})
|
||||
|
||||
it('GET /teams/:teamId/notifications/settings - returns default settings', async () => {
|
||||
vi.mocked(userMetadataService.getMetadata).mockResolvedValue(null)
|
||||
|
||||
const res = await app.request('/teams/t1/notifications/settings')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.comments).toBe(true)
|
||||
expect(json.yourUploads).toBe(false)
|
||||
|
||||
expect(userMetadataService.getMetadata).toHaveBeenCalledWith(
|
||||
'user1',
|
||||
't1',
|
||||
'notification_settings',
|
||||
)
|
||||
})
|
||||
|
||||
it('GET /teams/:teamId/notifications/settings - returns saved settings', async () => {
|
||||
vi.mocked(userMetadataService.getMetadata).mockResolvedValue({
|
||||
key: 'notification_settings',
|
||||
value: {
|
||||
comments: false,
|
||||
replies: false,
|
||||
mentions: true,
|
||||
yourUploads: true,
|
||||
otherUploads: false,
|
||||
statusUpdates: true,
|
||||
},
|
||||
})
|
||||
|
||||
const res = await app.request('/teams/t1/notifications/settings')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.comments).toBe(false)
|
||||
expect(json.yourUploads).toBe(true)
|
||||
})
|
||||
|
||||
it('POST /teams/:teamId/notifications/settings - saves settings', async () => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.mocked(userMetadataService.upsertMetadata).mockResolvedValue(undefined as any)
|
||||
|
||||
const res = await app.request('/teams/t1/notifications/settings', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
comments: false,
|
||||
replies: false,
|
||||
mentions: true,
|
||||
yourUploads: true,
|
||||
otherUploads: false,
|
||||
statusUpdates: true,
|
||||
}),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.success).toBe(true)
|
||||
|
||||
expect(userMetadataService.upsertMetadata).toHaveBeenCalledWith(
|
||||
'user1',
|
||||
't1',
|
||||
'notification_settings',
|
||||
{
|
||||
comments: false,
|
||||
replies: false,
|
||||
mentions: true,
|
||||
yourUploads: true,
|
||||
otherUploads: false,
|
||||
statusUpdates: true,
|
||||
},
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,113 @@
|
||||
import { zValidator } from '@hono/zod-validator'
|
||||
import { Hono } from 'hono'
|
||||
import { notificationService } from '@shumai/core/src/notification/notification'
|
||||
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
import {
|
||||
listNotificationsRequestSchema,
|
||||
markNotificationReadRequestSchema,
|
||||
notificationSettingsSchema,
|
||||
} from '@shumai/dtos'
|
||||
import { userMetadataService } from '@shumai/core/src/user-metadata/user-metadata'
|
||||
import type { Prisma } from '@shumai/db'
|
||||
|
||||
type User = Prisma.UserGetPayload<Record<string, never>>
|
||||
|
||||
const route = new Hono<{ Variables: { user: User } }>()
|
||||
.get(
|
||||
'/teams/:teamId/notifications',
|
||||
zValidator('query', listNotificationsRequestSchema),
|
||||
async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
const req = c.req.valid('query')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const res = await notificationService.list(teamId, user.id, {
|
||||
unreadOnly: req.unreadOnly,
|
||||
after: req.after,
|
||||
pageSize: req.pageSize,
|
||||
})
|
||||
|
||||
// To align with Go struct casing, map pageInfo to page_info
|
||||
return c.json({
|
||||
data: res.data,
|
||||
pageInfo: {
|
||||
total: res.pageInfo.total,
|
||||
cursor: res.pageInfo.cursor,
|
||||
},
|
||||
})
|
||||
},
|
||||
)
|
||||
.post(
|
||||
'/teams/:teamId/notifications/read',
|
||||
zValidator('json', markNotificationReadRequestSchema),
|
||||
async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
const req = c.req.valid('json')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
await notificationService.markRead(teamId, user.id, req.notificationId)
|
||||
|
||||
return new Response(null, { status: 204 })
|
||||
},
|
||||
)
|
||||
.get('/teams/:teamId/notifications/settings', async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const metadata = await userMetadataService.getMetadata(user.id, teamId, 'notification_settings')
|
||||
const settings = metadata
|
||||
? metadata.value
|
||||
: {
|
||||
comments: true,
|
||||
replies: true,
|
||||
mentions: true,
|
||||
yourUploads: false,
|
||||
otherUploads: true,
|
||||
statusUpdates: true,
|
||||
}
|
||||
|
||||
return c.json(settings)
|
||||
})
|
||||
.post(
|
||||
'/teams/:teamId/notifications/settings',
|
||||
zValidator('json', notificationSettingsSchema),
|
||||
async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
await userMetadataService.upsertMetadata(user.id, teamId, 'notification_settings', req)
|
||||
|
||||
return c.json({ success: true })
|
||||
},
|
||||
)
|
||||
|
||||
export default route
|
||||
@@ -0,0 +1,180 @@
|
||||
import { describe, expect, it, vi, beforeEach } from 'vitest'
|
||||
import { Hono, type Context, type Next } from 'hono'
|
||||
import projectRoute from './project'
|
||||
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
import { projectService } from '@shumai/core/src/project/project'
|
||||
import { assetService } from '@shumai/core/src/asset/asset'
|
||||
|
||||
vi.mock('./middleware/auth', () => ({
|
||||
authMiddleware: async (
|
||||
c: Context<{ Variables: { user: { id: string; name: string } } }>,
|
||||
next: Next,
|
||||
) => {
|
||||
c.set('user', { id: 'user1', name: 'Test User' })
|
||||
await next()
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@shumai/core/src/authz/authz')
|
||||
vi.mock('@shumai/core/src/project/project')
|
||||
vi.mock('@shumai/core/src/asset/asset')
|
||||
|
||||
describe('project api', () => {
|
||||
const app = new Hono<{ Variables: { user: { id: string; name: string } } }>()
|
||||
.use('*', async (c, next) => {
|
||||
c.set('user', { id: 'user1', name: 'Test User' })
|
||||
await next()
|
||||
})
|
||||
.route('/', projectRoute)
|
||||
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
vi.mocked(authzService.hasPermission).mockResolvedValue(undefined)
|
||||
})
|
||||
|
||||
it('GET /teams/:teamId/projects', async () => {
|
||||
vi.mocked(projectService.listProjects).mockResolvedValue({
|
||||
data: [{ id: 'foo', name: 'foo.png', rootFolder: 'uid' }] as any, // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
pageInfo: { total: 100, cursor: 'abc' },
|
||||
})
|
||||
|
||||
const res = await app.request('/teams/t/projects?page_size=10')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.data).toHaveLength(1)
|
||||
expect(json.pageInfo.total).toBe(100)
|
||||
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 () => {
|
||||
vi.mocked(projectService.createProject).mockResolvedValue({
|
||||
id: 'foo',
|
||||
name: 'foo.png',
|
||||
coverImage: 'http://s3/bucket/key',
|
||||
} as any) // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
|
||||
const res = await app.request('/teams/t/projects', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name: 'foo.png', coverImageKey: 'key' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.id).toBe('foo')
|
||||
expect(json.name).toBe('foo.png')
|
||||
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 /projects/:projectId', async () => {
|
||||
vi.mocked(projectService.updateProject).mockResolvedValue({
|
||||
id: 'foo',
|
||||
name: 'updated',
|
||||
coverImage: 'http://s3/bucket/key',
|
||||
} as any) // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
|
||||
const res = await app.request('/projects/foo', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name: 'updated' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
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 () => {
|
||||
vi.mocked(projectService.getProject).mockResolvedValue({
|
||||
id: 'p',
|
||||
name: 'foo.png',
|
||||
rootFolder: 'root_folder_id',
|
||||
} as any) // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
|
||||
const res = await app.request('/projects/p')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.rootFolder).toBe('root_folder_id')
|
||||
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 () => {
|
||||
vi.mocked(projectService.getProjectTeam).mockResolvedValue('teamId')
|
||||
|
||||
const res = await app.request('/projects/p/team')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
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 () => {
|
||||
vi.mocked(assetService.reparentAssets).mockResolvedValue(undefined)
|
||||
|
||||
const res = await app.request('/projects/p/reparent', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
newParentId: 'new_parent_id',
|
||||
assetIds: ['asset_1', 'asset_2'],
|
||||
}),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(204)
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: expect.anything(),
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id: 'new_parent_id',
|
||||
})
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: expect.anything(),
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id: 'asset_1',
|
||||
})
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: expect.anything(),
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id: 'asset_2',
|
||||
})
|
||||
expect(assetService.reparentAssets).toHaveBeenCalledWith({
|
||||
newParentId: 'new_parent_id',
|
||||
assetIds: ['asset_1', 'asset_2'],
|
||||
creatorId: 'user1',
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,248 @@
|
||||
import { Hono } from 'hono'
|
||||
import { zValidator } from '@hono/zod-validator'
|
||||
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
import { projectService } from '@shumai/core/src/project/project'
|
||||
import { assetService } from '@shumai/core/src/asset/asset'
|
||||
import { reparentAssetsRequestSchema, copyAssetsRequestSchema } from '@shumai/dtos'
|
||||
import {
|
||||
createProjectRequestSchema,
|
||||
updateProjectRequestSchema,
|
||||
listProjectsRequestSchema,
|
||||
recentlyDeletedRequestSchema,
|
||||
} from '@shumai/dtos'
|
||||
import { listMembersQuerySchema } from '@shumai/dtos'
|
||||
import type { Prisma } from '@shumai/db'
|
||||
|
||||
type User = Prisma.UserGetPayload<Record<string, never>>
|
||||
|
||||
const route = new Hono<{ Variables: { user: User } }>()
|
||||
.post('/teams/:teamId/projects', zValidator('json', createProjectRequestSchema), async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const newProject = await projectService.createProject(user, {
|
||||
teamId,
|
||||
...req,
|
||||
})
|
||||
|
||||
return c.json(newProject)
|
||||
})
|
||||
.put('/projects/:projectId', zValidator('json', updateProjectRequestSchema), async (c) => {
|
||||
const projectId = c.req.param('projectId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Project,
|
||||
id: projectId,
|
||||
})
|
||||
|
||||
const updatedProject = await projectService.updateProject({
|
||||
projectId,
|
||||
...req,
|
||||
})
|
||||
|
||||
return c.json(updatedProject)
|
||||
})
|
||||
.get(
|
||||
'/projects/:projectId/recently-deleted',
|
||||
zValidator('query', recentlyDeletedRequestSchema),
|
||||
async (c) => {
|
||||
const projectId = c.req.param('projectId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('query')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Project,
|
||||
id: projectId,
|
||||
})
|
||||
|
||||
const resp = await assetService.listChildren({
|
||||
projectId,
|
||||
assetType: req.assetType,
|
||||
showDeleted: true,
|
||||
after: req.after,
|
||||
first: req.first,
|
||||
})
|
||||
return c.json(resp)
|
||||
},
|
||||
)
|
||||
.get('/teams/:teamId/projects', zValidator('query', listProjectsRequestSchema), async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('query')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const res = await projectService.listProjects({
|
||||
teamId,
|
||||
userId: user.id,
|
||||
sortBy: req.sortBy,
|
||||
sortDirection: req.sortDirection,
|
||||
pagination: req,
|
||||
})
|
||||
|
||||
return c.json({
|
||||
data: res.data,
|
||||
pageInfo: {
|
||||
total: res.pageInfo.total,
|
||||
cursor: res.pageInfo.cursor,
|
||||
},
|
||||
})
|
||||
})
|
||||
.get('/projects/:projectId', async (c) => {
|
||||
const projectId = c.req.param('projectId')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Project,
|
||||
id: projectId,
|
||||
})
|
||||
|
||||
const p = await projectService.getProject(projectId)
|
||||
return c.json(p)
|
||||
})
|
||||
.delete('/projects/:projectId', async (c) => {
|
||||
const projectId = c.req.param('projectId')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Project,
|
||||
id: projectId,
|
||||
})
|
||||
|
||||
await projectService.deleteProject(projectId)
|
||||
return c.json({ success: true })
|
||||
})
|
||||
.get('/projects/:projectId/team', async (c) => {
|
||||
const projectId = c.req.param('projectId')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Project,
|
||||
id: projectId,
|
||||
})
|
||||
|
||||
const teamId = await projectService.getProjectTeam(projectId)
|
||||
return c.json({ teamId })
|
||||
})
|
||||
.get('/projects/:projectId/members', zValidator('query', listMembersQuerySchema), async (c) => {
|
||||
const projectId = c.req.param('projectId')
|
||||
const user = c.get('user')
|
||||
const { includeAgents } = c.req.valid('query')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Project,
|
||||
id: projectId,
|
||||
})
|
||||
|
||||
const members = await projectService.listProjectMembers({
|
||||
projectId,
|
||||
includeAgents: includeAgents,
|
||||
})
|
||||
return c.json(members)
|
||||
})
|
||||
.get('/projects/:projectId/bots', async (c) => {
|
||||
const projectId = c.req.param('projectId')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Project,
|
||||
id: projectId,
|
||||
})
|
||||
|
||||
// STUB: AgentService is not migrated yet.
|
||||
return c.json([])
|
||||
})
|
||||
|
||||
.post(
|
||||
'/projects/:projectId/reparent',
|
||||
zValidator('json', reparentAssetsRequestSchema),
|
||||
async (c) => {
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
// Check Edit permission on target folder/project
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id: req.newParentId,
|
||||
})
|
||||
|
||||
// Check Edit permission on all source assets
|
||||
for (const assetId of req.assetIds) {
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id: assetId,
|
||||
})
|
||||
}
|
||||
|
||||
await assetService.reparentAssets({
|
||||
...req,
|
||||
creatorId: user.id,
|
||||
})
|
||||
|
||||
return c.body(null, 204)
|
||||
},
|
||||
)
|
||||
.post('/projects/:projectId/copy', zValidator('json', copyAssetsRequestSchema), async (c) => {
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
// Check Edit permission on target folder/project
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id: req.newParentId,
|
||||
})
|
||||
|
||||
// Check Read permission on all source assets
|
||||
for (const assetId of req.assetIds) {
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Asset,
|
||||
id: assetId,
|
||||
})
|
||||
}
|
||||
|
||||
await assetService.copyAssets({
|
||||
...req,
|
||||
creatorId: user.id,
|
||||
})
|
||||
|
||||
return c.body(null, 204)
|
||||
})
|
||||
|
||||
export default route
|
||||
@@ -0,0 +1,192 @@
|
||||
import { describe, expect, it, vi, beforeEach } from 'vitest'
|
||||
import { Hono, type Context, type Next } from 'hono'
|
||||
import providerRoute from './provider'
|
||||
import { providerService } from '@shumai/core/src/provider/provider'
|
||||
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
|
||||
vi.mock('./middleware/auth', () => ({
|
||||
authMiddleware: async (
|
||||
c: Context<{ Variables: { user: { id: string; name: string } } }>,
|
||||
next: Next,
|
||||
) => {
|
||||
c.set('user', { id: 'user1', name: 'Test User' })
|
||||
await next()
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@shumai/core/src/authz/authz')
|
||||
vi.mock('@shumai/core/src/provider/provider')
|
||||
|
||||
describe('provider api', () => {
|
||||
const app = new Hono<{ Variables: { user: { id: string; name: string } } }>()
|
||||
.use('*', async (c, next) => {
|
||||
c.set('user', { id: 'user1', name: 'Test User' })
|
||||
await next()
|
||||
})
|
||||
.route('/', providerRoute)
|
||||
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
vi.mocked(authzService.hasPermission).mockResolvedValue(undefined)
|
||||
})
|
||||
|
||||
it('GET /teams/:teamId/providers returns providers', async () => {
|
||||
vi.mocked(providerService.listByTeam).mockResolvedValue([
|
||||
{ id: 'p1', name: 'openai', config: { api: 'openai' } },
|
||||
] as unknown as Awaited<ReturnType<typeof providerService.listByTeam>>)
|
||||
|
||||
const res = await app.request('/teams/t1/providers')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data).toHaveLength(1)
|
||||
expect(data[0].id).toBe('p1')
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: expect.anything(),
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Team,
|
||||
id: 't1',
|
||||
})
|
||||
})
|
||||
|
||||
it('GET /providers/:id/models returns models', async () => {
|
||||
vi.mocked(providerService.getById).mockResolvedValue({
|
||||
id: 'p1',
|
||||
teamId: 't1',
|
||||
} as unknown as Awaited<ReturnType<typeof providerService.getById>>)
|
||||
vi.mocked(providerService.listModelsByProvider).mockResolvedValue([
|
||||
{ modelId: 'm1', name: 'model1' },
|
||||
] as unknown as Awaited<ReturnType<typeof providerService.listModelsByProvider>>)
|
||||
|
||||
const res = await app.request('/providers/p1/models')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data).toHaveLength(1)
|
||||
expect(data[0].modelId).toBe('m1')
|
||||
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 () => {
|
||||
const config = {
|
||||
baseUrl: 'https://api.openai.com/v1',
|
||||
api: 'openai-completions',
|
||||
}
|
||||
const models = [
|
||||
{
|
||||
modelId: 'gpt-4',
|
||||
name: 'GPT-4',
|
||||
config: {
|
||||
api: 'openai-completions',
|
||||
reasoning: false,
|
||||
input: ['text' as const],
|
||||
contextWindow: 128000,
|
||||
maxTokens: 4096,
|
||||
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
|
||||
},
|
||||
},
|
||||
]
|
||||
vi.mocked(providerService.create).mockResolvedValue({
|
||||
id: 'p1',
|
||||
name: 'openai',
|
||||
config,
|
||||
models,
|
||||
} as unknown as Awaited<ReturnType<typeof providerService.create>>)
|
||||
|
||||
const res = await app.request('/teams/t1/providers', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name: 'openai', config, models }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data.name).toBe('openai')
|
||||
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 /providers/:id updates provider', async () => {
|
||||
const config = {
|
||||
baseUrl: 'https://new-url.com',
|
||||
api: 'openai-completions',
|
||||
}
|
||||
const models = [
|
||||
{
|
||||
modelId: 'gpt-4',
|
||||
name: 'GPT-4',
|
||||
config: {
|
||||
api: 'openai-completions',
|
||||
reasoning: false,
|
||||
input: ['text' as const],
|
||||
contextWindow: 128000,
|
||||
maxTokens: 4096,
|
||||
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
|
||||
},
|
||||
},
|
||||
]
|
||||
vi.mocked(providerService.getById).mockResolvedValue({
|
||||
id: 'p1',
|
||||
teamId: 't1',
|
||||
} as unknown as Awaited<ReturnType<typeof providerService.getById>>)
|
||||
vi.mocked(providerService.update).mockResolvedValue({
|
||||
id: 'p1',
|
||||
name: 'openai',
|
||||
config,
|
||||
models,
|
||||
} as unknown as Awaited<ReturnType<typeof providerService.update>>)
|
||||
|
||||
const res = await app.request('/providers/p1', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ config, models }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data.config.baseUrl).toBe('https://new-url.com')
|
||||
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 /providers/:id deletes provider', async () => {
|
||||
vi.mocked(providerService.getById).mockResolvedValue({
|
||||
id: 'p1',
|
||||
teamId: 't1',
|
||||
} as unknown as Awaited<ReturnType<typeof providerService.getById>>)
|
||||
vi.mocked(providerService.delete).mockResolvedValue({
|
||||
id: 'p1',
|
||||
} as unknown as Awaited<ReturnType<typeof providerService.delete>>)
|
||||
|
||||
const res = await app.request('/providers/p1', {
|
||||
method: 'DELETE',
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data.success).toBe(true)
|
||||
expect(providerService.delete).toHaveBeenCalledWith('t1', 'p1')
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: expect.anything(),
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Provider,
|
||||
id: 'p1',
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,97 @@
|
||||
import { zValidator } from '@hono/zod-validator'
|
||||
import { Hono } from 'hono'
|
||||
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
import { providerService } from '@shumai/core/src/provider/provider'
|
||||
import { createProviderRequestSchema, updateProviderRequestSchema } from '@shumai/dtos'
|
||||
import type { Prisma } from '@shumai/db'
|
||||
|
||||
type User = Prisma.UserGetPayload<Record<string, never>>
|
||||
|
||||
const route = new Hono<{ Variables: { user: User } }>()
|
||||
.get('/teams/:teamId/providers', async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const providers = await providerService.listByTeam(teamId)
|
||||
return c.json(providers)
|
||||
})
|
||||
|
||||
.get('/providers/:id/models', async (c) => {
|
||||
const id = c.req.param('id')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Provider,
|
||||
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)
|
||||
})
|
||||
|
||||
.post('/teams/:teamId/providers', zValidator('json', createProviderRequestSchema), async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
const user = c.get('user')
|
||||
const { name, config, models } = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const provider = await providerService.create(teamId, name, config, models)
|
||||
return c.json(provider)
|
||||
})
|
||||
|
||||
.put('/providers/:id', zValidator('json', updateProviderRequestSchema), async (c) => {
|
||||
const id = c.req.param('id')
|
||||
const user = c.get('user')
|
||||
const { config, models } = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Provider,
|
||||
id,
|
||||
})
|
||||
|
||||
const providerBefore = await providerService.getById(id)
|
||||
if (!providerBefore) throw new Error('Provider not found')
|
||||
|
||||
const provider = await providerService.update(providerBefore.teamId, id, config, models)
|
||||
return c.json(provider)
|
||||
})
|
||||
|
||||
.delete('/providers/:id', async (c) => {
|
||||
const id = c.req.param('id')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Provider,
|
||||
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 })
|
||||
})
|
||||
|
||||
export default route
|
||||
@@ -0,0 +1,36 @@
|
||||
import { Hono } from 'hono'
|
||||
import { inviteService } from '@shumai/core/src/invite/invite'
|
||||
import { InviteInfo } from '@shumai/dtos'
|
||||
|
||||
const app = new Hono()
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const mapToInviteInfo = (inv: any): InviteInfo => {
|
||||
const info: InviteInfo = {
|
||||
code: inv.code,
|
||||
role: inv.role!,
|
||||
teamId: inv.teamId,
|
||||
teamName: inv.team.name,
|
||||
inviterName: inv.inviter.name,
|
||||
isUsed: inv.used,
|
||||
}
|
||||
|
||||
if (inv.project) {
|
||||
info.projectId = inv.project.id
|
||||
info.projectName = inv.project.name
|
||||
}
|
||||
|
||||
return info
|
||||
}
|
||||
|
||||
const route = app.get('/invite/:code', async (c) => {
|
||||
const code = c.req.param('code')
|
||||
try {
|
||||
const inv = await inviteService.getInvite(code)
|
||||
return c.json(mapToInviteInfo(inv))
|
||||
} catch {
|
||||
return c.json({ error: 'Not found' }, 404)
|
||||
}
|
||||
})
|
||||
|
||||
export default route
|
||||
@@ -0,0 +1,250 @@
|
||||
import { Hono } from 'hono'
|
||||
import { zValidator } from '@hono/zod-validator'
|
||||
import { shareService } from '@shumai/core/src/share/share'
|
||||
import { assetService } from '@shumai/core/src/asset/asset'
|
||||
import { paginationParamsSchema } from '@shumai/dtos'
|
||||
import { z } from 'zod'
|
||||
import { metadataService } from '@shumai/core/src/metadata/metadata'
|
||||
import { FieldInfo } from '@shumai/dtos'
|
||||
import type { Prisma as PrismaType } from '@shumai/db'
|
||||
import { auth } from '@shumai/core/src/auth/auth'
|
||||
import { prisma } from '@shumai/db'
|
||||
import { createCommentRequestSchema } from '@shumai/dtos'
|
||||
import { notificationService } from '@shumai/core/src/notification/notification'
|
||||
|
||||
const app = new Hono()
|
||||
|
||||
function toFieldInfo(
|
||||
f: PrismaType.MetadataFieldGetPayload<Record<string, never>>,
|
||||
visible = false,
|
||||
): FieldInfo {
|
||||
return {
|
||||
id: f.key,
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
config: f.config as any,
|
||||
scope: f.scope ?? '',
|
||||
readOnly: f.readOnly,
|
||||
visible: visible,
|
||||
description: f.description,
|
||||
aiAutofill: f.aiAutofill,
|
||||
}
|
||||
}
|
||||
|
||||
const sharedChildrenRequestSchema = paginationParamsSchema.extend({
|
||||
assetType: z.string().optional(),
|
||||
})
|
||||
|
||||
const route = app
|
||||
.get('/shares/:shareId/info', async (c) => {
|
||||
const shareId = c.req.param('shareId')
|
||||
try {
|
||||
const shareLink = await shareService.getShareLink(shareId)
|
||||
return c.json({
|
||||
id: shareLink.id,
|
||||
name: shareLink.name,
|
||||
expireAt: shareLink.expireAt,
|
||||
isDisabled: shareLink.isDisabled,
|
||||
isExpired: shareLink.isExpired,
|
||||
hasPassword: shareLink.hasPassword,
|
||||
rootFolderId: shareLink.rootFolderId,
|
||||
projectId: shareLink.projectId,
|
||||
})
|
||||
} catch (err) {
|
||||
return c.json({ error: (err as Error).message }, 404)
|
||||
}
|
||||
})
|
||||
.get('/shares/:shareId/fields', async (c) => {
|
||||
const shareId = c.req.param('shareId')
|
||||
const password = c.req.header('x-share-password')
|
||||
|
||||
try {
|
||||
const shareLink = await shareService.getShareLink(shareId)
|
||||
await shareService.verifyPublicAccess(shareLink.rootFolderId, password)
|
||||
|
||||
const fields = await metadataService.listProjectFields(null, shareLink.projectId)
|
||||
const fieldVisibility = (shareLink.fieldVisibility || {}) as Record<string, boolean>
|
||||
|
||||
return c.json(
|
||||
fields
|
||||
.filter((f) => fieldVisibility[f.field.key])
|
||||
.map((f) => toFieldInfo(f.field, f.visible)),
|
||||
)
|
||||
} catch (err) {
|
||||
const msg = (err as Error).message
|
||||
if (msg === 'Invalid password for share link') {
|
||||
return c.json({ error: 'Unauthorized' }, 401)
|
||||
}
|
||||
if (msg === 'Share link has expired' || msg === 'Share link is disabled') {
|
||||
return c.json({ error: msg }, 403)
|
||||
}
|
||||
return c.json({ error: msg }, 500)
|
||||
}
|
||||
})
|
||||
.get(
|
||||
'/shares/:shareId/folders/:folderId/children',
|
||||
zValidator('query', sharedChildrenRequestSchema),
|
||||
async (c) => {
|
||||
const folderId = c.req.param('folderId')
|
||||
const password = c.req.header('x-share-password')
|
||||
const req = c.req.valid('query')
|
||||
|
||||
try {
|
||||
const shareLink = await shareService.verifyPublicAccess(folderId, password)
|
||||
|
||||
let sort: string | undefined
|
||||
let order: string | undefined
|
||||
|
||||
if (shareLink.defaultSortOrder) {
|
||||
const parts = shareLink.defaultSortOrder.split(':')
|
||||
sort = parts[0]
|
||||
order = parts[1]
|
||||
}
|
||||
|
||||
const res = await assetService.listChildren({
|
||||
...req,
|
||||
assetId: folderId,
|
||||
assetType: req.assetType || 'file',
|
||||
sort,
|
||||
order,
|
||||
})
|
||||
|
||||
return c.json(res)
|
||||
} catch (err) {
|
||||
const msg = (err as Error).message
|
||||
if (msg === 'Invalid password for share link') {
|
||||
return c.json({ error: 'Unauthorized' }, 401)
|
||||
}
|
||||
if (msg === 'Share link has expired' || msg === 'Share link is disabled') {
|
||||
return c.json({ error: msg }, 403)
|
||||
}
|
||||
return c.json({ error: msg }, 500)
|
||||
}
|
||||
},
|
||||
)
|
||||
.get('/shares/:shareId/files/:fileId', async (c) => {
|
||||
const fileId = c.req.param('fileId')
|
||||
const password = c.req.header('x-share-password')
|
||||
|
||||
try {
|
||||
await shareService.verifyPublicAccess(fileId, password)
|
||||
|
||||
const asset = await assetService.getAsset({ assetId: fileId })
|
||||
return c.json(asset)
|
||||
} catch (err) {
|
||||
const msg = (err as Error).message
|
||||
if (msg === 'Invalid password for share link') {
|
||||
return c.json({ error: 'Unauthorized' }, 401)
|
||||
}
|
||||
if (msg === 'Share link has expired' || msg === 'Share link is disabled') {
|
||||
return c.json({ error: msg }, 403)
|
||||
}
|
||||
return c.json({ error: msg }, 500)
|
||||
}
|
||||
})
|
||||
.get(
|
||||
'/shares/:shareId/files/:fileId/comments',
|
||||
zValidator('query', paginationParamsSchema),
|
||||
async (c) => {
|
||||
const fileId = c.req.param('fileId')
|
||||
const password = c.req.header('x-share-password')
|
||||
const req = c.req.valid('query')
|
||||
|
||||
try {
|
||||
await shareService.verifyPublicAccess(fileId, password)
|
||||
|
||||
const targetFileId = await assetService.resolveTargetAssetId(fileId)
|
||||
const res = await assetService.listComments(targetFileId, req)
|
||||
return c.json(res)
|
||||
} catch (err) {
|
||||
const msg = (err as Error).message
|
||||
if (msg === 'Invalid password for share link') {
|
||||
return c.json({ error: 'Unauthorized' }, 401)
|
||||
}
|
||||
if (msg === 'Share link has expired' || msg === 'Share link is disabled') {
|
||||
return c.json({ error: msg }, 403)
|
||||
}
|
||||
return c.json({ error: msg }, 500)
|
||||
}
|
||||
},
|
||||
)
|
||||
.post(
|
||||
'/shares/:shareId/files/:fileId/comments',
|
||||
zValidator('json', createCommentRequestSchema.omit({ assetId: true, userId: true })),
|
||||
async (c) => {
|
||||
const shareId = c.req.param('shareId')
|
||||
const fileId = c.req.param('fileId')
|
||||
const password = c.req.header('x-share-password')
|
||||
const guestUserId = c.req.header('x-guest-user-id')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
try {
|
||||
const shareLink = await shareService.getShareLink(shareId)
|
||||
await shareService.verifyPublicAccess(fileId, password)
|
||||
|
||||
const targetFileId = await assetService.resolveTargetAssetId(fileId)
|
||||
|
||||
const project = await prisma.project.findUnique({
|
||||
where: { id: shareLink.projectId },
|
||||
select: { teamId: true },
|
||||
})
|
||||
|
||||
if (!project) {
|
||||
throw new Error('Project not found')
|
||||
}
|
||||
|
||||
// Identify user
|
||||
let userId: string | null = null
|
||||
const session = await auth.api.getSession({
|
||||
headers: c.req.raw.headers,
|
||||
})
|
||||
|
||||
if (session?.user) {
|
||||
userId = session.user.id
|
||||
} else if (guestUserId) {
|
||||
const guestUser = await prisma.user.findUnique({
|
||||
where: { id: guestUserId },
|
||||
})
|
||||
if (guestUser) {
|
||||
userId = guestUser.id
|
||||
}
|
||||
}
|
||||
|
||||
if (!userId) {
|
||||
return c.json({ error: 'Unauthorized' }, 401)
|
||||
}
|
||||
|
||||
const comment = await assetService.createComment({
|
||||
assetId: targetFileId,
|
||||
userId: userId,
|
||||
replyToId: req.replyToId,
|
||||
message: req.message,
|
||||
annotations: req.annotations,
|
||||
second: req.second,
|
||||
attachmentIds: req.attachmentIds,
|
||||
})
|
||||
|
||||
const notifType = req.replyToId ? 'reply_created' : 'comment_created'
|
||||
|
||||
notificationService.create({
|
||||
type: notifType,
|
||||
teamId: project.teamId,
|
||||
creatorId: userId,
|
||||
assetId: targetFileId,
|
||||
commentMessage: req.message,
|
||||
})
|
||||
|
||||
return c.json(comment, 201)
|
||||
} catch (err) {
|
||||
const msg = (err as Error).message
|
||||
if (msg === 'Invalid password for share link') {
|
||||
return c.json({ error: 'Unauthorized' }, 401)
|
||||
}
|
||||
if (msg === 'Share link has expired' || msg === 'Share link is disabled') {
|
||||
return c.json({ error: msg }, 403)
|
||||
}
|
||||
return c.json({ error: msg }, 500)
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
export default route
|
||||
@@ -0,0 +1,57 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { Hono } from 'hono'
|
||||
|
||||
const { mockServeStatic } = vi.hoisted(() => ({
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
mockServeStatic: vi.fn<(args: any) => any>(() => (c: any) => c.text('static-file')),
|
||||
}))
|
||||
|
||||
vi.mock('hono/bun', () => ({
|
||||
serveStatic: mockServeStatic,
|
||||
}))
|
||||
|
||||
describe('S3 API', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('GET /files/* calls serveStatic with correct options', async () => {
|
||||
const { default: route } = await import('./s3')
|
||||
const app = new Hono().route('/files', route)
|
||||
|
||||
const res = await app.request('/files/b1/test.webp')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.text()).toBe('static-file')
|
||||
expect(mockServeStatic).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
root: './data',
|
||||
rewriteRequestPath: expect.any(Function),
|
||||
}),
|
||||
)
|
||||
|
||||
// Verify rewriteRequestPath logic
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const options = vi.mocked(mockServeStatic).mock.calls[0][0] as any
|
||||
if (options && options.rewriteRequestPath) {
|
||||
expect(options.rewriteRequestPath('/files/b1/test.webp')).toBe('b1/test.webp')
|
||||
}
|
||||
})
|
||||
|
||||
it('PUT /files/:bucket/:key calls s3Service.putObject', async () => {
|
||||
const { default: route } = await import('./s3')
|
||||
const app = new Hono().route('/files', route)
|
||||
const mockPut = vi.spyOn(s3Service, 'putObject').mockResolvedValue(undefined)
|
||||
const body = new TextEncoder().encode('test-data')
|
||||
|
||||
const res = await app.request('/files/b1/test.webp', {
|
||||
method: 'PUT',
|
||||
body,
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.text()).toBe('OK')
|
||||
expect(mockPut).toHaveBeenCalledWith('b1', 'test.webp', expect.any(Buffer), body.byteLength)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,27 @@
|
||||
import { Hono } from 'hono'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { serveStatic } from 'hono/bun'
|
||||
|
||||
const route = new Hono()
|
||||
.get(
|
||||
'/*',
|
||||
serveStatic({
|
||||
root: './data',
|
||||
rewriteRequestPath: (path) => path.replace(/^\/files\//, ''),
|
||||
}),
|
||||
)
|
||||
.put('/:bucket/:key{.+}', async (c) => {
|
||||
const bucket = c.req.param('bucket')
|
||||
const key = c.req.param('key')
|
||||
const body = await c.req.arrayBuffer()
|
||||
|
||||
try {
|
||||
await s3Service.putObject(bucket, key, Buffer.from(body), body.byteLength)
|
||||
return c.text('OK')
|
||||
} catch (e: unknown) {
|
||||
const error = e as Error
|
||||
return c.text(error.message || 'Internal Server Error', 500)
|
||||
}
|
||||
})
|
||||
|
||||
export default route
|
||||
@@ -0,0 +1,244 @@
|
||||
import { describe, expect, test, vi, beforeEach } from 'vitest'
|
||||
import { Hono } from 'hono'
|
||||
import shareRoute from './share'
|
||||
import publicShareRoute from './public-share'
|
||||
import { authMiddleware } from './middleware/auth'
|
||||
import { shareService } from '@shumai/core/src/share/share'
|
||||
import { assetService } from '@shumai/core/src/asset/asset'
|
||||
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
|
||||
vi.mock('./middleware/auth', () => ({
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
authMiddleware: async (c: any, next: any) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
c.set('user', { id: 'user1', name: 'Test User' } as any)
|
||||
await next()
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@shumai/core/src/authz/authz', () => ({
|
||||
authzService: {
|
||||
hasPermission: vi.fn().mockResolvedValue(undefined),
|
||||
},
|
||||
Permission: {
|
||||
Read: 'Read',
|
||||
Edit: 'Edit',
|
||||
Admin: 'Admin',
|
||||
},
|
||||
ResourceType: {
|
||||
Project: 'project',
|
||||
Share: 'share',
|
||||
Asset: 'asset',
|
||||
},
|
||||
}))
|
||||
|
||||
describe('Share API', () => {
|
||||
const app = new Hono()
|
||||
.route('/', publicShareRoute)
|
||||
.use('*', authMiddleware)
|
||||
.route('/', shareRoute)
|
||||
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
vi.mocked(authzService.hasPermission).mockResolvedValue(undefined)
|
||||
})
|
||||
|
||||
// Public Routes
|
||||
describe('GET /shares/:shareId/info', () => {
|
||||
test('Success', async () => {
|
||||
vi.spyOn(shareService, 'getShareLink').mockResolvedValue({
|
||||
id: 'share1',
|
||||
name: 'Public Share',
|
||||
isDisabled: false,
|
||||
isExpired: false,
|
||||
hasPassword: true,
|
||||
rootFolderId: 'folder1',
|
||||
projectId: 'project1',
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
})
|
||||
|
||||
const res = await app.request('/shares/share1/info', {
|
||||
method: 'GET',
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.json()
|
||||
expect(body.name).toBe('Public Share')
|
||||
expect(body.hasPassword).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('GET /shares/:shareId/folders/:folderId/children', () => {
|
||||
test('Success', async () => {
|
||||
vi.spyOn(shareService, 'verifyPublicAccess').mockResolvedValue({
|
||||
id: 'share1',
|
||||
name: 'My Share',
|
||||
isDisabled: false,
|
||||
rootFolderId: 'folder1',
|
||||
projectId: 'project1',
|
||||
password: null,
|
||||
expireAt: null,
|
||||
defaultSortOrder: 'name:asc',
|
||||
fieldVisibility: null,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} as any)
|
||||
vi.spyOn(assetService, 'listChildren').mockResolvedValue({
|
||||
data: [],
|
||||
pageInfo: { total: 0, cursor: undefined },
|
||||
})
|
||||
|
||||
const res = await app.request('/shares/share1/folders/folder1/children?assetType=file', {
|
||||
method: 'GET',
|
||||
headers: { 'x-share-password': 'pass' },
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(shareService.verifyPublicAccess).toHaveBeenCalledWith('folder1', 'pass')
|
||||
expect(assetService.listChildren).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
assetId: 'folder1',
|
||||
assetType: 'file',
|
||||
sort: 'name',
|
||||
order: 'asc',
|
||||
}),
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
// Protected Routes
|
||||
describe('POST /projects/:projectId/shares', () => {
|
||||
test('Success', async () => {
|
||||
vi.spyOn(shareService, 'createShareLink').mockResolvedValue({
|
||||
id: 'share1',
|
||||
name: 'test-share',
|
||||
isDisabled: false,
|
||||
rootFolderId: 'root1',
|
||||
projectId: 'project1',
|
||||
isExpired: false,
|
||||
hasPassword: false,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
})
|
||||
|
||||
const res = await app.request('/projects/project1/shares', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name: 'My Share' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.json()
|
||||
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' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('GET /projects/:projectId/shares', () => {
|
||||
test('Success', async () => {
|
||||
vi.spyOn(shareService, 'listProjectShareLinks').mockResolvedValue({
|
||||
data: [],
|
||||
pageInfo: { total: 0, cursor: undefined },
|
||||
})
|
||||
|
||||
const res = await app.request('/projects/project1/shares', {
|
||||
method: 'GET',
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
type: ResourceType.Project,
|
||||
id: 'project1',
|
||||
permission: Permission.Read,
|
||||
}),
|
||||
)
|
||||
expect(shareService.listProjectShareLinks).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
projectId: 'project1',
|
||||
}),
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('GET /shares/:shareId', () => {
|
||||
test('Success', async () => {
|
||||
vi.spyOn(shareService, 'getShareLink').mockResolvedValue({
|
||||
id: 'share1',
|
||||
name: 'test-share',
|
||||
isDisabled: false,
|
||||
rootFolderId: 'root1',
|
||||
projectId: 'project1',
|
||||
isExpired: false,
|
||||
hasPassword: false,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
})
|
||||
|
||||
const res = await app.request('/shares/share1', {
|
||||
method: 'GET',
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
type: ResourceType.Share,
|
||||
id: 'share1',
|
||||
permission: Permission.Read,
|
||||
}),
|
||||
)
|
||||
expect(shareService.getShareLink).toHaveBeenCalledWith('share1')
|
||||
})
|
||||
})
|
||||
|
||||
describe('POST /shares/:shareId/assets', () => {
|
||||
test('Success', async () => {
|
||||
vi.spyOn(shareService, 'getShareLink').mockResolvedValue({
|
||||
id: 'share1',
|
||||
name: 'test-share',
|
||||
isDisabled: false,
|
||||
rootFolderId: 'root1',
|
||||
projectId: 'project1',
|
||||
isExpired: false,
|
||||
hasPassword: false,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
})
|
||||
vi.spyOn(shareService, 'addAssetToShare').mockResolvedValue(1)
|
||||
|
||||
const res = await app.request('/shares/share1/assets', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ assetIds: ['asset1'] }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.json()
|
||||
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'] })
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,142 @@
|
||||
import { Hono } from 'hono'
|
||||
import { zValidator } from '@hono/zod-validator'
|
||||
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
import { shareService } from '@shumai/core/src/share/share'
|
||||
import {
|
||||
createShareLinkRequestSchema,
|
||||
updateShareLinkRequestSchema,
|
||||
listShareLinksRequestSchema,
|
||||
addAssetToShareRequestSchema,
|
||||
} from '@shumai/dtos'
|
||||
import type { Prisma } from '@shumai/db'
|
||||
|
||||
type User = Prisma.UserGetPayload<Record<string, never>>
|
||||
|
||||
const route = new Hono<{ Variables: { user: User } }>()
|
||||
.post(
|
||||
'/projects/:projectId/shares',
|
||||
zValidator('json', createShareLinkRequestSchema),
|
||||
async (c) => {
|
||||
const projectId = c.req.param('projectId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Project,
|
||||
id: projectId,
|
||||
})
|
||||
|
||||
const shareLink = await shareService.createShareLink(projectId, req)
|
||||
return c.json(shareLink)
|
||||
},
|
||||
)
|
||||
.get(
|
||||
'/projects/:projectId/shares',
|
||||
zValidator('query', listShareLinksRequestSchema),
|
||||
async (c) => {
|
||||
const projectId = c.req.param('projectId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('query')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Project,
|
||||
id: projectId,
|
||||
})
|
||||
|
||||
const res = await shareService.listProjectShareLinks({
|
||||
...req,
|
||||
projectId,
|
||||
})
|
||||
|
||||
return c.json(res)
|
||||
},
|
||||
)
|
||||
.get('/shares/:shareId', async (c) => {
|
||||
const shareId = c.req.param('shareId')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Share,
|
||||
id: shareId,
|
||||
})
|
||||
|
||||
const shareLink = await shareService.getShareLink(shareId)
|
||||
return c.json(shareLink)
|
||||
})
|
||||
.put('/shares/:shareId', zValidator('json', updateShareLinkRequestSchema), async (c) => {
|
||||
const shareId = c.req.param('shareId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Share,
|
||||
id: shareId,
|
||||
})
|
||||
|
||||
const updated = await shareService.updateShareLink(shareId, req)
|
||||
return c.json(updated)
|
||||
})
|
||||
.delete('/shares/:shareId', async (c) => {
|
||||
const shareId = c.req.param('shareId')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Share,
|
||||
id: shareId,
|
||||
})
|
||||
|
||||
await shareService.deleteShareLink(shareId)
|
||||
return c.body(null, 204)
|
||||
})
|
||||
.post('/shares/:shareId/assets', zValidator('json', addAssetToShareRequestSchema), async (c) => {
|
||||
const shareId = c.req.param('shareId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
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({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Asset,
|
||||
id: assetId,
|
||||
})
|
||||
}
|
||||
|
||||
const addedCount = await shareService.addAssetToShare(shareId, req)
|
||||
return c.json({ addedCount })
|
||||
})
|
||||
.delete('/shares/:shareId/assets/:assetId', async (c) => {
|
||||
const shareId = c.req.param('shareId')
|
||||
const assetId = c.req.param('assetId') // symlink asset id
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Share,
|
||||
id: shareId,
|
||||
})
|
||||
|
||||
await shareService.removeAssetFromShare(shareId, assetId)
|
||||
return c.body(null, 204)
|
||||
})
|
||||
|
||||
export default route
|
||||
@@ -0,0 +1,200 @@
|
||||
import { describe, expect, test, vi, beforeEach } from 'vitest'
|
||||
import { Hono } from 'hono'
|
||||
import skillRoute from './skill'
|
||||
import { skillService } from '@shumai/core/src/skill/skill'
|
||||
import { authMiddleware } from './middleware/auth'
|
||||
import { authzService, ResourceType, Permission } from '@shumai/core/src/authz/authz'
|
||||
|
||||
vi.mock('./middleware/auth', () => ({
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
authMiddleware: async (c: any, next: any) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
c.set('user', { id: 'user1', name: 'Test User' } as any)
|
||||
await next()
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@shumai/core/src/authz/authz', () => ({
|
||||
authzService: {
|
||||
hasPermission: vi.fn().mockResolvedValue(undefined),
|
||||
},
|
||||
Permission: {
|
||||
Read: 'Read',
|
||||
Edit: 'Edit',
|
||||
Admin: 'Admin',
|
||||
},
|
||||
ResourceType: {
|
||||
Team: 'team',
|
||||
Skill: 'skill',
|
||||
},
|
||||
}))
|
||||
|
||||
describe('Skill API', () => {
|
||||
const app = new Hono().use('*', authMiddleware).route('/', skillRoute)
|
||||
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
vi.mocked(authzService.hasPermission).mockResolvedValue(undefined)
|
||||
})
|
||||
|
||||
describe('GET /teams/:teamId/skills', () => {
|
||||
test('Success', async () => {
|
||||
const mockSkills = [
|
||||
{
|
||||
id: 'skill1',
|
||||
name: 'Skill 1',
|
||||
description: 'Desc 1',
|
||||
config: null,
|
||||
assetId: 'asset1',
|
||||
hash: 'hash1',
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
},
|
||||
]
|
||||
vi.spyOn(skillService, 'listSkills').mockResolvedValue(mockSkills)
|
||||
|
||||
const res = await app.request('/teams/team1/skills', {
|
||||
method: 'GET',
|
||||
headers: { Authorization: 'Bearer test' },
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({ skills: mockSkills })
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
type: ResourceType.Team,
|
||||
id: 'team1',
|
||||
permission: Permission.Admin,
|
||||
}),
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('POST /teams/:teamId/skills', () => {
|
||||
test('Success with assetId', async () => {
|
||||
const mockSkill = {
|
||||
id: 'skill1',
|
||||
name: 'Skill 1',
|
||||
description: 'Desc 1',
|
||||
config: null,
|
||||
assetId: 'asset1',
|
||||
hash: 'hash1',
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
}
|
||||
vi.spyOn(skillService, 'upsertSkill').mockResolvedValue(mockSkill)
|
||||
|
||||
const res = await app.request('/teams/team1/skills', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Authorization: 'Bearer test' },
|
||||
body: JSON.stringify({ assetId: 'asset1' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
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' })
|
||||
})
|
||||
|
||||
test('Success with githubUrl', async () => {
|
||||
const mockSkill = {
|
||||
id: 'skill1',
|
||||
name: 'Skill 1',
|
||||
description: 'Desc 1',
|
||||
config: null,
|
||||
assetId: 'asset1',
|
||||
hash: 'hash1',
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
}
|
||||
vi.spyOn(skillService, 'upsertSkill').mockResolvedValue(mockSkill)
|
||||
|
||||
const res = await app.request('/teams/team1/skills', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Authorization: 'Bearer test' },
|
||||
body: JSON.stringify({ githubUrl: 'https://github.com/test/repo' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual(mockSkill)
|
||||
expect(skillService.upsertSkill).toHaveBeenCalledWith('team1', {
|
||||
githubUrl: 'https://github.com/test/repo',
|
||||
})
|
||||
})
|
||||
|
||||
test('Forbidden without Admin permission', async () => {
|
||||
vi.mocked(authzService.hasPermission).mockRejectedValueOnce(new Error('Forbidden'))
|
||||
|
||||
const res = await app.request('/teams/team1/skills', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Authorization: 'Bearer test' },
|
||||
body: JSON.stringify({ assetId: 'asset1' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(500) // The app uses a global error handler that returns 500 for thrown errors in these tests
|
||||
})
|
||||
})
|
||||
|
||||
describe('DELETE /skills/:id', () => {
|
||||
test('Success', async () => {
|
||||
vi.spyOn(skillService, 'deleteSkill').mockResolvedValue(undefined)
|
||||
|
||||
const res = await app.request('/skills/skill1', {
|
||||
method: 'DELETE',
|
||||
headers: { Authorization: 'Bearer test' },
|
||||
})
|
||||
|
||||
expect(res.status).toBe(204)
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
type: ResourceType.Skill,
|
||||
id: 'skill1',
|
||||
permission: Permission.Admin,
|
||||
}),
|
||||
)
|
||||
expect(skillService.deleteSkill).toHaveBeenCalledWith('skill1')
|
||||
})
|
||||
})
|
||||
|
||||
describe('PATCH /skills/:id/config', () => {
|
||||
test('Success', async () => {
|
||||
const mockConfig = {
|
||||
environmentVariables: [{ name: 'TEST_VAR', default: 'test_val' }],
|
||||
}
|
||||
const mockSkill = {
|
||||
id: 'skill1',
|
||||
name: 'Skill 1',
|
||||
description: 'Desc 1',
|
||||
config: mockConfig,
|
||||
assetId: 'asset1',
|
||||
hash: 'hash1',
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
}
|
||||
vi.spyOn(skillService, 'updateSkillConfig').mockResolvedValue(mockSkill)
|
||||
|
||||
const res = await app.request('/skills/skill1/config', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json', Authorization: 'Bearer test' },
|
||||
body: JSON.stringify({ config: mockConfig }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
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)
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,77 @@
|
||||
import { Hono } from 'hono'
|
||||
import { zValidator } from '@hono/zod-validator'
|
||||
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
import { skillService } from '@shumai/core/src/skill/skill'
|
||||
import { upsertSkillRequestSchema, updateSkillConfigRequestSchema } from '@shumai/dtos'
|
||||
import type { Prisma } from '@shumai/db'
|
||||
|
||||
type User = Prisma.UserGetPayload<Record<string, never>>
|
||||
|
||||
const route = new Hono<{ Variables: { user: User } }>()
|
||||
.get('/teams/:teamId/skills', async (c) => {
|
||||
const user = c.get('user')
|
||||
const teamId = c.req.param('teamId')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const skills = await skillService.listSkills(teamId)
|
||||
return c.json({ skills })
|
||||
})
|
||||
.post('/teams/:teamId/skills', zValidator('json', upsertSkillRequestSchema), async (c) => {
|
||||
const user = c.get('user')
|
||||
const teamId = c.req.param('teamId')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
try {
|
||||
const skill = await skillService.upsertSkill(teamId, req)
|
||||
return c.json(skill)
|
||||
} catch (err: unknown) {
|
||||
if (err instanceof Error && err.name === 'ConflictError') {
|
||||
return c.json({ error: err.message }, 409)
|
||||
}
|
||||
throw err
|
||||
}
|
||||
})
|
||||
.delete('/skills/:id', async (c) => {
|
||||
const user = c.get('user')
|
||||
const id = c.req.param('id')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Skill,
|
||||
id,
|
||||
})
|
||||
|
||||
await skillService.deleteSkill(id)
|
||||
return new Response(null, { status: 204 })
|
||||
})
|
||||
.patch('/skills/:id/config', zValidator('json', updateSkillConfigRequestSchema), async (c) => {
|
||||
const user = c.get('user')
|
||||
const id = c.req.param('id')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Skill,
|
||||
id,
|
||||
})
|
||||
|
||||
const skill = await skillService.updateSkillConfig(id, req.config)
|
||||
return c.json(skill)
|
||||
})
|
||||
|
||||
export default route
|
||||
@@ -0,0 +1,278 @@
|
||||
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { Hono } from 'hono'
|
||||
import teamRoute from './team'
|
||||
import { authMiddleware } from './middleware/auth'
|
||||
import { teamService } from '@shumai/core/src/team/team'
|
||||
import { userMetadataService } from '@shumai/core/src/user-metadata/user-metadata'
|
||||
import { notificationService } from '@shumai/core/src/notification/notification'
|
||||
import { authzService, ResourceType, Permission } from '@shumai/core/src/authz/authz'
|
||||
|
||||
vi.mock('@shumai/core/src/authz/authz', () => ({
|
||||
authzService: {
|
||||
hasPermission: vi.fn().mockResolvedValue(undefined),
|
||||
},
|
||||
Permission: {
|
||||
Read: 'Read',
|
||||
Edit: 'Edit',
|
||||
Admin: 'Admin',
|
||||
},
|
||||
ResourceType: {
|
||||
Team: 'team',
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('./middleware/auth', () => ({
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
authMiddleware: async (c: any, next: any) => {
|
||||
c.set('user', { id: 'user1', name: 'Test User' })
|
||||
await next()
|
||||
},
|
||||
}))
|
||||
|
||||
describe('team api', () => {
|
||||
const app = new Hono().use('*', authMiddleware).route('/', teamRoute)
|
||||
let mockCreateTeam: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockGetUserTeams: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockJoinTeam: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockGetMe: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockGetTeamMembers: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockGetSettings: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockUpdateSettings: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockListUserMetadata: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockUpsertUserMetadata: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockCreateNotification: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockGetSandboxSettings: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockUpdateSandboxSettings: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
|
||||
beforeEach(() => {
|
||||
mockCreateTeam = vi.spyOn(teamService, 'createTeam')
|
||||
mockGetUserTeams = vi.spyOn(teamService, 'getUserTeams')
|
||||
mockJoinTeam = vi.spyOn(teamService, 'joinTeam')
|
||||
mockGetMe = vi.spyOn(teamService, 'getMe')
|
||||
mockGetTeamMembers = vi.spyOn(teamService, 'getTeamMembers')
|
||||
mockGetSettings = vi.spyOn(teamService, 'getSettings')
|
||||
mockUpdateSettings = vi.spyOn(teamService, 'updateSettings')
|
||||
mockListUserMetadata = vi.spyOn(userMetadataService, 'listMetadata')
|
||||
mockUpsertUserMetadata = vi.spyOn(userMetadataService, 'upsertMetadata')
|
||||
mockCreateNotification = vi.spyOn(notificationService, 'create').mockResolvedValue()
|
||||
mockGetSandboxSettings = vi.spyOn(teamService, 'getSandboxSettings')
|
||||
mockUpdateSandboxSettings = vi.spyOn(teamService, 'updateSandboxSettings')
|
||||
vi.mocked(authzService.hasPermission).mockResolvedValue(undefined)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('POST /teams creates a new team', async () => {
|
||||
const mockTeam = { id: 't1', name: 'New Team', updatedAt: new Date() }
|
||||
mockCreateTeam.mockResolvedValue(mockTeam)
|
||||
|
||||
const res = await app.request('/teams', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
name: 'New Team',
|
||||
}),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data.id).toBe('t1')
|
||||
expect(mockCreateTeam).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ id: 'user1' }),
|
||||
expect.objectContaining({ name: 'New Team' }),
|
||||
)
|
||||
})
|
||||
|
||||
it('GET /teams returns user teams', async () => {
|
||||
mockGetUserTeams.mockResolvedValue({
|
||||
data: [{ id: 't1', name: 'User Team', updatedAt: new Date() }],
|
||||
pageInfo: { total: 1, cursor: undefined },
|
||||
})
|
||||
|
||||
const res = await app.request('/teams?first=10')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data.data[0].id).toBe('t1')
|
||||
expect(mockGetUserTeams).toHaveBeenCalledWith(expect.objectContaining({ userId: 'user1' }))
|
||||
})
|
||||
|
||||
it('POST /teams/:teamId/members joins team and sends notification', async () => {
|
||||
mockJoinTeam.mockResolvedValue(undefined)
|
||||
|
||||
const res = await app.request('/teams/t1/members', { method: 'POST' })
|
||||
|
||||
expect(res.status).toBe(204)
|
||||
expect(mockJoinTeam).toHaveBeenCalledWith({ teamId: 't1', userId: 'user1' })
|
||||
expect(mockCreateNotification).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
type: 'new_user_join_team',
|
||||
teamId: 't1',
|
||||
userId: 'user1',
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('GET /teams/:teamId/me returns user role in team', async () => {
|
||||
mockGetMe.mockResolvedValue({ id: 'user1', name: 'Test User', role: 'owner' })
|
||||
|
||||
const res = await app.request('/teams/t1/me')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
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) })
|
||||
})
|
||||
|
||||
it('GET /teams/:teamId/members returns members', async () => {
|
||||
mockGetTeamMembers.mockResolvedValue([{ id: 'user1', name: 'Test User', role: 'owner' }])
|
||||
|
||||
const res = await app.request('/teams/t1/members')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
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 })
|
||||
})
|
||||
|
||||
it('GET /teams/:teamId/settings returns settings', async () => {
|
||||
mockGetSettings.mockResolvedValue({ someKey: 'some_value' })
|
||||
|
||||
const res = await app.request('/teams/t1/settings')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data.someKey).toBe('some_value')
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
type: ResourceType.Team,
|
||||
id: 't1',
|
||||
permission: Permission.Read,
|
||||
}),
|
||||
)
|
||||
expect(mockGetSettings).toHaveBeenCalledWith('t1')
|
||||
})
|
||||
|
||||
it('PATCH /teams/:teamId/settings updates settings', async () => {
|
||||
mockUpdateSettings.mockResolvedValue({ someKey: 'new_value' })
|
||||
|
||||
const res = await app.request('/teams/t1/settings', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ key: 'someKey', value: 'new_value' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
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')
|
||||
})
|
||||
|
||||
it('GET /teams/:teamId/user-metadata returns all metadata for the user in the team', async () => {
|
||||
mockListUserMetadata.mockResolvedValue([
|
||||
{ key: 'key1', value: 'value1' },
|
||||
{ key: 'key2', value: 'value2' },
|
||||
])
|
||||
|
||||
const res = await app.request('/teams/t1/user-metadata')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data).toHaveLength(2)
|
||||
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')
|
||||
})
|
||||
|
||||
it('PUT /teams/:teamId/user-metadata/:key upserts the metadata', async () => {
|
||||
mockUpsertUserMetadata.mockResolvedValue({ key: 'key1', value: 'value1' })
|
||||
|
||||
const res = await app.request('/teams/t1/user-metadata/key1', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ value: 'value1' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data.key).toBe('key1')
|
||||
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')
|
||||
})
|
||||
|
||||
it('GET /teams/:teamId/sandbox returns sandbox settings', async () => {
|
||||
mockGetSandboxSettings.mockResolvedValue({ allowedDomains: ['example.com'] })
|
||||
|
||||
const res = await app.request('/teams/t1/sandbox')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data.allowedDomains).toEqual(['example.com'])
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
type: ResourceType.Team,
|
||||
id: 't1',
|
||||
permission: Permission.Read,
|
||||
}),
|
||||
)
|
||||
expect(mockGetSandboxSettings).toHaveBeenCalledWith('t1')
|
||||
})
|
||||
|
||||
it('PUT /teams/:teamId/sandbox updates sandbox settings', async () => {
|
||||
mockUpdateSandboxSettings.mockResolvedValue({ allowedDomains: ['new.com'] })
|
||||
|
||||
const res = await app.request('/teams/t1/sandbox', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ allowedDomains: ['new.com'] }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
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'] })
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,200 @@
|
||||
import { Hono } from 'hono'
|
||||
import { zValidator } from '@hono/zod-validator'
|
||||
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
import { teamService } from '@shumai/core/src/team/team'
|
||||
import { userMetadataService } from '@shumai/core/src/user-metadata/user-metadata'
|
||||
import { notificationService } from '@shumai/core/src/notification/notification'
|
||||
import { NotificationType } from '@shumai/db'
|
||||
import {
|
||||
createTeamRequestSchema,
|
||||
getUserTeamsRequestSchema,
|
||||
updateTeamSettingsRequestSchema,
|
||||
listMembersQuerySchema,
|
||||
updateSandboxSettingsRequestSchema,
|
||||
} from '@shumai/dtos'
|
||||
import { updateUserMetadataRequestSchema } from '@shumai/dtos'
|
||||
import type { Prisma } from '@shumai/db'
|
||||
|
||||
type User = Prisma.UserGetPayload<Record<string, never>>
|
||||
|
||||
const route = new Hono<{ Variables: { user: User } }>()
|
||||
.post('/teams', zValidator('json', createTeamRequestSchema), async (c) => {
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
const newTeam = await teamService.createTeam(user, req)
|
||||
return c.json(newTeam)
|
||||
})
|
||||
.get('/teams', zValidator('query', getUserTeamsRequestSchema), async (c) => {
|
||||
const user = c.get('user')
|
||||
const pg = c.req.valid('query')
|
||||
|
||||
const teams = await teamService.getUserTeams({
|
||||
userId: user.id,
|
||||
pagination: pg,
|
||||
})
|
||||
|
||||
return c.json({
|
||||
data: teams.data,
|
||||
pageInfo: {
|
||||
total: teams.pageInfo.total,
|
||||
cursor: teams.pageInfo.cursor,
|
||||
},
|
||||
})
|
||||
})
|
||||
.post('/teams/:teamId/members', async (c) => {
|
||||
const user = c.get('user')
|
||||
const teamId = c.req.param('teamId')
|
||||
|
||||
await teamService.joinTeam({
|
||||
teamId,
|
||||
userId: user.id,
|
||||
})
|
||||
|
||||
await notificationService.create({
|
||||
type: NotificationType.new_user_join_team,
|
||||
teamId,
|
||||
userId: user.id,
|
||||
})
|
||||
|
||||
return new Response(null, { status: 204 })
|
||||
})
|
||||
.get('/teams/:teamId/me', async (c) => {
|
||||
const user = c.get('user')
|
||||
const teamId = c.req.param('teamId')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const me = await teamService.getMe({
|
||||
teamId,
|
||||
user,
|
||||
})
|
||||
|
||||
return c.json(me)
|
||||
})
|
||||
.get('/teams/:teamId/members', zValidator('query', listMembersQuerySchema), async (c) => {
|
||||
const user = c.get('user')
|
||||
const teamId = c.req.param('teamId')
|
||||
const { includeAgents } = c.req.valid('query')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const members = await teamService.getTeamMembers({
|
||||
teamId,
|
||||
includeAgents: includeAgents,
|
||||
})
|
||||
|
||||
return c.json(members)
|
||||
})
|
||||
.get('/teams/:teamId/settings', async (c) => {
|
||||
const user = c.get('user')
|
||||
const teamId = c.req.param('teamId')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const settings = await teamService.getSettings(teamId)
|
||||
return c.json(settings)
|
||||
})
|
||||
.patch(
|
||||
'/teams/:teamId/settings',
|
||||
zValidator('json', updateTeamSettingsRequestSchema),
|
||||
async (c) => {
|
||||
const user = c.get('user')
|
||||
const teamId = c.req.param('teamId')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const settings = await teamService.updateSettings(teamId, req.key, req.value)
|
||||
return c.json(settings)
|
||||
},
|
||||
)
|
||||
.get('/teams/:teamId/sandbox', async (c) => {
|
||||
const user = c.get('user')
|
||||
const teamId = c.req.param('teamId')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const sandbox = await teamService.getSandboxSettings(teamId)
|
||||
return c.json(sandbox)
|
||||
})
|
||||
.put(
|
||||
'/teams/:teamId/sandbox',
|
||||
zValidator('json', updateSandboxSettingsRequestSchema),
|
||||
async (c) => {
|
||||
const user = c.get('user')
|
||||
const teamId = c.req.param('teamId')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const sandbox = await teamService.updateSandboxSettings(teamId, req)
|
||||
return c.json(sandbox)
|
||||
},
|
||||
)
|
||||
.get('/teams/:teamId/user-metadata', async (c) => {
|
||||
const user = c.get('user')
|
||||
const teamId = c.req.param('teamId')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const metadata = await userMetadataService.listMetadata(user.id, teamId)
|
||||
return c.json(metadata)
|
||||
})
|
||||
.put(
|
||||
'/teams/:teamId/user-metadata/:key',
|
||||
zValidator('json', updateUserMetadataRequestSchema),
|
||||
async (c) => {
|
||||
const user = c.get('user')
|
||||
const teamId = c.req.param('teamId')
|
||||
const key = c.req.param('key')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const metadata = await userMetadataService.upsertMetadata(user.id, teamId, key, req.value)
|
||||
return c.json({ key: metadata.key, value: metadata.value })
|
||||
},
|
||||
)
|
||||
|
||||
export default route
|
||||
@@ -0,0 +1,122 @@
|
||||
import { describe, expect, it, vi, beforeEach } from 'vitest'
|
||||
import { Hono } from 'hono'
|
||||
import uploadRoute from './upload'
|
||||
import { authMiddleware } from './middleware/auth'
|
||||
import { uploadService } from '@shumai/core/src/upload/upload'
|
||||
import type { CreateUploadTaskResponse, TaskInfo } from '@shumai/dtos'
|
||||
import type { PaginatedData } from '@shumai/core/src/pagination'
|
||||
import { authzService, ResourceType, Permission } from '@shumai/core/src/authz/authz'
|
||||
|
||||
vi.mock('./middleware/auth', () => ({
|
||||
// We use any here because mocking Hono context and middleware
|
||||
// with full type safety is overly complex for these unit tests.
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
authMiddleware: async (c: any, next: any) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
c.set('user', { id: 'user1', name: 'Test User' } as any)
|
||||
await next()
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@shumai/core/src/authz/authz', () => ({
|
||||
authzService: {
|
||||
hasPermission: vi.fn().mockResolvedValue(undefined),
|
||||
},
|
||||
Permission: {
|
||||
Read: 'Read',
|
||||
Edit: 'Edit',
|
||||
Admin: 'Admin',
|
||||
},
|
||||
ResourceType: {
|
||||
Team: 'team',
|
||||
Asset: 'asset',
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@shumai/core/src/notification/notification', () => ({
|
||||
notificationService: {
|
||||
create: vi.fn().mockResolvedValue(undefined),
|
||||
},
|
||||
}))
|
||||
|
||||
describe('Upload API', () => {
|
||||
const app = new Hono().use('*', authMiddleware).route('/', uploadRoute)
|
||||
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
vi.mocked(authzService.hasPermission).mockResolvedValue(undefined)
|
||||
})
|
||||
|
||||
it('GET /teams/:teamId/upload/tasks', async () => {
|
||||
// We mock the return value as it is only used for checking the call
|
||||
vi.spyOn(uploadService, 'listUploadTasks').mockResolvedValue({
|
||||
data: [],
|
||||
pageInfo: {},
|
||||
} as unknown as PaginatedData<TaskInfo[]>)
|
||||
|
||||
const res = await app.request('/teams/team1/upload/tasks', {
|
||||
headers: { Authorization: 'Bearer test' },
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
type: ResourceType.Team,
|
||||
id: 'team1',
|
||||
permission: Permission.Read,
|
||||
}),
|
||||
)
|
||||
expect(uploadService.listUploadTasks).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('POST /teams/:teamId/upload/tasks', async () => {
|
||||
// We mock the return value as it is only used for checking the call
|
||||
vi.spyOn(uploadService, 'createUploadTask').mockResolvedValue({
|
||||
taskId: 'task1',
|
||||
presignedUrls: [],
|
||||
} as unknown as CreateUploadTaskResponse)
|
||||
|
||||
const res = await app.request('/teams/team1/upload/tasks', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Authorization: 'Bearer test' },
|
||||
body: JSON.stringify({
|
||||
parentId: 'parent1',
|
||||
files: [],
|
||||
}),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
type: ResourceType.Asset,
|
||||
id: 'parent1',
|
||||
permission: Permission.Edit,
|
||||
}),
|
||||
)
|
||||
expect(uploadService.createUploadTask).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('PATCH /teams/:teamId/upload/tasks/:taskId', async () => {
|
||||
vi.spyOn(uploadService, 'confirmFileUpload').mockResolvedValue(undefined)
|
||||
|
||||
const res = await app.request('/teams/team1/upload/tasks/task1', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json', Authorization: 'Bearer test' },
|
||||
body: JSON.stringify({
|
||||
fileId: 'file1',
|
||||
}),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
type: ResourceType.Asset,
|
||||
id: 'file1',
|
||||
permission: Permission.Edit,
|
||||
}),
|
||||
)
|
||||
expect(uploadService.confirmFileUpload).toHaveBeenCalledWith('user1', 'task1', {
|
||||
fileId: 'file1',
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,115 @@
|
||||
import { Hono } from 'hono'
|
||||
import { zValidator } from '@hono/zod-validator'
|
||||
import { uploadService } from '@shumai/core/src/upload/upload'
|
||||
import {
|
||||
confirmFileUploadRequestSchema,
|
||||
createUploadTaskRequestSchema,
|
||||
localUploadQuerySchema,
|
||||
} from '@shumai/dtos'
|
||||
import { paginationParamsSchema } from '@shumai/dtos'
|
||||
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
import { notificationService } from '@shumai/core/src/notification/notification'
|
||||
import { NotificationType } from '@shumai/db'
|
||||
import { s3Service, verifyLocalUrlSignature } from '@shumai/core/src/s3/s3'
|
||||
import type { Prisma } from '@shumai/db'
|
||||
|
||||
type User = Prisma.UserGetPayload<Record<string, never>>
|
||||
|
||||
const route = new Hono<{ Variables: { user: User } }>()
|
||||
.put('/upload/local', zValidator('query', localUploadQuerySchema), async (c) => {
|
||||
const { bucket, key, Signature } = c.req.valid('query')
|
||||
|
||||
if (!verifyLocalUrlSignature(bucket, key, Signature)) {
|
||||
return c.text('Invalid signature', 403)
|
||||
}
|
||||
|
||||
const contentType = c.req.header('Content-Type')
|
||||
let buffer: Buffer
|
||||
let size: number
|
||||
let finalContentType = contentType
|
||||
|
||||
if (contentType?.includes('multipart/form-data')) {
|
||||
const body = await c.req.parseBody()
|
||||
const file = body['file'] as File
|
||||
if (!file) {
|
||||
return c.text('No file uploaded', 400)
|
||||
}
|
||||
buffer = Buffer.from(await file.arrayBuffer())
|
||||
size = file.size
|
||||
finalContentType = file.type || 'application/octet-stream'
|
||||
} else {
|
||||
const arrayBuffer = await c.req.arrayBuffer()
|
||||
buffer = Buffer.from(arrayBuffer)
|
||||
size = arrayBuffer.byteLength
|
||||
}
|
||||
|
||||
await s3Service.putObject(bucket, key, buffer, size, finalContentType)
|
||||
|
||||
return c.json({ success: true })
|
||||
})
|
||||
.get('/teams/:teamId/upload/tasks', zValidator('query', paginationParamsSchema), async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
const user = c.get('user')
|
||||
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)
|
||||
return c.json(tasks)
|
||||
})
|
||||
.post(
|
||||
'/teams/:teamId/upload/tasks',
|
||||
zValidator('json', createUploadTaskRequestSchema),
|
||||
async (c) => {
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id: req.parentId,
|
||||
})
|
||||
|
||||
const resp = await uploadService.createUploadTask(user.id, req)
|
||||
return c.json(resp)
|
||||
},
|
||||
)
|
||||
.patch(
|
||||
'/teams/:teamId/upload/tasks/:taskId',
|
||||
zValidator('json', confirmFileUploadRequestSchema),
|
||||
async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
const taskId = c.req.param('taskId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id: req.fileId,
|
||||
})
|
||||
|
||||
await uploadService.confirmFileUpload(user.id, taskId, req)
|
||||
|
||||
if (!req.errorMessage) {
|
||||
await notificationService.create({
|
||||
type: NotificationType.successful_file_uploaded,
|
||||
teamId: teamId,
|
||||
creatorId: user.id,
|
||||
assetId: req.fileId,
|
||||
taskId: taskId,
|
||||
})
|
||||
}
|
||||
|
||||
return c.json({ success: true })
|
||||
},
|
||||
)
|
||||
|
||||
export default route
|
||||
@@ -0,0 +1,149 @@
|
||||
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { Hono } from 'hono'
|
||||
import versionStackRoute from './versionStack'
|
||||
import { authMiddleware } from './middleware/auth'
|
||||
import { versionStackService } from '@shumai/core/src/versionStack/versionStack'
|
||||
import { assetService } from '@shumai/core/src/asset/asset'
|
||||
import { authzService, ResourceType, Permission } from '@shumai/core/src/authz/authz'
|
||||
|
||||
vi.mock('@shumai/core/src/authz/authz', () => ({
|
||||
authzService: {
|
||||
hasPermission: vi.fn().mockResolvedValue(undefined),
|
||||
},
|
||||
Permission: {
|
||||
Read: 'Read',
|
||||
Edit: 'Edit',
|
||||
Admin: 'Admin',
|
||||
},
|
||||
ResourceType: {
|
||||
Project: 'project',
|
||||
Asset: 'asset',
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('./middleware/auth', () => ({
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
authMiddleware: async (c: any, next: any) => {
|
||||
c.set('user', { id: 'user1', name: 'Test User' })
|
||||
await next()
|
||||
},
|
||||
}))
|
||||
|
||||
describe('versionStack api', () => {
|
||||
let mockCreateVersionStack: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockChangeStackFileVersion: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockGetAsset: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockGetStackVersions: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
|
||||
beforeEach(() => {
|
||||
mockCreateVersionStack = vi.spyOn(versionStackService, 'createVersionStack')
|
||||
mockChangeStackFileVersion = vi.spyOn(versionStackService, 'changeStackFileVersion')
|
||||
mockGetAsset = vi.spyOn(assetService, 'getAsset')
|
||||
mockGetStackVersions = vi.spyOn(assetService, 'getStackVersions')
|
||||
vi.mocked(authzService.hasPermission).mockResolvedValue(undefined)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
describe('POST /projects/:projectID/version_stacks', () => {
|
||||
it('should create a version stack and return asset info', async () => {
|
||||
const mockStack = { id: 'stack1' }
|
||||
const mockAssetInfo = { id: 'stack1', type: 'version_stack', name: 'v1' }
|
||||
|
||||
mockCreateVersionStack.mockResolvedValue(mockStack)
|
||||
mockGetAsset.mockResolvedValue(mockAssetInfo)
|
||||
|
||||
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({ fileIds: ['f1', 'f2'] }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data).toEqual(mockAssetInfo)
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
type: ResourceType.Project,
|
||||
id: 'p1',
|
||||
permission: Permission.Edit,
|
||||
}),
|
||||
)
|
||||
expect(mockCreateVersionStack).toHaveBeenCalledWith({
|
||||
projectId: 'p1',
|
||||
creatorId: 'user1',
|
||||
fileIds: ['f1', 'f2'],
|
||||
})
|
||||
expect(mockGetAsset).toHaveBeenCalledWith({ assetId: 'stack1' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('POST /version_stacks/:stackID/order', () => {
|
||||
it('should change order and return 200', async () => {
|
||||
mockChangeStackFileVersion.mockResolvedValue()
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', versionStackRoute)
|
||||
|
||||
const res = await app.request('/version_stacks/stack1/order', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ fileId: 'f1', beforeId: 'f2' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
type: ResourceType.Asset,
|
||||
id: 'stack1',
|
||||
permission: Permission.Edit,
|
||||
}),
|
||||
)
|
||||
expect(mockChangeStackFileVersion).toHaveBeenCalledWith({
|
||||
stackId: 'stack1',
|
||||
fileId: 'f1',
|
||||
beforeId: 'f2',
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('GET /version_stacks/:stackID/versions', () => {
|
||||
it('should return stack versions', async () => {
|
||||
const mockVersions = [
|
||||
{
|
||||
id: 'v1',
|
||||
version: 1,
|
||||
name: 'version1.png',
|
||||
previewUrl: 'http://preview1',
|
||||
creator: { id: 'u1', name: 'User 1' },
|
||||
},
|
||||
]
|
||||
|
||||
mockGetStackVersions.mockResolvedValue(mockVersions)
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', versionStackRoute)
|
||||
|
||||
const res = await app.request('/version_stacks/stack1/versions', {
|
||||
method: 'GET',
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data).toEqual(mockVersions)
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
type: ResourceType.Asset,
|
||||
id: 'stack1',
|
||||
permission: Permission.Read,
|
||||
}),
|
||||
)
|
||||
expect(mockGetStackVersions).toHaveBeenCalledWith('stack1')
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,79 @@
|
||||
import { Hono } from 'hono'
|
||||
import { zValidator } from '@hono/zod-validator'
|
||||
import { versionStackService } from '@shumai/core/src/versionStack/versionStack'
|
||||
import { assetService } from '@shumai/core/src/asset/asset'
|
||||
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
import { createVersionStackRequestSchema, changeStackFileVersionRequestSchema } from '@shumai/dtos'
|
||||
import type { Prisma } from '@shumai/db'
|
||||
|
||||
type User = Prisma.UserGetPayload<Record<string, never>>
|
||||
|
||||
const app = new Hono<{ Variables: { user: User } }>()
|
||||
|
||||
const route = app
|
||||
.post(
|
||||
'/projects/:projectId/version_stacks',
|
||||
zValidator('json', createVersionStackRequestSchema),
|
||||
async (c) => {
|
||||
const projectId = c.req.param('projectId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Project,
|
||||
id: projectId,
|
||||
})
|
||||
|
||||
const stack = await versionStackService.createVersionStack({
|
||||
fileIds: req.fileIds,
|
||||
projectId,
|
||||
creatorId: user.id,
|
||||
})
|
||||
|
||||
const stackInfo = await assetService.getAsset({ assetId: stack.id })
|
||||
|
||||
return c.json(stackInfo)
|
||||
},
|
||||
)
|
||||
.post(
|
||||
'/version_stacks/:stackId/order',
|
||||
zValidator('json', changeStackFileVersionRequestSchema),
|
||||
async (c) => {
|
||||
const stackId = c.req.param('stackId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id: stackId,
|
||||
})
|
||||
|
||||
await versionStackService.changeStackFileVersion({
|
||||
stackId,
|
||||
fileId: req.fileId,
|
||||
beforeId: req.beforeId,
|
||||
})
|
||||
|
||||
return new Response(null, { status: 200 })
|
||||
},
|
||||
)
|
||||
.get('/version_stacks/:stackId/versions', async (c) => {
|
||||
const stackId = c.req.param('stackId')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Asset,
|
||||
id: stackId,
|
||||
})
|
||||
|
||||
const versions = await assetService.getStackVersions(stackId)
|
||||
return c.json(versions)
|
||||
})
|
||||
|
||||
export default route
|
||||
@@ -0,0 +1,22 @@
|
||||
import { loadEnvConfig } from '@shumai/core/src/env-loader'
|
||||
loadEnvConfig(process.cwd(), process.env.NODE_ENV !== 'production')
|
||||
|
||||
const command = process.argv[2]
|
||||
|
||||
if (command === 'worker') {
|
||||
const { run } = await import('./worker')
|
||||
run().catch((err) => {
|
||||
console.error(err)
|
||||
process.exit(1)
|
||||
})
|
||||
} else {
|
||||
// Default or 'serve' command
|
||||
const { run } = await import('./serve')
|
||||
run().catch((err) => {
|
||||
console.error(err)
|
||||
process.exit(1)
|
||||
})
|
||||
}
|
||||
|
||||
// Re-export AppType for frontend client.ts usage (type-only)
|
||||
export type { AppType } from './serve'
|
||||
@@ -0,0 +1,128 @@
|
||||
import index from '../../webui/index.html'
|
||||
|
||||
import type { Prisma } from '@shumai/db'
|
||||
import { Hono } from 'hono'
|
||||
import agentRoute from './api/agent'
|
||||
import attachmentRoute from './api/attachment'
|
||||
import authnRoute from './api/authn'
|
||||
import collectionRoute from './api/collection'
|
||||
import fileRoute from './api/file'
|
||||
import folderRoute from './api/folder'
|
||||
import inviteRoute from './api/invite'
|
||||
import metadataRoute from './api/metadata'
|
||||
import { authMiddleware } from './api/middleware/auth'
|
||||
import notificationRoute from './api/notification'
|
||||
import projectRoute from './api/project'
|
||||
import providerRoute from './api/provider'
|
||||
import publicInviteRoute from './api/public-invite'
|
||||
import publicShareRoute from './api/public-share'
|
||||
import s3Route from './api/s3'
|
||||
import shareRoute from './api/share'
|
||||
import skillRoute from './api/skill'
|
||||
import teamRoute from './api/team'
|
||||
import uploadRoute from './api/upload'
|
||||
import versionStackRoute from './api/versionStack'
|
||||
import { metadataService } from '@shumai/core/src/metadata/metadata'
|
||||
import { assetService } from '@shumai/core/src/asset/asset'
|
||||
import { workflowService } from '@shumai/workflow-core'
|
||||
import { initAgentWorkflows } from '@shumai/agent'
|
||||
import { initTranscodeWorkflows } from '@shumai/transcode'
|
||||
import { initDbWorkflows } from '@shumai/worker-db'
|
||||
|
||||
type User = Prisma.UserGetPayload<Record<string, never>>
|
||||
|
||||
const app = new Hono()
|
||||
|
||||
const apiRoute = new Hono<{ Variables: { user: User } }>()
|
||||
// Public Routes
|
||||
.route('/', authnRoute)
|
||||
.route('/', publicInviteRoute)
|
||||
.route('/', publicShareRoute)
|
||||
|
||||
// Protected Routes
|
||||
.use('*', authMiddleware)
|
||||
.route('/', inviteRoute)
|
||||
.route('/', providerRoute)
|
||||
.route('/', notificationRoute)
|
||||
.route('/', metadataRoute)
|
||||
.route('/', projectRoute)
|
||||
.route('/', collectionRoute)
|
||||
.route('/', teamRoute)
|
||||
.route('/', versionStackRoute)
|
||||
.route('/', fileRoute)
|
||||
.route('/', folderRoute)
|
||||
.route('/', agentRoute)
|
||||
.route('/', attachmentRoute)
|
||||
.route('/', uploadRoute)
|
||||
.route('/', shareRoute)
|
||||
.route('/', skillRoute)
|
||||
|
||||
app.route('/files', s3Route)
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
const apiAppRoute = app.route('/api', apiRoute)
|
||||
|
||||
export type AppType = typeof apiAppRoute
|
||||
|
||||
export async function run() {
|
||||
// Initialize workflows and activities for local executor mode
|
||||
initAgentWorkflows()
|
||||
initTranscodeWorkflows()
|
||||
initDbWorkflows()
|
||||
|
||||
// Start services
|
||||
await metadataService.syncSystemFields().catch(console.error)
|
||||
assetService.startCleanupJob()
|
||||
workflowService.start()
|
||||
if (process.env.WORKFLOW_EXECUTOR === 'temporal') {
|
||||
const args = process.argv.slice(2)
|
||||
let workersOption = ''
|
||||
for (let i = 0; i < args.length; i++) {
|
||||
if (args[i] === '--workers') {
|
||||
workersOption = args[i + 1] || ''
|
||||
} else if (args[i].startsWith('--workers=')) {
|
||||
workersOption = args[i].split('=')[1]
|
||||
}
|
||||
}
|
||||
|
||||
const queuesToStart = ['db_queue']
|
||||
if (workersOption === 'agent' || workersOption === 'ai') {
|
||||
queuesToStart.push('agent_queue')
|
||||
} else if (workersOption === 'transcode') {
|
||||
queuesToStart.push('transcode_queue')
|
||||
} else if (workersOption === 'all') {
|
||||
queuesToStart.push('agent_queue', 'transcode_queue')
|
||||
}
|
||||
|
||||
Promise.all(queuesToStart.map((q) => workflowService.startWorkers(q))).catch(console.error)
|
||||
}
|
||||
|
||||
const server = Bun.serve({
|
||||
port: 3000,
|
||||
fetch: app.fetch,
|
||||
routes: {
|
||||
// Serve index.html for root
|
||||
'/': index,
|
||||
|
||||
// Proxy API requests to Hono
|
||||
'/api/*': app.fetch,
|
||||
'/files/*': app.fetch,
|
||||
|
||||
// Catch-all for SPA routing (fallback to index.html)
|
||||
'/*': index,
|
||||
},
|
||||
development: process.env.NODE_ENV !== 'production',
|
||||
})
|
||||
|
||||
console.log(`🚀 Server running at ${server.url}`)
|
||||
|
||||
const shutdown = () => {
|
||||
console.log('\nShutting down gracefully...')
|
||||
assetService.stopCleanupJob()
|
||||
server.stop(true)
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
process.on('SIGINT', shutdown)
|
||||
process.on('SIGTERM', shutdown)
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import { workflowService } from '@shumai/workflow-core'
|
||||
import { TaskQueueAgent, TaskQueueTranscode } from '@shumai/workflow-core'
|
||||
import { initAgentWorkflows } from '@shumai/agent'
|
||||
import { initTranscodeWorkflows } from '@shumai/transcode'
|
||||
import { initDbWorkflows } from '@shumai/worker-db'
|
||||
|
||||
export async function run() {
|
||||
// Initialize workflows and activities
|
||||
initAgentWorkflows()
|
||||
initTranscodeWorkflows()
|
||||
initDbWorkflows()
|
||||
|
||||
const domain = process.argv[3]
|
||||
|
||||
if (!domain) {
|
||||
console.error('Please specify a worker domain.')
|
||||
console.log('Available domains: agent, transcode, all')
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
switch (domain) {
|
||||
case 'agent':
|
||||
case 'ai':
|
||||
await workflowService.startWorkers(TaskQueueAgent)
|
||||
break
|
||||
case 'transcode':
|
||||
await workflowService.startWorkers(TaskQueueTranscode)
|
||||
break
|
||||
case 'all':
|
||||
await Promise.all([
|
||||
workflowService.startWorkers(TaskQueueAgent),
|
||||
workflowService.startWorkers(TaskQueueTranscode),
|
||||
])
|
||||
break
|
||||
default:
|
||||
console.error('Unknown domain: ' + domain)
|
||||
console.log('Available domains: agent, transcode, all')
|
||||
process.exit(1)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user