-
Notifications
You must be signed in to change notification settings - Fork 3.7k
Expand file tree
/
Copy pathroute.ts
More file actions
186 lines (165 loc) · 6.28 KB
/
Copy pathroute.ts
File metadata and controls
186 lines (165 loc) · 6.28 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
import { createLogger } from '@sim/logger'
import { type NextRequest, NextResponse } from 'next/server'
import { createWorkflowContract, workflowListQuerySchema } from '@/lib/api/contracts/workflows'
import { parseRequest } from '@/lib/api/server'
import { checkSessionOrInternalAuth } from '@/lib/auth/hybrid'
import { generateRequestId } from '@/lib/core/utils/request'
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
import { captureServerEvent } from '@/lib/posthog/server'
import { performCreateWorkflow } from '@/lib/workflows/orchestration'
import { listWorkflowsForUser } from '@/lib/workflows/queries'
import { getUserEntityPermissions, workspaceExists } from '@/lib/workspaces/permissions/utils'
import { verifyWorkspaceMembership } from '@/app/api/workflows/utils'
const logger = createLogger('WorkflowAPI')
export const GET = withRouteHandler(async (request: NextRequest) => {
const requestId = generateRequestId()
const startTime = Date.now()
const url = new URL(request.url)
const query = workflowListQuerySchema.safeParse(Object.fromEntries(url.searchParams.entries()))
if (!query.success) {
return NextResponse.json(
{ error: 'Invalid query parameters', details: query.error.issues },
{ status: 400 }
)
}
const { workspaceId, scope } = query.data
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 }
)
}
}
const workflows = await listWorkflowsForUser({ userId, workspaceId, scope })
return NextResponse.json({ data: workflows }, { status: 200 })
} catch (error: any) {
const elapsed = Date.now() - startTime
logger.error(`[${requestId}] Workflow fetch error after ${elapsed}ms`, error)
return NextResponse.json({ error: 'Internal server error' }, { status: 500 })
}
})
// POST /api/workflows - Create a new workflow
export const POST = withRouteHandler(async (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 parsed = await parseRequest(createWorkflowContract, req, {})
if (!parsed.success) return parsed.response
const {
id: clientId,
name: requestedName,
description,
workspaceId,
folderId,
sortOrder: providedSortOrder,
deduplicate,
} = parsed.data.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 result = await performCreateWorkflow({
id: clientId,
name: requestedName,
description,
workspaceId,
folderId,
sortOrder: providedSortOrder,
deduplicate,
userId,
requestId,
})
if (!result.success || !result.workflow) {
const status =
result.errorCode === 'conflict' ? 409 : result.errorCode === 'validation' ? 400 : 500
return NextResponse.json({ error: result.error }, { status })
}
const createdWorkflow = result.workflow
import('@/lib/core/telemetry')
.then(({ PlatformEvents }) => {
PlatformEvents.workflowCreated({
workflowId: createdWorkflow.id,
name: createdWorkflow.name,
workspaceId: workspaceId || undefined,
folderId: folderId || undefined,
})
})
.catch(() => {
// Silently fail
})
logger.info(
`[${requestId}] Successfully created workflow ${createdWorkflow.id} with default blocks`
)
captureServerEvent(
userId,
'workflow_created',
{
workflow_id: createdWorkflow.id,
workspace_id: workspaceId ?? '',
name: createdWorkflow.name,
},
{
groups: workspaceId ? { workspace: workspaceId } : undefined,
setOnce: { first_workflow_created_at: new Date().toISOString() },
}
)
return NextResponse.json({
id: createdWorkflow.id,
name: createdWorkflow.name,
description: createdWorkflow.description,
workspaceId: createdWorkflow.workspaceId,
folderId: createdWorkflow.folderId,
sortOrder: createdWorkflow.sortOrder,
createdAt: createdWorkflow.createdAt,
updatedAt: createdWorkflow.updatedAt,
startBlockId: createdWorkflow.startBlockId,
subBlockValues: createdWorkflow.subBlockValues,
})
} catch (error) {
logger.error(`[${requestId}] Error creating workflow`, error)
return NextResponse.json({ error: 'Failed to create workflow' }, { status: 500 })
}
})