All files / comments create.js

100% Statements 102/102
92.53% Branches 62/67
100% Functions 2/2
100% Lines 97/97

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                                                2x 2x         2x           2x             2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x   2x 2x 2x   2x       38x 33x 33x 32x   1x 1x       2x 61x 61x 61x 56x     56x 1x     55x 55x 54x     54x 54x   1x     53x 53x       48x 3x     45x 45x 11x 2x   9x           9x 5x       38x   38x 38x   38x                                   38x 38x 38x 38x         38x 36x     36x 4x                       34x 34x           18x     18x   18x               18x 1x             33x                 33x 33x   17x 17x   16x     16x 2x 2x                         33x 33x   3x 2x     2x 1x     1x 1x 1x           1x         30x 28x 28x 28x     28x                                           1x       30x   30x           1x 1x      
/**
 * POST /v1/entities/{entityId}/items/{itemId}/comments
 * POST /v1/store/{packId}/comments
 *
 * Posts a comment (or, with `parentId`, a reply) on an item of an entity
 * whose owner enabled comments, or on a store pack whose managers did. Body:
 * { body: string, parentId?: string }.
 *
 * Access rules are shared with the other comments endpoints (see
 * utils/commentAccess.js, which resolves the thread: the item or the pack). A
 * reply is only allowed under an approved comment. The comment row, the
 * thread's comment counter and the parent's reply counter are written in one
 * transaction, so they cannot drift apart.
 *
 * Credits: like items/create.js, the author pays for what the comment stores
 * (storage estimate + measured write throughput), with a 402 preflight. When
 * an admin marks `comments/create` as free (LambdaBillingTable), the whole
 * charge — preflight, 402 and storage debit — is skipped, not just the
 * baseline pools: a user with a zero balance (there is no signup grant) must
 * still be able to comment. See docs/architecture/MODERATION.md "Credits".
 *
 * @implements UC-COMMENT-002.1, UC-COMMENT-003.1, UC-COMMENT-007.1, UC-COMMENT-008.1, UC-COMMENT-009.1, UC-MOD-001.1, UC-MOD-005.1, UC-MOD-006.1, UC-STORE-009.1
 */
 
const { randomUUID } = require('crypto')
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const {
  DynamoDBDocumentClient,
  GetCommand,
  TransactWriteCommand
} = require('@aws-sdk/lib-dynamodb')
const {
  resolveCommentContext,
  isBlockedFromCommenting,
  errorResponse,
  CORS_HEADERS
} = require('../utils/commentAccess')
const {
  COMMENT_STATUS,
  commentSortKey,
  approvedParentKey,
  validateCommentBody,
  toPublicComment
} = require('../utils/comments')
const { buildCommentCountUpdate } = require('../utils/commentCount')
const { prepareSubmission } = require('../utils/moderation/engine')
const { getSubject } = require('../utils/moderation/subjects')
const { resolvePublicUsers } = require('../utils/userFollows')
const { isValidUuid } = require('../utils/isValidUuid')
const { resolveBillingUserId, getCreditsBalance, debitCredits } = require('../utils/creditsLedger')
const { getPricingConfig } = require('../utils/pricingConfig')
const { getFreeFunctionKeys } = require('../utils/lambdaBillingConfig')
const { getConsumedCapacity } = require('../shared/usage-tracking')
const { isE2eTestEmail } = require('../utils/e2eTestUser')
 
const client = new DynamoDBClient({})
const { checkCanPost } = require('../utils/accountSanctions')
const docClient = DynamoDBDocumentClient.from(client)
 
const FUNCTION_KEY = 'comments/create'
 
/** True when an admin marked comment creation as free. Fails closed (charges) if the config is unreadable. */
async function isCommentCreationFree() {
  if (!process.env.LAMBDA_BILLING_TABLE_NAME) return false
  try {
    const freeKeys = await getFreeFunctionKeys(docClient, process.env.LAMBDA_BILLING_TABLE_NAME)
    return freeKeys.has(FUNCTION_KEY)
  } catch (error) {
    console.error('[comments/create] Could not read the free-function config:', error)
    return false
  }
}
 
exports.handler = async (event) => {
  try {
    const context = await resolveCommentContext(docClient, event)
    if (context.response) return context.response
    const { auth, thread } = context
    // A platform admin reads another flow's private threads to act on a
    // report; posting there stays for the entity's own members
    if (thread.viaPlatformAdmin) {
      return errorResponse(403, 'Access denied to this entity')
    }
    // A restricted or banned account comments nowhere (UC-REPORT-007.1)
    const restricted = await checkCanPost(docClient, auth.userId)
    if (restricted) return restricted
    const threadKey = thread.key
 
    let payload
    try {
      payload = JSON.parse(event.body || '{}')
    } catch {
      return errorResponse(400, 'Invalid JSON body')
    }
 
    const validation = validateCommentBody(payload.body)
    if (!validation.valid) return errorResponse(400, validation.error)
 
    // A block stops the author from commenting on this entity or pack, and
    // nothing else: they can still vote in the moderation queue.
    if (await isBlockedFromCommenting(docClient, thread.blocksKey, auth.userId)) {
      return errorResponse(403, 'COMMENT_BLOCKED')
    }
 
    const parentId = payload.parentId ?? null
    if (parentId !== null) {
      if (typeof parentId !== 'string' || !isValidUuid(parentId)) {
        return errorResponse(400, 'Invalid parentId')
      }
      const parentResult = await docClient.send(
        new GetCommand({
          TableName: process.env.COMMENTS_TABLE_NAME,
          Key: { itemId: threadKey, id: parentId }
        })
      )
      if (!parentResult.Item || parentResult.Item.status !== COMMENT_STATUS.APPROVED) {
        return errorResponse(404, 'Parent comment not found')
      }
    }
 
    const { moderated } = thread
 
    const now = new Date().toISOString()
    const id = randomUUID()
    // `itemId` is the thread key: the item's id, or the pack's
    const comment = {
      itemId: threadKey,
      id,
      ...thread.rowFields,
      ...(parentId !== null && { parentId }),
      authorId: auth.userId,
      body: validation.body,
      status: moderated ? COMMENT_STATUS.PENDING : COMMENT_STATUS.APPROVED,
      replyCount: 0,
      createdAt: now,
      sortKey: commentSortKey(now, id),
      // Approved comments join the public lists; the others stay in their
      // author's "awaiting review" list until decided.
      ...(moderated
        ? { unapprovedKey: `${auth.userId}#${threadKey}` }
        : { approvedParentKey: approvedParentKey(threadKey, parentId) })
    }
 
    const billingUserId = resolveBillingUserId(auth)
    const isFree = await isCommentCreationFree()
    const pricing = await getPricingConfig(docClient, process.env.PRICING_CONFIG_TABLE_NAME)
    const storageCreditEstimate = Math.ceil(
      (Buffer.byteLength(JSON.stringify(comment), 'utf8') / 1024) *
        pricing.dynamodb_storage_credits_per_kb
    )
 
    if (!isFree) {
      const { balance: creditsBalance, isPlatformAdmin } = billingUserId
        ? await getCreditsBalance(docClient, process.env.USERS_TABLE_NAME, billingUserId)
        : { balance: 0, isPlatformAdmin: false }
      if (!billingUserId || (!isPlatformAdmin && creditsBalance < storageCreditEstimate)) {
        return {
          statusCode: 402,
          headers: CORS_HEADERS,
          body: JSON.stringify({
            error: 'INSUFFICIENT_CREDITS',
            required: storageCreditEstimate,
            balance: creditsBalance
          })
        }
      }
    }
 
    let submission = null
    if (moderated) {
      // Whether the author's own "do I have enough to review?" existence check
      // (inside prepareSubmission) should look at the test queue or the real
      // one — the same split the review queue itself uses (see
      // subjects/commentSubject.js's isVisibleToReviewer). One bounded read by
      // primary key, not a scan.
      const authorResult = await docClient.send(
        new GetCommand({ TableName: process.env.USERS_TABLE_NAME, Key: { id: auth.userId } })
      )
      const authorIsTest = isE2eTestEmail(authorResult.Item?.email)
 
      submission = await prepareSubmission(docClient, {
        subjectType: thread.subjectType,
        subjectId: id,
        authorId: auth.userId,
        scopeFlowId: thread.scopeFlowId,
        subjectRef: getSubject(thread.subjectType).buildSubjectRef(thread.subjectRef),
        authorIsTest
      })
      if (!submission.ok) {
        return errorResponse(403, 'MODERATION_QUOTA_REQUIRED', {
          required: submission.required,
          have: submission.have
        })
      }
    }
 
    const transactItems = [
      {
        Put: {
          TableName: process.env.COMMENTS_TABLE_NAME,
          Item: comment,
          ConditionExpression: 'attribute_not_exists(id)'
        }
      }
    ]
    let parentCheckIndex = -1
    if (moderated) {
      // Counters and the parent's reply count move when the comment is approved
      transactItems.push(submission.taskItem)
      if (submission.spendItem) transactItems.push(submission.spendItem)
    } else {
      transactItems.push(
        buildCommentCountUpdate(process.env.ITEM_COMMENT_COUNT_TABLE_NAME, threadKey, 1)
      )
      if (parentId !== null) {
        parentCheckIndex = transactItems.length
        transactItems.push({
          Update: {
            TableName: process.env.COMMENTS_TABLE_NAME,
            Key: { itemId: threadKey, id: parentId },
            UpdateExpression: 'ADD replyCount :one',
            ConditionExpression: '#status = :approved',
            ExpressionAttributeNames: { '#status': 'status' },
            ExpressionAttributeValues: { ':one': 1, ':approved': COMMENT_STATUS.APPROVED }
          }
        })
      }
    }
 
    try {
      await docClient.send(new TransactWriteCommand({ TransactItems: transactItems }))
    } catch (error) {
      if (error.name === 'TransactionCanceledException') {
        const reasons = error.CancellationReasons || []
        // The parent was deleted or otherwise left the approved state between
        // the check above and the write.
        if (parentCheckIndex >= 0 && reasons[parentCheckIndex]?.Code === 'ConditionalCheckFailed') {
          return errorResponse(404, 'Parent comment not found')
        }
        // Another request spent the points between the check and the write
        const spendIndex = submission?.spendItem ? transactItems.indexOf(submission.spendItem) : -1
        Eif (spendIndex >= 0 && reasons[spendIndex]?.Code === 'ConditionalCheckFailed') {
          return errorResponse(403, 'MODERATION_QUOTA_REQUIRED', {
            required: submission.spendItem.Update.ExpressionAttributeValues[':required'],
            have: submission.have
          })
        }
      }
      throw error
    }
 
    // The comment durably exists: debit for what it really cost. Best-effort,
    // like items/create.js — a failure only means this write went unbilled.
    if (!isFree) {
      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: billingUserId,
          // The flow the author is acting in, not the entity's owner: the cost is theirs.
          flowId: auth.flowId,
          charges: [
            {
              pool: 'dynamodb_storage',
              operation: 'comment_create',
              costCredits: storageCreditEstimate,
              referenceId: id
            },
            {
              pool: 'dynamodb_throughput',
              operation: 'comment_create',
              costCredits: throughputCreditCost,
              referenceId: id
            }
          ]
        })
      } catch (creditError) {
        console.error('[comments/create] Failed to debit credits:', creditError)
      }
    }
 
    const authors = await resolvePublicUsers(docClient, process.env.USERS_TABLE_NAME, [auth.userId])
 
    return {
      statusCode: 201,
      headers: CORS_HEADERS,
      body: JSON.stringify(toPublicComment(comment, authors.get(auth.userId)))
    }
  } catch (error) {
    console.error('[comments/create] Exception:', error.message, error.stack)
    return errorResponse(500, 'Failed to create comment')
  }
}