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 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 | 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 71x 9x 4x 4x 4x 4x 5x 5x 62x 46x 46x 39x 78x 39x 39x 37x 37x 10x 10x 10x 10x 10x 10x 47x 11x 3x 3x 3x 3x 3x 1x 2x 48x 12x 11x 8x 7x 7x 5x 44x 44x 61x 44x 61x 44x 37x 37x 21x 37x 37x 21x 37x 48x 48x 48x 48x 5x 5x 5x 7x 44x 44x 1x 10x 10x 10x 13x 11x 7x 10x 3x 3x 3x 3x 3x 3x 3x 3x 10x 11x 11x 11x 11x 3x 3x 3x 3x 8x 11x 11x 11x 11x 14x 14x 11x 3x 3x 3x 11x 11x 11x 10x 16x 16x 16x 16x 1x 15x 15x 1x 14x 14x 13x 13x 13x 13x 6x 6x 7x 7x 7x 1x 6x 6x 6x 6x 6x 10x 24x 24x 23x 22x 22x 22x 2x 20x 14x 14x 14x 14x 1x 1x 10x 66x 66x 66x 66x 65x 65x 65x 65x 65x 65x 65x 65x 2x 63x 63x 63x 63x 60x 59x 63x 61x 60x 60x 59x 59x 2x 57x 131x 57x 8x 8x 8x 8x 8x 8x 51x 105x 44x 44x 44x 44x 44x 44x 44x 44x 61x 44x 44x 61x 1x 61x 44x 44x 44x 2x 2x 10x | /**
* Conversation routes - private messaging.
*
* GET /api/conversations/:id/messages -> Get conversation messages
* POST /api/conversations/:id/messages -> Send message (with FCM push + RTDB broadcast)
*/
const router = require('express').Router();
const { db, rtdb, FieldValue } = require('../utils/firebase');
const { generateId, now } = require('../utils/helpers');
const { sendPushToUser } = require('../utils/fcm');
const { requireSameCohort } = require('../middleware/sameCohort');
const { cohortFromClaim, effectiveCohort } = require('../utils/firebase-claims');
const { isLiveAdmin, checkSuspension } = require('../middleware/auth');
const { auditAdminFlagBypass } = require('../utils/segregation-audit');
const { isAgeGatingEnabled } = require('../safety/age-gating-flag');
const { checkFeatureAccess } = require('../safety/enforce');
const log = require('../utils/log');
const { openStream } = require('../utils/sse');
/**
* UK OSA #17 PR 4 + PR 8 — combined gate for conversation reads.
*
* Two gate paths, in order:
*
* 1. (PR 8) `crossCohortAtMigration: true` → 404 regardless of
* current cohorts. Set by the migration script on 1:1 cross-
* cohort threads. The flag is the load-bearing rules-side hide
* (firestore.rules denies reads on the parent + every
* subcollection when set, per PR 3); Express mirrors the 404
* as defence in depth. Admin callers are exempt (live-admin
* re-check, same pattern as `requireSameCohort`) — moderators
* need cross-cohort visibility for forensics. No audit row is
* written here: the migration already wrote one per migrated
* thread, and a per-request audit on a known-blocked thread
* would be noise.
*
* 2. (PR 4) Runtime cohort gate — 1:1 only. Looks up the OTHER
* participant's current cohort and 404s if it mismatches the
* caller's. Group conversations skip both gates (the freeze
* semantics for groups are participant-list only — existing
* members keep read+write per design doc § "Migration").
*/
async function gateCrossCohortConversation(req, res, conv) {
if (conv?.crossCohortAtMigration === true) {
// Admin re-check matches requireSameCohort's pattern (60s
// adminClaimCache, demoted-admin defence). Honoured here so a
// mod can read a hidden thread for an appeal without bypassing
// the rest of the gate machinery.
if (req?.auth?.token?.admin === true) {
const liveAdmin = req?.auth?.uid ? await isLiveAdmin(req.auth.uid) : false;
Eif (liveAdmin) {
auditAdminFlagBypass(req, String(req?.params?.id ?? ''));
return false;
}
}
res.status(404).json({ error: 'Not found' });
return true;
}
if (conv?.isGroup) return false;
const participantIds = (conv?.participantIds || []).map(String);
if (participantIds.length !== 2) return false;
const callerId = String(req.auth.uniqueId);
const otherId = participantIds.find((p) => p !== callerId);
Iif (!otherId) return false;
return requireSameCohort(req, res, otherId, async () => {
const snap = await db.doc(`users/${otherId}`).get();
return snap.exists ? snap.data() : null;
});
}
const DEFAULT_MESSAGE_LIMIT = 50;
const MAX_MESSAGE_LIMIT = 200;
const MAX_TEXT_LENGTH = 2000;
const MAX_IMAGES_PER_MESSAGE = 10;
const MAX_SENDER_NAME_LENGTH = 50;
const VALID_MESSAGE_TYPES = ['TEXT', 'IMAGE', 'STICKER', 'ROOM_INVITE', 'MOD_ACTION'];
/**
* Build a plain message object from a Firestore message doc.
*/
function buildMessage(doc) {
return {
id: doc.id,
messageId: doc.id,
senderId: doc.senderId || '',
senderName: doc.senderName || '',
text: doc.text || '',
imageUrls: doc.imageUrls || [],
type: doc.type || 'TEXT',
createdAt: doc.createdAt || 0,
editedAt: doc.editedAt || null,
editCount: doc.editCount || 0,
replyToMessageId: doc.replyToId || doc.replyToMessageId || null,
replyToText: doc.replyToText || null,
replyToSenderName: doc.replyToSenderName || null,
stickerUrl: doc.stickerUrl || null,
roomInviteId: doc.roomInviteId || null,
roomInviteName: doc.roomInviteName || null,
reactions: doc.reactions || {},
isRecalled: !!doc.isRecalled,
isHidden: !!doc.isHidden,
hiddenBy: doc.hiddenBy || null,
};
}
/** Check if the current time falls within a user's DND schedule. */
function isInDndPeriod(user) {
if (!user.dndEnabled) return false;
const utcNow = new Date();
const currentMinutes = utcNow.getUTCHours() * 60 + utcNow.getUTCMinutes();
const dndStart = (user.dndStartHour || 0) * 60 + (user.dndStartMinute || 0);
const dndEnd = (user.dndEndHour || 0) * 60 + (user.dndEndMinute || 0);
if (dndStart <= dndEnd) {
return currentMinutes >= dndStart && currentMinutes < dndEnd;
}
return currentMinutes >= dndStart || currentMinutes < dndEnd;
}
/** Determine if a recipient should receive a notification. */
function shouldNotifyRecipient(user, settings) {
if (!user) return false;
if (user.pmNotificationsEnabled === false) return false;
if (isInDndPeriod(user)) return false;
if (settings?.isMuted) return false;
// SHY-0496: a migrated device appears ONLY in fcmInstallationIds. Checking
// fcmTokens alone made this return false for every upgraded user, so their
// DM notifications stopped -- silently, because "should not notify" is
// indistinguishable from "notified successfully" downstream.
const reachable = (user.fcmTokens?.length ?? 0) > 0 || (user.fcmInstallationIds?.length ?? 0) > 0;
if (!reachable) return false;
return true;
}
/**
* Send FCM push notifications to conversation participants (except sender).
* Uses batch Firestore reads to minimize read cost.
*/
async function sendMessageNotifications(
conversationId,
senderId,
senderName,
previewText,
type,
recipients,
isGroup,
groupName,
) {
try {
Iif (recipients.length === 0) return;
const userRefs = recipients.map((p) => db.doc(`users/${p.userId}`));
const settingsRefs = recipients.map((p) =>
db.doc(`conversations/${conversationId}/userSettings/${p.userId}`),
);
const [userSnaps, settingsSnaps] = await Promise.all([
db.getAll(...userRefs),
db.getAll(...settingsRefs),
]);
const usersById = {};
for (const snap of userSnaps) {
if (snap.exists) usersById[snap.id] = snap.data();
}
const settingsById = {};
for (const snap of settingsSnaps) {
if (snap.exists) settingsById[snap.id] = snap.data();
}
for (const p of recipients) {
const recipientId = p.userId;
const user = usersById[recipientId];
const settings = settingsById[recipientId];
if (!shouldNotifyRecipient(user, settings)) continue;
const showPreview = user.pmNotificationPreview !== false;
const data = {
type: 'PM',
senderId,
senderName: isGroup ? `${senderName} (${groupName || 'Group'})` : senderName,
messageText: showPreview ? previewText : 'New message',
conversationId,
isGroup: String(isGroup),
showPreview: String(showPreview),
};
await sendPushToUser(recipientId, data, {
userData: user,
senderUniqueId: senderId,
recipientUniqueId: recipientId,
});
}
} catch (err) {
log.error('conversations', 'Failed to send message notifications', {
conversationId,
error: err.message,
});
}
}
/** Broadcast a conversation event via RTDB. */
async function broadcastToConversation(conversationId, data) {
try {
await rtdb.ref(`conversations/${conversationId}/events/lastEvent`).set({
type: data.type,
ts: Date.now(),
});
} catch (err) {
log.error('conversations', 'Failed to write RTDB event', {
conversationId,
error: err.message,
});
}
}
// -- Get messages --
// -- The conversation READ path (SHY-0458) --
//
// These exist because the client used to read conversations straight from
// Firestore, and could not. `firestore.rules:355` dereferences
// `resource.data.participantIds`, so reading a conversation that does not exist
// YET is a rules EVALUATION ERROR rather than a miss:
//
// GET /conversations/50000010_50000020 -> 403
// "evaluation error at L355:21 for 'get' @ L355, Null value error."
//
// `getOrCreateConversation` opens with exactly that read, so no conversation
// could ever be created and every first message was silently dropped. Deciding
// this server-side also puts it where every other authorization decision in
// this app already lives (EPIC-0006).
const DEFAULT_CONVERSATION_LIMIT = 50;
const MAX_CONVERSATION_LIMIT = 200;
/**
* Orders two id strings deterministically, by code unit.
*
* Sonar's S2871 asks for an explicit comparator on `.sort()` and suggests
* `localeCompare`. Taking that suggestion here would be a defect: these sorts
* decide a conversation's IDENTITY, and iOS, Android and the server must all
* compute the same one. `localeCompare` is locale-dependent, so the same pair
* of people could resolve to different threads on two devices. Code-unit order
* is what the clients already use, and it is the same everywhere.
*/
const byCodeUnit = (a, b) => {
if (a < b) return -1;
return a > b ? 1 : 0;
};
/** The id the clients already generate: both ids sorted, joined with "_". */
function conversationIdFor(a, b) {
return [String(a), String(b)].sort(byCodeUnit).join('_');
}
// -- List the caller's conversations --
router.get('/conversations', async (req, res) => {
try {
// participantIds are stored as STRINGS; req.auth.uniqueId is a NUMBER.
// Same coercion the message routes already document.
const callerId = String(req.auth.uniqueId);
const limit = Math.min(
Number.parseInt(req.query.limit, 10) || DEFAULT_CONVERSATION_LIMIT,
MAX_CONVERSATION_LIMIT,
);
const snap = await db
.collection('conversations')
.where('participantIds', 'array-contains', callerId)
.orderBy('lastMessageAt', 'desc')
.limit(limit)
.get();
// Filtered HERE rather than with a `where` on the flag: a query filter also
// drops documents that simply lack the field, which is every conversation
// written before the migration backfill. UK OSA #17 — threads frozen at
// migration stay hidden either way.
const conversations = snap.docs
.map((d) => ({ ...d.data(), id: d.id }))
.filter((c) => c.crossCohortAtMigration !== true);
return res.json(conversations);
} catch (err) {
log.error('conversations', 'Failed to list conversations', {
callerId: req.auth?.uniqueId,
error: err.message,
});
return res.status(500).json({ error: 'Internal server error' });
}
});
// -- Live conversation list over SSE (SHY-0169) --
//
// The replacement for the client's own Firestore listener. The server holds the
// listener with the Admin SDK and fans out; the client subscribes to an
// ordinary authed route, so who may see what is decided here rather than by
// rules evaluated on a phone (EPIC-0006).
//
// Authorization is re-checked PER FAN-OUT, not only at subscribe. A stream is a
// single request, so `authMiddleware` runs its suspension check once and then
// never again for the life of a connection that may last hours — without the
// re-check, suspending somebody would not stop their messages arriving.
router.get('/conversations/stream', async (req, res) => {
const callerId = String(req.auth.uniqueId);
const stream = openStream(req, res);
const deliver = async (conversations) => {
// Re-checked every time. `checkSuspension` is the same function the auth
// middleware uses, cache and all.
if (await checkSuspension(callerId)) {
log.info('conversations', 'Closing stream for suspended caller', { callerId });
stream.send('closed', { reason: 'suspended' });
stream.close();
return;
}
stream.send('conversations', conversations);
};
try {
const query = db
.collection('conversations')
.where('participantIds', 'array-contains', callerId)
.orderBy('lastMessageAt', 'desc')
.limit(DEFAULT_CONVERSATION_LIMIT);
const unsubscribe = query.onSnapshot(
(snap) => {
const conversations = snap.docs
.map((d) => ({ ...d.data(), id: d.id }))
.filter((c) => c.crossCohortAtMigration !== true);
// Deliberately not awaited: onSnapshot is a sync callback, and an
// unhandled rejection here would take the process down.
deliver(conversations).catch((err) =>
log.error('conversations', 'Stream delivery failed', {
callerId,
error: err.message,
}),
);
},
(err) => {
log.error('conversations', 'Stream listener failed', { callerId, error: err.message });
stream.send('error', { error: 'stream failed' });
stream.close();
},
);
// The expensive half. Released when the phone goes away, or it lives for
// the life of the process.
stream.onClose(() => {
try {
unsubscribe();
} catch (err) {
log.error('conversations', 'Failed to detach stream listener', { error: err.message });
}
});
} catch (err) {
log.error('conversations', 'Failed to open conversation stream', {
callerId,
error: err.message,
});
stream.send('error', { error: 'stream failed' });
stream.close();
}
});
// -- Get or create the 1:1 conversation with another person --
router.post('/conversations', async (req, res) => {
try {
const callerId = String(req.auth.uniqueId);
const raw = req.body?.otherUserId;
if (raw === undefined || raw === null || String(raw).trim() === '') {
return res.status(400).json({ error: 'otherUserId required' });
}
const otherId = String(raw).trim();
if (otherId === callerId) {
return res.status(400).json({ error: 'Cannot start a conversation with yourself' });
}
const otherSnap = await db.doc(`users/${otherId}`).get();
if (!otherSnap.exists) return res.status(404).json({ error: 'User not found' });
const other = otherSnap.data() || {};
// Cohort gate, server-side. 404 rather than 403 so a refusal does not
// confirm that the account exists — the same posture the read gate takes.
//
// SHY-0468: this read `req.auth.cohort`, which `authMiddleware` never
// sets — the claim lives at `req.auth.token.cohort`. `callerCohort` was
// therefore always undefined, the `&&` short-circuited, and the gate
// passed EVERY caller: an adult could open a thread with a minor. The
// second half was the same shape of hole, one step along — a target whose
// `cohort` field was missing also skipped the check.
//
// Both sides now use the resolvers the rest of the codebase already uses
// (`sameCohort.js`, `config.js`, `livekit.js`). Each falls back to
// 'minor' rather than to "unknown", so a stripped claim or an absent
// field restricts the caller instead of freeing them, and
// `effectiveCohort` honours an admin `cohortOverride` the raw field
// ignores.
const callerCohort = cohortFromClaim(req);
const otherCohort = effectiveCohort(other);
if (otherCohort !== callerCohort) {
log.info('conversations', 'Refused cross-cohort conversation', {
callerId,
otherId,
callerCohort,
otherCohort,
});
return res.status(404).json({ error: 'User not found' });
}
const conversationId = conversationIdFor(callerId, otherId);
const existing = await db.doc(`conversations/${conversationId}`).get();
if (existing.exists) {
return res.json({ ...existing.data(), id: conversationId });
}
const timestamp = now();
const doc = {
participantIds: [callerId, otherId].sort(byCodeUnit),
isGroup: false,
crossCohortAtMigration: false,
createdAt: timestamp,
lastMessageAt: timestamp,
};
await db.doc(`conversations/${conversationId}`).set(doc);
log.info('conversations', 'Created conversation', { conversationId, callerId, otherId });
return res.json({ ...doc, id: conversationId });
} catch (err) {
log.error('conversations', 'Failed to get or create conversation', {
callerId: req.auth?.uniqueId,
error: err.message,
});
return res.status(500).json({ error: 'Internal server error' });
}
});
router.get('/conversations/:id/messages', async (req, res) => {
try {
// Verify the requester is a participant
const convSnap = await db.doc(`conversations/${req.params.id}`).get();
if (!convSnap.exists) return res.status(404).json({ error: 'Conversation not found' });
const conv = convSnap.data();
const participantIds = conv.participantIds || [];
if (!participantIds.map(String).includes(String(req.auth.uniqueId))) {
return res.status(403).json({ error: 'Not a participant of this conversation' });
}
if (await gateCrossCohortConversation(req, res, conv)) return;
const limit = Math.min(
Number.parseInt(req.query.limit, 10) || DEFAULT_MESSAGE_LIMIT,
MAX_MESSAGE_LIMIT,
);
const snap = await db
.collection(`conversations/${req.params.id}/messages`)
.orderBy('createdAt', 'desc')
.limit(limit)
.get();
// Spread the payload BEFORE writing the trusted doc-ref id, so that a
// same-named `id` field in the stored message data (whether from a
// future schema migration or an adversarial Firestore write) cannot
// override the doc's true identity in the response. buildMessage
// below reads `doc.id`, so a payload-supplied id would otherwise
// propagate all the way to the JSON sent to the client.
const messages = snap.docs.map((d) => ({ ...d.data(), id: d.id }));
// Return in chronological order (oldest first)
return res.json(messages.toReversed().map(buildMessage));
} catch (err) {
log.error('conversations', 'Failed to fetch messages', {
conversationId: req.params.id,
error: err.message,
});
return res.status(500).json({ error: 'Internal server error' });
}
});
// -- Send message --
router.post('/conversations/:id/messages', async (req, res) => {
try {
const uniqueId = req.auth.uniqueId;
const body = req.body;
if (!body) return res.status(400).json({ error: 'Invalid body' });
const conversationId = req.params.id;
const messageId = generateId();
const timestamp = now();
const type = body.type || 'TEXT';
const senderId = uniqueId;
const senderName = (body.senderName || '').slice(0, MAX_SENDER_NAME_LENGTH);
const text = (body.text || '').slice(0, MAX_TEXT_LENGTH);
// Validate message type
if (!VALID_MESSAGE_TYPES.includes(type)) {
return res.status(400).json({ error: 'Invalid message type' });
}
// Validate imageUrls count
const imageUrls = Array.isArray(body.imageUrls)
? body.imageUrls.slice(0, MAX_IMAGES_PER_MESSAGE)
: [];
log.info('conversations', 'Sending message', { conversationId, senderId, type });
// Build preview text for lastMessage
let previewText = text;
if (type === 'IMAGE') previewText = '[Image]';
else if (type === 'STICKER') previewText = '[Sticker]';
else if (type === 'ROOM_INVITE') previewText = '[Room Invite]';
// Read conversation to get participant list and group info
const convSnap = await db.doc(`conversations/${conversationId}`).get();
if (!convSnap.exists) return res.status(404).json({ error: 'Conversation not found' });
const convDoc = convSnap.data();
if (!convDoc) return res.status(500).json({ error: 'Corrupted conversation data' });
const participantIds = convDoc.participantIds || [];
// participantIds are stored as STRINGS (the app writes them, firestore.rules
// enforces `string(callerUniqueId()) in participantIds`) but senderId
// (req.auth.uniqueId) is a NUMBER — coerce both, as the GET route above
// (line ~222) already does, so this check isn't type-fooled into a 403.
if (!participantIds.map(String).includes(String(senderId))) {
return res.status(403).json({ error: 'Not a participant of this conversation' });
}
// SHY-0060 — per-feature age gate on 1:1 DMs (inert unless the operator
// flag is ON). A DM with a mutually-followed user is 13+ (bidirectional
// consent); a DM with anyone else is 18+ (the stranger predator-vector).
// Group conversations are moderated multi-user spaces — out of scope. The
// flag is checked first so the sender doc is loaded only when gating is on.
// IDs cross a String/Number boundary here: participantIds are stored as
// STRINGS (firestore.rules + the app), senderId (req.auth.uniqueId) is a
// NUMBER, and followingIds/followerIds are NUMBERS (the follow route
// writes parseInt'd ids). Coerce everything to String for comparison —
// the same pattern this file's GET route + gateCrossCohortConversation use.
const senderIdStr = String(senderId);
const dmRecipientIds = participantIds.map(String).filter((pid) => pid !== senderIdStr);
if (!convDoc.isGroup && dmRecipientIds.length === 1 && (await isAgeGatingEnabled(db))) {
const senderData = (await db.doc(`users/${senderId}`).get()).data() || {};
const recipientId = dmRecipientIds[0]; // String
const mutualFollow =
Array.isArray(senderData.followingIds) &&
Array.isArray(senderData.followerIds) &&
senderData.followingIds.map(String).includes(recipientId) &&
senderData.followerIds.map(String).includes(recipientId);
const dmFeature = mutualFollow
? 'DIRECT_MESSAGE_WITH_FOLLOWED_USER'
: 'DIRECT_MESSAGE_WITH_STRANGER';
const dmBlock = await checkFeatureAccess(db, dmFeature, senderData);
if (dmBlock) return res.status(dmBlock.status).json(dmBlock.body);
}
if (await gateCrossCohortConversation(req, res, convDoc)) return;
// Same String/Number coercion as the participant check above — without it a
// String-typed participantIds array never filters out the Number senderId,
// so the sender would be counted as their own recipient (self-unread +
// self-notify). Recipient ids feed userSettings doc paths (coercion-safe).
const recipientIds = participantIds.map(String).filter((pid) => pid !== String(senderId));
const isGroup = !!convDoc.isGroup;
const groupName = convDoc.groupName || null;
const msgData = {
senderId,
senderName,
text,
type,
imageUrls,
stickerUrl: body.stickerUrl || null,
roomInviteId: body.roomInviteId || null,
roomInviteName: body.roomInviteName || null,
replyToId: body.replyToMessageId || null,
replyToText: body.replyToText || null,
replyToSenderName: body.replyToSenderName || null,
reactions: {},
isRecalled: false,
isHidden: false,
hiddenBy: null,
editCount: 0,
editedAt: null,
createdAt: timestamp,
};
// Batch: write message + update conversation lastMessage + increment unread counts
const lastMessage = { text: previewText, senderId, senderName, type, createdAt: timestamp };
const batch = db.batch();
batch.set(db.doc(`conversations/${conversationId}/messages/${messageId}`), msgData);
batch.set(
db.doc(`conversations/${conversationId}`),
{
lastMessage,
lastMessageAt: timestamp,
},
{ merge: true },
);
// Increment unread counts for all recipients (set+merge in case doc doesn't exist yet)
for (const pid of recipientIds) {
batch.set(
db.doc(`conversations/${conversationId}/userSettings/${pid}`),
{
unreadCount: FieldValue.increment(1),
},
{ merge: true },
);
}
await batch.commit();
// Un-hide conversation for all recipients (fire-and-forget)
Promise.all(
recipientIds.map((pid) =>
db
.doc(`conversations/${conversationId}/userSettings/${pid}`)
.set({ isHidden: false }, { merge: true }),
),
).catch((err) =>
log.error('conversations', 'Failed to un-hide for recipients', {
conversationId,
error: err.message,
}),
);
// FCM notifications + RTDB broadcast (fire-and-forget)
const recipients = recipientIds.map((id) => ({ userId: id }));
sendMessageNotifications(
conversationId,
senderId,
senderName,
previewText,
type,
recipients,
isGroup,
groupName,
).catch((err) =>
log.error('conversations', 'Failed to send notifications', {
conversationId,
error: err.message,
}),
);
broadcastToConversation(conversationId, { type: 'new_message' }).catch((err) =>
log.error('conversations', 'Failed to broadcast event', {
conversationId,
error: err.message,
}),
);
// Spread msgData BEFORE the trusted server-generated `id` so that
// an `id` field never wins from the spread side — defensive
// ordering for the day msgData gains an `id` field via a future
// schema migration. `replyToMessageId` is also written last so it
// overrides msgData.replyToMessageId if present (the explicit
// rewrite from `replyToId` is the canonical name).
return res.json(
buildMessage({ ...msgData, id: messageId, replyToMessageId: msgData.replyToId }),
);
} catch (err) {
log.error('conversations', 'Failed to send message', {
conversationId: req.params.id,
senderId: req.auth?.uniqueId,
error: err.message,
});
return res.status(500).json({ error: 'Internal server error' });
}
});
module.exports = router;
|