Skip to content

refactor: Improve type safety and resolve FIXME in sendMessage.ts#39564

Open
aniruddhaadak80 wants to merge 1 commit into
RocketChat:developfrom
aniruddhaadak80:refactor/send-message-type-safety
Open

refactor: Improve type safety and resolve FIXME in sendMessage.ts#39564
aniruddhaadak80 wants to merge 1 commit into
RocketChat:developfrom
aniruddhaadak80:refactor/send-message-type-safety

Conversation

@aniruddhaadak80
Copy link
Copy Markdown
Contributor

@aniruddhaadak80 aniruddhaadak80 commented Mar 12, 2026

Closes #39560

This PR addresses long-standing technical debt in the core 'sendMessage.ts' function:

  1. Resolves the 'FIXME' by removing the manual type cast on 'username' and providing a safe fallback.
  2. Replaces several 'any' types in 'sendMessage' and helper functions with stronger type definitions from '@rocket.chat/core-typings'.
  3. Improves overall maintainability and reduces the risk of runtime errors in the message-sending pipeline.

Summary by CodeRabbit

  • Bug Fixes
    • Enhanced message sending system to properly validate inputs and handle cases where user information may be incomplete, improving overall system reliability.

Copilot AI review requested due to automatic review settings March 12, 2026 15:44
@dionisio-bot
Copy link
Copy Markdown
Contributor

dionisio-bot Bot commented Mar 12, 2026

Looks like this PR is not ready to merge, because of the following issues:

  • This PR is missing the 'stat: QA assured' label
  • This PR is missing the required milestone or project

Please fix the issues and try again

If you have any trouble, please check the PR guidelines

@changeset-bot
Copy link
Copy Markdown

changeset-bot Bot commented Mar 12, 2026

⚠️ No Changeset found

Latest commit: 5f6d18f

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@CLAassistant
Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution.
You have signed the CLA already but the status is still pending? Let us recheck it.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Mar 12, 2026

Walkthrough

Type safety improvements to the sendMessage function by replacing any type parameters with explicit types: user now has a defined structure with _id, optional username, and optional name; message uses Partial<IMessage>; room uses Pick<IRoom, '_id'>. The prepareMessageObject function now safely defaults missing username to an empty string instead of type casting.

Changes

Cohort / File(s) Summary
Type Safety Refactoring
apps/meteor/app/lib/server/functions/sendMessage.ts
Replaced any types in sendMessage function signature with explicit types: user object with _id (required) and optional username/name fields; message as Partial<IMessage>; room as Pick<IRoom, '_id'>. Added explicit input validation guards for user, message, and room._id. Updated prepareMessageObject to safely default username to empty string instead of type casting.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Suggested labels

type: chore

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main refactoring effort: improving type safety and resolving the FIXME in sendMessage.ts, which aligns perfectly with the changeset.
Linked Issues check ✅ Passed The PR successfully addresses all three objectives from issue #39560: resolves the FIXME on line 205 with safe username handling, replaces any types with stronger type definitions, and ensures the user parameter accurately reflects expected structure.
Out of Scope Changes check ✅ Passed All changes are directly related to improving type safety in sendMessage.ts and resolving the specified FIXME. No unrelated modifications were introduced beyond the scope of the linked issue.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

📝 Coding Plan for PR comments
  • Generate coding plan

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR aims to improve type safety in sendMessage.ts by replacing any types with more specific ones and resolving a FIXME comment about the username cast.

Changes:

  • Replaces username as string cast with username || '' fallback in prepareMessageObject
  • Adds explicit type annotations for user, message, and room parameters of sendMessage

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

*/
export const sendMessage = async function (user: any, message: any, room: any, options: SendMessageOptions = {}) {
export const sendMessage = async function (
user: { _id: string; username?: string; name?: string },
Copy link

Copilot AI Mar 12, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

afterSaveMessage expects user: IUser (see apps/meteor/app/lib/server/lib/afterSaveMessage.ts:8), but the new signature types user as { _id: string; username?: string; name?: string }. This will also cause a TypeScript compilation error. Consider using a type like IUser or at least a type that's compatible with all downstream consumers.

Copilot uses AI. Check for mistakes.
message.u = {
_id,
username: username as string, // FIXME: this is wrong but I don't want to change it now
username: username || '',
Copy link

Copilot AI Mar 12, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Using an empty string as a fallback for username silently hides the problem — messages will be stored in the database with username: '', which could cause display issues or break username-based lookups downstream. Consider throwing an error or logging a warning if username is undefined, rather than silently substituting an empty string.

Copilot uses AI. Check for mistakes.
export const sendMessage = async function (
user: { _id: string; username?: string; name?: string },
message: Partial<IMessage>,
room: Pick<IRoom, '_id'>,
Copy link

Copilot AI Mar 12, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

afterSaveMessage (line 297) expects room: IRoom, but the new signature types room as Pick<IRoom, '_id'>. This will cause a TypeScript compilation error. The room parameter type needs to be widened — at minimum to IRoom, or you could keep it as any until the callers and downstream functions are also properly typed.

Suggested change
room: Pick<IRoom, '_id'>,
room: IRoom,

Copilot uses AI. Check for mistakes.
Copy link
Copy Markdown
Contributor

@cubic-dev-ai cubic-dev-ai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No issues found across 1 file

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
apps/meteor/app/lib/server/functions/sendMessage.ts (1)

232-233: ⚠️ Potential issue | 🟠 Major

Guard will throw TypeError if room is null at runtime.

The type signature declares room: Pick<IRoom, '_id'> as non-nullable, but processWebhookMessage.ts constructs a union type where roomData.room can be IRoom | null. When an error occurs with separateResponse disabled, null is passed to sendMessage, and !room._id will throw a TypeError instead of returning false.

Suggested fix
- if (!user || !message || !room._id) {
+ if (!user || !message || !room?._id) {
		return false;
	}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/meteor/app/lib/server/functions/sendMessage.ts` around lines 232 - 233,
The guard in sendMessage is dereferencing room._id and will throw if room is
null; update the check in the sendMessage function to verify room exists before
accessing its _id (e.g., ensure you test room for null/undefined first) and/or
adjust the sendMessage signature to accept room: Pick<IRoom, '_id'> | null so
callers like processWebhookMessage.ts that may pass null are covered; ensure the
guard uses the null-safe condition (check room, then room._id) and return false
when room is missing.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@apps/meteor/app/lib/server/functions/sendMessage.ts`:
- Around line 224-227: The sendMessage signature is too narrow for
validateMessage which reads user.token and room.v?.token for livechat
impersonation checks; update the sendMessage parameter types so the user
parameter includes an optional token field (e.g., user: { _id: string;
username?: string; name?: string; token?: string }) and the room parameter
allows the nested v?.token (e.g., room: Pick<IRoom, '_id' | 'v'> or an
appropriate type that exposes v?: { token?: string }) so callers cannot omit
those fields required by validateMessage; ensure references to sendMessage,
validateMessage, user.token and room.v?.token are accounted for across usages.

---

Outside diff comments:
In `@apps/meteor/app/lib/server/functions/sendMessage.ts`:
- Around line 232-233: The guard in sendMessage is dereferencing room._id and
will throw if room is null; update the check in the sendMessage function to
verify room exists before accessing its _id (e.g., ensure you test room for
null/undefined first) and/or adjust the sendMessage signature to accept room:
Pick<IRoom, '_id'> | null so callers like processWebhookMessage.ts that may pass
null are covered; ensure the guard uses the null-safe condition (check room,
then room._id) and return false when room is missing.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 7fd0a271-7e03-4ada-a232-d022b09916ee

📥 Commits

Reviewing files that changed from the base of the PR and between 7485960 and 5f6d18f.

📒 Files selected for processing (1)
  • apps/meteor/app/lib/server/functions/sendMessage.ts
📜 Review details
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: cubic · AI code reviewer
🧰 Additional context used
📓 Path-based instructions (1)
**/*.{ts,tsx,js}

📄 CodeRabbit inference engine (.cursor/rules/playwright.mdc)

**/*.{ts,tsx,js}: Write concise, technical TypeScript/JavaScript with accurate typing in Playwright tests
Avoid code comments in the implementation

Files:

  • apps/meteor/app/lib/server/functions/sendMessage.ts
🧠 Learnings (12)
📓 Common learnings
Learnt from: ggazzo
Repo: RocketChat/Rocket.Chat PR: 35995
File: apps/meteor/app/api/server/v1/rooms.ts:1107-1112
Timestamp: 2026-02-23T17:53:18.785Z
Learning: In Rocket.Chat PR reviews, maintain strict scope boundaries—when a PR is focused on a specific endpoint (e.g., rooms.favorite), avoid reviewing or suggesting changes to other endpoints that were incidentally refactored (e.g., rooms.invite) unless explicitly requested by maintainers.
Learnt from: ricardogarim
Repo: RocketChat/Rocket.Chat PR: 37205
File: ee/packages/federation-matrix/src/FederationMatrix.ts:296-301
Timestamp: 2025-10-28T16:53:42.761Z
Learning: In the Rocket.Chat federation-matrix integration (ee/packages/federation-matrix/), the createRoom method from rocket.chat/federation-sdk will support a 4-argument signature (userId, roomName, visibility, displayName) in newer versions. Code using this 4-argument call is forward-compatible with planned library updates and should not be flagged as an error.
Learnt from: ricardogarim
Repo: RocketChat/Rocket.Chat PR: 37205
File: ee/packages/federation-matrix/src/FederationMatrix.ts:296-301
Timestamp: 2025-10-28T16:53:42.761Z
Learning: In the Rocket.Chat federation-matrix integration (ee/packages/federation-matrix/), the createRoom method from rocket.chat/federation-sdk will support a 4-argument signature (userId, roomName, visibility, displayName) in newer versions. Code using this 4-argument call is forward-compatible with planned library updates and should not be flagged as an error.
Learnt from: juliajforesti
Repo: RocketChat/Rocket.Chat PR: 39545
File: apps/meteor/client/views/room/body/hooks/useHasNewMessages.ts:59-61
Timestamp: 2026-03-11T22:04:16.136Z
Learning: In `apps/meteor/client/views/room/body/hooks/useHasNewMessages.ts`, the `msg.u._id === uid` early-return in the `streamNewMessage` handler is intentional: the "New messages" indicator is designed to notify about messages from other users only. Self-sent messages — including those sent from a different session/device — are always skipped, by design. Do not flag this as a multi-session regression.
📚 Learning: 2026-03-11T22:04:16.136Z
Learnt from: juliajforesti
Repo: RocketChat/Rocket.Chat PR: 39545
File: apps/meteor/client/views/room/body/hooks/useHasNewMessages.ts:59-61
Timestamp: 2026-03-11T22:04:16.136Z
Learning: In `apps/meteor/client/views/room/body/hooks/useHasNewMessages.ts`, the `msg.u._id === uid` early-return in the `streamNewMessage` handler is intentional: the "New messages" indicator is designed to notify about messages from other users only. Self-sent messages — including those sent from a different session/device — are always skipped, by design. Do not flag this as a multi-session regression.

Applied to files:

  • apps/meteor/app/lib/server/functions/sendMessage.ts
📚 Learning: 2026-02-24T19:16:35.307Z
Learnt from: sampaiodiego
Repo: RocketChat/Rocket.Chat PR: 39003
File: apps/meteor/client/lib/chats/flows/sendMessage.ts:39-45
Timestamp: 2026-02-24T19:16:35.307Z
Learning: In apps/meteor/client/lib/chats/flows/sendMessage.ts, when sdk.call('sendMessage', ...) throws an error, the message is intentionally left with temp: true (not deleted or cleaned up) to support a future retry UI feature. This allows users to retry sending failed messages rather than losing them.

Applied to files:

  • apps/meteor/app/lib/server/functions/sendMessage.ts
📚 Learning: 2026-01-17T01:51:47.764Z
Learnt from: tassoevan
Repo: RocketChat/Rocket.Chat PR: 38219
File: packages/core-typings/src/cloud/Announcement.ts:5-6
Timestamp: 2026-01-17T01:51:47.764Z
Learning: In packages/core-typings/src/cloud/Announcement.ts, the AnnouncementSchema.createdBy field intentionally overrides IBannerSchema.createdBy (object with _id and optional username) with a string enum ['cloud', 'system'] to match existing runtime behavior. This is documented as technical debt with a FIXME comment at apps/meteor/app/cloud/server/functions/syncWorkspace/handleCommsSync.ts:53 and should not be flagged as an error until the runtime behavior is corrected.

Applied to files:

  • apps/meteor/app/lib/server/functions/sendMessage.ts
📚 Learning: 2025-11-19T18:20:37.116Z
Learnt from: gabriellsh
Repo: RocketChat/Rocket.Chat PR: 37419
File: apps/meteor/server/services/media-call/service.ts:141-141
Timestamp: 2025-11-19T18:20:37.116Z
Learning: In apps/meteor/server/services/media-call/service.ts, the sendHistoryMessage method should use call.caller.id or call.createdBy?.id as the message author, not call.transferredBy?.id. Even for transferred calls, the message should appear in the DM between the two users who are calling each other, not sent by the person who transferred the call.

Applied to files:

  • apps/meteor/app/lib/server/functions/sendMessage.ts
📚 Learning: 2026-03-09T18:39:21.178Z
Learnt from: Harxhit
Repo: RocketChat/Rocket.Chat PR: 39476
File: apps/meteor/server/methods/addAllUserToRoom.ts:0-0
Timestamp: 2026-03-09T18:39:21.178Z
Learning: In apps/meteor/server/methods/addAllUserToRoom.ts, the implementation uses a single cursor pass (Users.find(userFilter).batchSize(100)) that collects both the full user objects (collectedUsers: IUser[]) and their usernames (usernames: string[]) in one iteration. `beforeAddUserToRoom` is then called once with the full usernames batch (preserving batch-validation semantics), and the subsequent subscription/message processing loop iterates over the same stable `collectedUsers` array — no second DB query is made. This avoids any race condition between validation and processing while preserving the original batch-validation behavior.

Applied to files:

  • apps/meteor/app/lib/server/functions/sendMessage.ts
📚 Learning: 2026-03-03T11:11:48.541Z
Learnt from: ahmed-n-abdeltwab
Repo: RocketChat/Rocket.Chat PR: 39230
File: apps/meteor/app/api/server/v1/chat.ts:214-222
Timestamp: 2026-03-03T11:11:48.541Z
Learning: In apps/meteor/server/lib/moderation/reportMessage.ts, the reportMessage function validates that description is not empty or whitespace-only with `if (!description.trim())`. When migrating the chat.reportMessage endpoint to OpenAPI, adding minLength validation to the schema preserves this existing behavior.

Applied to files:

  • apps/meteor/app/lib/server/functions/sendMessage.ts
📚 Learning: 2025-10-28T16:53:42.761Z
Learnt from: ricardogarim
Repo: RocketChat/Rocket.Chat PR: 37205
File: ee/packages/federation-matrix/src/FederationMatrix.ts:296-301
Timestamp: 2025-10-28T16:53:42.761Z
Learning: In the Rocket.Chat federation-matrix integration (ee/packages/federation-matrix/), the createRoom method from rocket.chat/federation-sdk will support a 4-argument signature (userId, roomName, visibility, displayName) in newer versions. Code using this 4-argument call is forward-compatible with planned library updates and should not be flagged as an error.

Applied to files:

  • apps/meteor/app/lib/server/functions/sendMessage.ts
📚 Learning: 2026-03-12T10:26:19.756Z
Learnt from: ahmed-n-abdeltwab
Repo: RocketChat/Rocket.Chat PR: 39340
File: apps/meteor/app/api/server/v1/im.ts:1349-1398
Timestamp: 2026-03-12T10:26:19.756Z
Learning: In `apps/meteor/app/api/server/v1/im.ts` (PR `#39340`), the `DmEndpoints` type intentionally includes temporary stub entries for `/v1/im.kick`, `/v1/dm.kick`, `/v1/im.leave`, and `/v1/dm.leave` (using `DmKickProps` and `DmLeaveProps`) even though no route handlers exist for them yet. These stubs were added to preserve type compatibility after removing the original `DmLeaveProps` and related files. They are planned for cleanup in a follow-up PR. Do not flag these as missing implementations when reviewing this file until the follow-up is merged.

Applied to files:

  • apps/meteor/app/lib/server/functions/sendMessage.ts
📚 Learning: 2026-01-19T18:17:46.433Z
Learnt from: gabriellsh
Repo: RocketChat/Rocket.Chat PR: 38262
File: apps/meteor/client/lib/utils/normalizeMessagePreview/getMessagePreview.ts:24-33
Timestamp: 2026-01-19T18:17:46.433Z
Learning: In the Rocket.Chat repository, usernames (lastMessage.u.username) and display names (lastMessage.u.name) are sanitized/escaped centrally elsewhere in the system, so individual display functions like getMessagePreview do not need to escape these values before interpolating them into strings.

Applied to files:

  • apps/meteor/app/lib/server/functions/sendMessage.ts
📚 Learning: 2026-02-26T19:25:44.063Z
Learnt from: gabriellsh
Repo: RocketChat/Rocket.Chat PR: 38778
File: packages/ui-voip/src/providers/useMediaSession.ts:192-192
Timestamp: 2026-02-26T19:25:44.063Z
Learning: In the Rocket.Chat repository, do not reference Biome lint rules in code review feedback. Biome is not used even if biome.json exists; only reference Biome rules if there is explicit, project-wide usage documented. For TypeScript files, review lint implications without Biome guidance unless the project enables Biome rules.

Applied to files:

  • apps/meteor/app/lib/server/functions/sendMessage.ts
📚 Learning: 2026-02-26T19:25:44.063Z
Learnt from: gabriellsh
Repo: RocketChat/Rocket.Chat PR: 38778
File: packages/ui-voip/src/providers/useMediaSession.ts:192-192
Timestamp: 2026-02-26T19:25:44.063Z
Learning: In this repository (RocketChat/Rocket.Chat), Biome lint rules are not used even if a biome.json exists. When reviewing TypeScript files (e.g., packages/ui-voip/src/providers/useMediaSession.ts), ensure lint suggestions do not reference Biome-specific rules. Rely on general ESLint/TypeScript lint rules and project conventions instead.

Applied to files:

  • apps/meteor/app/lib/server/functions/sendMessage.ts
🔇 Additional comments (1)
apps/meteor/app/lib/server/functions/sendMessage.ts (1)

202-206: Good removal of the username cast.

Defaulting username to a string here keeps message.u.username well-defined without the old assertion.

Comment on lines +224 to +227
export const sendMessage = async function (
user: { _id: string; username?: string; name?: string },
message: Partial<IMessage>,
room: Pick<IRoom, '_id'>,
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

cd apps/meteor/app/lib/server/functions && wc -l sendMessage.ts

Repository: RocketChat/Rocket.Chat

Length of output: 84


🏁 Script executed:

head -250 apps/meteor/app/lib/server/functions/sendMessage.ts | tail -50

Repository: RocketChat/Rocket.Chat

Length of output: 1281


🏁 Script executed:

sed -n '169,180p' apps/meteor/app/lib/server/functions/sendMessage.ts

Repository: RocketChat/Rocket.Chat

Length of output: 462


🏁 Script executed:

sed -n '224,240p' apps/meteor/app/lib/server/functions/sendMessage.ts

Repository: RocketChat/Rocket.Chat

Length of output: 544


🏁 Script executed:

sed -n '120,185p' apps/meteor/app/lib/server/functions/sendMessage.ts

Repository: RocketChat/Rocket.Chat

Length of output: 1838


🏁 Script executed:

grep -n "user\." apps/meteor/app/lib/server/functions/sendMessage.ts | head -20

Repository: RocketChat/Rocket.Chat

Length of output: 262


🏁 Script executed:

grep -n "room\." apps/meteor/app/lib/server/functions/sendMessage.ts | head -20

Repository: RocketChat/Rocket.Chat

Length of output: 357


🏁 Script executed:

fd -t f "IUser" --extension ts | head -5

Repository: RocketChat/Rocket.Chat

Length of output: 357


🏁 Script executed:

rg "interface IUser|type IUser" --type ts -A 20 | head -60

Repository: RocketChat/Rocket.Chat

Length of output: 6017


🏁 Script executed:

rg "interface IRoom|type IRoom" --type ts -A 20 | head -80

Repository: RocketChat/Rocket.Chat

Length of output: 5271


🏁 Script executed:

rg "interface IUser" packages/core-typings/src/IUser.ts -A 50 | head -80

Repository: RocketChat/Rocket.Chat

Length of output: 1582


🏁 Script executed:

rg "^\s*(token|v)\s*[?:]" packages/core-typings/src/IUser.ts packages/core-typings/src/IRoom.ts

Repository: RocketChat/Rocket.Chat

Length of output: 394


🏁 Script executed:

sed -n '1,50p' apps/meteor/app/lib/server/functions/sendMessage.ts

Repository: RocketChat/Rocket.Chat

Length of output: 1788


🏁 Script executed:

rg "token\s*:" packages/core-typings/src/IUser.ts -B 2 -A 2

Repository: RocketChat/Rocket.Chat

Length of output: 457


🏁 Script executed:

grep -n "prepareMessageObject\|validateMessage" apps/meteor/app/lib/server/functions/sendMessage.ts

Repository: RocketChat/Rocket.Chat

Length of output: 342


🏁 Script executed:

rg "sendMessage\(" apps/meteor/app/lib/server/functions/ -A 2 -B 2 | head -40

Repository: RocketChat/Rocket.Chat

Length of output: 545


🏁 Script executed:

rg "sendMessage\(" apps/meteor/app --type ts | head -20

Repository: RocketChat/Rocket.Chat

Length of output: 2308


🏁 Script executed:

grep -rn "user\.token" apps/meteor/app/lib/server/functions/sendMessage.ts

Repository: RocketChat/Rocket.Chat

Length of output: 158


🏁 Script executed:

sed -n '224,240p' apps/meteor/app/lib/server/functions/sendMessage.ts

Repository: RocketChat/Rocket.Chat

Length of output: 544


🏁 Script executed:

rg "export interface IUser" packages/core-typings/src/IUser.ts -A 100 | head -120

Repository: RocketChat/Rocket.Chat

Length of output: 2833


🏁 Script executed:

grep -n "^\s*token\s*" packages/core-typings/src/IUser.ts

Repository: RocketChat/Rocket.Chat

Length of output: 128


🏁 Script executed:

rg "user\.token\s*=" apps/meteor/app -B 5 -A 2 | head -40

Repository: RocketChat/Rocket.Chat

Length of output: 746


🏁 Script executed:

rg "\.token\s*=" apps/meteor/app/lib/server/functions/sendMessage.ts -B 3 -A 2

Repository: RocketChat/Rocket.Chat

Length of output: 300


🏁 Script executed:

rg "\btoken\b" packages/core-typings/src/ILivechatVisitor.ts -A 2 -B 2

Repository: RocketChat/Rocket.Chat

Length of output: 359


🏁 Script executed:

rg "validateMessage" apps/meteor/app/lib/server/functions/sendMessage.ts -B 10 -A 10 | head -60

Repository: RocketChat/Rocket.Chat

Length of output: 1602


🏁 Script executed:

rg "type.*User.*token\|interface.*User.*token" --type ts packages/core-typings/src | head -20

Repository: RocketChat/Rocket.Chat

Length of output: 48


🏁 Script executed:

git log --oneline -n 20 -- apps/meteor/app/lib/server/functions/sendMessage.ts | head -15

Repository: RocketChat/Rocket.Chat

Length of output: 142


🏁 Script executed:

git show 5f6d18fe7c --stat

Repository: RocketChat/Rocket.Chat

Length of output: 50379


🏁 Script executed:

git show 5f6d18fe7c -- apps/meteor/app/lib/server/functions/sendMessage.ts | head -100

Repository: RocketChat/Rocket.Chat

Length of output: 3127


🏁 Script executed:

rg "sendMessage\(" apps/meteor/app/livechat/server/methods/sendMessageLivechat.ts -B 5 -A 10

Repository: RocketChat/Rocket.Chat

Length of output: 395


🏁 Script executed:

sed -n '1,30p' apps/meteor/app/livechat/server/methods/sendMessageLivechat.ts

Repository: RocketChat/Rocket.Chat

Length of output: 1011


🏁 Script executed:

grep -n "sendMessage" apps/meteor/app/livechat/server/methods/sendMessageLivechat.ts -A 20 | head -40

Repository: RocketChat/Rocket.Chat

Length of output: 1076


🏁 Script executed:

rg "guest.*token\|token.*guest" apps/meteor/app/livechat/server -B 3 -A 3 | head -60

Repository: RocketChat/Rocket.Chat

Length of output: 48


🏁 Script executed:

sed -n '45,120p' apps/meteor/app/livechat/server/methods/sendMessageLivechat.ts

Repository: RocketChat/Rocket.Chat

Length of output: 971


🏁 Script executed:

rg "sendMessage\(" apps/meteor/app/livechat/server/lib/messages.ts -B 10 -A 20 | head -100

Repository: RocketChat/Rocket.Chat

Length of output: 718


🏁 Script executed:

head -100 apps/meteor/app/livechat/server/lib/messages.ts

Repository: RocketChat/Rocket.Chat

Length of output: 3585


🏁 Script executed:

sed -n '1,100p' packages/core-typings/src/IRoom.ts | grep -A 5 "^\s*v\s*"

Repository: RocketChat/Rocket.Chat

Length of output: 48


🏁 Script executed:

rg "^\s*v\s*[?:]" packages/core-typings/src/IRoom.ts -B 2 -A 5

Repository: RocketChat/Rocket.Chat

Length of output: 523


🏁 Script executed:

sed -n '151,180p' apps/meteor/app/lib/server/functions/sendMessage.ts

Repository: RocketChat/Rocket.Chat

Length of output: 843


🏁 Script executed:

rg "ILivechatVisitor" packages/core-typings/src -l

Repository: RocketChat/Rocket.Chat

Length of output: 354


🏁 Script executed:

sed -n '1,80p' packages/core-typings/src/ILivechatVisitor.ts

Repository: RocketChat/Rocket.Chat

Length of output: 1363


The signature is still narrower than the implementation requires.

validateMessage() (line 169) reads user.token and room.v?.token to check livechat guest impersonation. The current signature omits these fields, allowing callers to satisfy the type while passing objects missing fields that affect permission validation.

Suggested fix
- user: { _id: string; username?: string; name?: string },
+ user: { _id: string; username?: string; name?: string; token?: string },
- room: Pick<IRoom, '_id'>,
+ room: Pick<IRoom, '_id' | 'v'>,
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/meteor/app/lib/server/functions/sendMessage.ts` around lines 224 - 227,
The sendMessage signature is too narrow for validateMessage which reads
user.token and room.v?.token for livechat impersonation checks; update the
sendMessage parameter types so the user parameter includes an optional token
field (e.g., user: { _id: string; username?: string; name?: string; token?:
string }) and the room parameter allows the nested v?.token (e.g., room:
Pick<IRoom, '_id' | 'v'> or an appropriate type that exposes v?: { token?:
string }) so callers cannot omit those fields required by validateMessage;
ensure references to sendMessage, validateMessage, user.token and room.v?.token
are accounted for across usages.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Refactor: Improve type safety and resolve FIXME in sendMessage.ts

3 participants