All files / entities list.js

95.37% Statements 103/108
74.32% Branches 55/74
100% Functions 19/19
96.8% Lines 91/94

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 2801x 1x 1x 1x 1x 1x 1x 1x   1x 1x   1x     8x       16x                 40x   40x 41x 40x 40x   39x       21x 21x 11x   10x 5x   6x 14x           26x 26x   2x 2x   2x 3x       25x   3x 3x   6x           24x   24x 24x   24x                         24x     24x 24x 24x 24x   24x 1x                   23x 23x 2x                     21x                   20x 20x 19x           19x   2x 2x 2x 2x   2x               2x 2x 2x 2x 2x                               20x             20x 20x 26x       2x                     20x   20x 20x 20x             20x 20x 20x 20x             20x   2x     20x 20x 20x 20x     25x               20x 25x           20x                             1x 1x                     1x      
const { getActiveFlowId } = require('../shared/activeFlow')
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const { DynamoDBDocumentClient, QueryCommand, BatchGetCommand } = require('@aws-sdk/lib-dynamodb')
const { requirePermission } = require('../utils/requirePermission')
const { permissionChecker } = require('../utils/PermissionChecker')
const { getSubscriberCounts } = require('../utils/entitySubscriberCount')
const { parseSimpleSort, applySimpleSort } = require('../utils/simpleSort')
const { withPackSources } = require('../utils/packSource')
 
const client = new DynamoDBClient({})
const docClient = DynamoDBDocumentClient.from(client)
 
const ENTITY_SORT_FIELDS = ['name', 'createdAt']
 
function getEntityDisplayName(entity) {
  return typeof entity.name === 'string' ? entity.name : entity.name?.en || ''
}
 
function getEntitySortValue(entity, fieldId) {
  return fieldId === 'createdAt' ? entity.createdAt || '' : getEntityDisplayName(entity)
}
 
// Follows every page (via LastEvaluatedKey) rather than taking just the
// first one — a single Query call only returns up to ~1MB of items, so a
// flow with enough entities/links would otherwise have the rest silently
// dropped, with search, sort and pagination all then operating on an
// incomplete set with no indication to the caller.
async function queryAllPages(queryParams) {
  const items = []
  let ExclusiveStartKey
  do {
    const result = await docClient.send(new QueryCommand({ ...queryParams, ExclusiveStartKey }))
    items.push(...(result.Items || []))
    ExclusiveStartKey = result.LastEvaluatedKey
  } while (ExclusiveStartKey)
  return items
}
 
function extractSearchableText(value) {
  Iif (value === null || value === undefined) return []
  if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
    return [String(value)]
  }
  if (Array.isArray(value)) {
    return value.flatMap((entry) => extractSearchableText(entry))
  }
  Eif (typeof value === 'object') {
    return Object.values(value).flatMap((entry) => extractSearchableText(entry))
  }
  return []
}
 
function matchesQuery(value, query) {
  const normalizedQuery = typeof query === 'string' ? query.trim().toLowerCase() : ''
  if (!normalizedQuery) return true
 
  const terms = normalizedQuery.split(/\s+/).filter(Boolean)
  Iif (terms.length === 0) return true
 
  const haystack = extractSearchableText(value).join(' ').toLowerCase()
  return terms.every((term) => haystack.includes(term))
}
 
async function filterReadableEntities(entities, userId, flowId) {
  if (!entities.some((entity) => entity.visibility === 'restricted')) return entities
 
  const { permissions = [] } = await permissionChecker.getUserPermissions(userId, flowId)
  return entities.filter(
    (entity) =>
      entity.visibility !== 'restricted' ||
      permissionChecker.grantsOnEntity(permissions, `entities-${entity.id}:read`, entity)
  )
}
 
async function getEntitiesHandler(event) {
  try {
    // Extract flowId from JWT claims
    const flowId = await getActiveFlowId(event)
    const currentUserId = event.requestContext?.authorizer?.claims?.sub
 
    Iif (!flowId) {
      return {
        statusCode: 401,
        headers: {
          'Content-Type': 'application/json',
          'Access-Control-Allow-Origin': '*'
        },
        body: JSON.stringify({ error: 'Missing flow context' })
      }
    }
 
    // Pagination support - Note: For simplicity, we load all and paginate in memory
    // For large datasets, consider using DynamoDB pagination on each query separately
    const requestedLimit = event.queryStringParameters?.limit
      ? parseInt(event.queryStringParameters.limit, 10)
      : 30
    const limit = Number.isNaN(requestedLimit) ? 30 : Math.min(Math.max(requestedLimit, 1), 100)
    const nextToken = event.queryStringParameters?.nextToken
    const search = event.queryStringParameters?.search
    const offset = nextToken ? parseInt(Buffer.from(nextToken, 'base64').toString(), 10) : 0
 
    if (Number.isNaN(offset) || offset < 0) {
      return {
        statusCode: 400,
        headers: {
          'Content-Type': 'application/json',
          'Access-Control-Allow-Origin': '*'
        },
        body: JSON.stringify({ error: 'Invalid nextToken' })
      }
    }
 
    const sort = parseSimpleSort(event.queryStringParameters?.sort, ENTITY_SORT_FIELDS)
    if (sort?.error) {
      return {
        statusCode: 400,
        headers: {
          'Content-Type': 'application/json',
          'Access-Control-Allow-Origin': '*'
        },
        body: JSON.stringify({ error: sort.error, ...(sort.fieldId && { fieldId: sort.fieldId }) })
      }
    }
 
    // Query only this flow's own entities
    const flowEntitiesItems = await queryAllPages({
      TableName: process.env.TABLE_NAME,
      IndexName: 'flowIndex',
      KeyConditionExpression: 'flowId = :flowId',
      ExpressionAttributeValues: {
        ':flowId': flowId
      }
    })
 
    // Query linked entities for this flow (if EntityLinksTable is configured)
    const linkedEntities = []
    if (process.env.ENTITY_LINKS_TABLE_NAME) {
      const links = await queryAllPages({
        TableName: process.env.ENTITY_LINKS_TABLE_NAME,
        KeyConditionExpression: 'flowId = :flowId',
        ExpressionAttributeValues: { ':flowId': flowId }
      })
 
      if (links.length > 0) {
        // Batch-get linked entities in chunks of 25 (DynamoDB safe limit)
        const BATCH_SIZE = 25
        for (let i = 0; i < links.length; i += BATCH_SIZE) {
          const chunk = links.slice(i, i + BATCH_SIZE)
          const keys = chunk.map((link) => ({ id: link.entityId }))
 
          const batchResult = await docClient.send(
            new BatchGetCommand({
              RequestItems: {
                [process.env.TABLE_NAME]: { Keys: keys }
              }
            })
          )
 
          const fetched = batchResult.Responses?.[process.env.TABLE_NAME] || []
          for (const entity of fetched) {
            const link = links.find((l) => l.entityId === entity.id)
            Eif (link) {
              linkedEntities.push({
                ...entity,
                linked: true,
                sourceFlowId: link.sourceFlowId,
                linkedAt: link.linkedAt,
                archivedAt: link.archivedAt || null
              })
            }
          }
        }
      }
    }
 
    // A restricted entity is invisible to members who can't read it
    // (UC-ENTITY-007.2 AC-5). Permissions are resolved once, and only when the
    // flow actually has a restricted entity.
    const visibleOwnEntities = await filterReadableEntities(
      flowEntitiesItems,
      currentUserId,
      flowId
    )
 
    // Own entities first, then linked entities
    const allEntities = [...visibleOwnEntities, ...linkedEntities]
    const filteredEntities = allEntities.filter((entity) =>
      matchesQuery(
        {
          name: entity.name,
          description: entity.description,
          fields: entity.fields?.map((field) => ({
            name: field.name,
            placeholder: field.placeholder,
            options: field.options
          }))
        },
        search
      )
    )
 
    // Sort (defaults to Query/BatchGet order, i.e. unsorted) before pagination
    if (sort) applySimpleSort(filteredEntities, sort, getEntitySortValue)
 
    const paginatedEntities = filteredEntities.slice(offset, offset + limit)
    const hasMore = offset + limit < filteredEntities.length
    const responseNextToken = hasMore
      ? Buffer.from(String(offset + limit)).toString('base64')
      : null
 
    // Mark entities the current user personally subscribes to — a user can
    // now subscribe to any entity in their own flow (public or private), not
    // just other flows' public entities via the Catalog.
    let subscribedEntityIds = new Set()
    Eif (currentUserId && process.env.ENTITY_SUBSCRIPTIONS_TABLE_NAME) {
      try {
        const subscriptionsResult = await docClient.send(
          new QueryCommand({
            TableName: process.env.ENTITY_SUBSCRIPTIONS_TABLE_NAME,
            KeyConditionExpression: 'userId = :userId',
            ExpressionAttributeValues: { ':userId': currentUserId }
          })
        )
        subscribedEntityIds = new Set((subscriptionsResult.Items || []).map((s) => s.entityId))
      } catch (subscriptionErr) {
        console.error('[entities/list] Error fetching subscriptions:', subscriptionErr)
      }
    }
    let subscriberCounts = new Map()
    Eif (process.env.ENTITY_SUBSCRIBER_COUNT_TABLE_NAME) {
      try {
        subscriberCounts = await getSubscriberCounts(
          docClient,
          process.env.ENTITY_SUBSCRIBER_COUNT_TABLE_NAME,
          paginatedEntities.map((entity) => entity.id)
        )
      } catch (subscriberCountErr) {
        console.error('[entities/list] Error fetching subscriber counts:', subscriberCountErr)
      }
    }
 
    // A copy installed from a pack says which (UC-STORE-016.1)
    const sourcedEntities = await withPackSources(docClient, paginatedEntities)
    const enrichedEntities = sourcedEntities.map((entity) => ({
      ...entity,
      subscribedByCurrentUser: subscribedEntityIds.has(entity.id),
      subscriberCount: subscriberCounts.get(entity.id) ?? 0
    }))
 
    return {
      statusCode: 200,
      headers: {
        'Content-Type': 'application/json',
        'Access-Control-Allow-Origin': '*'
      },
      body: JSON.stringify({
        items: enrichedEntities,
        nextToken: responseNextToken,
        hasMore,
        filteredTotal: filteredEntities.length,
        total: allEntities.length
      })
    }
  } catch (error) {
    console.error('Error fetching entities:', error)
    return {
      statusCode: 500,
      headers: {
        'Content-Type': 'application/json',
        'Access-Control-Allow-Origin': '*'
      },
      body: JSON.stringify({ error: 'Failed to fetch entities' })
    }
  }
}
 
exports.handler = requirePermission(getEntitiesHandler, {
  permission: 'entities:list'
})