|
| 1 | +import { db } from '@sim/db' |
| 2 | +import { copilotChats, workflow, workspace } from '@sim/db/schema' |
| 3 | +import { createLogger } from '@sim/logger' |
| 4 | +import { eq } from 'drizzle-orm' |
| 5 | +import { type NextRequest, NextResponse } from 'next/server' |
| 6 | +import { getSession } from '@/lib/auth' |
| 7 | +import { verifyEffectiveSuperUser } from '@/lib/templates/permissions' |
| 8 | +import { parseWorkflowJson } from '@/lib/workflows/operations/import-export' |
| 9 | +import { |
| 10 | + loadWorkflowFromNormalizedTables, |
| 11 | + saveWorkflowToNormalizedTables, |
| 12 | +} from '@/lib/workflows/persistence/utils' |
| 13 | +import { sanitizeForExport } from '@/lib/workflows/sanitization/json-sanitizer' |
| 14 | + |
| 15 | +const logger = createLogger('SuperUserImportWorkflow') |
| 16 | + |
| 17 | +interface ImportWorkflowRequest { |
| 18 | + workflowId: string |
| 19 | + targetWorkspaceId: string |
| 20 | +} |
| 21 | + |
| 22 | +/** |
| 23 | + * POST /api/superuser/import-workflow |
| 24 | + * |
| 25 | + * Superuser endpoint to import a workflow by ID along with its copilot chats. |
| 26 | + * This creates a copy of the workflow in the target workspace with new IDs. |
| 27 | + * Only the workflow structure and copilot chats are copied - no deployments, |
| 28 | + * webhooks, triggers, or other sensitive data. |
| 29 | + * |
| 30 | + * Requires both isSuperUser flag AND superUserModeEnabled setting. |
| 31 | + */ |
| 32 | +export async function POST(request: NextRequest) { |
| 33 | + try { |
| 34 | + const session = await getSession() |
| 35 | + if (!session?.user?.id) { |
| 36 | + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) |
| 37 | + } |
| 38 | + |
| 39 | + const { effectiveSuperUser, isSuperUser, superUserModeEnabled } = |
| 40 | + await verifyEffectiveSuperUser(session.user.id) |
| 41 | + |
| 42 | + if (!effectiveSuperUser) { |
| 43 | + logger.warn('Non-effective-superuser attempted to access import-workflow endpoint', { |
| 44 | + userId: session.user.id, |
| 45 | + isSuperUser, |
| 46 | + superUserModeEnabled, |
| 47 | + }) |
| 48 | + return NextResponse.json({ error: 'Forbidden: Superuser access required' }, { status: 403 }) |
| 49 | + } |
| 50 | + |
| 51 | + const body: ImportWorkflowRequest = await request.json() |
| 52 | + const { workflowId, targetWorkspaceId } = body |
| 53 | + |
| 54 | + if (!workflowId) { |
| 55 | + return NextResponse.json({ error: 'workflowId is required' }, { status: 400 }) |
| 56 | + } |
| 57 | + |
| 58 | + if (!targetWorkspaceId) { |
| 59 | + return NextResponse.json({ error: 'targetWorkspaceId is required' }, { status: 400 }) |
| 60 | + } |
| 61 | + |
| 62 | + // Verify target workspace exists |
| 63 | + const [targetWorkspace] = await db |
| 64 | + .select({ id: workspace.id, ownerId: workspace.ownerId }) |
| 65 | + .from(workspace) |
| 66 | + .where(eq(workspace.id, targetWorkspaceId)) |
| 67 | + .limit(1) |
| 68 | + |
| 69 | + if (!targetWorkspace) { |
| 70 | + return NextResponse.json({ error: 'Target workspace not found' }, { status: 404 }) |
| 71 | + } |
| 72 | + |
| 73 | + // Get the source workflow |
| 74 | + const [sourceWorkflow] = await db |
| 75 | + .select() |
| 76 | + .from(workflow) |
| 77 | + .where(eq(workflow.id, workflowId)) |
| 78 | + .limit(1) |
| 79 | + |
| 80 | + if (!sourceWorkflow) { |
| 81 | + return NextResponse.json({ error: 'Source workflow not found' }, { status: 404 }) |
| 82 | + } |
| 83 | + |
| 84 | + // Load the workflow state from normalized tables |
| 85 | + const normalizedData = await loadWorkflowFromNormalizedTables(workflowId) |
| 86 | + |
| 87 | + if (!normalizedData) { |
| 88 | + return NextResponse.json( |
| 89 | + { error: 'Workflow has no normalized data - cannot import' }, |
| 90 | + { status: 400 } |
| 91 | + ) |
| 92 | + } |
| 93 | + |
| 94 | + // Use existing export logic to create export format |
| 95 | + const workflowState = { |
| 96 | + blocks: normalizedData.blocks, |
| 97 | + edges: normalizedData.edges, |
| 98 | + loops: normalizedData.loops, |
| 99 | + parallels: normalizedData.parallels, |
| 100 | + metadata: { |
| 101 | + name: sourceWorkflow.name, |
| 102 | + description: sourceWorkflow.description ?? undefined, |
| 103 | + color: sourceWorkflow.color, |
| 104 | + }, |
| 105 | + } |
| 106 | + |
| 107 | + const exportData = sanitizeForExport(workflowState) |
| 108 | + |
| 109 | + // Use existing import logic (parseWorkflowJson regenerates IDs automatically) |
| 110 | + const { data: importedData, errors } = parseWorkflowJson(JSON.stringify(exportData)) |
| 111 | + |
| 112 | + if (!importedData || errors.length > 0) { |
| 113 | + return NextResponse.json( |
| 114 | + { error: `Failed to parse workflow: ${errors.join(', ')}` }, |
| 115 | + { status: 400 } |
| 116 | + ) |
| 117 | + } |
| 118 | + |
| 119 | + // Create new workflow record |
| 120 | + const newWorkflowId = crypto.randomUUID() |
| 121 | + const now = new Date() |
| 122 | + |
| 123 | + await db.insert(workflow).values({ |
| 124 | + id: newWorkflowId, |
| 125 | + userId: session.user.id, |
| 126 | + workspaceId: targetWorkspaceId, |
| 127 | + folderId: null, // Don't copy folder association |
| 128 | + name: `[Debug Import] ${sourceWorkflow.name}`, |
| 129 | + description: sourceWorkflow.description, |
| 130 | + color: sourceWorkflow.color, |
| 131 | + lastSynced: now, |
| 132 | + createdAt: now, |
| 133 | + updatedAt: now, |
| 134 | + isDeployed: false, // Never copy deployment status |
| 135 | + runCount: 0, |
| 136 | + variables: sourceWorkflow.variables || {}, |
| 137 | + }) |
| 138 | + |
| 139 | + // Save using existing persistence logic |
| 140 | + const saveResult = await saveWorkflowToNormalizedTables(newWorkflowId, importedData) |
| 141 | + |
| 142 | + if (!saveResult.success) { |
| 143 | + // Clean up the workflow record if save failed |
| 144 | + await db.delete(workflow).where(eq(workflow.id, newWorkflowId)) |
| 145 | + return NextResponse.json( |
| 146 | + { error: `Failed to save workflow state: ${saveResult.error}` }, |
| 147 | + { status: 500 } |
| 148 | + ) |
| 149 | + } |
| 150 | + |
| 151 | + // Copy copilot chats associated with the source workflow |
| 152 | + const sourceCopilotChats = await db |
| 153 | + .select() |
| 154 | + .from(copilotChats) |
| 155 | + .where(eq(copilotChats.workflowId, workflowId)) |
| 156 | + |
| 157 | + let copilotChatsImported = 0 |
| 158 | + |
| 159 | + for (const chat of sourceCopilotChats) { |
| 160 | + await db.insert(copilotChats).values({ |
| 161 | + userId: session.user.id, |
| 162 | + workflowId: newWorkflowId, |
| 163 | + title: chat.title ? `[Import] ${chat.title}` : null, |
| 164 | + messages: chat.messages, |
| 165 | + model: chat.model, |
| 166 | + conversationId: null, // Don't copy conversation ID |
| 167 | + previewYaml: chat.previewYaml, |
| 168 | + planArtifact: chat.planArtifact, |
| 169 | + config: chat.config, |
| 170 | + createdAt: new Date(), |
| 171 | + updatedAt: new Date(), |
| 172 | + }) |
| 173 | + copilotChatsImported++ |
| 174 | + } |
| 175 | + |
| 176 | + logger.info('Superuser imported workflow', { |
| 177 | + userId: session.user.id, |
| 178 | + sourceWorkflowId: workflowId, |
| 179 | + newWorkflowId, |
| 180 | + targetWorkspaceId, |
| 181 | + copilotChatsImported, |
| 182 | + }) |
| 183 | + |
| 184 | + return NextResponse.json({ |
| 185 | + success: true, |
| 186 | + newWorkflowId, |
| 187 | + copilotChatsImported, |
| 188 | + }) |
| 189 | + } catch (error) { |
| 190 | + logger.error('Error importing workflow', error) |
| 191 | + return NextResponse.json({ error: 'Internal server error' }, { status: 500 }) |
| 192 | + } |
| 193 | +} |
0 commit comments