All files / flows create.js

100% Statements 63/63
97.91% Branches 47/48
100% Functions 2/2
100% Lines 59/59

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 2761x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x   33x         1x 34x 34x 34x 33x   33x 1x             32x 2x 2x 2x 2x                     30x 1x               29x 29x         28x 28x 1x                       27x           26x 1x                 25x     25x         25x 2x                     23x 23x     23x                                       23x                                                         23x                                                                         21x               21x 21x 21x     21x                                         1x     21x           4x         4x 2x 2x 1x           1x             2x              
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const { DynamoDBDocumentClient, TransactWriteCommand } = require('@aws-sdk/lib-dynamodb')
const { randomUUID } = require('crypto')
const { findFlowNameConflict } = require('../utils/nameUniqueness')
const { validateDescription } = require('../utils/validateDescription')
const { isValidUuid } = require('../utils/isValidUuid')
const { MAX_FLOW_SETTINGS_BYTES } = require('../utils/constants')
const { getCreditsBalance, debitCredits } = require('../utils/creditsLedger')
const { getPricingConfig } = require('../utils/pricingConfig')
const { getConsumedCapacity } = require('../shared/usage-tracking')
const { syncFlowSearchIndex } = require('../utils/directorySearchIndex')
 
const dynamoClient = new DynamoDBClient({})
const docClient = DynamoDBDocumentClient.from(dynamoClient)
 
const getCorsHeaders = () => ({
  'Content-Type': 'application/json',
  'Access-Control-Allow-Origin': '*'
})
 
exports.handler = async (event) => {
  try {
    const pricing = await getPricingConfig(docClient, process.env.PRICING_CONFIG_TABLE_NAME)
    const body = JSON.parse(event.body || '{}')
    const userId = event.requestContext?.authorizer?.claims?.sub
 
    if (!userId) {
      return {
        statusCode: 401,
        headers: getCorsHeaders(),
        body: JSON.stringify({ error: 'Not authenticated' })
      }
    }
 
    if (!body.name || !body.slug) {
      const missing = []
      if (!body.name) missing.push('Flow Name')
      if (!body.slug) missing.push('Identifier')
      return {
        statusCode: 400,
        headers: getCorsHeaders(),
        body: JSON.stringify({ error: `Missing required fields: ${missing.join(', ')}` })
      }
    }
 
    // Callers may supply the flow's id up front (generated client-side before
    // the first request), so image fields (picture/icon) uploaded during
    // creation can be keyed by the real id from the start instead of a
    // throwaway placeholder that would never get reconciled afterward.
    if (body.id !== undefined && !isValidUuid(body.id)) {
      return {
        statusCode: 400,
        headers: getCorsHeaders(),
        body: JSON.stringify({ error: 'Invalid id: must be a UUID' })
      }
    }
 
    // Validate description: cannot exceed the maximum number of line breaks
    const descriptionValidation = validateDescription(body.description)
    if (!descriptionValidation.valid) return descriptionValidation.errorResponse
 
    // Bound the one open-ended piece of a flow — see constants.js's
    // MAX_FLOW_SETTINGS_BYTES and docs/architecture/USAGE_METERING.md
    // "Bounding storage before it can be priced".
    const settingsSizeBytes = Buffer.byteLength(JSON.stringify(body.settings || {}))
    if (settingsSizeBytes > MAX_FLOW_SETTINGS_BYTES) {
      return {
        statusCode: 400,
        headers: getCorsHeaders(),
        body: JSON.stringify({
          error: 'FLOW_SETTINGS_TOO_LARGE',
          maxBytes: MAX_FLOW_SETTINGS_BYTES,
          actualBytes: settingsSizeBytes
        })
      }
    }
 
    // Verify flow name is unique among the flows owned by this user
    const nameConflict = await findFlowNameConflict(docClient, {
      tableName: process.env.FLOWS_TABLE_NAME,
      ownerId: userId,
      name: body.name
    })
 
    if (nameConflict) {
      return {
        statusCode: 409,
        headers: getCorsHeaders(),
        body: JSON.stringify({ error: 'A flow with this name already exists' })
      }
    }
 
    // Storage-credit preflight — see docs/architecture/USAGE_METERING.md
    // "DynamoDB storage credits" (same model as items/entities create).
    const storageCreditEstimate = Math.ceil(
      (settingsSizeBytes / 1024) * pricing.dynamodb_storage_credits_per_kb
    )
    const { balance: creditsBalance, isPlatformAdmin } = await getCreditsBalance(
      docClient,
      process.env.USERS_TABLE_NAME,
      userId
    )
    if (!isPlatformAdmin && creditsBalance < storageCreditEstimate) {
      return {
        statusCode: 402,
        headers: getCorsHeaders(),
        body: JSON.stringify({
          error: 'INSUFFICIENT_CREDITS',
          required: storageCreditEstimate,
          balance: creditsBalance
        })
      }
    }
 
    const flowId = body.id || randomUUID()
    const now = new Date().toISOString()
 
    // Create flow
    const flow = {
      id: flowId,
      name: body.name,
      slug: body.slug,
      ownerId: userId,
      joinPolicy: body.joinPolicy || 'invite-only',
      status: 'active',
      createdAt: now,
      // Constant partition value for the platformStatsIndex GSI, letting the
      // platform-admin dashboard query "all flows by creation date" without a scan.
      gsiPk: 'FLOW',
      defaultLanguage: body.defaultLanguage || 'en',
      enabledLanguages: body.enabledLanguages || ['en', 'fr'],
      settings: body.settings || {},
      ...(body.description && { description: body.description }),
      ...(body.picture && { picture: body.picture }),
      ...(body.icon && { icon: body.icon })
    }
 
    // Create default Admin role
    const adminRole = {
      PK: `FLOW#${flowId}`,
      SK: 'ROLE#admin',
      flowId,
      roleId: 'admin',
      // Hardcoded translations for every currently supported language — add a key
      // here whenever a new language is added to the app (e.g. flows-ui's
      // SUPPORTED_UI_LANGUAGES in useLanguage.ts), or new flows' Administrator role
      // will be missing that translation and silently fall back to English.
      name: { en: 'Administrator', fr: 'Administrateur' },
      description: {
        en: 'Full access to all flow resources',
        fr: 'Accès complet à toutes les ressources du flow'
      },
      permissions: ['*:*'],
      isSystemRole: true,
      createdBy: 'SYSTEM',
      createdAt: now,
      updatedAt: now
    }
 
    // Flow + slug reservation + system role + owner membership must be created
    // atomically. The slug reservation (FlowSlugsTable, conditioned on
    // attribute_not_exists(slug)) is what makes slug uniqueness race-proof —
    // unlike the old slugIndex GSI precheck (a plain read-then-write), two
    // concurrent creates with the same slug can no longer both succeed. A
    // partial write of the rest (e.g. flow created but role/membership
    // missing) would also silently strand the owner with zero permissions,
    // since permission checks never fall back to ownerId.
    await docClient.send(
      new TransactWriteCommand({
        TransactItems: [
          {
            Put: {
              TableName: process.env.FLOWS_TABLE_NAME,
              Item: flow,
              ConditionExpression: 'attribute_not_exists(id)'
            }
          },
          {
            Put: {
              TableName: process.env.FLOW_SLUGS_TABLE_NAME,
              Item: { slug: body.slug, flowId },
              ConditionExpression: 'attribute_not_exists(slug)'
            }
          },
          { Put: { TableName: process.env.ROLES_TABLE_NAME, Item: adminRole } },
          {
            Put: {
              TableName: process.env.FLOW_MEMBERSHIPS_TABLE_NAME,
              Item: {
                userId: userId,
                flowId,
                roleIds: ['admin'], // Assign Admin role to creator
                status: 'active',
                invitedBy: userId,
                joinedAt: now
              }
            }
          }
        ]
      })
    )
 
    // Best-effort from here: a failure doesn't unwind the write — see
    // items/create.js's identical reasoning.
    await syncFlowSearchIndex(
      docClient,
      process.env.FIELD_VALUE_INDEX_TABLE_NAME,
      flowId,
      null,
      flow
    )
 
    try {
      const { writeUnits } = getConsumedCapacity()
      const throughputCreditCost = Math.ceil(
        writeUnits * pricing.dynamodb_throughput_credits_per_wru
      )
      await debitCredits(docClient, {
        usersTableName: process.env.USERS_TABLE_NAME,
        creditsLedgerTableName: process.env.CREDITS_LEDGER_TABLE_NAME,
        userId,
        flowId,
        charges: [
          {
            pool: 'dynamodb_storage',
            operation: 'flow_create',
            costCredits: storageCreditEstimate,
            referenceId: flowId
          },
          {
            pool: 'dynamodb_throughput',
            operation: 'flow_create',
            costCredits: throughputCreditCost,
            referenceId: flowId
          }
        ]
      })
    } catch (creditError) {
      console.error('Failed to debit credits for flow create:', creditError)
    }
 
    return {
      statusCode: 201,
      headers: getCorsHeaders(),
      body: JSON.stringify(flow)
    }
  } catch (error) {
    console.error('Error:', error)
 
    // The flow Put and the slug reservation Put each carry their own
    // ConditionExpression (in that order), so CancellationReasons tells us
    // which one actually collided.
    if (error.name === 'TransactionCanceledException') {
      const slugReasonCode = error.CancellationReasons?.[1]?.Code
      if (slugReasonCode === 'ConditionalCheckFailed') {
        return {
          statusCode: 409,
          headers: getCorsHeaders(),
          body: JSON.stringify({ error: 'Slug already exists' })
        }
      }
      return {
        statusCode: 409,
        headers: getCorsHeaders(),
        body: JSON.stringify({ error: 'A flow with this id already exists' })
      }
    }
 
    return {
      statusCode: 500,
      headers: getCorsHeaders(),
      body: JSON.stringify({ error: 'Failed to create flow' })
    }
  }
}