-
Notifications
You must be signed in to change notification settings - Fork 3.5k
Expand file tree
/
Copy pathroute.ts
More file actions
299 lines (263 loc) · 9.24 KB
/
route.ts
File metadata and controls
299 lines (263 loc) · 9.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
import { db } from '@sim/db'
import { permissions, workflow, workflowFolder } from '@sim/db/schema'
import { createLogger } from '@sim/logger'
import { and, asc, count, eq, inArray, isNull, min } from 'drizzle-orm'
import { type NextRequest, NextResponse } from 'next/server'
import { z } from 'zod'
import { AuditAction, AuditResourceType, recordAudit } from '@/lib/audit/log'
import { checkSessionOrInternalAuth } from '@/lib/auth/hybrid'
import { generateRequestId } from '@/lib/core/utils/request'
import { getUserEntityPermissions, workspaceExists } from '@/lib/workspaces/permissions/utils'
import { verifyWorkspaceMembership } from '@/app/api/workflows/utils'
const logger = createLogger('WorkflowAPI')
const DEFAULT_PAGE_LIMIT = 200
const MAX_PAGE_LIMIT = 500
const CreateWorkflowSchema = z.object({
name: z.string().min(1, 'Name is required'),
description: z.string().optional().default(''),
color: z.string().optional().default('#3972F6'),
workspaceId: z.string().optional(),
folderId: z.string().nullable().optional(),
sortOrder: z.number().int().optional(),
})
// GET /api/workflows - Get workflows for user (optionally filtered by workspaceId)
export async function GET(request: NextRequest) {
const requestId = generateRequestId()
const startTime = Date.now()
const url = new URL(request.url)
const workspaceId = url.searchParams.get('workspaceId')
const rawLimit = url.searchParams.get('limit')
const rawOffset = url.searchParams.get('offset')
const limit = Math.min(
Math.max(1, rawLimit ? Number(rawLimit) : DEFAULT_PAGE_LIMIT),
MAX_PAGE_LIMIT
)
const offset = Math.max(0, rawOffset ? Number(rawOffset) : 0)
try {
const auth = await checkSessionOrInternalAuth(request, { requireWorkflowId: false })
if (!auth.success || !auth.userId) {
logger.warn(`[${requestId}] Unauthorized workflow access attempt`)
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
const userId = auth.userId
if (workspaceId) {
const wsExists = await workspaceExists(workspaceId)
if (!wsExists) {
logger.warn(
`[${requestId}] Attempt to fetch workflows for non-existent workspace: ${workspaceId}`
)
return NextResponse.json(
{ error: 'Workspace not found', code: 'WORKSPACE_NOT_FOUND' },
{ status: 404 }
)
}
const userRole = await verifyWorkspaceMembership(userId, workspaceId)
if (!userRole) {
logger.warn(
`[${requestId}] User ${userId} attempted to access workspace ${workspaceId} without membership`
)
return NextResponse.json(
{ error: 'Access denied to this workspace', code: 'WORKSPACE_ACCESS_DENIED' },
{ status: 403 }
)
}
}
let workflows
let total: number
const orderByClause = [asc(workflow.sortOrder), asc(workflow.createdAt), asc(workflow.id)]
if (workspaceId) {
const whereCondition = eq(workflow.workspaceId, workspaceId)
const [countResult, workflowRows] = await Promise.all([
db.select({ count: count() }).from(workflow).where(whereCondition),
db
.select()
.from(workflow)
.where(whereCondition)
.orderBy(...orderByClause)
.limit(limit)
.offset(offset),
])
total = countResult[0]?.count ?? 0
workflows = workflowRows
} else {
const workspacePermissionRows = await db
.select({ workspaceId: permissions.entityId })
.from(permissions)
.where(and(eq(permissions.userId, userId), eq(permissions.entityType, 'workspace')))
const workspaceIds = workspacePermissionRows.map((row) => row.workspaceId)
if (workspaceIds.length === 0) {
return NextResponse.json(
{ data: [], pagination: { total: 0, limit, offset, hasMore: false } },
{ status: 200 }
)
}
const whereCondition = inArray(workflow.workspaceId, workspaceIds)
const [countResult, workflowRows] = await Promise.all([
db.select({ count: count() }).from(workflow).where(whereCondition),
db
.select()
.from(workflow)
.where(whereCondition)
.orderBy(...orderByClause)
.limit(limit)
.offset(offset),
])
total = countResult[0]?.count ?? 0
workflows = workflowRows
}
return NextResponse.json(
{
data: workflows,
pagination: {
total,
limit,
offset,
hasMore: offset + workflows.length < total,
},
},
{ status: 200 }
)
} catch (error: any) {
const elapsed = Date.now() - startTime
logger.error(`[${requestId}] Workflow fetch error after ${elapsed}ms`, error)
return NextResponse.json({ error: error.message }, { status: 500 })
}
}
// POST /api/workflows - Create a new workflow
export async function POST(req: NextRequest) {
const requestId = generateRequestId()
const auth = await checkSessionOrInternalAuth(req, { requireWorkflowId: false })
if (!auth.success || !auth.userId) {
logger.warn(`[${requestId}] Unauthorized workflow creation attempt`)
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
const userId = auth.userId
try {
const body = await req.json()
const {
name,
description,
color,
workspaceId,
folderId,
sortOrder: providedSortOrder,
} = CreateWorkflowSchema.parse(body)
if (!workspaceId) {
logger.warn(`[${requestId}] Workflow creation blocked: missing workspaceId`)
return NextResponse.json(
{
error:
'workspaceId is required. Personal workflows are deprecated and cannot be created.',
},
{ status: 400 }
)
}
const workspacePermission = await getUserEntityPermissions(userId, 'workspace', workspaceId)
if (!workspacePermission || workspacePermission === 'read') {
logger.warn(
`[${requestId}] User ${userId} attempted to create workflow in workspace ${workspaceId} without write permissions`
)
return NextResponse.json(
{ error: 'Write or Admin access required to create workflows in this workspace' },
{ status: 403 }
)
}
const workflowId = crypto.randomUUID()
const now = new Date()
logger.info(`[${requestId}] Creating workflow ${workflowId} for user ${userId}`)
import('@/lib/core/telemetry')
.then(({ PlatformEvents }) => {
PlatformEvents.workflowCreated({
workflowId,
name,
workspaceId: workspaceId || undefined,
folderId: folderId || undefined,
})
})
.catch(() => {
// Silently fail
})
let sortOrder: number
if (providedSortOrder !== undefined) {
sortOrder = providedSortOrder
} else {
const workflowParentCondition = folderId
? eq(workflow.folderId, folderId)
: isNull(workflow.folderId)
const folderParentCondition = folderId
? eq(workflowFolder.parentId, folderId)
: isNull(workflowFolder.parentId)
const [[workflowMinResult], [folderMinResult]] = await Promise.all([
db
.select({ minOrder: min(workflow.sortOrder) })
.from(workflow)
.where(and(eq(workflow.workspaceId, workspaceId), workflowParentCondition)),
db
.select({ minOrder: min(workflowFolder.sortOrder) })
.from(workflowFolder)
.where(and(eq(workflowFolder.workspaceId, workspaceId), folderParentCondition)),
])
const minSortOrder = [workflowMinResult?.minOrder, folderMinResult?.minOrder].reduce<
number | null
>((currentMin, candidate) => {
if (candidate == null) return currentMin
if (currentMin == null) return candidate
return Math.min(currentMin, candidate)
}, null)
sortOrder = minSortOrder != null ? minSortOrder - 1 : 0
}
await db.insert(workflow).values({
id: workflowId,
userId,
workspaceId,
folderId: folderId || null,
sortOrder,
name,
description,
color,
lastSynced: now,
createdAt: now,
updatedAt: now,
isDeployed: false,
runCount: 0,
variables: {},
})
logger.info(`[${requestId}] Successfully created empty workflow ${workflowId}`)
recordAudit({
workspaceId,
actorId: userId,
actorName: auth.userName,
actorEmail: auth.userEmail,
action: AuditAction.WORKFLOW_CREATED,
resourceType: AuditResourceType.WORKFLOW,
resourceId: workflowId,
resourceName: name,
description: `Created workflow "${name}"`,
metadata: { name },
request: req,
})
return NextResponse.json({
id: workflowId,
name,
description,
color,
workspaceId,
folderId,
sortOrder,
createdAt: now,
updatedAt: now,
})
} catch (error) {
if (error instanceof z.ZodError) {
logger.warn(`[${requestId}] Invalid workflow creation data`, {
errors: error.errors,
})
return NextResponse.json(
{ error: 'Invalid request data', details: error.errors },
{ status: 400 }
)
}
logger.error(`[${requestId}] Error creating workflow`, error)
return NextResponse.json({ error: 'Failed to create workflow' }, { status: 500 })
}
}