All files / store flow.js

100% Statements 37/37
90.47% Branches 19/21
100% Functions 5/5
100% Lines 33/33

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                                1x 1x         1x 1x 1x 1x   1x   1x 1x   1x     3x 3x   1x       1x 9x 9x 9x 8x 8x   7x 7x         7x 7x 3x   3x 2x   1x     5x                                   5x   4x 4x                   1x 1x      
/**
 * GET /v1/store/flow
 *
 * The packs of the active flow, the most recently created first, for the
 * publish panel to choose the pack a new version is for (UC-STORE-008.2). Each
 * says whether the caller may publish its next version: holding
 * `packs:publish`, and being its author or the flow's owner. One Query on
 * `flowIndex` per page; never says who published a pack.
 *
 * Query params:
 * - limit: page size (default 30, max 100)
 * - nextToken: opaque cursor returned by the previous page
 *
 * @implements UC-STORE-008.2
 */
 
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const { DynamoDBDocumentClient, QueryCommand } = require('@aws-sdk/lib-dynamodb')
const {
  authenticateModerator: authenticateUser,
  errorResponse,
  jsonResponse
} = require('../utils/moderation/access')
const { hasPermission } = require('../shared/auth-helper')
const { permissionChecker } = require('../utils/PermissionChecker')
const { PUBLISH_PERMISSION, packsTable } = require('../utils/packs')
 
const docClient = DynamoDBDocumentClient.from(new DynamoDBClient({}))
 
const DEFAULT_LIMIT = 30
const MAX_LIMIT = 100
 
const encodeToken = (key) => Buffer.from(JSON.stringify(key)).toString('base64')
 
function decodeToken(token) {
  try {
    return JSON.parse(Buffer.from(token, 'base64').toString())
  } catch {
    return null
  }
}
 
exports.handler = async (event) => {
  try {
    const caller = await authenticateUser(event)
    if (caller.response) return caller.response
    const { auth } = caller
    if (!auth.flowId) return errorResponse(403, 'NO_ACTIVE_FLOW')
 
    const rawLimit = parseInt(event.queryStringParameters?.limit, 10)
    const limit = Number.isFinite(rawLimit)
      ? Math.min(Math.max(rawLimit, 1), MAX_LIMIT)
      : DEFAULT_LIMIT
 
    let exclusiveStartKey
    const nextToken = event.queryStringParameters?.nextToken
    if (nextToken) {
      const key = decodeToken(nextToken)
      // A client-controlled cursor must stay in the active flow
      if (key?.flowId !== auth.flowId || typeof key.id !== 'string') {
        return errorResponse(400, 'Invalid nextToken')
      }
      exclusiveStartKey = { id: key.id, flowId: key.flowId, createdAt: key.createdAt }
    }
 
    const [result, mayPublish, isOwner] = await Promise.all([
      docClient.send(
        new QueryCommand({
          TableName: packsTable(),
          IndexName: 'flowIndex',
          KeyConditionExpression: 'flowId = :flowId',
          ExpressionAttributeValues: { ':flowId': auth.flowId },
          ScanIndexForward: false,
          Limit: limit,
          ExclusiveStartKey: exclusiveStartKey
        })
      ),
      hasPermission(auth, PUBLISH_PERMISSION),
      permissionChecker.isOwner(auth.userId, auth.flowId)
    ])
 
    // A row with no published version (left by the moderated design of the
    // Store's first weeks) is no pack anyone can see
    const packs = (result.Items || []).filter((pack) => pack.currentVersion)
 
    return jsonResponse(200, {
      items: packs.map((pack) => ({
        id: pack.id,
        name: pack.name,
        description: pack.description ?? '',
        version: pack.currentVersion,
        canPublishVersion: mayPublish && (isOwner || pack.authorId === auth.userId)
      })),
      nextToken: result.LastEvaluatedKey ? encodeToken(result.LastEvaluatedKey) : null
    })
  } catch (error) {
    console.error('[store/flow] Exception:', error.message, error.stack)
    return errorResponse(500, 'Failed to list the flow packs')
  }
}