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 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 7x 1x 23x 23x 23x 1x 22x 21x 20x 20x 1x 19x 19x 1x 18x 18x 2x 16x 16x 1x 15x 15x 1x 14x 14x 14x 14x 1x 13x 13x 5x 8x 8x 8x 4x 4x 4x 2x 1x 5x 5x 5x 5x 10x 5x 5x 5x 1x 1x 4x 4x 1x 4x 1x 1x | /**
* POST /v1/conversations/{conversationId}/messages
* Body: { body }
*
* Sends a message in an existing conversation. Verifies participancy via a
* Get on ConversationParticipantsTable (PK userId, SK conversationId — the
* same check messages/list.js uses), then what the caller may send right
* now (utils/directMessages.js's describeSendState): a block on either side,
* or an unanswered message request, refuses it — existing messages stay
* readable either way. Writes the message plus both participants'
* denormalized recency/preview rows and the conversation summary row in one
* transaction.
*
* The one message of a request (its requester's first) is special: it
* re-checks the recipient's "who can message me" setting, counts against the
* requester's daily quota (429 once used up), and lists the request in the
* recipient's Requests tab (`requestedAt`) rather than their Inbox
* (`lastMessageAt`).
*
* The WebSocket push to the recipient's live connections happens *after*
* the transaction commits and is strictly best-effort: a push failure is
* logged and swallowed, never turned into a failed send — the recipient
* still sees the message on their next inbox/messages fetch either way.
*
* @implements UC-DM-002.2, UC-DM-007.1, UC-DM-009.1, UC-DM-010.1
*/
const { randomUUID } = require('crypto')
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const {
DynamoDBDocumentClient,
GetCommand,
TransactWriteCommand
} = require('@aws-sdk/lib-dynamodb')
const {
getBlockState,
describeSendState,
canStartConversation,
consumeRequestQuota
} = require('../utils/directMessages')
const { pushToUserConnections } = require('../utils/webSocketPush')
const { checkCanPost } = require('../utils/accountSanctions')
const { MAX_MESSAGE_BODY_BYTES } = require('../utils/constants')
const client = new DynamoDBClient({})
const docClient = DynamoDBDocumentClient.from(client)
const CORS_HEADERS = {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
}
const PREVIEW_MAX_CHARS = 120
const REFUSALS = {
blocked_by_you: { error: 'You blocked this user', code: 'BLOCKED_BY_YOU' },
unavailable: { error: 'You cannot message this user', code: 'UNAVAILABLE' },
awaiting_acceptance: {
error: 'Your message request has not been accepted yet',
code: 'REQUEST_PENDING'
},
request_received: {
error: 'Accept this message request before replying',
code: 'REQUEST_NOT_ACCEPTED'
}
}
function forbidden(sendState) {
return {
statusCode: 403,
headers: CORS_HEADERS,
body: JSON.stringify(REFUSALS[sendState])
}
}
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 sends nothing (UC-REPORT-007.1)
const restricted = await checkCanPost(docClient, senderId)
if (restricted) return restricted
const conversationId = event.pathParameters?.conversationId
if (!conversationId) {
return {
statusCode: 400,
headers: CORS_HEADERS,
body: JSON.stringify({ error: 'Missing conversationId' })
}
}
let requestBody
try {
requestBody = JSON.parse(event.body || '{}')
} catch {
return {
statusCode: 400,
headers: CORS_HEADERS,
body: JSON.stringify({ error: 'Invalid JSON body' })
}
}
const messageBody = requestBody.body
if (!messageBody || typeof messageBody !== 'string' || !messageBody.trim()) {
return {
statusCode: 400,
headers: CORS_HEADERS,
body: JSON.stringify({ error: 'Message body is required' })
}
}
const bodySizeBytes = Buffer.byteLength(messageBody)
if (bodySizeBytes > MAX_MESSAGE_BODY_BYTES) {
return {
statusCode: 400,
headers: CORS_HEADERS,
body: JSON.stringify({
error: 'Message body too large',
maxBytes: MAX_MESSAGE_BODY_BYTES,
actualBytes: bodySizeBytes
})
}
}
const participantRow = await docClient.send(
new GetCommand({
TableName: process.env.CONVERSATION_PARTICIPANTS_TABLE_NAME,
Key: { userId: senderId, conversationId }
})
)
if (!participantRow.Item) {
return {
statusCode: 403,
headers: CORS_HEADERS,
body: JSON.stringify({ error: 'You are not a participant in this conversation' })
}
}
const recipientId = participantRow.Item.otherUserId
const [conversationResult, blocks] = await Promise.all([
docClient.send(
new GetCommand({
TableName: process.env.CONVERSATIONS_TABLE_NAME,
Key: { id: conversationId }
})
),
getBlockState(docClient, process.env.USER_BLOCKS_TABLE_NAME, senderId, recipientId)
])
const conversation = conversationResult.Item
if (!conversation) {
return {
statusCode: 404,
headers: CORS_HEADERS,
body: JSON.stringify({ error: 'Conversation not found' })
}
}
const sendState = describeSendState(conversation, senderId, blocks)
if (sendState !== 'ok' && sendState !== 'request_first_message') {
return forbidden(sendState)
}
const isRequest = sendState === 'request_first_message'
const now = new Date().toISOString()
if (isRequest) {
const recipientResult = await docClient.send(
new GetCommand({
TableName: process.env.USERS_TABLE_NAME,
Key: { id: recipientId }
})
)
const allowed =
!!recipientResult.Item &&
(await canStartConversation(
docClient,
{
userFollowsTableName: process.env.USER_FOLLOWS_TABLE_NAME,
flowMembershipsTableName: process.env.FLOW_MEMBERSHIPS_TABLE_NAME
},
senderId,
recipientResult.Item
))
if (!allowed) return forbidden('unavailable')
if (!(await consumeRequestQuota(docClient, process.env.USERS_TABLE_NAME, senderId, now))) {
return {
statusCode: 429,
headers: CORS_HEADERS,
body: JSON.stringify({
error: 'Daily message request limit reached',
code: 'REQUEST_LIMIT_REACHED'
})
}
}
}
const id = randomUUID()
const preview =
messageBody.length > PREVIEW_MAX_CHARS
? `${messageBody.slice(0, PREVIEW_MAX_CHARS)}…`
: messageBody
const message = {
id,
conversationId,
sortKey: `${now}#${id}`,
senderId,
recipientId,
body: messageBody,
createdAt: now
}
// The recipient's row of a request is listed in their Requests tab
// (`requestedAt`), not their Inbox (`lastMessageAt`), until accepted.
const buildParticipantSummaryUpdate = (
userId,
{ listedAs = 'lastMessageAt', unread } = {}
) => ({
Update: {
TableName: process.env.CONVERSATION_PARTICIPANTS_TABLE_NAME,
Key: { userId, conversationId },
UpdateExpression:
`SET ${listedAs} = :now, lastMessagePreview = :preview, lastMessageSenderId = :senderId` +
(unread ? ', unreadCount = if_not_exists(unreadCount, :zero) + :one' : ''),
ExpressionAttributeValues: {
':now': now,
':preview': preview,
':senderId': senderId,
...(unread ? { ':zero': 0, ':one': 1 } : {})
}
}
})
// Guards the state describeSendState saw: a request's one message can't
// be sent twice by concurrent requests, and a conversation's status can't
// have changed underneath.
const conversationUpdate = isRequest
? {
UpdateExpression:
'SET lastMessageAt = :now, lastMessagePreview = :preview, lastMessageSenderId = :senderId, requestSentAt = :now',
ConditionExpression: '#status = :pending AND attribute_not_exists(requestSentAt)',
ExpressionAttributeValues: { ':pending': 'pending' }
}
: {
UpdateExpression:
'SET lastMessageAt = :now, lastMessagePreview = :preview, lastMessageSenderId = :senderId',
ConditionExpression: 'attribute_not_exists(#status) OR #status = :accepted',
ExpressionAttributeValues: { ':accepted': 'accepted' }
}
try {
await docClient.send(
new TransactWriteCommand({
TransactItems: [
{
Put: {
TableName: process.env.MESSAGES_TABLE_NAME,
Item: message
}
},
{
Update: {
TableName: process.env.CONVERSATIONS_TABLE_NAME,
Key: { id: conversationId },
UpdateExpression: conversationUpdate.UpdateExpression,
ConditionExpression: conversationUpdate.ConditionExpression,
ExpressionAttributeNames: { '#status': 'status' },
ExpressionAttributeValues: {
':now': now,
':preview': preview,
':senderId': senderId,
...conversationUpdate.ExpressionAttributeValues
}
}
},
buildParticipantSummaryUpdate(senderId),
buildParticipantSummaryUpdate(recipientId, {
listedAs: isRequest ? 'requestedAt' : 'lastMessageAt',
unread: true
})
]
})
)
} catch (error) {
Iif (error.name !== 'TransactionCanceledException') throw error
return {
statusCode: 409,
headers: CORS_HEADERS,
body: JSON.stringify({ error: 'This conversation changed, reload it and try again' })
}
}
try {
await pushToUserConnections(recipientId, {
type: 'message',
conversationId,
message: { id, conversationId, senderId, body: messageBody, createdAt: now }
})
} catch (pushError) {
console.error('[messages/create] WebSocket push failed:', pushError.message)
}
return {
statusCode: 201,
headers: CORS_HEADERS,
body: JSON.stringify({
id,
conversationId,
senderId,
body: messageBody,
createdAt: now
})
}
} catch (error) {
console.error('[messages/create] Exception:', error.message, error.stack)
return {
statusCode: 500,
headers: CORS_HEADERS,
body: JSON.stringify({ error: 'Failed to send message' })
}
}
}
|