All files / entities delete.js

95.83% Statements 92/96
85.96% Branches 49/57
80% Functions 4/5
95.83% Lines 92/96

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 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 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 3161x 1x           1x 1x 1x 1x           1x 1x 1x 1x 1x 1x 1x 1x 1x         1x 1x             1x   1x 1x 1x   1x         1x 29x 29x 29x   29x 1x             28x 1x               27x                     27x             26x 2x             24x     24x 2x                       22x         3x           3x 3x   3x 1x                   2x 2x               2x     2x                           19x 11x 11x     11x 11x               11x 11x 8x 1x     11x     8x         11x     8x         11x 1x 1x 1x   1x 1x           11x 11x 1x 1x       11x       11x 1x     11x 1x                   19x 7x                 19x 1x     19x       19x           19x 1x                     19x 2x               19x                   18x           18x   18x   2x 2x                 1x      
const { getActiveFlowId } = require('../shared/activeFlow')
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const {
  DynamoDBDocumentClient,
  GetCommand,
  DeleteCommand,
  QueryCommand
} = require('@aws-sdk/lib-dynamodb')
const { requirePermission } = require('../utils/requirePermission')
const { RESERVED_ENTITY_IDS } = require('../utils/constants')
const { batchDelete } = require('../utils/batchWrite')
const {
  getReferencedEntityIds,
  adjustCounters,
  deleteAllCountersForEntity,
  rankConsumerFlows
} = require('../utils/referenceCounters')
const { transferEntityOwnership } = require('../utils/entityOwnershipTransfer')
const { cleanupRolesForDeletedEntity } = require('../utils/entityDeletionRoleCleanup')
const { deleteAllReservationsForEntity } = require('../utils/uniqueFieldValue')
const { deleteItemCount } = require('../utils/entityItemCount')
const { deleteSubscriberCount } = require('../utils/entitySubscriberCount')
const { deleteAllSubscriptionsForEntity } = require('../utils/entitySubscriptions')
const { deleteLikeCount } = require('../utils/itemLikeCount')
const { deleteAllLikesForItem } = require('../utils/itemLikes')
const {
  deleteAllCommentsForItem,
  deleteAllCommentBlocksForEntity,
  commentTablesFromEnv
} = require('../utils/commentCleanup')
const { S3Client } = require('@aws-sdk/client-s3')
const {
  getItemFileKeys,
  getBrandingKeys,
  entityKeyGuard,
  deleteKeys,
  deletePrefix
} = require('../utils/s3Cleanup')
 
const client = new DynamoDBClient({})
const docClient = DynamoDBDocumentClient.from(client)
const s3Client = new S3Client({ region: 'eu-central-1' })
 
const CORS_HEADERS = {
  'Content-Type': 'application/json',
  'Access-Control-Allow-Origin': '*'
}
 
const deleteEntityHandler = async (event) => {
  try {
    const id = event.pathParameters?.entityId
    const flowId = await getActiveFlowId(event)
 
    if (!flowId) {
      return {
        statusCode: 401,
        headers: CORS_HEADERS,
        body: JSON.stringify({ error: 'Missing flow context' })
      }
    }
 
    if (!id) {
      return {
        statusCode: 400,
        headers: CORS_HEADERS,
        body: JSON.stringify({ error: 'Missing id' })
      }
    }
 
    // Prevent deletion of system entities
    Iif (RESERVED_ENTITY_IDS.includes(id)) {
      return {
        statusCode: 403,
        headers: CORS_HEADERS,
        body: JSON.stringify({
          error: `Cannot delete system entity "${id}". System entities are protected.`
        })
      }
    }
 
    // Verify entity exists and ownership
    const result = await docClient.send(
      new GetCommand({
        TableName: process.env.TABLE_NAME,
        Key: { id }
      })
    )
 
    if (!result.Item) {
      return {
        statusCode: 404,
        headers: CORS_HEADERS,
        body: JSON.stringify({ error: 'Entity not found' })
      }
    }
 
    const entity = result.Item
 
    // Only owner flow can delete
    if (entity.flowId !== flowId) {
      return {
        statusCode: 403,
        headers: CORS_HEADERS,
        body: JSON.stringify({ error: 'Access denied - only owner can delete' })
      }
    }
 
    // Public entities with active links can't be deleted outright — ownership
    // transfers automatically to the flow with the most items pointing into
    // it (see docs/architecture/PUBLIC_ENTITIES.md). Only public entities can
    // ever be linked (entities/link.js enforces this), so private ones skip
    // straight to the delete path below.
    if (
      entity.visibility === 'public' &&
      process.env.ENTITY_LINKS_TABLE_NAME &&
      process.env.ENTITY_REFERENCE_COUNTERS_TABLE_NAME
    ) {
      const ranked = await rankConsumerFlows(docClient, {
        entityLinksTableName: process.env.ENTITY_LINKS_TABLE_NAME,
        countersTableName: process.env.ENTITY_REFERENCE_COUNTERS_TABLE_NAME,
        entityId: id
      })
 
      Eif (ranked.length > 0) {
        const confirmTransfer = event.queryStringParameters?.confirmTransfer === 'true'
 
        if (!confirmTransfer) {
          return {
            statusCode: 409,
            headers: CORS_HEADERS,
            body: JSON.stringify({
              requiresConfirmation: true,
              totalFlowsCount: ranked.length
            })
          }
        }
 
        const [target, ...otherCandidates] = ranked
        const transferResult = await transferEntityOwnership(docClient, {
          entitiesTableName: process.env.TABLE_NAME,
          entityLinksTableName: process.env.ENTITY_LINKS_TABLE_NAME,
          flowsTableName: process.env.FLOWS_TABLE_NAME,
          fieldValueIndexTableName: process.env.FIELD_VALUE_INDEX_TABLE_NAME,
          entityId: id,
          previousFlowId: flowId,
          newFlowId: target.flowId,
          otherLinkedFlowIds: otherCandidates.map((candidate) => candidate.flowId)
        })
 
        return {
          statusCode: 200,
          headers: CORS_HEADERS,
          body: JSON.stringify({ transferred: true, ...transferResult })
        }
      }
    }
 
    // No active consumers — safe to actually delete. Cascade the entity's own
    // items first (this handler used to leave them orphaned), accumulating
    // reference-counter deltas for any OTHER entity those items pointed at —
    // this flow keeps existing, so unlike a whole-flow deletion we can't just
    // wipe every counter row for it, only the ones this entity's items
    // contributed. Piggybacks on the item Query already needed to delete them.
    if (process.env.ITEMS_TABLE_NAME) {
      const fields = entity.fields || []
      const deltas = new Map()
      let lastKey
 
      do {
        const itemsResult = await docClient.send(
          new QueryCommand({
            TableName: process.env.ITEMS_TABLE_NAME,
            KeyConditionExpression: 'entityId = :entityId',
            ExpressionAttributeValues: { ':entityId': id },
            ExclusiveStartKey: lastKey
          })
        )
        const items = itemsResult.Items || []
        for (const item of items) {
          for (const targetEntityId of getReferencedEntityIds(fields, item)) {
            deltas.set(targetEntityId, (deltas.get(targetEntityId) || 0) - 1)
          }
        }
        await batchDelete(
          docClient,
          process.env.ITEMS_TABLE_NAME,
          items.map((item) => ({ entityId: item.entityId, id: item.id }))
        )
 
        // Exact keys, since items created before the entities/{id}/ layout keep
        // their files under the older {flowId}/{entityId}/… one.
        await deleteKeys(
          s3Client,
          process.env.ATTACHMENTS_BUCKET_NAME,
          items.flatMap((item) => getItemFileKeys(fields, item)),
          entityKeyGuard(id)
        )
 
        // These items are gone — any likes on them are stale.
        if (process.env.ITEM_LIKES_TABLE_NAME || process.env.ITEM_LIKE_COUNT_TABLE_NAME) {
          for (const item of items) {
            Eif (process.env.ITEM_LIKES_TABLE_NAME) {
              await deleteAllLikesForItem(docClient, process.env.ITEM_LIKES_TABLE_NAME, item.id)
            }
            Eif (process.env.ITEM_LIKE_COUNT_TABLE_NAME) {
              await deleteLikeCount(docClient, process.env.ITEM_LIKE_COUNT_TABLE_NAME, item.id)
            }
          }
        }
 
        // ...and so are their comments (with their counters and pending moderation tasks).
        const commentTables = commentTablesFromEnv()
        if (commentTables) {
          for (const item of items) {
            await deleteAllCommentsForItem(docClient, commentTables, item.id)
          }
        }
 
        lastKey = itemsResult.LastEvaluatedKey
      } while (lastKey)
 
      // The entity's list of users blocked from commenting goes with it.
      if (process.env.COMMENT_BLOCKS_TABLE_NAME) {
        await deleteAllCommentBlocksForEntity(docClient, process.env.COMMENT_BLOCKS_TABLE_NAME, id)
      }
 
      if (deltas.size > 0 && process.env.ENTITY_REFERENCE_COUNTERS_TABLE_NAME) {
        await adjustCounters(
          docClient,
          process.env.ENTITY_REFERENCE_COUNTERS_TABLE_NAME,
          flowId,
          deltas
        )
      }
    }
 
    // This entity is gone — nothing can reference it anymore.
    if (process.env.ENTITY_REFERENCE_COUNTERS_TABLE_NAME) {
      await deleteAllCountersForEntity(
        docClient,
        process.env.ENTITY_REFERENCE_COUNTERS_TABLE_NAME,
        id
      )
    }
 
    // Every unique-field reservation this entity's (now-deleted) items held
    // is stale — release them all via the entityIndex GSI.
    if (process.env.FIELD_VALUE_INDEX_TABLE_NAME) {
      await deleteAllReservationsForEntity(docClient, process.env.FIELD_VALUE_INDEX_TABLE_NAME, id)
    }
 
    Iif (process.env.ENTITY_ITEM_COUNT_TABLE_NAME) {
      await deleteItemCount(docClient, process.env.ENTITY_ITEM_COUNT_TABLE_NAME, id)
    }
 
    Iif (process.env.ENTITY_SUBSCRIBER_COUNT_TABLE_NAME) {
      await deleteSubscriberCount(docClient, process.env.ENTITY_SUBSCRIBER_COUNT_TABLE_NAME, id)
    }
 
    // Any user subscriptions to this now-gone entity are stale — release them
    // via the entityIndex GSI (mirrors the reservation cleanup above).
    if (process.env.ENTITY_SUBSCRIPTIONS_TABLE_NAME) {
      await deleteAllSubscriptionsForEntity(
        docClient,
        process.env.ENTITY_SUBSCRIPTIONS_TABLE_NAME,
        id
      )
    }
 
    // Roles may hold permissions scoped to this entity (e.g.
    // `entities-{id}:update`) — those become dangling references once it's
    // gone. Strip them, dropping any role left with zero permissions along
    // with its membership links (see TODO.md "RBAC & Roles").
    if (process.env.ROLES_TABLE_NAME && process.env.FLOW_MEMBERSHIPS_TABLE_NAME) {
      await cleanupRolesForDeletedEntity(docClient, {
        rolesTableName: process.env.ROLES_TABLE_NAME,
        flowMembershipsTableName: process.env.FLOW_MEMBERSHIPS_TABLE_NAME,
        flowId,
        entityId: id
      })
    }
 
    await docClient.send(
      new DeleteCommand({
        TableName: process.env.TABLE_NAME,
        Key: { id }
      })
    )
 
    // The entity's own picture/icon, plus anything left under its folder (files
    // of items whose row is gone, replaced or abandoned uploads). Last, so a
    // failed delete never leaves the entity pointing at a missing image.
    await deleteKeys(
      s3Client,
      process.env.ATTACHMENTS_BUCKET_NAME,
      getBrandingKeys(entity),
      entityKeyGuard(id)
    )
    await deletePrefix(s3Client, process.env.ATTACHMENTS_BUCKET_NAME, `entities/${id}/`)
 
    return { statusCode: 204, headers: CORS_HEADERS, body: '' }
  } catch (error) {
    console.error('Error:', error)
    return {
      statusCode: 500,
      headers: CORS_HEADERS,
      body: JSON.stringify({ error: 'Failed to delete entity' })
    }
  }
}
 
// Wrap with permission check: require 'entities-{id}:delete' permission
exports.handler = requirePermission(deleteEntityHandler, {
  permission: (event) => `entities-${event.pathParameters?.entityId}:delete`
})