|
| 1 | +import { db } from '@sim/db' |
| 2 | +import { skill } from '@sim/db/schema' |
| 3 | +import { createLogger } from '@sim/logger' |
| 4 | +import { desc, eq } from 'drizzle-orm' |
| 5 | +import { type NextRequest, NextResponse } from 'next/server' |
| 6 | +import { z } from 'zod' |
| 7 | +import { checkSessionOrInternalAuth } from '@/lib/auth/hybrid' |
| 8 | +import { generateRequestId } from '@/lib/core/utils/request' |
| 9 | +import { upsertSkills } from '@/lib/workflows/skills/operations' |
| 10 | +import { getUserEntityPermissions } from '@/lib/workspaces/permissions/utils' |
| 11 | + |
| 12 | +const logger = createLogger('SkillsAPI') |
| 13 | + |
| 14 | +const SkillSchema = z.object({ |
| 15 | + skills: z.array( |
| 16 | + z.object({ |
| 17 | + id: z.string().optional(), |
| 18 | + name: z |
| 19 | + .string() |
| 20 | + .min(1, 'Skill name is required') |
| 21 | + .max(64) |
| 22 | + .regex(/^[a-z0-9]+(-[a-z0-9]+)*$/, 'Name must be kebab-case (e.g. my-skill)'), |
| 23 | + description: z.string().min(1, 'Description is required').max(1024), |
| 24 | + content: z.string().min(1, 'Content is required'), |
| 25 | + }) |
| 26 | + ), |
| 27 | + workspaceId: z.string().optional(), |
| 28 | +}) |
| 29 | + |
| 30 | +/** GET - Fetch all skills for a workspace */ |
| 31 | +export async function GET(request: NextRequest) { |
| 32 | + const requestId = generateRequestId() |
| 33 | + const searchParams = request.nextUrl.searchParams |
| 34 | + const workspaceId = searchParams.get('workspaceId') |
| 35 | + |
| 36 | + try { |
| 37 | + const authResult = await checkSessionOrInternalAuth(request, { requireWorkflowId: false }) |
| 38 | + if (!authResult.success || !authResult.userId) { |
| 39 | + logger.warn(`[${requestId}] Unauthorized skills access attempt`) |
| 40 | + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) |
| 41 | + } |
| 42 | + |
| 43 | + const userId = authResult.userId |
| 44 | + |
| 45 | + if (!workspaceId) { |
| 46 | + logger.warn(`[${requestId}] Missing workspaceId`) |
| 47 | + return NextResponse.json({ error: 'workspaceId is required' }, { status: 400 }) |
| 48 | + } |
| 49 | + |
| 50 | + const userPermission = await getUserEntityPermissions(userId, 'workspace', workspaceId) |
| 51 | + if (!userPermission) { |
| 52 | + logger.warn(`[${requestId}] User ${userId} does not have access to workspace ${workspaceId}`) |
| 53 | + return NextResponse.json({ error: 'Access denied' }, { status: 403 }) |
| 54 | + } |
| 55 | + |
| 56 | + const result = await db |
| 57 | + .select() |
| 58 | + .from(skill) |
| 59 | + .where(eq(skill.workspaceId, workspaceId)) |
| 60 | + .orderBy(desc(skill.createdAt)) |
| 61 | + |
| 62 | + return NextResponse.json({ data: result }, { status: 200 }) |
| 63 | + } catch (error) { |
| 64 | + logger.error(`[${requestId}] Error fetching skills:`, error) |
| 65 | + return NextResponse.json({ error: 'Failed to fetch skills' }, { status: 500 }) |
| 66 | + } |
| 67 | +} |
| 68 | + |
| 69 | +/** POST - Create or update skills */ |
| 70 | +export async function POST(req: NextRequest) { |
| 71 | + const requestId = generateRequestId() |
| 72 | + |
| 73 | + try { |
| 74 | + const authResult = await checkSessionOrInternalAuth(req, { requireWorkflowId: false }) |
| 75 | + if (!authResult.success || !authResult.userId) { |
| 76 | + logger.warn(`[${requestId}] Unauthorized skills update attempt`) |
| 77 | + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) |
| 78 | + } |
| 79 | + |
| 80 | + const userId = authResult.userId |
| 81 | + const body = await req.json() |
| 82 | + |
| 83 | + try { |
| 84 | + const { skills, workspaceId } = SkillSchema.parse(body) |
| 85 | + |
| 86 | + if (!workspaceId) { |
| 87 | + logger.warn(`[${requestId}] Missing workspaceId in request body`) |
| 88 | + return NextResponse.json({ error: 'workspaceId is required' }, { status: 400 }) |
| 89 | + } |
| 90 | + |
| 91 | + const userPermission = await getUserEntityPermissions(userId, 'workspace', workspaceId) |
| 92 | + if (!userPermission) { |
| 93 | + logger.warn( |
| 94 | + `[${requestId}] User ${userId} does not have access to workspace ${workspaceId}` |
| 95 | + ) |
| 96 | + return NextResponse.json({ error: 'Access denied' }, { status: 403 }) |
| 97 | + } |
| 98 | + |
| 99 | + if (userPermission !== 'admin' && userPermission !== 'write') { |
| 100 | + logger.warn( |
| 101 | + `[${requestId}] User ${userId} does not have write permission for workspace ${workspaceId}` |
| 102 | + ) |
| 103 | + return NextResponse.json({ error: 'Write permission required' }, { status: 403 }) |
| 104 | + } |
| 105 | + |
| 106 | + const resultSkills = await upsertSkills({ |
| 107 | + skills, |
| 108 | + workspaceId, |
| 109 | + userId, |
| 110 | + requestId, |
| 111 | + }) |
| 112 | + |
| 113 | + return NextResponse.json({ success: true, data: resultSkills }) |
| 114 | + } catch (validationError) { |
| 115 | + if (validationError instanceof z.ZodError) { |
| 116 | + logger.warn(`[${requestId}] Invalid skills data`, { |
| 117 | + errors: validationError.errors, |
| 118 | + }) |
| 119 | + return NextResponse.json( |
| 120 | + { error: 'Invalid request data', details: validationError.errors }, |
| 121 | + { status: 400 } |
| 122 | + ) |
| 123 | + } |
| 124 | + throw validationError |
| 125 | + } |
| 126 | + } catch (error) { |
| 127 | + logger.error(`[${requestId}] Error updating skills`, error) |
| 128 | + const errorMessage = error instanceof Error ? error.message : 'Failed to update skills' |
| 129 | + return NextResponse.json({ error: errorMessage }, { status: 500 }) |
| 130 | + } |
| 131 | +} |
| 132 | + |
| 133 | +/** DELETE - Delete a skill by ID */ |
| 134 | +export async function DELETE(request: NextRequest) { |
| 135 | + const requestId = generateRequestId() |
| 136 | + const searchParams = request.nextUrl.searchParams |
| 137 | + const skillId = searchParams.get('id') |
| 138 | + const workspaceId = searchParams.get('workspaceId') |
| 139 | + |
| 140 | + try { |
| 141 | + const authResult = await checkSessionOrInternalAuth(request, { requireWorkflowId: false }) |
| 142 | + if (!authResult.success || !authResult.userId) { |
| 143 | + logger.warn(`[${requestId}] Unauthorized skill deletion attempt`) |
| 144 | + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) |
| 145 | + } |
| 146 | + |
| 147 | + const userId = authResult.userId |
| 148 | + |
| 149 | + if (!skillId) { |
| 150 | + logger.warn(`[${requestId}] Missing skill ID for deletion`) |
| 151 | + return NextResponse.json({ error: 'Skill ID is required' }, { status: 400 }) |
| 152 | + } |
| 153 | + |
| 154 | + if (!workspaceId) { |
| 155 | + logger.warn(`[${requestId}] Missing workspaceId for deletion`) |
| 156 | + return NextResponse.json({ error: 'workspaceId is required' }, { status: 400 }) |
| 157 | + } |
| 158 | + |
| 159 | + const userPermission = await getUserEntityPermissions(userId, 'workspace', workspaceId) |
| 160 | + if (!userPermission) { |
| 161 | + logger.warn(`[${requestId}] User ${userId} does not have access to workspace ${workspaceId}`) |
| 162 | + return NextResponse.json({ error: 'Access denied' }, { status: 403 }) |
| 163 | + } |
| 164 | + |
| 165 | + if (userPermission !== 'admin' && userPermission !== 'write') { |
| 166 | + logger.warn( |
| 167 | + `[${requestId}] User ${userId} does not have write permission for workspace ${workspaceId}` |
| 168 | + ) |
| 169 | + return NextResponse.json({ error: 'Write permission required' }, { status: 403 }) |
| 170 | + } |
| 171 | + |
| 172 | + const existingSkill = await db.select().from(skill).where(eq(skill.id, skillId)).limit(1) |
| 173 | + |
| 174 | + if (existingSkill.length === 0) { |
| 175 | + logger.warn(`[${requestId}] Skill not found: ${skillId}`) |
| 176 | + return NextResponse.json({ error: 'Skill not found' }, { status: 404 }) |
| 177 | + } |
| 178 | + |
| 179 | + if (existingSkill[0].workspaceId !== workspaceId) { |
| 180 | + logger.warn(`[${requestId}] Skill ${skillId} does not belong to workspace ${workspaceId}`) |
| 181 | + return NextResponse.json({ error: 'Skill not found' }, { status: 404 }) |
| 182 | + } |
| 183 | + |
| 184 | + await db.delete(skill).where(eq(skill.id, skillId)) |
| 185 | + |
| 186 | + logger.info(`[${requestId}] Deleted skill: ${skillId}`) |
| 187 | + return NextResponse.json({ success: true }) |
| 188 | + } catch (error) { |
| 189 | + logger.error(`[${requestId}] Error deleting skill:`, error) |
| 190 | + return NextResponse.json({ error: 'Failed to delete skill' }, { status: 500 }) |
| 191 | + } |
| 192 | +} |
0 commit comments