fix(gitgram): fix broken messaging (Account/User id mismatch) + chat IDOR + SEO gap

Audited gitgram-ai end to end by actually running the backend against a
live Postgres instance (not just reading/trusting the existing Jest
suite, which mocks Prisma and therefore never hits real FK constraints
or real route wiring).

Critical, feature-breaking bug: Message.senderId/receiverId and
MessageReaction.userId are foreign keys into Account, but every
messaging controller function wrote/read req.userId (a User id) into
those columns directly. Verified live: every message send (1:1 DM and
group chat) failed with a Prisma foreign-key-constraint violation, and
group messages additionally violated the (until now) required
non-null receiverId column since group messages have no single
receiver. Messaging has never worked through this code path. Fixed by
resolving the caller's Account id once per request (matching the
`prisma.account.findFirst({ where: { userId } })` pattern already used
elsewhere in the codebase, e.g. followRequestController) and using it
consistently for every Message/MessageReaction read, write, and
ownership check, while keeping ChatMember/UserBlock/socket rooms on the
real User id they were already consistent with. Added a Prisma
migration making Message.receiverId nullable for group-only messages.
Verified against a live Postgres test database: registered 3 users,
created a group chat, sent and read 1:1 and group messages, reacted,
and marked conversations read -- all succeed now.

Cross-tenant IDOR (same bug class found on Scribase today): GET
/api/v1/messages/chats/:chatId had no membership check at all -- any
authenticated user could read any group chat's messages by chatId
alone (every sibling function in the same file -- getMessage,
reportMessage, assertMessageAccess -- already enforced membership, this
one endpoint was the outlier). Also hardened sendMessage so posting
into a chatId you don't belong to is rejected. Verified live: a
non-member now gets 403 on both reads and writes to a chat they're not
in; an actual member still gets 200.

Unrelated build blocker found while standing up the backend to test
this: gitgram/backend/tsconfig.json set `ignoreDeprecations: "6.0"`,
which the pinned typescript@^5.9.3 doesn't recognize -- `tsc`/`ts-node`
hard-error with TS5103 before compiling a single file. Backend could
not build or boot in dev mode at all. Fixed to "5.0".

SEO gap: gitgram/web (Next.js 14 app dir) had no robots.txt and no
sitemap anywhere, static or dynamic -- zero crawl directives, no
sitemap reference for search engines. Added app/robots.ts (disallows
authenticated-only surfaces, allows public ones) and app/sitemap.ts
(static public marketing/discovery routes).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
caelum0x 2026-10-24 22:20:32 +03:00
parent 8a9dd77a78
commit 487e43129f
6 changed files with 259 additions and 59 deletions

View File

@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "Message" ALTER COLUMN "receiverId" DROP NOT NULL;

View File

@ -571,7 +571,9 @@ model Follow {
model Message {
id String @id @default(cuid())
senderId String
receiverId String
// Nullable: group-chat messages (chatId set) have no single receiver. Only
// 1:1 direct messages populate this.
receiverId String?
chatId String?
content String @db.Text
mediaUrl String?
@ -582,9 +584,9 @@ model Message {
deletedForSender Boolean @default(false)
createdAt DateTime @default(now())
sender Account @relation("MessageSender", fields: [senderId], references: [id], onDelete: Cascade)
receiver Account @relation("MessageReceiver", fields: [receiverId], references: [id], onDelete: Cascade)
chat Chat? @relation(fields: [chatId], references: [id], onDelete: Cascade)
sender Account @relation("MessageSender", fields: [senderId], references: [id], onDelete: Cascade)
receiver Account? @relation("MessageReceiver", fields: [receiverId], references: [id], onDelete: Cascade)
chat Chat? @relation(fields: [chatId], references: [id], onDelete: Cascade)
reactions MessageReaction[]

View File

@ -6,6 +6,34 @@ import { blockService } from '../services/blockService';
import logger from '../utils/logger';
import { asyncHandler, Errors, ApiError } from '../middleware/errorHandler';
/**
* Message.senderId / Message.receiverId / MessageReaction.userId are foreign
* keys into Account, not User, even though every other identifier in this
* file (req.userId, ChatMember.userId, UserBlock, socket room names,
* isUserOnline) is a User id. Passing a raw User id into those columns
* violates the FK constraint -- sending a message or reacting to one failed
* outright for every caller until these helpers were introduced. Resolve the
* caller's (or another participant's) Account id once per request instead.
*/
async function getOwnAccountId(userId: string): Promise<string> {
const account = await prisma.account.findFirst({ where: { userId }, select: { id: true } });
if (!account) {
throw Errors.notFound('Account');
}
return account.id;
}
async function getAccountIdForUser(userId: string): Promise<string | null> {
const account = await prisma.account.findFirst({ where: { userId }, select: { id: true } });
return account?.id ?? null;
}
async function getUserIdForAccount(accountId: string | null | undefined): Promise<string | null> {
if (!accountId) return null;
const account = await prisma.account.findUnique({ where: { id: accountId }, select: { userId: true } });
return account?.userId ?? null;
}
export const sendMessage = asyncHandler(async (req: AuthRequest, res: Response) => {
const userId = req.userId!;
const { receiverId, content, mediaUrl, chatId } = req.body;
@ -18,14 +46,38 @@ export const sendMessage = asyncHandler(async (req: AuthRequest, res: Response)
}
}
// Cross-tenant guard: a group-chat message must come from an actual member
// of that chat, otherwise any authenticated user could inject messages into
// any chat by guessing/supplying its chatId.
if (chatId) {
const membership = await prisma.chatMember.findFirst({
where: { chatId, userId },
select: { id: true },
});
if (!membership) {
throw Errors.forbidden('Not authorized to send messages in this chat');
}
}
const senderAccountId = await getOwnAccountId(userId);
let receiverAccountId: string | null = null;
if (receiverId) {
receiverAccountId = await getAccountIdForUser(receiverId);
if (!receiverAccountId) {
throw Errors.notFound('Recipient');
}
} else if (!chatId) {
throw Errors.badRequest('Either receiverId or chatId is required');
}
// Check if recipient is online to set deliveredAt
const recipientOnline = isUserOnline(receiverId);
const now = new Date();
const message = await prisma.message.create({
data: {
senderId: userId,
receiverId,
senderId: senderAccountId,
receiverId: receiverAccountId,
chatId,
content,
mediaUrl,
@ -70,11 +122,17 @@ export const getMessages = asyncHandler(async (req: AuthRequest, res: Response)
throw Errors.forbidden('Cannot access messages with this user');
}
const ownAccountId = await getOwnAccountId(userId);
const otherAccountId = await getAccountIdForUser(otherUserId);
if (!otherAccountId) {
throw Errors.notFound('User');
}
const messages = await prisma.message.findMany({
where: {
OR: [
{ senderId: userId, receiverId: otherUserId },
{ senderId: otherUserId, receiverId: userId }
{ senderId: ownAccountId, receiverId: otherAccountId },
{ senderId: otherAccountId, receiverId: ownAccountId }
]
},
include: {
@ -93,7 +151,7 @@ export const getMessages = asyncHandler(async (req: AuthRequest, res: Response)
// Format messages with read receipt status and aggregated reactions
const formattedMessages = messages.map(msg => ({
...msg,
reactions: aggregateReactions(msg.reactions, userId),
reactions: aggregateReactions(msg.reactions, ownAccountId),
readAt: msg.readAt?.toISOString() || null,
deliveredAt: msg.deliveredAt?.toISOString() || null,
status: msg.read ? 'read' : (msg.deliveredAt ? 'delivered' : 'sent')
@ -104,15 +162,21 @@ export const getMessages = asyncHandler(async (req: AuthRequest, res: Response)
export const getConversations = asyncHandler(async (req: AuthRequest, res: Response) => {
const userId = req.userId!;
const ownAccountId = await getOwnAccountId(userId);
// Get blocked user IDs to filter out from conversations
const blockedIds = await blockService.getAllBlockedIds(userId);
// Get blocked user IDs to filter out from conversations, translated to the
// Account ids that Message.senderId/receiverId actually store.
const blockedUserIds = await blockService.getAllBlockedIds(userId);
const blockedAccounts = blockedUserIds.length
? await prisma.account.findMany({ where: { userId: { in: blockedUserIds } }, select: { id: true } })
: [];
const blockedAccountIds = new Set(blockedAccounts.map(a => a.id));
const messages = await prisma.message.findMany({
where: {
OR: [
{ senderId: userId },
{ receiverId: userId }
{ senderId: ownAccountId },
{ receiverId: ownAccountId }
]
},
distinct: ['senderId', 'receiverId'],
@ -132,15 +196,16 @@ export const getConversations = asyncHandler(async (req: AuthRequest, res: Respo
const conversationPartnerIds: string[] = [];
messages.forEach(msg => {
const otherId = msg.senderId === userId ? msg.receiverId : msg.senderId;
const otherId = msg.senderId === ownAccountId ? msg.receiverId : msg.senderId;
if (!otherId) return; // group-chat message with no single receiver
// Skip blocked users
if (blockedIds.includes(otherId)) {
if (blockedAccountIds.has(otherId)) {
return;
}
if (!conversations.has(otherId)) {
conversationPartnerIds.push(otherId);
conversations.set(otherId, {
user: msg.senderId === userId ? msg.receiver : msg.sender,
user: msg.senderId === ownAccountId ? msg.receiver : msg.sender,
lastMessage: {
...msg,
readAt: msg.readAt?.toISOString() || null,
@ -157,7 +222,7 @@ export const getConversations = asyncHandler(async (req: AuthRequest, res: Respo
by: ['senderId'],
where: {
senderId: { in: conversationPartnerIds },
receiverId: userId,
receiverId: ownAccountId,
read: false,
deletedForSender: false
},
@ -180,10 +245,16 @@ export const markAsRead = asyncHandler(async (req: AuthRequest, res: Response) =
const { otherUserId } = req.params;
const now = new Date();
const ownAccountId = await getOwnAccountId(userId);
const otherAccountId = await getAccountIdForUser(otherUserId);
if (!otherAccountId) {
throw Errors.notFound('User');
}
const result = await prisma.message.updateMany({
where: {
senderId: otherUserId,
receiverId: userId,
senderId: otherAccountId,
receiverId: ownAccountId,
read: false
},
data: {
@ -197,8 +268,8 @@ export const markAsRead = asyncHandler(async (req: AuthRequest, res: Response) =
// Get the message IDs that were marked as read
const readMessages = await prisma.message.findMany({
where: {
senderId: otherUserId,
receiverId: userId,
senderId: otherAccountId,
receiverId: ownAccountId,
readAt: now
},
select: { id: true }
@ -244,10 +315,23 @@ export const createGroupChat = asyncHandler(async (req: AuthRequest, res: Respon
});
export const getChatMessages = asyncHandler(async (req: AuthRequest, res: Response) => {
const userId = req.userId!;
const { chatId } = req.params;
const { page = 1, limit = 50 } = req.query;
const skip = (Number(page) - 1) * Number(limit);
// Cross-tenant guard: only members of this chat may read its messages.
// Without this check any authenticated user could read any group chat's
// messages by chatId alone.
const membership = await prisma.chatMember.findFirst({
where: { chatId, userId },
select: { id: true },
});
if (!membership) {
throw Errors.forbidden('Not authorized to view this chat');
}
const messages = await prisma.message.findMany({
where: { chatId },
include: {
@ -309,7 +393,8 @@ export const editMessage = asyncHandler(async (req: AuthRequest, res: Response)
throw Errors.notFound('Message');
}
if (message.senderId !== userId) {
const ownAccountId = await getOwnAccountId(userId);
if (message.senderId !== ownAccountId) {
throw Errors.forbidden('Not authorized to edit this message');
}
@ -335,9 +420,13 @@ export const editMessage = asyncHandler(async (req: AuthRequest, res: Response)
}
});
// Emit socket event for real-time update
// Emit socket event for real-time update. Socket rooms are keyed by User
// id, so the Account id on the message has to be translated back.
if (global.io && message.receiverId) {
global.io.to(`user:${message.receiverId}`).emit('message:edited', updatedMessage);
const receiverUserId = await getUserIdForAccount(message.receiverId);
if (receiverUserId) {
global.io.to(`user:${receiverUserId}`).emit('message:edited', updatedMessage);
}
}
if (global.io && message.chatId) {
global.io.to(`chat:${message.chatId}`).emit('message:edited', updatedMessage);
@ -363,7 +452,8 @@ export const deleteMessage = asyncHandler(async (req: AuthRequest, res: Response
throw Errors.notFound('Message');
}
if (message.senderId !== userId) {
const ownAccountId = await getOwnAccountId(userId);
if (message.senderId !== ownAccountId) {
throw Errors.forbidden('Not authorized to delete this message');
}
@ -378,7 +468,10 @@ export const deleteMessage = asyncHandler(async (req: AuthRequest, res: Response
// Emit socket event for real-time update
if (global.io && message.receiverId) {
global.io.to(`user:${message.receiverId}`).emit('message:deleted', { messageId, forEveryone: true });
const receiverUserId = await getUserIdForAccount(message.receiverId);
if (receiverUserId) {
global.io.to(`user:${receiverUserId}`).emit('message:deleted', { messageId, forEveryone: true });
}
}
if (global.io && message.chatId) {
global.io.to(`chat:${message.chatId}`).emit('message:deleted', { messageId, forEveryone: true });
@ -421,7 +514,8 @@ export const getMessage = asyncHandler(async (req: AuthRequest, res: Response) =
}
// Ensure user is participant
if (message.senderId !== userId && message.receiverId !== userId) {
const ownAccountId = await getOwnAccountId(userId);
if (message.senderId !== ownAccountId && message.receiverId !== ownAccountId) {
// Check if user is in the chat
if (message.chatId) {
const membership = await prisma.chatMember.findFirst({
@ -465,7 +559,8 @@ export const reportMessage = asyncHandler(async (req: AuthRequest, res: Response
}
// Verify user has access to this message
if (message.senderId !== userId && message.receiverId !== userId) {
const ownAccountId = await getOwnAccountId(userId);
if (message.senderId !== ownAccountId && message.receiverId !== ownAccountId) {
if (message.chatId) {
const membership = await prisma.chatMember.findFirst({
where: { chatId: message.chatId, userId }
@ -502,11 +597,17 @@ export const markConversationAsRead = asyncHandler(async (req: AuthRequest, res:
const now = new Date();
const ownAccountId = await getOwnAccountId(userId);
const partnerAccountId = await getAccountIdForUser(conversationPartnerId);
if (!partnerAccountId) {
throw Errors.notFound('User');
}
// Mark all unread messages from the other user as read
const result = await prisma.message.updateMany({
where: {
senderId: conversationPartnerId,
receiverId: userId,
senderId: partnerAccountId,
receiverId: ownAccountId,
read: false
},
data: {
@ -518,8 +619,8 @@ export const markConversationAsRead = asyncHandler(async (req: AuthRequest, res:
// Get the IDs of messages that were marked as read for WebSocket notification
const readMessages = await prisma.message.findMany({
where: {
senderId: conversationPartnerId,
receiverId: userId,
senderId: partnerAccountId,
receiverId: ownAccountId,
readAt: now
},
select: { id: true }
@ -561,7 +662,8 @@ export const markMessageAsRead = asyncHandler(async (req: AuthRequest, res: Resp
}
// Only the receiver can mark a message as read
if (message.receiverId !== userId) {
const ownAccountId = await getOwnAccountId(userId);
if (message.receiverId !== ownAccountId) {
throw Errors.forbidden('Not authorized to mark this message as read');
}
@ -593,11 +695,14 @@ export const markMessageAsRead = asyncHandler(async (req: AuthRequest, res: Resp
// Emit WebSocket event to notify sender that their message was read
if (global.io) {
global.io.to(`user:${message.senderId}`).emit('message:read', {
readBy: userId,
messageIds: [messageId],
readAt: now.toISOString()
});
const senderUserId = await getUserIdForAccount(message.senderId);
if (senderUserId) {
global.io.to(`user:${senderUserId}`).emit('message:read', {
readBy: userId,
messageIds: [messageId],
readAt: now.toISOString()
});
}
// Also emit to chat room if it's a group chat
if (message.chatId) {
@ -622,10 +727,11 @@ export const markMessageAsRead = asyncHandler(async (req: AuthRequest, res: Resp
*/
export const getUnreadCount = asyncHandler(async (req: AuthRequest, res: Response) => {
const userId = req.userId!;
const ownAccountId = await getOwnAccountId(userId);
const count = await prisma.message.count({
where: {
receiverId: userId,
receiverId: ownAccountId,
read: false,
deletedForSender: false
}
@ -646,10 +752,11 @@ const MAX_REACTIONS_PER_USER = 5;
* to (DM sender/receiver or a member of the group chat). Throws otherwise.
*/
async function assertMessageAccess(
message: { senderId: string; receiverId: string; chatId: string | null },
message: { senderId: string; receiverId: string | null; chatId: string | null },
userId: string,
ownAccountId: string,
): Promise<void> {
if (message.senderId === userId || message.receiverId === userId) {
if (message.senderId === ownAccountId || message.receiverId === ownAccountId) {
return;
}
if (message.chatId) {
@ -706,17 +813,19 @@ export const addReaction = asyncHandler(async (req: AuthRequest, res: Response)
throw Errors.notFound('Message');
}
await assertMessageAccess(message, userId);
const ownAccountId = await getOwnAccountId(userId);
await assertMessageAccess(message, userId, ownAccountId);
// Enforce the per-user reaction cap, but allow re-adding an emoji the user
// already has (idempotent) so the cap can't lock a user out of a no-op.
// MessageReaction.userId is an Account id FK, like Message.senderId/receiverId.
const existing = await prisma.messageReaction.findUnique({
where: { messageId_userId_emoji: { messageId, userId, emoji } },
where: { messageId_userId_emoji: { messageId, userId: ownAccountId, emoji } },
});
if (!existing) {
const distinctCount = await prisma.messageReaction.count({
where: { messageId, userId },
where: { messageId, userId: ownAccountId },
});
if (distinctCount >= MAX_REACTIONS_PER_USER) {
throw Errors.badRequest(
@ -724,7 +833,7 @@ export const addReaction = asyncHandler(async (req: AuthRequest, res: Response)
);
}
await prisma.messageReaction.create({
data: { messageId, userId, emoji },
data: { messageId, userId: ownAccountId, emoji },
});
}
@ -732,15 +841,22 @@ export const addReaction = asyncHandler(async (req: AuthRequest, res: Response)
where: { messageId },
select: { emoji: true, userId: true },
});
const aggregated = aggregateReactions(reactions, userId);
const aggregated = aggregateReactions(reactions, ownAccountId);
// Notify the other participant(s) so reactions appear in real time.
// Notify the other participant(s) so reactions appear in real time. Socket
// rooms are keyed by User id, so translate the Account ids back.
if (global.io) {
const payload = { messageId, userId, emoji, reactions: aggregated };
if (message.receiverId) {
global.io.to(`user:${message.receiverId}`).emit('message:reaction', payload);
const [receiverUserId, senderUserId] = await Promise.all([
getUserIdForAccount(message.receiverId),
getUserIdForAccount(message.senderId),
]);
if (receiverUserId) {
global.io.to(`user:${receiverUserId}`).emit('message:reaction', payload);
}
if (senderUserId) {
global.io.to(`user:${senderUserId}`).emit('message:reaction', payload);
}
global.io.to(`user:${message.senderId}`).emit('message:reaction', payload);
if (message.chatId) {
global.io.to(`chat:${message.chatId}`).emit('message:reaction', payload);
}
@ -768,24 +884,31 @@ export const removeReaction = asyncHandler(async (req: AuthRequest, res: Respons
throw Errors.notFound('Message');
}
await assertMessageAccess(message, userId);
const ownAccountId = await getOwnAccountId(userId);
await assertMessageAccess(message, userId, ownAccountId);
await prisma.messageReaction.deleteMany({
where: { messageId, userId, emoji },
where: { messageId, userId: ownAccountId, emoji },
});
const reactions = await prisma.messageReaction.findMany({
where: { messageId },
select: { emoji: true, userId: true },
});
const aggregated = aggregateReactions(reactions, userId);
const aggregated = aggregateReactions(reactions, ownAccountId);
if (global.io) {
const payload = { messageId, userId, emoji, removed: true, reactions: aggregated };
if (message.receiverId) {
global.io.to(`user:${message.receiverId}`).emit('message:reaction', payload);
const [receiverUserId, senderUserId] = await Promise.all([
getUserIdForAccount(message.receiverId),
getUserIdForAccount(message.senderId),
]);
if (receiverUserId) {
global.io.to(`user:${receiverUserId}`).emit('message:reaction', payload);
}
if (senderUserId) {
global.io.to(`user:${senderUserId}`).emit('message:reaction', payload);
}
global.io.to(`user:${message.senderId}`).emit('message:reaction', payload);
if (message.chatId) {
global.io.to(`chat:${message.chatId}`).emit('message:reaction', payload);
}
@ -812,14 +935,15 @@ export const searchMessages = asyncHandler(async (req: AuthRequest, res: Respons
}
const searchTerm = query.trim();
const ownAccountId = await getOwnAccountId(userId);
// Fetch matching messages where the current user is a participant
const messages = await prisma.message.findMany({
where: {
content: { contains: searchTerm, mode: 'insensitive' },
OR: [
{ senderId: userId },
{ receiverId: userId },
{ senderId: ownAccountId },
{ receiverId: ownAccountId },
{
chatId: {
in: (

View File

@ -15,7 +15,11 @@
// TS7.0 turns the legacy "node" (node10) resolver into a hard error. We keep
// node10 semantics intentionally (CommonJS output) and silence the pre-7.0
// deprecation so `tsc --noEmit` stays green until a deliberate resolver bump.
"ignoreDeprecations": "6.0",
// "6.0" is not a value the pinned typescript@^5.9.3 (see package.json)
// recognizes -- it hard-errors with TS5103 and the project fails to build
// or even boot via ts-node at all. "5.0" is the value this TS major
// actually accepts for this flag.
"ignoreDeprecations": "5.0",
"typeRoots": ["./node_modules/@types"],
"declaration": true,
"declarationMap": true,

38
gitgram/web/app/robots.ts Normal file
View File

@ -0,0 +1,38 @@
import type { MetadataRoute } from 'next'
const SITE_URL = process.env.NEXT_PUBLIC_SITE_URL || 'https://gitgram.app'
// There was no robots.txt (static or dynamic) anywhere in the app, so search
// engines had no explicit crawl directives and no sitemap reference for this
// site. Authenticated/private surfaces (messages, settings, admin, etc.) are
// disallowed; public profile/repo/discovery pages remain crawlable.
export default function robots(): MetadataRoute.Robots {
return {
rules: {
userAgent: '*',
allow: '/',
disallow: [
'/api/',
'/admin',
'/settings',
'/messages',
'/notifications',
'/account',
'/create',
'/create-change-story',
'/create-story',
'/drafts',
'/edit',
'/backup',
'/compose',
'/camera',
'/chat',
'/follow-requests',
'/creator-studio',
'/api-test',
],
},
sitemap: `${SITE_URL}/sitemap.xml`,
host: SITE_URL,
}
}

View File

@ -0,0 +1,30 @@
import type { MetadataRoute } from 'next'
const SITE_URL = process.env.NEXT_PUBLIC_SITE_URL || 'https://gitgram.app'
// Static, always-public marketing/discovery routes. User/repo profile pages
// are dynamic ([username], [owner]/[repo]) and intentionally left out here
// rather than querying the database at build time from this file; add a
// dedicated sitemap route (e.g. app/sitemap/[id]/route.ts with
// generateSitemaps) if those need to be indexed individually.
const STATIC_ROUTES = [
'',
'/explore',
'/discover',
'/trending',
'/search',
'/pricing',
'/about',
'/terms',
'/privacy-policy',
]
export default function sitemap(): MetadataRoute.Sitemap {
const now = new Date()
return STATIC_ROUTES.map((path) => ({
url: `${SITE_URL}${path}`,
lastModified: now,
changeFrequency: path === '' ? 'daily' : 'weekly',
priority: path === '' ? 1 : 0.7,
}))
}