All files / conversations create.js

100% Statements 56/56
100% Branches 34/34
100% Functions 3/3
100% Lines 52/52

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                                                      1x 1x         1x               1x   1x 1x 1x   1x           6x               1x 19x 19x 19x 1x               18x 17x     16x 16x   1x             15x 15x 3x             12x 1x             11x           11x 1x             10x           10x 2x             8x             8x 5x 5x 3x 3x                   1x     2x       4x 4x             3x                 3x 1x             2x 2x   2x 2x                           4x                                 2x                               2x           2x 2x              
/**
 * POST /v1/conversations
 * Body: { recipientId }
 *
 * Gets or creates a direct-message conversation between the caller and
 * `recipientId`. Looked up by the deterministic `participantsKey` GSI first
 * so repeat "Message" clicks reuse the same conversation instead of forking
 * a new one. When the caller is the recipient of a pending or declined
 * request from that user, reaching for "Message" themselves accepts it.
 *
 * A new conversation is 'accepted' (straight to both inboxes) when the
 * recipient is connected with the caller, a 'pending' message request
 * otherwise — see utils/directMessages.js. A request's recipient row carries
 * neither `lastMessageAt` nor `requestedAt` until its first message is sent
 * (messages/create.js), so it shows in none of the recipient's lists yet.
 *
 * Note: ConversationsTable's primary key is a random `id`, not
 * `participantsKey`, so a true uniqueness ConditionExpression against
 * concurrent duplicate creates isn't possible on a GSI attribute — there is
 * a narrow race window where two simultaneous first-message clicks for the
 * same pair could each miss the pre-check and create their own row. Accepted
 * as a low-severity, low-frequency edge case rather than adding a separate
 * reservation table (like NicknamesTable's) just for this.
 *
 * @implements UC-DM-002.2, UC-DM-003.2
 */
 
const { randomUUID } = require('crypto')
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const {
  DynamoDBDocumentClient,
  GetCommand,
  TransactWriteCommand
} = require('@aws-sdk/lib-dynamodb')
const {
  buildParticipantsKey,
  conversationStatus,
  getBlockState,
  evaluateNewConversation,
  findConversation,
  acceptConversation
} = require('../utils/directMessages')
 
const client = new DynamoDBClient({})
const { checkCanPost } = require('../utils/accountSanctions')
const docClient = DynamoDBDocumentClient.from(client)
 
const CORS_HEADERS = {
  'Content-Type': 'application/json',
  'Access-Control-Allow-Origin': '*'
}
 
function toResponse(conversation, recipientId, status) {
  return {
    id: conversation.id,
    otherUserId: recipientId,
    createdAt: conversation.createdAt,
    status
  }
}
 
exports.handler = async (event) => {
  try {
    const senderId = event.requestContext?.authorizer?.claims?.sub
    if (!senderId) {
      return {
        statusCode: 401,
        headers: CORS_HEADERS,
        body: JSON.stringify({ error: 'Unauthorized' })
      }
    }
 
    // A restricted or banned account starts no conversation (UC-REPORT-007.1)
    const restricted = await checkCanPost(docClient, senderId)
    if (restricted) return restricted
 
    let body
    try {
      body = JSON.parse(event.body || '{}')
    } catch {
      return {
        statusCode: 400,
        headers: CORS_HEADERS,
        body: JSON.stringify({ error: 'Invalid JSON body' })
      }
    }
 
    const recipientId = body.recipientId
    if (!recipientId || typeof recipientId !== 'string') {
      return {
        statusCode: 400,
        headers: CORS_HEADERS,
        body: JSON.stringify({ error: 'Missing recipientId' })
      }
    }
 
    if (recipientId === senderId) {
      return {
        statusCode: 400,
        headers: CORS_HEADERS,
        body: JSON.stringify({ error: 'Cannot start a conversation with yourself' })
      }
    }
 
    const recipientResult = await docClient.send(
      new GetCommand({
        TableName: process.env.USERS_TABLE_NAME,
        Key: { id: recipientId }
      })
    )
    if (!recipientResult.Item) {
      return {
        statusCode: 404,
        headers: CORS_HEADERS,
        body: JSON.stringify({ error: 'Recipient not found' })
      }
    }
 
    const blocks = await getBlockState(
      docClient,
      process.env.USER_BLOCKS_TABLE_NAME,
      senderId,
      recipientId
    )
    if (blocks.blockedByUser || blocks.blockedByOther) {
      return {
        statusCode: 403,
        headers: CORS_HEADERS,
        body: JSON.stringify({ error: 'You cannot message this user' })
      }
    }
 
    const existing = await findConversation(
      docClient,
      process.env.CONVERSATIONS_TABLE_NAME,
      senderId,
      recipientId
    )
 
    if (existing) {
      let status = conversationStatus(existing)
      if (status !== 'accepted' && existing.requesterId !== senderId) {
        try {
          await acceptConversation(
            docClient,
            {
              conversationsTableName: process.env.CONVERSATIONS_TABLE_NAME,
              participantsTableName: process.env.CONVERSATION_PARTICIPANTS_TABLE_NAME
            },
            existing,
            senderId,
            new Date().toISOString()
          )
          status = 'accepted'
        } catch (error) {
          // Accepted concurrently (another tab): nothing left to do
          if (error.name !== 'TransactionCanceledException') throw error
        }
      }
      // The requester is never told their request was declined
      if (status === 'declined') status = 'pending'
      return {
        statusCode: 200,
        headers: CORS_HEADERS,
        body: JSON.stringify(toResponse(existing, recipientId, status))
      }
    }
 
    const evaluation = await evaluateNewConversation(
      docClient,
      {
        userFollowsTableName: process.env.USER_FOLLOWS_TABLE_NAME,
        flowMembershipsTableName: process.env.FLOW_MEMBERSHIPS_TABLE_NAME
      },
      senderId,
      recipientResult.Item
    )
    if (!evaluation.allowed) {
      return {
        statusCode: 403,
        headers: CORS_HEADERS,
        body: JSON.stringify({ error: 'You cannot message this user' })
      }
    }
 
    const participantsKey = buildParticipantsKey(senderId, recipientId)
    const status = evaluation.direct ? 'accepted' : 'pending'
 
    const now = new Date().toISOString()
    const conversation = {
      id: randomUUID(),
      participantIds: [senderId, recipientId].sort(),
      participantsKey,
      createdAt: now,
      lastMessageAt: now,
      lastMessagePreview: null,
      lastMessageSenderId: null,
      status,
      requesterId: senderId
    }
 
    // `listed: false` leaves out `lastMessageAt`, keeping a request out of
    // its recipient's Inbox (recencyIndex) — see the header comment.
    const buildParticipantRow = (userId, otherUserId, listed) => ({
      Put: {
        TableName: process.env.CONVERSATION_PARTICIPANTS_TABLE_NAME,
        Item: {
          userId,
          conversationId: conversation.id,
          otherUserId,
          status,
          unreadCount: 0,
          lastReadAt: now,
          ...(listed ? { lastMessageAt: now } : {}),
          lastMessagePreview: null,
          lastMessageSenderId: null
        }
      }
    })
 
    await docClient.send(
      new TransactWriteCommand({
        TransactItems: [
          {
            Put: {
              TableName: process.env.CONVERSATIONS_TABLE_NAME,
              Item: conversation,
              ConditionExpression: 'attribute_not_exists(id)'
            }
          },
          buildParticipantRow(senderId, recipientId, true),
          buildParticipantRow(recipientId, senderId, evaluation.direct)
        ]
      })
    )
 
    return {
      statusCode: 201,
      headers: CORS_HEADERS,
      body: JSON.stringify(toResponse(conversation, recipientId, status))
    }
  } catch (error) {
    console.error('[conversations/create] Exception:', error.message, error.stack)
    return {
      statusCode: 500,
      headers: CORS_HEADERS,
      body: JSON.stringify({ error: 'Failed to create conversation' })
    }
  }
}