RocketChat / RocketChat/Rocket.Chat

Unsafe `username as string` type assertion in prepareMessageObject

Open
#38,799 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

type: bug
Dominant language
TypeScript
Stars
46.1k
Forks
13.9k
Avg merge
3d 3h
Merged PRs (30d)
130

Description

Description

In [apps/meteor/app/lib/server/functions/sendMessage.ts], the [prepareMessageObject] function uses an unsafe type assertion at line 206:

const { _id, username, name } = user;
message.u = {
    _id,
    username: username as string, // FIXME: this is wrong but I don't want to change it now
    name,
};

The user parameter types username as string | undefined, but the as string assertion silently bypasses this. If username is actually undefined, the IMessage.u.username field will be set to undefined, violating the IMessage contract.

Impact

  • Messages stored with username: undefined in the database
  • Downstream rendering could display "undefined" as a username
  • The existing FIXME comment acknowledges this is wrong but defers the fix

Proposed Fix

Replace the unsafe type assertion with a runtime guard that throws a descriptive error when username is undefined:

const { _id, username, name } = user;
if (!username) {
    throw new Error(`Cannot send message: user ${_id} has no username`);
}
message.u = {
    _id,
    username,
    name,
};

This fails fast with a clear error instead of silently propagating invalid data.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start in apps/meteor/app/lib/server/functions/sendMessage.ts at prepareMessageObject and inspect how the user object reaches the message assignment around line 206. Done means the unsafe assertion and FIXME are removed, missing usernames fail with the proposed descriptive error, and valid usernames remain assigned to IMessage.u.username.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
backend
Issue type
Bug
Difficulty
2/5
Estimated time
1-3 hours
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
48/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.