All files / flows delete.js

100% Statements 35/35
100% Branches 14/14
100% Functions 2/2
100% Lines 34/34

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 1271x 1x 1x         1x 1x 1x 1x   1x 1x 1x   15x         1x 15x 15x 15x   15x 1x             14x 1x               13x             12x 1x                   11x 11x 1x             10x             10x   10x 1x             9x                                                     9x   9x   1x 1x              
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const { DynamoDBDocumentClient, GetCommand } = require('@aws-sdk/lib-dynamodb')
const { S3Client } = require('@aws-sdk/client-s3')
const {
  computeFlowDeletionImpact,
  cascadeDeleteFlow,
  toPublicImpact
} = require('../utils/flowDeletionCascade')
const { deleteAllPacksForFlow } = require('../utils/packCleanup')
const { permissionChecker } = require('../utils/PermissionChecker')
const { commentTablesFromEnv } = require('../utils/commentCleanup')
 
const client = new DynamoDBClient({})
const docClient = DynamoDBDocumentClient.from(client)
const s3Client = new S3Client({ region: 'eu-central-1' })
 
const getCorsHeaders = () => ({
  'Content-Type': 'application/json',
  'Access-Control-Allow-Origin': '*'
})
 
exports.handler = async (event) => {
  try {
    const flowId = event.pathParameters?.flowId
    const userId = event.requestContext?.authorizer?.claims?.sub
 
    if (!userId) {
      return {
        statusCode: 401,
        headers: getCorsHeaders(),
        body: JSON.stringify({ error: 'Not authenticated' })
      }
    }
 
    if (!flowId) {
      return {
        statusCode: 400,
        headers: getCorsHeaders(),
        body: JSON.stringify({ error: 'Missing flowId' })
      }
    }
 
    // Verify flow exists
    const flowResult = await docClient.send(
      new GetCommand({
        TableName: process.env.FLOWS_TABLE_NAME,
        Key: { id: flowId }
      })
    )
 
    if (!flowResult.Item) {
      return {
        statusCode: 404,
        headers: getCorsHeaders(),
        body: JSON.stringify({ error: 'Flow not found' })
      }
    }
 
    // The flow owner is always assigned the flow's admin role (*:*) at creation
    // time and can't have it stripped, so this permission check is the only
    // authorization gate — no separate ownerId comparison is needed.
    const permissionResult = await permissionChecker.hasPermission(userId, flowId, 'flows:delete')
    if (!permissionResult.hasPermission) {
      return {
        statusCode: 403,
        headers: getCorsHeaders(),
        body: JSON.stringify({ error: 'You do not have permission to delete this flow' })
      }
    }
 
    const impact = await computeFlowDeletionImpact(docClient, {
      entitiesTableName: process.env.ENTITIES_TABLE_NAME,
      entityLinksTableName: process.env.ENTITY_LINKS_TABLE_NAME,
      countersTableName: process.env.ENTITY_REFERENCE_COUNTERS_TABLE_NAME,
      flowId
    })
 
    const confirmTransfer = event.queryStringParameters?.confirmTransfer === 'true'
 
    if (impact.entitiesToTransfer.length > 0 && !confirmTransfer) {
      return {
        statusCode: 409,
        headers: getCorsHeaders(),
        body: JSON.stringify({ requiresConfirmation: true, ...toPublicImpact(impact) })
      }
    }
 
    await cascadeDeleteFlow(docClient, {
      flowsTableName: process.env.FLOWS_TABLE_NAME,
      flowSlugsTableName: process.env.FLOW_SLUGS_TABLE_NAME,
      entitiesTableName: process.env.ENTITIES_TABLE_NAME,
      itemsTableName: process.env.ITEMS_TABLE_NAME,
      rolesTableName: process.env.ROLES_TABLE_NAME,
      flowMembershipsTableName: process.env.FLOW_MEMBERSHIPS_TABLE_NAME,
      entityLinksTableName: process.env.ENTITY_LINKS_TABLE_NAME,
      countersTableName: process.env.ENTITY_REFERENCE_COUNTERS_TABLE_NAME,
      apiKeysTableName: process.env.API_KEYS_TABLE,
      fieldValueIndexTableName: process.env.FIELD_VALUE_INDEX_TABLE_NAME,
      entityItemCountTableName: process.env.ENTITY_ITEM_COUNT_TABLE_NAME,
      entitySubscriberCountTableName: process.env.ENTITY_SUBSCRIBER_COUNT_TABLE_NAME,
      entitySubscriptionsTableName: process.env.ENTITY_SUBSCRIPTIONS_TABLE_NAME,
      itemLikesTableName: process.env.ITEM_LIKES_TABLE_NAME,
      itemLikeCountTableName: process.env.ITEM_LIKE_COUNT_TABLE_NAME,
      commentTables: commentTablesFromEnv() ?? undefined,
      commentBlocksTableName: process.env.COMMENT_BLOCKS_TABLE_NAME,
      membershipRequestsTableName: process.env.MEMBERSHIP_REQUESTS_TABLE_NAME,
      flowPagesTableName: process.env.FLOW_PAGES_TABLE_NAME,
      s3Client,
      attachmentsBucketName: process.env.ATTACHMENTS_BUCKET_NAME,
      flowId,
      slug: flowResult.Item.slug,
      impact
    })
    // Installed copies are independent: only the Store's packs go with their flow.
    await deleteAllPacksForFlow(docClient, flowId)
 
    return { statusCode: 204, headers: getCorsHeaders(), body: '' }
  } catch (error) {
    console.error('Error deleting flow:', error)
    return {
      statusCode: 500,
      headers: getCorsHeaders(),
      body: JSON.stringify({ error: 'Failed to delete flow' })
    }
  }
}