Skip to content

chore: undo loadMissedMessages deprecation from #40711#40981

Merged
ggazzo merged 6 commits into
developfrom
feat/chat-history-endpoint
Jun 17, 2026
Merged

chore: undo loadMissedMessages deprecation from #40711#40981
ggazzo merged 6 commits into
developfrom
feat/chat-history-endpoint

Conversation

@ggazzo

@ggazzo ggazzo commented Jun 16, 2026

Copy link
Copy Markdown
Member

Proposed changes

Follow-up to #40711.

Reverts the loadMissedMessages deprecation introduced in #40711.

#40711 migrated the reconnect catch-up hook (useLoadMissedMessages) from the loadMissedMessages DDP method to /v1/chat.syncMessages, and marked the method deprecated. chat.syncMessages is the right long-term target — it queries by _updatedAt (+ the trash collection), so on reconnect it also reconciles edits and deletions made while offline, not just new messages.

However, that query is currently too slow for the reconnect path. This PR rolls the hook back to the loadMissedMessages DDP method and removes the premature deprecation notice. A TODO(ddp-removal) is left in the hook documenting that we should move to chat.syncMessages once the query is optimized.

Changes

  • useLoadMissedMessages → calls the loadMissedMessages DDP method again (with a TODO to revisit chat.syncMessages).
  • loadMissedMessages method → deprecation notice removed.

An earlier iteration of this branch explored a room-type-agnostic /v1/chat.history endpoint as the replacement; that was dropped in favor of simply reverting the deprecation until the chat.syncMessages query is fast enough.

How to test

  • Drop the connection, post messages from another session, restore the connection → missed messages appear on reconnect (via the DDP method).
  • No loadMissedMessages deprecation warning is logged on use.
    ARCH-2164

Summary by CodeRabbit

  • Refactor
    • Updated how the app retrieves messages that were missed during offline periods
    • Removed deprecated logging from the message-retrieval system

@dionisio-bot

dionisio-bot Bot commented Jun 16, 2026

Copy link
Copy Markdown
Contributor

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

  • This PR is missing the 'stat: QA assured' label

Please fix the issues and try again

If you have any trouble, please check the PR guidelines

@changeset-bot

changeset-bot Bot commented Jun 16, 2026

Copy link
Copy Markdown

⚠️ No Changeset found

Latest commit: cacda99

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

@coderabbitai

coderabbitai Bot commented Jun 16, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

The client useLoadMissedMessages hook replaces the REST-based /v1/chat.syncMessages flow (including message mapping, stale-insert filtering, and deletion reconciliation) with a direct callWithErrorHandling('loadMissedMessages', rid, lastMessage.ts) Meteor method call that upserts returned messages. The server loadMissedMessages method drops its deprecation logger import and call.

Changes

loadMissedMessages reconnect flow

Layer / File(s) Summary
Client hook and server method changes
apps/meteor/client/views/root/hooks/useLoadMissedMessages.ts, apps/meteor/server/methods/loadMissedMessages.ts
Client hook swaps the REST sync path for callWithErrorHandling('loadMissedMessages', ...) with a direct upsert, removing mapping/filtering/deletion reconciliation. A TODO comment marks the intended future migration back to /v1/chat.syncMessages. Server method removes methodDeprecationLogger import and its invocation, leaving validation and DB query logic intact.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Suggested labels

type: bug

Suggested reviewers

  • tassoevan
  • sampaiodiego
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title 'chore: undo loadMissedMessages deprecation from #40711' directly and accurately summarizes the main change: reverting the deprecation of the loadMissedMessages method as introduced in PR #40711.

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

Warning

Review ran into problems

🔥 Problems

Errors were encountered while retrieving linked issues.

Errors (1)
  • ARCH-2164: Request failed with status code 401

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.

@ggazzo ggazzo force-pushed the feat/chat-history-endpoint branch from c2546e8 to 6247a46 Compare June 16, 2026 19:11
@codecov

codecov Bot commented Jun 16, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 70.15%. Comparing base (fbf3672) to head (cacda99).
⚠️ Report is 10 commits behind head on develop.

Additional details and impacted files

Impacted file tree graph

@@             Coverage Diff             @@
##           develop   #40981      +/-   ##
===========================================
+ Coverage    70.08%   70.15%   +0.06%     
===========================================
  Files         3357     3358       +1     
  Lines       129543   129559      +16     
  Branches     22474    22468       -6     
===========================================
+ Hits         90787    90886      +99     
+ Misses       35456    35355     -101     
- Partials      3300     3318      +18     
Flag Coverage Δ
unit 70.08% <ø> (+0.04%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

ggazzo added 2 commits June 16, 2026 16:43
Add a new `GET /v1/chat.history` REST endpoint that returns a room's
message history by `roomId` regardless of room type (channel, private
group or DM), mirroring the behavior of `channels.history`,
`groups.history` and `im.history` without requiring the caller to know
the room type beforehand.

It reuses `getChannelHistory`, which resolves access via
`Authorization.canReadRoom`, so the same `{ rid, ts }`-indexed range
query is used for any room. This provides a performant REST replacement
for the deprecated `loadMissedMessages` DDP method, whose deprecation
notice now points to `/v1/chat.history`.
Replace the `chat.syncMessages` REST call in the reconnect hook with the
new `GET /v1/chat.history` endpoint.

On reconnection the hook now fetches only messages created after the
newest loaded message's timestamp (`ts`) via a single indexed range
query, instead of scanning `_updatedAt` plus the trash collection.
@ggazzo ggazzo force-pushed the feat/chat-history-endpoint branch from 6247a46 to daa2272 Compare June 16, 2026 19:43
@ggazzo ggazzo added this to the 8.6.0 milestone Jun 17, 2026
ggazzo added 3 commits June 17, 2026 18:35
chat.history replaces the deprecated loadMissedMessages DDP method only.
The reconnect hook must keep chat.syncMessages so it still reconciles
edits and deletions made while offline.
Reconnect catch-up now uses /v1/chat.history. Page through with offset
so the server-side count clamp (API_Upper_Count_Limit) cannot silently
drop missed messages when many were sent while offline.
Reverts the loadMissedMessages deprecation added in #40711. Removes the
new chat.history REST endpoint (types, tests) and points the reconnect
catch-up back at the loadMissedMessages DDP method.

chat.syncMessages would be the right long-term target (it also reconciles
edits/deletions on reconnect), but its _updatedAt + trash-collection query
is currently too slow for this path; left a TODO to optimize that query
before migrating.
@ggazzo ggazzo changed the title feat(chat): add room-type-agnostic chat.history endpoint revert(chat): undo loadMissedMessages deprecation from #40711 Jun 17, 2026
@ggazzo ggazzo marked this pull request as ready for review June 17, 2026 22:49
@ggazzo ggazzo requested review from a team as code owners June 17, 2026 22:49

@coderabbitai coderabbitai Bot left a comment

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.

🧹 Nitpick comments (1)
apps/meteor/client/views/root/hooks/useLoadMissedMessages.ts (1)

31-31: 💤 Low value

Redundant Array.from() call.

result is already IMessage[] when truthy (per the server method's false | IMessage[] return type), so Array.from() is unnecessary.

♻️ Suggested simplification
-			await Promise.all(Array.from(result).map((msg) => upsertMessage({ msg, subscription })));
+			await Promise.all(result.map((msg) => upsertMessage({ msg, subscription })));
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/meteor/client/views/root/hooks/useLoadMissedMessages.ts` at line 31, In
the useLoadMissedMessages hook, remove the redundant Array.from() wrapper around
result in the Promise.all mapping operation. Since result is already typed as
IMessage[] (per the server method's false | IMessage[] return type), you can
call map() directly on result without converting it to an array first.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@apps/meteor/client/views/root/hooks/useLoadMissedMessages.ts`:
- Line 31: In the useLoadMissedMessages hook, remove the redundant Array.from()
wrapper around result in the Promise.all mapping operation. Since result is
already typed as IMessage[] (per the server method's false | IMessage[] return
type), you can call map() directly on result without converting it to an array
first.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 1480eedc-4887-4a78-b6bd-365d8074a91d

📥 Commits

Reviewing files that changed from the base of the PR and between 02b8008 and cacda99.

📒 Files selected for processing (2)
  • apps/meteor/client/views/root/hooks/useLoadMissedMessages.ts
  • apps/meteor/server/methods/loadMissedMessages.ts
💤 Files with no reviewable changes (1)
  • apps/meteor/server/methods/loadMissedMessages.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). (4)
  • GitHub Check: 📦 Build Packages
  • GitHub Check: Hacktron Security Check
  • GitHub Check: CodeQL-Build
  • GitHub Check: CodeQL-Build
🧰 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/client/views/root/hooks/useLoadMissedMessages.ts
🧠 Learnings (5)
📚 Learning: 2026-02-10T16:32:42.586Z
Learnt from: tassoevan
Repo: RocketChat/Rocket.Chat PR: 38528
File: apps/meteor/client/startup/roles.ts:14-14
Timestamp: 2026-02-10T16:32:42.586Z
Learning: In Rocket.Chat's Meteor client code, DDP streams use EJSON and Date fields arrive as Date objects; do not manually construct new Date() in stream handlers (for example, in sdk.stream()). Only REST API responses return plain JSON where dates are strings, so implement explicit conversion there if needed. Apply this guidance to all TypeScript files under apps/meteor/client to ensure consistent date handling in DDP streams and REST responses.

Applied to files:

  • apps/meteor/client/views/root/hooks/useLoadMissedMessages.ts
📚 Learning: 2026-05-11T20:30:35.265Z
Learnt from: tassoevan
Repo: RocketChat/Rocket.Chat PR: 40480
File: apps/meteor/client/meteor/startup/accounts.ts:59-61
Timestamp: 2026-05-11T20:30:35.265Z
Learning: In Rocket.Chat’s Meteor client code, when calling `dispatchToastMessage` with `{ type: 'error' }`, pass the raw caught error object as `message` without manual normalization. `dispatchToastMessage` is designed to accept `message: unknown` for error toasts, so avoid converting errors to strings (e.g., `String(error)`) or extracting `error.message` before passing them.

Applied to files:

  • apps/meteor/client/views/root/hooks/useLoadMissedMessages.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/client/views/root/hooks/useLoadMissedMessages.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/client/views/root/hooks/useLoadMissedMessages.ts
📚 Learning: 2026-05-06T12:21:44.083Z
Learnt from: juliajforesti
Repo: RocketChat/Rocket.Chat PR: 40256
File: apps/meteor/client/components/CreateDiscussion/CreateDiscussion.tsx:121-149
Timestamp: 2026-05-06T12:21:44.083Z
Learning: Field wrappers in rocket.chat/fuselage-forms (Field, FieldLabel, FieldRow, FieldError, FieldHint) auto-create htmlFor/id associations, aria-describedby, and role="alert" for errors. Do not manually set htmlFor, id, aria-describedby, or role attributes when using these wrappers. This automatic wiring does not apply to plain rocket.chat/fuselage components, which require explicit ID wiring per the accessibility docs. In code reviews, prefer using fuselage-forms wrappers for form fields and verify there is no unnecessary manual ID/aria wiring in files that use these wrappers. If a component uses plain fuselage components, ensure proper id wiring as per docs.

Applied to files:

  • apps/meteor/client/views/root/hooks/useLoadMissedMessages.ts
🔇 Additional comments (2)
apps/meteor/client/views/root/hooks/useLoadMissedMessages.ts (2)

6-6: LGTM!


41-57: LGTM!

@ggazzo ggazzo changed the title revert(chat): undo loadMissedMessages deprecation from #40711 chore: undo loadMissedMessages deprecation from #40711 Jun 17, 2026
@ggazzo ggazzo merged commit 6033e93 into develop Jun 17, 2026
17 of 18 checks passed
@ggazzo ggazzo deleted the feat/chat-history-endpoint branch June 17, 2026 22:54

@hacktron-app hacktron-app Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

1 issue found across 1 file

Severity Count
MEDIUM 1

View full scan results

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

MEDIUM Unbounded Database Query and Resource Exhaustion in loadMissedMessages Method

The server-side Meteor method loadMissedMessages fetches missed messages in a room after a given timestamp start without enforcing any limit or pagination. It calls Messages.findVisibleByRoomIdAfterTimestamp and converts the resulting cursor directly to an array via .toArray().

If an attacker (or any authorized user of a room) calls this method with a very old timestamp (e.g., new Date(0)) in a room/channel containing a large history of messages, the server will query and load all of those messages into memory at once before serializing and sending them to the client. This can lead to severe resource exhaustion, high CPU usage, and potentially an Out Of Memory (OOM) crash of the Node.js server process, resulting in a Denial of Service (DoS) for all users of the platform.

Steps to Reproduce

An attacker can execute the following DDP method call over WebSockets for any room they have access to (e.g., a large public channel like #general):

Meteor.call('loadMissedMessages', 'GENERAL_ROOM_ID', new Date(0), (err, res) => {
    if (err) console.error(err);
    else console.log(`Fetched ${res.length} messages`);
});

If the channel has hundreds of thousands of messages, this triggers a massive database fetch and memory allocation, leading to server instability or crash.

Trace
graph TD
    subgraph SG0 ["apps/meteor/app/authorization/server/functions/canAccessRoom.ts"]
        ._Rocket.Chat_apps_meteor_app_authorization_server_functions_canAccessRoom.ts["Exports authorization functions and room access attributes for room access control."]
    end
    style SG0 fill:#2a2a2a,stroke:#444,color:#aaa
    subgraph SG1 ["apps/meteor/client/meteor/overrides/userAndUsers.ts"]
        Meteor.userId["Overrides Meteor.userId to return the reactive userId from the local store."]
    end
    style SG1 fill:#2a2a2a,stroke:#444,color:#aaa
    subgraph SG2 ["apps/meteor/client/meteor/user.ts"]
        watchUserId["Watches the userId store and returns the reactive current user ID."]
    end
    style SG2 fill:#2a2a2a,stroke:#444,color:#aaa
    subgraph SG3 ["apps/meteor/client/meteor/watch.ts"]
        watch["watch"]
    end
    style SG3 fill:#2a2a2a,stroke:#444,color:#aaa
    subgraph SG4 ["apps/meteor/server/methods/loadMissedMessages.ts"]
        loadMissedMessages{{"Server-side Meteor method to fetch missed messages for a room after a timestamp."}}
    end
    style SG4 fill:#2a2a2a,stroke:#444,color:#aaa
    loadMissedMessages --> Meteor.userId
    loadMissedMessages --> ._Rocket.Chat_apps_meteor_app_authorization_server_functions_canAccessRoom.ts
    Meteor.userId --> watchUserId
    watchUserId --> watch
Loading
Fix with AI

Open in Cursor Open in Claude

A security vulnerability was found by Hacktron.

File: apps/meteor/server/methods/loadMissedMessages.ts
Severity: medium

Vulnerability: Unbounded Database Query and Resource Exhaustion in loadMissedMessages Method

Description:
The server-side Meteor method `loadMissedMessages` fetches missed messages in a room after a given timestamp `start` without enforcing any limit or pagination. It calls `Messages.findVisibleByRoomIdAfterTimestamp` and converts the resulting cursor directly to an array via `.toArray()`. 

If an attacker (or any authorized user of a room) calls this method with a very old timestamp (e.g., `new Date(0)`) in a room/channel containing a large history of messages, the server will query and load all of those messages into memory at once before serializing and sending them to the client. This can lead to severe resource exhaustion, high CPU usage, and potentially an Out Of Memory (OOM) crash of the Node.js server process, resulting in a Denial of Service (DoS) for all users of the platform.

Proof of Concept:
An attacker can execute the following DDP method call over WebSockets for any room they have access to (e.g., a large public channel like `#general`):

```javascript
Meteor.call('loadMissedMessages', 'GENERAL_ROOM_ID', new Date(0), (err, res) => {
    if (err) console.error(err);
    else console.log(`Fetched ${res.length} messages`);
});
```

If the channel has hundreds of thousands of messages, this triggers a massive database fetch and memory allocation, leading to server instability or crash.

Affected Code:
- [loadMissedMessages.ts L17-L36](https://github.com/RocketChat/Rocket.Chat/blob/develop/apps/meteor/server/methods/loadMissedMessages.ts#L17-L36)
```typescript
		return Messages.findVisibleByRoomIdAfterTimestamp(rid, start, true, {
			sort: {
				ts: -1,
			},
		}).toArray();
```

Acceptance criteria:
- Acceptance is defined by the **actual reported behavior**, not by tests passing.
- Reproduce the issue, or narrow the exact code path that produces it, *before* changing code. State what you confirmed.
- Fix the underlying cause. Mitigations that paper over the reported behavior do not count as a fix.
- Add a regression test that fails on the unpatched code and passes on the fix. If a regression test is genuinely impractical (e.g. race condition, infra-level issue), say so and explain why.
- Existing tests passing is **not** the bar. Do not declare done on tests-pass theatre.

Only change what is necessary to fix this vulnerability. Do not refactor adjacent code or modify unrelated files.

Triage: Reply !fp <reason> (false positive), !valid (confirmed), or !accepted_risk <reason>. Any other reply is saved as a triage note.
Reason is optional but improves future scans — e.g. !fp internal endpoint, not user-facing.

View finding in Hacktron

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.

2 participants