diff --git a/packages/api/src/agent.test.ts b/packages/api/src/agent.test.ts index 8904b0ef..37d64845 100644 --- a/packages/api/src/agent.test.ts +++ b/packages/api/src/agent.test.ts @@ -11,22 +11,15 @@ vi.mock('@shumai/core/src/auditLog/auditLog', () => ({ logAction: vi.fn().mockResolvedValue({}), }, })) -vi.mock('@shumai/db', async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - prisma: { - agent: { - findUnique: vi.fn().mockResolvedValue({ teamId: 'team1' }), - }, - }, - } -}) describe('Agent API', () => { beforeEach(() => { vi.clearAllMocks() vi.mocked(authzService.hasPermission).mockResolvedValue(undefined) + vi.mocked(agentService.getAgent).mockResolvedValue({ + id: 'agent1', + teamId: 'team1', + } as unknown as Awaited>) }) describe('GET /teams/:teamId/agents', () => { diff --git a/packages/api/src/agent.ts b/packages/api/src/agent.ts index ea58d04d..2f082b51 100644 --- a/packages/api/src/agent.ts +++ b/packages/api/src/agent.ts @@ -13,7 +13,6 @@ import { } from '@shumai/dtos' import type { Prisma } from '@shumai/db' -import { prisma } from '@shumai/db' import { auditLogService } from '@shumai/core/src/auditLog/auditLog' type User = Prisma.UserGetPayload> @@ -163,10 +162,7 @@ const route = new Hono<{ Variables: { user: User } }>() id: agentId, }) - const existingAgent = await prisma.agent.findUnique({ - where: { id: agentId }, - select: { teamId: true }, - }) + const existingAgent = await agentService.getAgent({ agentId }) await agentService.deleteAgent({ agentId, diff --git a/packages/api/src/attachment.test.ts b/packages/api/src/attachment.test.ts index 0daeae43..7eb4ab2f 100644 --- a/packages/api/src/attachment.test.ts +++ b/packages/api/src/attachment.test.ts @@ -19,24 +19,17 @@ vi.mock('./middleware/auth', () => ({ vi.mock('@shumai/core/src/authz/authz') vi.mock('@shumai/core/src/asset/asset') +vi.mock('@shumai/core/src/project/project', () => ({ + projectService: { + getProjectTeam: vi.fn().mockResolvedValue('t1'), + }, +})) vi.mock('@shumai/core/src/auditLog/auditLog', () => ({ auditLogService: { logAction: vi.fn().mockResolvedValue({}), }, })) -vi.mock('@shumai/db', async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - prisma: { - project: { - findUnique: vi.fn().mockResolvedValue({ teamId: 't1' }), - }, - }, - } -}) - vi.mock('@shumai/core/src/s3/s3', () => ({ s3Service: { presign: vi.fn().mockResolvedValue('http://mock-s3-url'), diff --git a/packages/api/src/attachment.ts b/packages/api/src/attachment.ts index a73b32ec..551ae78c 100644 --- a/packages/api/src/attachment.ts +++ b/packages/api/src/attachment.ts @@ -4,7 +4,8 @@ import { postAttachmentRequestSchema, AuditAction } from '@shumai/dtos' import { assetService } from '@shumai/core/src/asset/asset' import { s3Service } from '@shumai/core/src/s3/s3' import { auditLogService } from '@shumai/core/src/auditLog/auditLog' -import { AssetType, prisma } from '@shumai/db' +import { projectService } from '@shumai/core/src/project/project' +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' @@ -38,14 +39,11 @@ const route = new Hono<{ Variables: { user: User } }>().post( creatorId: user.id, }) - const proj = await prisma.project.findUnique({ - where: { id: projectId }, - select: { teamId: true }, - }) - if (proj) { + const teamId = await projectService.getProjectTeam(projectId).catch(() => null) + if (teamId) { await auditLogService.logAction({ action: AuditAction.file_create, - teamId: proj.teamId, + teamId, userId: user.id, projectId, itemId: assetInfo.id, diff --git a/packages/api/src/authn.ts b/packages/api/src/authn.ts index 77793b9f..5eb39148 100644 --- a/packages/api/src/authn.ts +++ b/packages/api/src/authn.ts @@ -1,9 +1,9 @@ import { Hono } from 'hono' import { teamService } from '@shumai/core/src/team/team' +import { userService } from '@shumai/core/src/user/user' 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() @@ -31,13 +31,10 @@ const route = app 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', - }, + const user = await userService.createGuestUser({ + name: username, + email: dummyEmail, + guestEmail: email, }) return c.json({ id: user.id }) diff --git a/packages/api/src/file.test.ts b/packages/api/src/file.test.ts index 6cc92673..3f06cd69 100644 --- a/packages/api/src/file.test.ts +++ b/packages/api/src/file.test.ts @@ -1,6 +1,5 @@ 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' @@ -66,6 +65,7 @@ describe('file api', () => { vi.spyOn(assetService, 'createComment').mockImplementation(vi.fn()) vi.spyOn(assetService, 'completeComment').mockImplementation(vi.fn()) vi.spyOn(assetService, 'deleteComment').mockImplementation(vi.fn()) + vi.spyOn(assetService, 'getComment').mockResolvedValue({ id: 'comment1', assetId: 'file1' } as any) vi.spyOn(assetService, 'listComments').mockImplementation(vi.fn()) vi.spyOn(assetService, 'restoreAssets').mockImplementation(vi.fn()) vi.spyOn(metadataService, 'updateAssetMetadata').mockImplementation(vi.fn()) @@ -278,9 +278,9 @@ describe('file api', () => { project: { teamId: 'test-team' }, } as any) // eslint-disable-line @typescript-eslint/no-explicit-any - const mockFindUnique = vi.spyOn(prisma.assetComment, 'findUnique').mockResolvedValue({ + vi.mocked(assetService.getComment).mockResolvedValue({ id: 'parent-comment-id', - creatorId: 'parent-comment-creator-id', + creator: { id: 'parent-comment-creator-id' }, } as any) // eslint-disable-line @typescript-eslint/no-explicit-any const app = new Hono().use('*', authMiddleware).route('/', fileRoute) @@ -306,8 +306,6 @@ describe('file api', () => { userId: 'parent-comment-creator-id', commentMessage: 'hello reply', }) - - mockFindUnique.mockRestore() }) it('GET /files/:fileId/comments', async () => { diff --git a/packages/api/src/file.ts b/packages/api/src/file.ts index 19202065..77cc8b02 100644 --- a/packages/api/src/file.ts +++ b/packages/api/src/file.ts @@ -5,7 +5,6 @@ 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 type { Prisma } from '@shumai/db' -import { prisma } from '@shumai/db' import { auditLogService } from '@shumai/core/src/auditLog/auditLog' import { createCommentRequestSchema, @@ -187,11 +186,9 @@ const route = new Hono<{ Variables: { user: User } }>() let targetUserId: string | undefined if (req.replyToId) { - const parentComment = await prisma.assetComment.findUnique({ - where: { id: req.replyToId }, - }) - if (parentComment?.creatorId) { - targetUserId = parentComment.creatorId + const parentComment = await assetService.getComment(req.replyToId).catch(() => null) + if (parentComment?.creator?.id) { + targetUserId = parentComment.creator.id } } @@ -245,10 +242,7 @@ const route = new Hono<{ Variables: { user: User } }>() id: commentId, }) - const commentData = await prisma.assetComment.findUnique({ - where: { id: commentId }, - select: { assetId: true }, - }) + const commentData = await assetService.getComment(commentId).catch(() => null) const updated = await assetService.completeComment(commentId, req.isCompleted, user.id) @@ -277,10 +271,7 @@ const route = new Hono<{ Variables: { user: User } }>() id: commentId, }) - const commentData = await prisma.assetComment.findUnique({ - where: { id: commentId }, - select: { assetId: true }, - }) + const commentData = await assetService.getComment(commentId).catch(() => null) await assetService.deleteComment({ commentId, userId: user.id }) diff --git a/packages/api/src/metadata.test.ts b/packages/api/src/metadata.test.ts index 4bfab793..9a200970 100644 --- a/packages/api/src/metadata.test.ts +++ b/packages/api/src/metadata.test.ts @@ -18,22 +18,16 @@ vi.mock('./middleware/auth', () => ({ vi.mock('@shumai/core/src/authz/authz') vi.mock('@shumai/core/src/metadata/metadata') +vi.mock('@shumai/core/src/project/project', () => ({ + projectService: { + getProjectTeam: vi.fn().mockResolvedValue('t1'), + }, +})) vi.mock('@shumai/core/src/auditLog/auditLog', () => ({ auditLogService: { logAction: vi.fn().mockResolvedValue({}), }, })) -vi.mock('@shumai/db', async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - prisma: { - project: { - findUnique: vi.fn().mockResolvedValue({ teamId: 't1' }), - }, - }, - } -}) describe('metadata api', () => { const app = new Hono<{ Variables: { user: { id: string; name: string } } }>() diff --git a/packages/api/src/metadata.ts b/packages/api/src/metadata.ts index 90d91426..6be33322 100644 --- a/packages/api/src/metadata.ts +++ b/packages/api/src/metadata.ts @@ -1,6 +1,7 @@ import { zValidator } from '@hono/zod-validator' import { Hono } from 'hono' import { metadataService } from '@shumai/core/src/metadata/metadata' +import { projectService } from '@shumai/core/src/project/project' import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz' import { createFieldRequestSchema, @@ -10,7 +11,6 @@ import { AuditAction, } from '@shumai/dtos' import type { Prisma } from '@shumai/db' -import { prisma } from '@shumai/db' import { auditLogService } from '@shumai/core/src/auditLog/auditLog' type User = Prisma.UserGetPayload> @@ -98,11 +98,7 @@ const route = new Hono<{ Variables: { user: User } }>() let teamId = field.teamId if (field.projectId && !teamId) { - const proj = await prisma.project.findUnique({ - where: { id: field.projectId }, - select: { teamId: true }, - }) - teamId = proj?.teamId || null + teamId = await projectService.getProjectTeam(field.projectId).catch(() => null) } if (teamId) { @@ -141,11 +137,7 @@ const route = new Hono<{ Variables: { user: User } }>() let teamId = field.teamId if (field.projectId && !teamId) { - const proj = await prisma.project.findUnique({ - where: { id: field.projectId }, - select: { teamId: true }, - }) - teamId = proj?.teamId || null + teamId = await projectService.getProjectTeam(field.projectId).catch(() => null) } if (teamId) { @@ -174,15 +166,12 @@ const route = new Hono<{ Variables: { user: User } }>() const field = await metadataService.createProjectField(projectId, req) - const proj = await prisma.project.findUnique({ - where: { id: projectId }, - select: { teamId: true }, - }) + const teamId = await projectService.getProjectTeam(projectId).catch(() => null) - if (proj) { + if (teamId) { await auditLogService.logAction({ action: AuditAction.metadata_field_create, - teamId: proj.teamId, + teamId, userId: user.id, projectId, itemId: field.key, diff --git a/packages/api/src/middleware/auth.test.ts b/packages/api/src/middleware/auth.test.ts index 27367422..6f1c3e23 100644 --- a/packages/api/src/middleware/auth.test.ts +++ b/packages/api/src/middleware/auth.test.ts @@ -2,7 +2,8 @@ import { describe, expect, it, vi, beforeEach } from 'vitest' import { Hono } from 'hono' import { authMiddleware } from './auth' import { auth } from '@shumai/core/src/auth/auth' -import { prisma } from '@shumai/db' +import { userService } from '@shumai/core/src/user/user' +import { teamService } from '@shumai/core/src/team/team' vi.mock('@shumai/core/src/auth/auth', () => ({ auth: { @@ -12,14 +13,15 @@ vi.mock('@shumai/core/src/auth/auth', () => ({ }, })) -vi.mock('@shumai/db', () => ({ - prisma: { - user: { - findUnique: vi.fn(), - }, - teamMember: { - findFirst: vi.fn(), - }, +vi.mock('@shumai/core/src/user/user', () => ({ + userService: { + getUserById: vi.fn(), + }, +})) + +vi.mock('@shumai/core/src/team/team', () => ({ + teamService: { + hasWritableRoleInAnyTeam: vi.fn(), }, })) @@ -39,7 +41,7 @@ describe('authMiddleware', () => { // eslint-disable-next-line @typescript-eslint/no-explicit-any vi.mocked(auth.api.getSession).mockResolvedValue({ user: { id: 'user1' } } as any) // eslint-disable-next-line @typescript-eslint/no-explicit-any - vi.mocked(prisma.user.findUnique).mockResolvedValue({ id: 'user1' } as any) + vi.mocked(userService.getUserById).mockResolvedValue({ id: 'user1' } as any) const res = await app.request('/test') expect(res.status).toBe(200) @@ -61,7 +63,7 @@ describe('authMiddleware', () => { // eslint-disable-next-line @typescript-eslint/no-explicit-any vi.mocked(auth.api.getSession).mockResolvedValue({ user: { id: 'user1' } } as any) // eslint-disable-next-line @typescript-eslint/no-explicit-any - vi.mocked(prisma.user.findUnique).mockResolvedValue({ id: 'user1' } as any) + vi.mocked(userService.getUserById).mockResolvedValue({ id: 'user1' } as any) const res = await app.request('/test') expect(res.status).toBe(200) @@ -71,8 +73,8 @@ describe('authMiddleware', () => { // eslint-disable-next-line @typescript-eslint/no-explicit-any vi.mocked(auth.api.getSession).mockResolvedValue({ user: { id: 'user1' } } as any) // eslint-disable-next-line @typescript-eslint/no-explicit-any - vi.mocked(prisma.user.findUnique).mockResolvedValue({ id: 'user1' } as any) - vi.mocked(prisma.teamMember.findFirst).mockResolvedValue(null) // No owner/editor role + vi.mocked(userService.getUserById).mockResolvedValue({ id: 'user1' } as any) + vi.mocked(teamService.hasWritableRoleInAnyTeam).mockResolvedValue(false) // No owner/editor role const res = await app.request('/test', { method: 'POST' }) expect(res.status).toBe(403) @@ -83,7 +85,7 @@ describe('authMiddleware', () => { // eslint-disable-next-line @typescript-eslint/no-explicit-any vi.mocked(auth.api.getSession).mockResolvedValue({ user: { id: 'user1' } } as any) // eslint-disable-next-line @typescript-eslint/no-explicit-any - vi.mocked(prisma.user.findUnique).mockResolvedValue({ id: 'user1' } as any) + vi.mocked(userService.getUserById).mockResolvedValue({ id: 'user1' } as any) const res = await app.request('/test/search', { method: 'POST' }) expect(res.status).toBe(200) @@ -93,12 +95,8 @@ describe('authMiddleware', () => { // eslint-disable-next-line @typescript-eslint/no-explicit-any vi.mocked(auth.api.getSession).mockResolvedValue({ user: { id: 'user1' } } as any) // eslint-disable-next-line @typescript-eslint/no-explicit-any - vi.mocked(prisma.user.findUnique).mockResolvedValue({ id: 'user1' } as any) - vi.mocked(prisma.teamMember.findFirst).mockResolvedValue({ - id: 'member1', - role: 'owner', - // eslint-disable-next-line @typescript-eslint/no-explicit-any - } as any) + vi.mocked(userService.getUserById).mockResolvedValue({ id: 'user1' } as any) + vi.mocked(teamService.hasWritableRoleInAnyTeam).mockResolvedValue(true) const res = await app.request('/test', { method: 'POST' }) expect(res.status).toBe(200) @@ -108,12 +106,8 @@ describe('authMiddleware', () => { // eslint-disable-next-line @typescript-eslint/no-explicit-any vi.mocked(auth.api.getSession).mockResolvedValue({ user: { id: 'user1' } } as any) // eslint-disable-next-line @typescript-eslint/no-explicit-any - vi.mocked(prisma.user.findUnique).mockResolvedValue({ id: 'user1' } as any) - vi.mocked(prisma.teamMember.findFirst).mockResolvedValue({ - id: 'member1', - role: 'editor', - // eslint-disable-next-line @typescript-eslint/no-explicit-any - } as any) + vi.mocked(userService.getUserById).mockResolvedValue({ id: 'user1' } as any) + vi.mocked(teamService.hasWritableRoleInAnyTeam).mockResolvedValue(true) const res = await app.request('/test', { method: 'POST' }) expect(res.status).toBe(200) diff --git a/packages/api/src/middleware/auth.ts b/packages/api/src/middleware/auth.ts index be7e7b0b..47f690c9 100644 --- a/packages/api/src/middleware/auth.ts +++ b/packages/api/src/middleware/auth.ts @@ -1,6 +1,7 @@ import type { Prisma } from '@shumai/db' import { auth } from '@shumai/core/src/auth/auth' -import { prisma } from '@shumai/db' +import { userService } from '@shumai/core/src/user/user' +import { teamService } from '@shumai/core/src/team/team' import { createMiddleware } from 'hono/factory' type User = Prisma.UserGetPayload> @@ -24,9 +25,7 @@ export const authMiddleware = createMiddleware<{ } try { - const user = await prisma.user.findUnique({ - where: { id: session.user.id }, - }) + const user = await userService.getUserById(session.user.id) if (!user) { return c.json({ error: 'User not found' }, 401) @@ -38,14 +37,9 @@ export const authMiddleware = createMiddleware<{ const method = c.req.method.toUpperCase() const path = c.req.path if (['POST', 'PUT', 'PATCH', 'DELETE'].includes(method) && !path.endsWith('/search')) { - const member = await prisma.teamMember.findFirst({ - where: { - userId: user.id, - role: { in: ['owner', 'editor'] }, - }, - }) + const hasWritable = await teamService.hasWritableRoleInAnyTeam(user.id) - if (!member) { + if (!hasWritable) { return c.json({ error: 'System is in read-only mode' }, 403) } } diff --git a/packages/api/src/middleware/tokenAuth.test.ts b/packages/api/src/middleware/tokenAuth.test.ts index b6b2bd87..d29d9a36 100644 --- a/packages/api/src/middleware/tokenAuth.test.ts +++ b/packages/api/src/middleware/tokenAuth.test.ts @@ -1,13 +1,12 @@ import { describe, expect, it, vi, beforeEach } from 'vitest' import { Hono } from 'hono' import { tokenAuthMiddleware } from './tokenAuth' -import { prisma } from '@shumai/db' +import { apiTokenService } from '@shumai/core/src/user/api-token' +import type { Prisma } from '@shumai/db' -vi.mock('@shumai/db', () => ({ - prisma: { - apiToken: { - findUnique: vi.fn(), - }, +vi.mock('@shumai/core/src/user/api-token', () => ({ + apiTokenService: { + validateToken: vi.fn(), }, })) @@ -31,21 +30,11 @@ describe('tokenAuthMiddleware', () => { }) it('sets user when valid Authorization Bearer token is provided', async () => { - vi.mocked(prisma.apiToken.findUnique).mockResolvedValue({ - id: 'token1', - token: 'ulid_token_123', - name: 'cli-key', - userId: 'user123', - createdAt: new Date(), - updatedAt: new Date(), - user: { - id: 'user123', - name: 'John Doe', - email: 'john@example.com', - }, - // Mocking the complex PrismaPromise return type of findUnique is not feasible without any here. - // eslint-disable-next-line @typescript-eslint/no-explicit-any - } as any) + vi.mocked(apiTokenService.validateToken).mockResolvedValue({ + id: 'user123', + name: 'John Doe', + email: 'john@example.com', + } as unknown as Prisma.UserGetPayload>) const res = await app.request('/test', { headers: { @@ -54,28 +43,15 @@ describe('tokenAuthMiddleware', () => { }) expect(res.status).toBe(200) expect(await res.text()).toBe('user:user123') - expect(prisma.apiToken.findUnique).toHaveBeenCalledWith({ - where: { token: 'ulid_token_123' }, - include: { user: true }, - }) + expect(apiTokenService.validateToken).toHaveBeenCalledWith('ulid_token_123') }) it('sets user when valid x-api-key header is provided', async () => { - vi.mocked(prisma.apiToken.findUnique).mockResolvedValue({ - id: 'token1', - token: 'ulid_token_123', - name: 'cli-key', - userId: 'user123', - createdAt: new Date(), - updatedAt: new Date(), - user: { - id: 'user123', - name: 'John Doe', - email: 'john@example.com', - }, - // Mocking the complex PrismaPromise return type of findUnique is not feasible without any here. - // eslint-disable-next-line @typescript-eslint/no-explicit-any - } as any) + vi.mocked(apiTokenService.validateToken).mockResolvedValue({ + id: 'user123', + name: 'John Doe', + email: 'john@example.com', + } as unknown as Prisma.UserGetPayload>) const res = await app.request('/test', { headers: { @@ -87,7 +63,7 @@ describe('tokenAuthMiddleware', () => { }) it('returns 401 when invalid token is provided', async () => { - vi.mocked(prisma.apiToken.findUnique).mockResolvedValue(null) + vi.mocked(apiTokenService.validateToken).mockResolvedValue(null) const res = await app.request('/test', { headers: { diff --git a/packages/api/src/middleware/tokenAuth.ts b/packages/api/src/middleware/tokenAuth.ts index a3f37847..ce3c2b82 100644 --- a/packages/api/src/middleware/tokenAuth.ts +++ b/packages/api/src/middleware/tokenAuth.ts @@ -1,5 +1,5 @@ import type { Prisma } from '@shumai/db' -import { prisma } from '@shumai/db' +import { apiTokenService } from '@shumai/core/src/user/api-token' import { createMiddleware } from 'hono/factory' type User = Prisma.UserGetPayload> @@ -16,16 +16,13 @@ export const tokenAuthMiddleware = createMiddleware<{ : c.req.header('x-api-key') || null if (token) { - const apiToken = await prisma.apiToken.findUnique({ - where: { token }, - include: { user: true }, - }) + const user = await apiTokenService.validateToken(token) - if (!apiToken) { + if (!user) { return c.json({ error: 'Unauthorized: Invalid API Key' }, 401) } - c.set('user', apiToken.user) + c.set('user', user) } await next() diff --git a/packages/api/src/project.test.ts b/packages/api/src/project.test.ts index dbe355c9..363817e1 100644 --- a/packages/api/src/project.test.ts +++ b/packages/api/src/project.test.ts @@ -5,6 +5,7 @@ import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/a import { projectService } from '@shumai/core/src/project/project' import { assetService } from '@shumai/core/src/asset/asset' import { auditLogService } from '@shumai/core/src/auditLog/auditLog' +import type { ProjectInfo } from '@shumai/dtos' vi.mock('./middleware/auth', () => ({ authMiddleware: async ( @@ -17,7 +18,22 @@ vi.mock('./middleware/auth', () => ({ })) vi.mock('@shumai/core/src/authz/authz') -vi.mock('@shumai/core/src/project/project') +vi.mock('@shumai/core/src/project/project', () => ({ + projectService: { + createProject: vi.fn(), + updateProject: vi.fn(), + getProject: vi.fn(), + getProjectTeam: vi.fn().mockResolvedValue('t1'), + deleteProject: vi.fn(), + listProjects: vi.fn(), + getUserProjects: vi.fn(), + listProjectMembers: vi.fn(), + addProjectMember: vi.fn(), + updateMemberRole: vi.fn(), + removeMember: vi.fn(), + getProjectMe: vi.fn(), + }, +})) vi.mock('@shumai/core/src/asset/asset') vi.mock('@shumai/core/src/auditLog/auditLog', () => ({ auditLogService: { @@ -25,21 +41,6 @@ vi.mock('@shumai/core/src/auditLog/auditLog', () => ({ listAuditLogs: vi.fn().mockResolvedValue({ nodes: [], pageInfo: {}, total: 0 }), }, })) -vi.mock('@shumai/db', async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - prisma: { - teamMember: { - findMany: vi.fn(), - }, - project: { - findMany: vi.fn(), - findUnique: vi.fn(), - }, - }, - } -}) describe('project api', () => { const app = new Hono<{ Variables: { user: { id: string; name: string } } }>() @@ -163,10 +164,7 @@ describe('project api', () => { }) it('POST /projects/:projectId/reparent', async () => { - const { prisma } = await import('@shumai/db') - // Mocking partial Prisma project model in test - // eslint-disable-next-line @typescript-eslint/no-explicit-any - vi.mocked(prisma.project.findUnique).mockResolvedValue({ id: 'p', teamId: 't1' } as any) + vi.mocked(projectService.getProjectTeam).mockResolvedValue('t1') vi.mocked(assetService.reparentAssets).mockResolvedValue(undefined) const res = await app.request('/projects/p/reparent', { @@ -219,10 +217,7 @@ describe('project api', () => { }) it('POST /projects/:projectId/copy', async () => { - const { prisma } = await import('@shumai/db') - // Mocking partial Prisma project model in test - // eslint-disable-next-line @typescript-eslint/no-explicit-any - vi.mocked(prisma.project.findUnique).mockResolvedValue({ id: 'p', teamId: 't1' } as any) + vi.mocked(projectService.getProjectTeam).mockResolvedValue('t1') vi.mocked(assetService.copyAssets).mockResolvedValue(undefined) const res = await app.request('/projects/p/copy', { @@ -320,24 +315,16 @@ describe('project api', () => { }) it('GET /projects', async () => { - const { prisma } = await import('@shumai/db') - vi.mocked(prisma.teamMember.findMany).mockResolvedValue([ - { id: 'tm1', teamId: 'team1', userId: 'user1', scope: 'team' }, - // Mocking complex Prisma client returns requires any here - // eslint-disable-next-line @typescript-eslint/no-explicit-any - ] as any) - vi.mocked(prisma.project.findMany).mockResolvedValue([ + vi.mocked(projectService.getUserProjects).mockResolvedValue([ { id: 'proj1', name: 'My Project', teamId: 'team1', - rootFolderId: 'folder1', + rootFolder: 'folder1', enableNotification: true, - updatedAt: new Date('2026-06-21T00:00:00.000Z'), + updatedAt: '2026-06-21T00:00:00.000Z', }, - // Mocking complex Prisma client returns requires any here - // eslint-disable-next-line @typescript-eslint/no-explicit-any - ] as any) + ] as unknown as ProjectInfo[]) const res = await app.request('/projects?first=10') @@ -352,13 +339,6 @@ describe('project api', () => { enableNotification: true, updatedAt: '2026-06-21T00:00:00.000Z', }) - expect(prisma.teamMember.findMany).toHaveBeenCalledWith({ - where: { userId: 'user1' }, - }) - expect(prisma.project.findMany).toHaveBeenCalledWith({ - where: { teamId: 'team1' }, - orderBy: { id: 'desc' }, - take: 10, - }) + expect(projectService.getUserProjects).toHaveBeenCalledWith('user1', 10) }) }) diff --git a/packages/api/src/project.ts b/packages/api/src/project.ts index 08f65099..bfd00419 100644 --- a/packages/api/src/project.ts +++ b/packages/api/src/project.ts @@ -14,7 +14,6 @@ import { } from '@shumai/dtos' import { listMembersQuerySchema, paginationParamsSchema, AuditAction } from '@shumai/dtos' import type { Prisma } from '@shumai/db' -import { prisma } from '@shumai/db' import { auditLogService } from '@shumai/core/src/auditLog/auditLog' type User = Prisma.UserGetPayload> @@ -25,41 +24,16 @@ const route = new Hono<{ Variables: { user: User } }>() const req = c.req.valid('query') const limit = req.first ? Math.min(req.first, 200) : 200 - const teamMembers = await prisma.teamMember.findMany({ - where: { userId: user.id }, - }) - - type ProjectType = Prisma.ProjectGetPayload> - const allProjects: ProjectType[] = [] - - for (const member of teamMembers) { - const where: Prisma.ProjectWhereInput = { - teamId: member.teamId, - } - if (member.scope === 'project') { - where.members = { - some: { teamMemberId: member.id }, - } - } - const teamProjects = await prisma.project.findMany({ - where, - orderBy: { id: 'desc' }, - take: limit - allProjects.length, - }) - allProjects.push(...teamProjects) - if (allProjects.length >= limit) { - break - } - } + const allProjects = await projectService.getUserProjects(user.id, limit) return c.json({ data: allProjects.map((p) => ({ id: p.id, name: p.name, teamId: p.teamId, - rootFolder: p.rootFolderId || undefined, + rootFolder: p.rootFolder, enableNotification: p.enableNotification, - updatedAt: p.updatedAt.toISOString(), + updatedAt: p.updatedAt, })), }) }) @@ -107,14 +81,10 @@ const route = new Hono<{ Variables: { user: User } }>() ...req, }) - const proj = await prisma.project.findUnique({ - where: { id: projectId }, - select: { teamId: true }, - }) - if (proj) { + if (updatedProject) { await auditLogService.logAction({ action: AuditAction.project_update, - teamId: proj.teamId, + teamId: updatedProject.teamId, userId: user.id, projectId, itemId: projectId, @@ -161,14 +131,11 @@ const route = new Hono<{ Variables: { user: User } }>() await assetService.emptyTrash(projectId) - const proj = await prisma.project.findUnique({ - where: { id: projectId }, - select: { teamId: true }, - }) - if (proj) { + const teamId = await projectService.getProjectTeam(projectId).catch(() => null) + if (teamId) { await auditLogService.logAction({ action: AuditAction.project_empty_trash, - teamId: proj.teamId, + teamId, userId: user.id, projectId, itemId: projectId, @@ -230,16 +197,13 @@ const route = new Hono<{ Variables: { user: User } }>() id: projectId, }) - const proj = await prisma.project.findUnique({ - where: { id: projectId }, - select: { teamId: true }, - }) + const teamId = await projectService.getProjectTeam(projectId).catch(() => null) await projectService.deleteProject(projectId) - if (proj) { + if (teamId) { await auditLogService.logAction({ action: AuditAction.project_delete, - teamId: proj.teamId, + teamId, userId: user.id, projectId, itemId: projectId, @@ -326,15 +290,12 @@ const route = new Hono<{ Variables: { user: User } }>() creatorId: user.id, }) - const proj = await prisma.project.findUnique({ - where: { id: projectId }, - select: { teamId: true }, - }) - if (proj) { + const teamId = await projectService.getProjectTeam(projectId).catch(() => null) + if (teamId) { for (const assetId of req.assetIds) { await auditLogService.logAction({ action: AuditAction.asset_reparent, - teamId: proj.teamId, + teamId, userId: user.id, projectId, itemId: assetId, @@ -373,15 +334,12 @@ const route = new Hono<{ Variables: { user: User } }>() creatorId: user.id, }) - const proj = await prisma.project.findUnique({ - where: { id: projectId }, - select: { teamId: true }, - }) - if (proj) { + const teamId = await projectService.getProjectTeam(projectId).catch(() => null) + if (teamId) { for (const assetId of req.assetIds) { await auditLogService.logAction({ action: AuditAction.asset_copy, - teamId: proj.teamId, + teamId, userId: user.id, projectId, itemId: assetId, @@ -413,14 +371,11 @@ const route = new Hono<{ Variables: { user: User } }>() role: req.role, }) - const proj = await prisma.project.findUnique({ - where: { id: projectId }, - select: { teamId: true }, - }) - if (proj) { + const teamId = await projectService.getProjectTeam(projectId).catch(() => null) + if (teamId) { await auditLogService.logAction({ action: AuditAction.project_member_update, - teamId: proj.teamId, + teamId, userId: user.id, projectId, itemId: userId, @@ -442,16 +397,13 @@ const route = new Hono<{ Variables: { user: User } }>() id: projectId, }) - const proj = await prisma.project.findUnique({ - where: { id: projectId }, - select: { teamId: true }, - }) + const teamId = await projectService.getProjectTeam(projectId).catch(() => null) await projectService.removeMember(projectId, userId) - if (proj) { + if (teamId) { await auditLogService.logAction({ action: AuditAction.project_member_remove, - teamId: proj.teamId, + teamId, userId: user.id, projectId, itemId: userId, @@ -481,14 +433,11 @@ const route = new Hono<{ Variables: { user: User } }>() role: req.role, }) - const proj = await prisma.project.findUnique({ - where: { id: projectId }, - select: { teamId: true }, - }) - if (proj) { + const teamId = await projectService.getProjectTeam(projectId).catch(() => null) + if (teamId) { await auditLogService.logAction({ action: AuditAction.project_member_add, - teamId: proj.teamId, + teamId, userId: user.id, projectId, itemId: req.userId, diff --git a/packages/api/src/public-share.ts b/packages/api/src/public-share.ts index 9687c039..5367aaf4 100644 --- a/packages/api/src/public-share.ts +++ b/packages/api/src/public-share.ts @@ -8,8 +8,9 @@ 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 { projectService } from '@shumai/core/src/project/project' +import { userService } from '@shumai/core/src/user/user' 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' import { @@ -204,14 +205,7 @@ const route = app 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') - } + const teamId = await projectService.getProjectTeam(shareLink.projectId) // Identify user let userId: string | null = null @@ -222,9 +216,7 @@ const route = app if (session?.user) { userId = session.user.id } else if (guestUserId) { - const guestUser = await prisma.user.findUnique({ - where: { id: guestUserId }, - }) + const guestUser = await userService.getUserById(guestUserId) if (guestUser) { userId = guestUser.id } @@ -248,7 +240,7 @@ const route = app notificationService.create({ type: notifType, - teamId: project.teamId, + teamId: teamId, creatorId: userId, assetId: targetFileId, commentMessage: req.message, diff --git a/packages/api/src/share.test.ts b/packages/api/src/share.test.ts index ee1a5ea1..11633342 100644 --- a/packages/api/src/share.test.ts +++ b/packages/api/src/share.test.ts @@ -41,17 +41,11 @@ vi.mock('@shumai/core/src/auditLog/auditLog', () => ({ }, })) -vi.mock('@shumai/db', async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - prisma: { - project: { - findUnique: vi.fn().mockResolvedValue({ teamId: 't1' }), - }, - }, - } -}) +vi.mock('@shumai/core/src/project/project', () => ({ + projectService: { + getProjectTeam: vi.fn().mockResolvedValue('t1'), + }, +})) describe('Share API', () => { const app = new Hono() diff --git a/packages/api/src/share.ts b/packages/api/src/share.ts index a821eafe..2b5036bd 100644 --- a/packages/api/src/share.ts +++ b/packages/api/src/share.ts @@ -2,6 +2,7 @@ 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 { projectService } from '@shumai/core/src/project/project' import { createShareLinkRequestSchema, updateShareLinkRequestSchema, @@ -10,7 +11,6 @@ import { AuditAction, } from '@shumai/dtos' import type { Prisma } from '@shumai/db' -import { prisma } from '@shumai/db' import { auditLogService } from '@shumai/core/src/auditLog/auditLog' type User = Prisma.UserGetPayload> @@ -33,14 +33,11 @@ const route = new Hono<{ Variables: { user: User } }>() const shareLink = await shareService.createShareLink(projectId, req, user.id) - const proj = await prisma.project.findUnique({ - where: { id: projectId }, - select: { teamId: true }, - }) - if (proj) { + const teamId = await projectService.getProjectTeam(projectId).catch(() => null) + if (teamId) { await auditLogService.logAction({ action: AuditAction.share_create, - teamId: proj.teamId, + teamId, userId: user.id, projectId, itemId: shareLink.id, @@ -103,14 +100,11 @@ const route = new Hono<{ Variables: { user: User } }>() const updated = await shareService.updateShareLink(shareId, req) if (existingShare) { - const proj = await prisma.project.findUnique({ - where: { id: existingShare.projectId }, - select: { teamId: true }, - }) - if (proj) { + const teamId = await projectService.getProjectTeam(existingShare.projectId).catch(() => null) + if (teamId) { await auditLogService.logAction({ action: AuditAction.share_update, - teamId: proj.teamId, + teamId, userId: user.id, projectId: existingShare.projectId, itemId: shareId, @@ -135,14 +129,11 @@ const route = new Hono<{ Variables: { user: User } }>() await shareService.deleteShareLink(shareId) if (existingShare) { - const proj = await prisma.project.findUnique({ - where: { id: existingShare.projectId }, - select: { teamId: true }, - }) - if (proj) { + const teamId = await projectService.getProjectTeam(existingShare.projectId).catch(() => null) + if (teamId) { await auditLogService.logAction({ action: AuditAction.share_delete, - teamId: proj.teamId, + teamId, userId: user.id, projectId: existingShare.projectId, itemId: shareId, diff --git a/packages/api/src/skill.test.ts b/packages/api/src/skill.test.ts index f4e7983b..0361d9c7 100644 --- a/packages/api/src/skill.test.ts +++ b/packages/api/src/skill.test.ts @@ -13,17 +13,16 @@ vi.mock('@shumai/core/src/auditLog/auditLog', () => ({ }, })) -vi.mock('@shumai/db', async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - prisma: { - skill: { - findUnique: vi.fn().mockResolvedValue({ teamId: 'team1' }), - }, - }, - } -}) +vi.mock('@shumai/core/src/skill/skill', () => ({ + skillService: { + listSkills: vi.fn(), + upsertSkill: vi.fn(), + deleteSkill: vi.fn(), + updateSkillConfig: vi.fn(), + updateSkillPermission: vi.fn(), + getSkill: vi.fn().mockResolvedValue({ id: 'skill1', teamId: 'team1' }), + }, +})) vi.mock('./middleware/auth', () => ({ // eslint-disable-next-line @typescript-eslint/no-explicit-any @@ -55,6 +54,10 @@ describe('Skill API', () => { beforeEach(() => { vi.restoreAllMocks() vi.mocked(authzService.hasPermission).mockResolvedValue(undefined) + vi.mocked(skillService.getSkill).mockResolvedValue({ + id: 'skill1', + teamId: 'team1', + } as unknown as Awaited>) }) describe('GET /teams/:teamId/skills', () => { diff --git a/packages/api/src/skill.ts b/packages/api/src/skill.ts index 9b0b70a1..c26d7082 100644 --- a/packages/api/src/skill.ts +++ b/packages/api/src/skill.ts @@ -9,7 +9,6 @@ import { AuditAction, } from '@shumai/dtos' import type { Prisma } from '@shumai/db' -import { prisma } from '@shumai/db' import { auditLogService } from '@shumai/core/src/auditLog/auditLog' type User = Prisma.UserGetPayload> @@ -68,10 +67,7 @@ const route = new Hono<{ Variables: { user: User } }>() id, }) - const existingSkill = await prisma.skill.findUnique({ - where: { id }, - select: { teamId: true }, - }) + const existingSkill = await skillService.getSkill(id) await skillService.deleteSkill(id) @@ -98,10 +94,7 @@ const route = new Hono<{ Variables: { user: User } }>() id, }) - const existingSkill = await prisma.skill.findUnique({ - where: { id }, - select: { teamId: true }, - }) + const existingSkill = await skillService.getSkill(id) const skill = await skillService.updateSkillConfig(id, req.config) @@ -131,10 +124,7 @@ const route = new Hono<{ Variables: { user: User } }>() id, }) - const existingSkill = await prisma.skill.findUnique({ - where: { id }, - select: { teamId: true }, - }) + const existingSkill = await skillService.getSkill(id) const skill = await skillService.updateSkillPermission(id, req.permission) diff --git a/packages/core/src/agent/agent.ts b/packages/core/src/agent/agent.ts index bc175b9c..c1072f49 100644 --- a/packages/core/src/agent/agent.ts +++ b/packages/core/src/agent/agent.ts @@ -300,6 +300,12 @@ export class AgentService { }) } + async getAgent(params: { agentId: string }) { + return this.prismaClient.agent.findUnique({ + where: { id: params.agentId }, + }) + } + async deleteAgent(params: DeleteAgentParams) { const { agentId } = params diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 4d0db652..81b6c693 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -17,6 +17,7 @@ export * from './transcode/transcode' export * from './upload/upload' export * from './user-metadata/user-metadata' export * from './user/avatar' +export * from './user/user' export * from './versionStack/versionStack' export * from './hyrumtoken' export * from './pagination' diff --git a/packages/core/src/project/project.ts b/packages/core/src/project/project.ts index 62697c6d..115ba57b 100644 --- a/packages/core/src/project/project.ts +++ b/packages/core/src/project/project.ts @@ -160,6 +160,38 @@ export class ProjectService { return res } + async getUserProjects(userId: string, limit = 200): Promise { + const teamMembers = await prisma.teamMember.findMany({ + where: { userId }, + }) + + const allProjects: ProjectInfo[] = [] + + for (const member of teamMembers) { + const where: Prisma.ProjectWhereInput = { + teamId: member.teamId, + } + if (member.scope === 'project') { + where.members = { + some: { teamMemberId: member.id }, + } + } + const teamProjects = await prisma.project.findMany({ + where, + orderBy: { id: 'desc' }, + take: limit - allProjects.length, + include: { rootFolder: true }, + }) + const infos = await Promise.all(teamProjects.map((p) => this.toProjectInfo(p))) + allProjects.push(...infos) + if (allProjects.length >= limit) { + break + } + } + + return allProjects + } + async addProjectMember(req: ServiceAddProjectMemberRequest): Promise { const user = await prisma.user.findUnique({ where: { id: req.userId } }) if (!user) throw new Error('User not found') diff --git a/packages/core/src/skill/skill.ts b/packages/core/src/skill/skill.ts index 3754c789..547483ac 100644 --- a/packages/core/src/skill/skill.ts +++ b/packages/core/src/skill/skill.ts @@ -275,6 +275,17 @@ export class SkillService { return { name, description } } + async getSkill(id: string) { + const s = await this.prismaClient.skill.findUnique({ + where: { id }, + }) + if (!s) return null + return { + ...this.toSkillInfo(s), + teamId: s.teamId, + } + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any private toSkillInfo(s: any): SkillInfo { return { diff --git a/packages/core/src/team/team.ts b/packages/core/src/team/team.ts index aef23b31..8ac4988a 100644 --- a/packages/core/src/team/team.ts +++ b/packages/core/src/team/team.ts @@ -364,6 +364,16 @@ export class TeamService { } } + async hasWritableRoleInAnyTeam(userId: string): Promise { + const member = await prisma.teamMember.findFirst({ + where: { + userId, + role: { in: ['owner', 'editor'] }, + }, + }) + return !!member + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any private toTeamInfo(team: any): TeamInfo { return { diff --git a/packages/core/src/user/user.ts b/packages/core/src/user/user.ts new file mode 100644 index 00000000..3e624ae2 --- /dev/null +++ b/packages/core/src/user/user.ts @@ -0,0 +1,24 @@ +import { prisma } from '@shumai/db' + +export class UserService { + constructor(private readonly prismaClient: typeof prisma = prisma) {} + + async getUserById(id: string) { + return this.prismaClient.user.findUnique({ + where: { id }, + }) + } + + async createGuestUser(data: { name: string; email: string; guestEmail: string }) { + return this.prismaClient.user.create({ + data: { + name: data.name, + email: data.email, + guestEmail: data.guestEmail, + type: 'human', + }, + }) + } +} + +export const userService = new UserService()