feat: move MCP to /mcp and add teammate operations (#500)

* feat(operations): move MCP to /mcp and add search, comment, metadata, version, and upload operations

- Serve the MCP server at /mcp instead of /api/mcp
- Add search_assets, copy_assets, get_folder_instructions, list_comments,
  create_comment, resolve_comment, list_metadata_fields,
  update_asset_metadata, create_version_stack, list_versions, and
  remove_version on the agent, MCP, and CLI
- Add create_file and create_version (agent, MCP) with Creation Context
  metadata, and complete_upload (MCP) for presigned two-step uploads
- Replace the native agent create_file/create_version tools with
  Operation-backed ones
- Route the comment-complete, metadata, copy, version stack, and
  AGENTS.md read REST endpoints through their Operations

* docs(readme): add built-in MCP server and CLI to features list
This commit is contained in:
Yiling-J
2026-10-27 14:37:26 +08:00
committed by GitHub
parent 50fbd97953
commit b3cae4f2b0
81 changed files with 4111 additions and 1397 deletions
+58 -28
View File
@@ -1,5 +1,6 @@
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'
import { Hono, type Context, type Next } from 'hono'
import { HTTPException } from 'hono/http-exception'
import fileRoute from './file'
import { assetService } from '@shumai/core/src/asset/asset'
import { metadataService } from '@shumai/core/src/metadata/metadata'
@@ -8,7 +9,12 @@ import { s3Service } from '@shumai/core/src/s3/s3'
import { transcodeService } from '@shumai/core'
import { authMiddleware } from './middleware/auth'
import { authzService, ResourceType, Permission } from '@shumai/core/src/authz/authz'
import { renameAssetOp, runOperation } from '@shumai/core/src/operations'
import {
renameAssetOp,
resolveCommentOp,
runOperation,
updateAssetMetadataOp,
} from '@shumai/core/src/operations'
vi.mock('fs', async (importOriginal) => {
const actual = (await importOriginal()) as Record<string, unknown>
@@ -450,8 +456,9 @@ describe('file api', () => {
expect(resInvalidTz.status).toBe(400)
})
it('POST /comments/:commentId/complete', async () => {
vi.mocked(assetService.completeComment).mockResolvedValue({
it('POST /comments/:commentId/complete runs resolve_comment and returns the comment', async () => {
vi.mocked(runOperation).mockResolvedValue({ commentId: 'comment-id', resolved: true })
vi.mocked(assetService.getComment).mockResolvedValue({
id: 'comment-id',
assetId: 'file-id',
message: 'hello',
@@ -483,12 +490,33 @@ describe('file api', () => {
expect(json.isCompleted).toBe(true)
expect(json.completionLastChangedBy.id).toBe('user1')
expect(authzService.hasPermission).toHaveBeenCalledWith({
user: { id: 'user1', name: 'Test User' },
permission: Permission.Read,
type: ResourceType.Comment,
expect(runOperation).toHaveBeenCalledWith(
resolveCommentOp,
{ userId: 'user1', via: 'api' },
{ commentId: 'comment-id', reopen: false },
)
expect(assetService.getComment).toHaveBeenCalledWith('comment-id', 'user1')
})
it('POST /comments/:commentId/complete reopens with isCompleted false', async () => {
vi.mocked(runOperation).mockResolvedValue({ commentId: 'comment-id', resolved: false })
vi.mocked(assetService.getComment).mockResolvedValue({
id: 'comment-id',
isCompleted: false,
} as any) // eslint-disable-line @typescript-eslint/no-explicit-any
const app = new Hono().use('*', authMiddleware).route('/', fileRoute)
await app.request('/comments/comment-id/complete', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ isCompleted: false }),
})
expect(runOperation).toHaveBeenCalledWith(
resolveCommentOp,
{ userId: 'user1', via: 'api' },
{ commentId: 'comment-id', reopen: true },
)
})
it('DELETE /comments/:commentId', async () => {
@@ -625,41 +653,43 @@ describe('file api', () => {
)
})
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
it('PATCH /files/:fileId/metadata runs update_asset_metadata', async () => {
vi.mocked(runOperation).mockResolvedValue({ assetId: 'test-id', updatedKeys: ['status'] })
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' }]),
body: JSON.stringify([
{ key: 'status', value: 'approved' },
{ key: 'rating', value: 4 },
]),
})
expect(res.status).toBe(200)
expect(runOperation).toHaveBeenCalledWith(
updateAssetMetadataOp,
{ userId: 'user1', via: 'api' },
{ assetId: 'test-id', values: { status: 'approved', rating: 4 } },
)
})
expect(authzService.hasPermission).toHaveBeenCalledWith({
user: { id: 'user1', name: 'Test User' },
permission: Permission.Edit,
type: ResourceType.Asset,
id: 'test-id',
it('PATCH /files/:fileId/metadata does nothing for an empty list', async () => {
vi.mocked(runOperation).mockClear()
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([]),
})
expect(notificationService.create).toHaveBeenCalledWith({
type: 'metadata_field_updated_status',
teamId: 'test-team',
creatorId: 'user1',
assetId: 'test-id',
})
expect(res.status).toBe(200)
expect(runOperation).not.toHaveBeenCalled()
})
it('PATCH /files/:fileId/metadata rejects readonly fields with 422', async () => {
vi.mocked(metadataService.updateAssetMetadata).mockRejectedValue(
new Error('Field some-key is read-only'),
vi.mocked(runOperation).mockRejectedValue(
new HTTPException(422, { message: 'Field some-key is read-only' }),
)
const app = new Hono().use('*', authMiddleware).route('/', fileRoute)
+28 -71
View File
@@ -1,12 +1,16 @@
import { zValidator } from '@hono/zod-validator'
import { assetService } from '@shumai/core/src/asset/asset'
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
import { metadataService } from '@shumai/core/src/metadata/metadata'
import { notificationService } from '@shumai/core/src/notification/notification'
import { commentService } from '@shumai/core/src/comment/comment'
import { s3Service } from '@shumai/core/src/s3/s3'
import type { Prisma } from '@shumai/db'
import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
import { renameAssetOp, runOperation } from '@shumai/core/src/operations'
import {
renameAssetOp,
resolveCommentOp,
runOperation,
updateAssetMetadataOp,
} from '@shumai/core/src/operations'
import {
createCommentRequestSchema,
deleteFilesRequestSchema,
@@ -26,6 +30,7 @@ import {
import { transcodeService, buildContentDisposition } from '@shumai/core'
import fs from 'fs'
import { Hono } from 'hono'
import { HTTPException } from 'hono/http-exception'
import os from 'os'
import path from 'path'
import { ulid } from 'ulid'
@@ -106,37 +111,23 @@ const route = new Hono<{ Variables: { user: User } }>()
'/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,
})
if (req.length === 0) return c.json('')
try {
await metadataService.updateAssetMetadata(fileId, req)
await runOperation(
updateAssetMetadataOp,
{ userId: c.get('user').id, via: 'api' },
{
assetId: c.req.param('fileId'),
values: Object.fromEntries(req.map((m) => [m.key, m.value])),
},
)
} catch (err) {
if (err instanceof Error && err.message.includes('is read-only')) {
if (err instanceof HTTPException && err.status === 422) {
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)
notificationService.create({
type: 'metadata_field_updated_status',
teamId: context.teamId,
creatorId: user.id,
assetId: fileId,
})
}
return c.json('')
},
)
@@ -155,7 +146,9 @@ const route = new Hono<{ Variables: { user: User } }>()
id: fileId,
})
const comment = await assetService.createComment({
// The web app can attach markup and files, which the create_comment Operation doesn't
// expose; both post through the same service, so notifications are the same.
const comment = await commentService.postComment({
assetId: fileId,
userId: user.id,
replyToId: req.replyToId,
@@ -165,27 +158,7 @@ const route = new Hono<{ Variables: { user: User } }>()
attachmentIds: req.attachmentIds,
})
const notifType = req.replyToId ? 'reply_created' : 'comment_created'
const context = await assetService.getAssetContext(fileId)
let targetUserId: string | undefined
if (req.replyToId) {
const parentComment = await assetService.getComment(req.replyToId).catch(() => null)
if (parentComment?.creator?.id) {
targetUserId = parentComment.creator.id
}
}
notificationService.create({
type: notifType,
teamId: context.teamId,
creatorId: user.id,
assetId: fileId,
userId: targetUserId,
commentMessage: req.message,
})
await auditLogService.logAction({
action: AuditAction.comment_create,
teamId: context.teamId,
@@ -282,29 +255,13 @@ const route = new Hono<{ Variables: { user: User } }>()
const user = c.get('user')
const req = c.req.valid('json')
await authzService.hasPermission({
user,
permission: Permission.Read,
type: ResourceType.Comment,
id: commentId,
})
const commentData = await assetService.getComment(commentId).catch(() => null)
const updated = await assetService.completeComment(commentId, req.isCompleted, user.id)
if (commentData?.assetId) {
const context = await assetService.getAssetContext(commentData.assetId)
await auditLogService.logAction({
action: AuditAction.comment_complete,
teamId: context.teamId,
userId: user.id,
projectId: context.projectId,
itemId: commentId,
})
}
return c.json(updated)
await runOperation(
resolveCommentOp,
{ userId: user.id, via: 'api' },
{ commentId, reopen: !req.isCompleted },
)
// The web app shows the whole comment, so respond with it rather than the summary.
return c.json(await assetService.getComment(commentId, user.id))
},
)
.delete('/comments/:commentId', async (c) => {
+17 -13
View File
@@ -6,7 +6,12 @@ import { searchService } from '@shumai/core/src/search/search'
import { authzService, ResourceType, Permission } from '@shumai/core/src/authz/authz'
import { authMiddleware } from './middleware/auth'
import { HTTPException } from 'hono/http-exception'
import { createFolderOp, renameAssetOp, runOperation } from '@shumai/core/src/operations'
import {
createFolderOp,
getFolderInstructionsOp,
renameAssetOp,
runOperation,
} from '@shumai/core/src/operations'
import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
@@ -357,23 +362,22 @@ describe('folder api', () => {
})
})
it('GET /folders/:folderId/agentsmd', async () => {
vi.spyOn(assetService, 'getAgentsMd').mockResolvedValue('# Folder Guidelines')
it('GET /folders/:folderId/agentsmd runs get_folder_instructions', async () => {
vi.mocked(runOperation).mockResolvedValue({
folderId: 'test-id',
content: '# Folder Guidelines',
})
const app = new Hono().use('*', authMiddleware).route('/', folderRoute)
const res = await app.request('/folders/test-id/agentsmd')
expect(res.status).toBe(200)
const json = await res.json()
expect(json.content).toBe('# Folder Guidelines')
expect(authzService.hasPermission).toHaveBeenCalledWith({
user: { id: 'user1', name: 'Test User' },
permission: Permission.Read,
type: ResourceType.Asset,
id: 'test-id',
})
expect(assetService.getAgentsMd).toHaveBeenCalledWith('test-id')
expect(await res.json()).toEqual({ content: '# Folder Guidelines' })
expect(runOperation).toHaveBeenCalledWith(
getFolderInstructionsOp,
{ userId: 'user1', via: 'api' },
{ folderId: 'test-id' },
)
})
it('PATCH /folders/:folderId/agentsmd', async () => {
+11 -12
View File
@@ -14,7 +14,12 @@ import { listChildrenRequestSchema, updateAssetOrderRequestSchema, AuditAction }
import { searchRequestSchema } from '@shumai/dtos'
import type { Prisma } from '@shumai/db'
import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
import { createFolderOp, renameAssetOp, runOperation } from '@shumai/core/src/operations'
import {
createFolderOp,
getFolderInstructionsOp,
renameAssetOp,
runOperation,
} from '@shumai/core/src/operations'
type User = Prisma.UserGetPayload<Record<string, never>>
@@ -150,17 +155,11 @@ const route = new Hono<{ Variables: { user: User } }>()
return c.json(result)
})
.get('/folders/:folderId/agentsmd', 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 content = await assetService.getAgentsMd(folderId)
const { content } = await runOperation(
getFolderInstructionsOp,
{ userId: c.get('user').id, via: 'api' },
{ folderId: c.req.param('folderId') },
)
return c.json({ content })
})
.patch(
+8 -3
View File
@@ -42,11 +42,9 @@ const apiRoute = new Hono<{ Variables: { user: User } }>()
.route('/', localUploadRoute)
.route('/', mcpOauthCallbackRoute)
// Programmatic endpoints: API token required, session cookies not accepted
// Programmatic endpoint for the CLI: API token required, session cookies not accepted
.use('/ops/*', requireApiTokenMiddleware)
.use('/mcp', requireApiTokenMiddleware)
.route('/', operationsRoute)
.route('/', mcpServerRoute)
// Selected routes supporting API token authentication
.use('/projects', tokenAuthMiddleware)
@@ -82,6 +80,13 @@ const apiRoute = new Hono<{ Variables: { user: User } }>()
.route('/', kanbanRoute)
.route('/', mediaGenerationRoute)
// Shumai's MCP server lives at the root (`/mcp`), next to the API rather than inside it, so
// it can also be served from a dedicated host (e.g. `https://mcp.example.com/mcp`). It takes
// API tokens only. The `/api/mcp/servers` routes are a separate feature: external MCP servers
// that Shumai's own agent connects to.
app.use('/mcp', requireApiTokenMiddleware)
app.route('/', mcpServerRoute)
app.route('/files', s3Route)
// eslint-disable-next-line @typescript-eslint/no-unused-vars
@@ -11,7 +11,7 @@ import { apiTokenService } from '@shumai/core/src/user/api-token'
import app from './index'
/**
* End-to-end through the composed API app: API token auth → /api/mcp and /api/ops →
* End-to-end through the composed API app: API token auth → /mcp and /api/ops →
* runOperation → core services → database. Nothing is mocked.
*/
describe('MCP server and /api/ops (integration)', () => {
@@ -49,7 +49,7 @@ describe('MCP server and /api/ops (integration)', () => {
})
async function connect(token: string): Promise<Client> {
const transport = new StreamableHTTPClientTransport(new URL('http://shumai.test/api/mcp'), {
const transport = new StreamableHTTPClientTransport(new URL('http://shumai.test/mcp'), {
requestInit: { headers: { Authorization: `Bearer ${token}` } },
fetch: async (input, init) => app.request(String(input), init),
})
@@ -110,11 +110,11 @@ describe('MCP server and /api/ops (integration)', () => {
Accept: 'application/json, text/event-stream',
}
const missing = await app.request('/api/mcp', { method: 'POST', headers, body: initialize })
const missing = await app.request('/mcp', { method: 'POST', headers, body: initialize })
expect(missing.status).toBe(401)
expect(missing.headers.get('WWW-Authenticate')).toContain('Bearer')
const invalid = await app.request('/api/mcp', {
const invalid = await app.request('/mcp', {
method: 'POST',
headers: { ...headers, Authorization: 'Bearer shumai_invalid' },
body: initialize,
@@ -163,6 +163,21 @@ describe('MCP server and /api/ops (integration)', () => {
expect(res.status).toBe(401)
})
it('no longer serves the MCP server under /api', async () => {
const res = await app.request('/api/mcp', {
method: 'POST',
headers: {
Authorization: `Bearer ${ownerToken}`,
'Content-Type': 'application/json',
Accept: 'application/json, text/event-stream',
},
body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/list' }),
})
// It falls through to the session-only API routes instead of answering as MCP.
expect(res.status).toBe(401)
expect(await res.text()).not.toContain('jsonrpc')
})
describe('read_asset', () => {
const bucket = 'shumai-test-mcp-read'
const originalBucket = process.env.S3_BUCKET
@@ -303,5 +318,53 @@ describe('MCP server and /api/ops (integration)', () => {
expect(result.isError).toBe(true)
})
it('lets an MCP client upload a file: create_file, PUT the bytes, complete_upload', async () => {
const client = await connect(ownerToken)
const started = await client.callTool({
name: 'create_file',
arguments: { parent: rootFolderId, name: 'upload.png' },
})
expect(started.isError).toBeFalsy()
const { uploadId, uploadUrl, method } = started.structuredContent as {
uploadId: string
uploadUrl: string
method: string
key?: string
}
expect(method).toBe('PUT')
expect(started.structuredContent).not.toHaveProperty('key')
// Upload the bytes the way an agent would with curl, to the API's local storage
const link = new URL(uploadUrl)
const put = await app.request(link.pathname + link.search, {
method: 'PUT',
headers: { 'Content-Type': 'image/png', 'Content-Length': String(png.length) },
body: png,
})
expect(put.status).toBe(200)
const completed = await client.callTool({ name: 'complete_upload', arguments: { uploadId } })
expect(completed.isError).toBeFalsy()
const file = completed.structuredContent as { id: string; name: string; size: number }
expect(file).toMatchObject({ name: 'upload.png', size: png.length })
const row = await prisma.asset.findUniqueOrThrow({ where: { id: file.id } })
expect(row).toMatchObject({ parentId: rootFolderId, creatorId: owner.id })
const audit = await prisma.auditLog.findFirstOrThrow({
where: { action: 'file_create', itemId: file.id },
})
expect(audit).toMatchObject({ userId: owner.id, teamId, projectId, via: 'mcp' })
})
it('does not let a reviewer start an upload over MCP', async () => {
const client = await connect(reviewerToken)
const result = await client.callTool({
name: 'create_file',
arguments: { parent: rootFolderId, name: 'nope.png' },
})
expect(result.isError).toBe(true)
})
})
})
+14
View File
@@ -53,15 +53,29 @@ describe('MCP server', () => {
const { tools } = await client.listTools()
expect(tools.map((t) => t.name).sort()).toEqual([
'complete_upload',
'copy_assets',
'create_comment',
'create_file',
'create_folder',
'create_version',
'create_version_stack',
'delete_asset',
'download_asset',
'get_asset_render',
'get_folder_instructions',
'list_assets',
'list_comments',
'list_metadata_fields',
'list_projects',
'list_versions',
'move_assets',
'read_asset',
'remove_version',
'rename_asset',
'resolve_comment',
'search_assets',
'update_asset_metadata',
])
const createFolder = tools.find((t) => t.name === 'create_folder')!
+8 -3
View File
@@ -15,10 +15,15 @@ export const MCP_SERVER_VERSION = '1.0.0'
export const MCP_SERVER_INSTRUCTIONS = [
'Shumai is a media asset workspace organized as teams > projects > folders > files.',
'Start with list_projects to find a project and its rootFolderId, then pass folder IDs as',
'`parent` to list_assets and create_folder. list_assets is paginated: when',
'pageInfo.hasNextPage is true, call it again with after = pageInfo.endCursor.',
'`parent` to list_assets, search_assets, and create_folder. List and search tools are',
'paginated: when pageInfo.hasNextPage is true, call them again with after = pageInfo.endCursor.',
'Use read_asset to look at a file (image, video frames, PDF pages, 3D views, or text);',
'if it returns status "pending", call get_asset_render with its taskId.',
'Review feedback lives in comments: list_comments, create_comment, and resolve_comment.',
'Files carry metadata (status, rating, custom fields): list_metadata_fields gives the keys for',
'update_asset_metadata. Before adding files to a folder, check get_folder_instructions.',
'To upload, call create_file (or create_version for a new version of a file), PUT the bytes',
'to the returned uploadUrl, then call complete_upload with the uploadId.',
].join(' ')
/**
@@ -126,7 +131,7 @@ const mcpHandler = createMcpHandler(({ authInfo }) => {
return buildMcpServer(userId)
})
/** Shumai's MCP server (Streamable HTTP). Mounted at `/api/mcp` behind API token auth. */
/** Shumai's MCP server (Streamable HTTP). Mounted at `/mcp` behind API token auth. */
const route = new Hono<{ Variables: { user: User } }>().all('/mcp', (c) => {
const user = c.get('user')
return mcpHandler.fetch(c.req.raw, {
+11 -18
View File
@@ -4,9 +4,8 @@ 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'
import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
import type { ProjectInfo } from '@shumai/dtos'
import { moveAssetsOp, runOperation } from '@shumai/core/src/operations'
import { copyAssetsOp, moveAssetsOp, runOperation } from '@shumai/core/src/operations'
vi.mock('./middleware/auth', () => ({
authMiddleware: async (
@@ -209,9 +208,11 @@ describe('project api', () => {
)
})
it('POST /projects/:projectId/copy', async () => {
vi.mocked(projectService.getProjectTeam).mockResolvedValue('t1')
vi.mocked(assetService.copyAssets).mockResolvedValue(undefined)
it('POST /projects/:projectId/copy runs copy_assets', async () => {
vi.mocked(runOperation).mockResolvedValue({
copiedAssetIds: ['copy_1'],
newParentId: 'new_parent_id',
})
const res = await app.request('/projects/p/copy', {
method: 'POST',
@@ -223,19 +224,11 @@ describe('project api', () => {
})
expect(res.status).toBe(204)
expect(assetService.copyAssets).toHaveBeenCalledWith({
newParentId: 'new_parent_id',
assetIds: ['asset_1'],
withComments: false,
creatorId: 'user1',
})
expect(auditLogService.logAction).toHaveBeenCalledWith({
action: 'asset_copy',
teamId: 't1',
userId: 'user1',
projectId: 'p',
itemId: 'asset_1',
})
expect(runOperation).toHaveBeenCalledWith(
copyAssetsOp,
{ userId: 'user1', via: 'api' },
{ assetIds: ['asset_1'], newParentId: 'new_parent_id', withComments: false },
)
})
it('POST /projects/:projectId/empty-trash', async () => {
+7 -40
View File
@@ -18,7 +18,7 @@ import {
import { listMembersQuerySchema, AuditAction } from '@shumai/dtos'
import type { Prisma } from '@shumai/db'
import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
import { moveAssetsOp, runOperation } from '@shumai/core/src/operations'
import { copyAssetsOp, moveAssetsOp, runOperation } from '@shumai/core/src/operations'
type User = Prisma.UserGetPayload<Record<string, never>>
@@ -303,46 +303,13 @@ const route = new Hono<{ Variables: { user: User } }>()
},
)
.post('/projects/:projectId/copy', zValidator('json', copyAssetsRequestSchema), async (c) => {
const projectId = c.req.param('projectId')
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,
})
const teamId = await projectService.getProjectTeam(projectId).catch(() => null)
if (teamId) {
for (const assetId of req.assetIds) {
await auditLogService.logAction({
action: AuditAction.asset_copy,
teamId,
userId: user.id,
projectId,
itemId: assetId,
})
}
}
// Team/project for authorization and audit come from the assets themselves, not the path.
await runOperation(
copyAssetsOp,
{ userId: c.get('user').id, via: 'api' },
{ assetIds: req.assetIds, newParentId: req.newParentId, withComments: req.withComments },
)
return c.body(null, 204)
})
.patch(
+26 -27
View File
@@ -5,6 +5,12 @@ 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'
import { createVersionStackOp, removeVersionOp, runOperation } from '@shumai/core/src/operations'
vi.mock('@shumai/core/src/operations', async (importOriginal) => ({
...(await importOriginal<typeof import('@shumai/core/src/operations')>()),
runOperation: vi.fn(),
}))
vi.mock('@shumai/core/src/authz/authz', () => ({
authzService: {
@@ -50,11 +56,16 @@ describe('versionStack api', () => {
})
describe('POST /projects/:projectID/version_stacks', () => {
it('should create a version stack and return asset info', async () => {
const mockStack = { id: 'stack1' }
it('runs create_version_stack and returns the stack asset info', async () => {
const mockAssetInfo = { id: 'stack1', type: 'version_stack', name: 'v1' }
mockCreateVersionStack.mockResolvedValue(mockStack)
vi.mocked(runOperation).mockResolvedValue({
id: 'stack1',
name: 'v1',
type: 'version_stack',
size: 0,
projectId: 'p1',
})
mockGetAsset.mockResolvedValue(mockAssetInfo)
const app = new Hono().use('*', authMiddleware).route('/', versionStackRoute)
@@ -69,18 +80,12 @@ describe('versionStack api', () => {
const data = await res.json()
expect(data).toEqual(mockAssetInfo)
expect(authzService.hasPermission).toHaveBeenCalledWith(
expect.objectContaining({
type: ResourceType.Project,
id: 'p1',
permission: Permission.Edit,
}),
expect(runOperation).toHaveBeenCalledWith(
createVersionStackOp,
{ userId: 'user1', via: 'api' },
{ fileIds: ['f1', 'f2'] },
)
expect(mockCreateVersionStack).toHaveBeenCalledWith({
projectId: 'p1',
creatorId: 'user1',
fileIds: ['f1', 'f2'],
})
expect(mockCreateVersionStack).not.toHaveBeenCalled()
expect(mockGetAsset).toHaveBeenCalledWith({ assetId: 'stack1' })
})
})
@@ -150,8 +155,8 @@ describe('versionStack api', () => {
})
describe('DELETE /version_stacks/:stackId/versions/:versionId', () => {
it('should remove version from stack and return 200', async () => {
mockRemoveVersionFromStack.mockResolvedValue()
it('runs remove_version and returns 200', async () => {
vi.mocked(runOperation).mockResolvedValue({ versionId: 'v1', stackId: 'stack1' })
const app = new Hono().use('*', authMiddleware).route('/', versionStackRoute)
@@ -160,18 +165,12 @@ describe('versionStack api', () => {
})
expect(res.status).toBe(200)
expect(authzService.hasPermission).toHaveBeenCalledWith(
expect.objectContaining({
type: ResourceType.Asset,
id: 'stack1',
permission: Permission.Edit,
}),
expect(runOperation).toHaveBeenCalledWith(
removeVersionOp,
{ userId: 'user1', via: 'api' },
{ versionId: 'v1' },
)
expect(mockRemoveVersionFromStack).toHaveBeenCalledWith({
stackId: 'stack1',
fileId: 'v1',
})
expect(mockRemoveVersionFromStack).not.toHaveBeenCalled()
})
})
})
+14 -35
View File
@@ -3,6 +3,7 @@ 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 { createVersionStackOp, removeVersionOp, runOperation } from '@shumai/core/src/operations'
import { createVersionStackRequestSchema, changeStackFileVersionRequestSchema } from '@shumai/dtos'
import type { Prisma } from '@shumai/db'
@@ -15,26 +16,14 @@ const route = app
'/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)
// Authorization and the stack's project come from the files, not the path.
const stack = await runOperation(
createVersionStackOp,
{ userId: c.get('user').id, via: 'api' },
{ fileIds: req.fileIds },
)
return c.json(await assetService.getAsset({ assetId: stack.id }))
},
)
.post(
@@ -76,22 +65,12 @@ const route = app
return c.json(versions)
})
.delete('/version_stacks/:stackId/versions/:versionId', async (c) => {
const stackId = c.req.param('stackId')
const versionId = c.req.param('versionId')
const user = c.get('user')
await authzService.hasPermission({
user,
permission: Permission.Edit,
type: ResourceType.Asset,
id: stackId,
})
await versionStackService.removeVersionFromStack({
stackId,
fileId: versionId,
})
// The stack is the version's parent; the path's stackId is not needed.
await runOperation(
removeVersionOp,
{ userId: c.get('user').id, via: 'api' },
{ versionId: c.req.param('versionId') },
)
return new Response(null, { status: 200 })
})