Skip to content

Release 8.5.1 - #40893

Merged
rocketchat-github-ci merged 12 commits into
masterfrom
release-8.5.1
Jun 15, 2026
Merged

Release 8.5.1#40893
rocketchat-github-ci merged 12 commits into
masterfrom
release-8.5.1

Conversation

@rocketchat-github-ci

@rocketchat-github-ci rocketchat-github-ci commented Jun 11, 2026

Copy link
Copy Markdown
Collaborator

Summary by CodeRabbit

  • Chores

    • Recorded multiple patch releases and a security hotfix.
  • New Features / Security

    • Hardened Apple Sign‑In: safer token validation and client secret generation; web login hidden when config incomplete.
    • HTML exports and emailed exports now escape content and include a restrictive Content‑Security‑Policy.
  • Bug Fixes / Permissions

    • File downloads limited to file owner; stricter upload access and deletion authorization.
    • Fingerprint API now requires manage‑cloud permission (403 when unauthorized).
  • Tests

    • Added coverage for Apple auth, file access/deletion, and export HTML safety.

You can see below a preview of the release change log:

8.5.1

Engine versions

  • Node: 22.22.3
  • Deno: 2.3.1
  • MongoDB: 8.0
  • Apps-Engine: 1.63.0

Patch Changes

@dionisio-bot

dionisio-bot Bot commented Jun 11, 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
  • 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

@coderabbitai

coderabbitai Bot commented Jun 11, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

Walkthrough

Replaces Apple JWT handling and client-secret signing with node:crypto, updates Apple login wiring and tests, enforces owner-only file downloads and room-directive file context, tightens deleteFileMessage auth with tests, requires manage-cloud on /api/v1/fingerprint with tests, and escapes HTML/CSP in exports and emails.

Changes

Apple OAuth changes

Layer / File(s) Summary
Apple JWT verification & API
apps/meteor/app/apple/lib/handleIdentityToken.ts, apps/meteor/app/apple/lib/handleIdentityToken.spec.ts
Fetches/caches Apple JWKS, validates JWT parts/exp/iss/aud, verifies RSA-SHA256 signatures with node:crypto, changes handleIdentityToken to accept clientId and return generic payload, and adds tests for audience/kid/expiration flows.
Apple client secret generation & service registration
apps/meteor/app/apple/server/appleOauthRegisterService.ts
Generates Apple client secret JWT using node:crypto (createPrivateKey + sign), normalizes settings input, wraps generation/upsert in try/catch, and sets showButton based on completeness/errors.
Apple login handler wiring & tests
apps/meteor/app/apple/server/AppleCustomOAuth.ts, apps/meteor/app/apple/server/loginHandler.ts, apps/meteor/app/apple/server/loginHandler.spec.ts, apps/meteor/jest.config.ts, apps/meteor/definition/externals/meteor/accounts-base.d.ts
Passes configured clientId into handleIdentityToken, reads only identityToken/fullName from requests, treats missing/undefined userId as cancellation, adds unit tests validating email handling and clientId use, adds Apple spec globs to Jest, and updates externals typing to async return.

File upload, room directives, and livechat

Layer / File(s) Summary
File store onRead enforcement & request auth
apps/meteor/app/file-upload/server/lib/FileUpload.ts, apps/meteor/app/file-upload/server/lib/FileUpload.spec.ts
Enforces owner-only downloads in UserDataFiles.onRead; adds getRequestUserId to resolve rc_uid/rc_token from query/cookies/headers and validate login token; adds tests for credential permutations and onRead behavior.
Room directives signature and livechat checks
apps/meteor/definition/IRoomTypeConfig.ts, apps/meteor/server/lib/rooms/roomCoordinator.ts, apps/meteor/server/lib/rooms/roomTypes/livechat.ts
Adds IUpload type and extends canAccessUploadedFile to accept optional file; updates RoomCoordinator and livechat checks to require token/rid and ensure file.rid matches rc_rid before allowing access; adjusts FileUpload to pass file into directives and includes tests.

deleteFileMessage method & tests

Layer / File(s) Summary
Server method implementation
apps/meteor/server/methods/deleteFileMessage.ts
Requires authenticated user, validates fileID, prefers message-deletion path when message exists, otherwise loads user and upload and authorizes via Upload.canDeleteFile before deleting the upload.
Unit tests for deleteFileMessage
apps/meteor/tests/unit/server/methods/deleteFileMessage.spec.ts
Proxyquire/sinon tests covering unauthenticated rejection, message-associated deletion, orphan-file/no-user, missing upload, unauthorized rejection, and successful upload deletion paths.

Fingerprint API permission and tests

Layer / File(s) Summary
API permission + tests
apps/meteor/app/api/server/v1/misc.ts, apps/meteor/tests/end-to-end/api/miscellaneous.ts
Adds permissionsRequired: ['manage-cloud'] to POST /api/v1/fingerprint, adds 403 response validation via validateForbiddenErrorResponse, and adds end-to-end tests asserting 401/403/200 scenarios.
Patch bump Changesets entries
.changeset/bump-patch-1781187995605.md, .changeset/rich-bananas-shine.md, .changeset/salty-suits-strive.md
Three Changeset files added declaring patch bumps for @rocket.chat/meteor (one marked security hotfix and one noting the fingerprint permission fix).

Export HTML escaping & email

Layer / File(s) Summary
HTML export and email escaping
apps/meteor/server/lib/dataExport/exportRoomMessagesToFile.ts, apps/meteor/server/lib/dataExport/processDataDownloads.ts, apps/meteor/server/lib/dataExport/sendViaEmail.ts, apps/meteor/tests/unit/server/lib/dataExport/exportRoomMessagesToFile.spec.ts
Adds escapeHTML usage for message bodies, usernames, and attachment text in HTML exports and email bodies, writes CSP meta tags in HTML exports, escapes attachment URLs/titles, and adds unit tests confirming escaping and that JSON exports remain unescaped.

Sequence Diagram

sequenceDiagram
  participant Client
  participant Server_handleIdentityToken
  participant AppleJWKS
  participant nodeCrypto
  Client->>Server_handleIdentityToken: POST identityToken + clientId
  Server_handleIdentityToken->>AppleJWKS: GET /.well-known/jwks.json (cached / refresh)
  AppleJWKS-->>Server_handleIdentityToken: JWK set
  Server_handleIdentityToken->>nodeCrypto: createPublicKey + verify RSA-SHA256(signature)
  nodeCrypto-->>Server_handleIdentityToken: verification result
  Server_handleIdentityToken-->>Client: decoded payload / service data
Loading

Estimated code review effort:
🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs:

Suggested labels:
area: authentication

Suggested reviewers:

  • ricardogarim
  • sampaiodiego
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 16.67% 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
Title check ✅ Passed The pull request title 'Release 8.5.1' directly and concisely summarizes the main purpose of the changeset, which is a release version bump.
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.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

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


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.

@changeset-bot

changeset-bot Bot commented Jun 11, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 01a1846

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 4 packages
Name Type
@rocket.chat/meteor Patch
@rocket.chat/federation-matrix Patch
@rocket.chat/core-typings Patch
@rocket.chat/rest-typings Patch

Not sure what this means? Click here to learn what changesets are.

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

@cubic-dev-ai cubic-dev-ai 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.

No issues found across 2 files

Re-trigger cubic

Co-authored-by: Julio Araujo <julio.araujo@rocket.chat>
Co-authored-by: Matheus Cardoso <matheus@cardo.so>
@julio-rocketchat
julio-rocketchat requested a review from a team as a code owner June 11, 2026 16:42

@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

roomCoordinator
.getRoomDirectives(rc_room_type)
.canAccessUploadedFile({ rc_uid: rc_uid || '', rc_rid: rc_rid || '', rc_token: rc_token || '' });
.canAccessUploadedFile({ rc_uid: rc_uid || '', rc_rid: rc_rid || '', rc_token: rc_token || '' }, file);

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 Deleted Files in Messages with Keep History Enabled are Accessible to Unauthorized Users

When a user deletes a chat message containing an uploaded file and the server has Message_KeepHistory enabled (a common configuration for compliance and auditing), the file is not deleted from the storage. Instead, the message is hidden/archived, and the associated file records in the Uploads collection are marked with _hidden: true.

However, the file access authorization function FileUpload.requestCanAccessFiles only checks if the requesting user has access to the room (file.rid) where the file was posted. It completely omits checking whether the file's _hidden attribute is set to true.

Consequently, any user who is a member of the room (or any user if the room is public) can still successfully request and download the "deleted" file if they possess its file ID or direct URL (e.g., from browser history, cached client logs, or previous notifications), bypassing the deletion boundary.

Steps to Reproduce
  1. User A uploads a sensitive file to a private room.
  2. User A deletes the message containing the file. The file is marked as _hidden: true in the database.
  3. User B (another member of the private room) uses the previously cached file URL to download the file:
curl -H "X-User-Id: <user_b_id>" -H "X-Auth-Token: <user_b_token>" "https://<rocketchat-domain>/file-upload/<file_id>/<file_name>"

The server responds with 200 OK and serves the file, despite it being deleted.

Fix with AI

Open in Cursor Open in Claude

A security vulnerability was found by Hacktron.

File: apps/meteor/app/file-upload/server/lib/FileUpload.ts
Lines: 499
Severity: medium

Vulnerability: Deleted Files in Messages with Keep History Enabled are Accessible to Unauthorized Users

Description:
When a user deletes a chat message containing an uploaded file and the server has `Message_KeepHistory` enabled (a common configuration for compliance and auditing), the file is not deleted from the storage. Instead, the message is hidden/archived, and the associated file records in the `Uploads` collection are marked with `_hidden: true`.

However, the file access authorization function `FileUpload.requestCanAccessFiles` only checks if the requesting user has access to the room (`file.rid`) where the file was posted. It completely omits checking whether the file's `_hidden` attribute is set to `true`. 

Consequently, any user who is a member of the room (or any user if the room is public) can still successfully request and download the "deleted" file if they possess its file ID or direct URL (e.g., from browser history, cached client logs, or previous notifications), bypassing the deletion boundary.

Proof of Concept:
1. User A uploads a sensitive file to a private room.
2. User A deletes the message containing the file. The file is marked as `_hidden: true` in the database.
3. User B (another member of the private room) uses the previously cached file URL to download the file:

```bash
curl -H "X-User-Id: <user_b_id>" -H "X-Auth-Token: <user_b_token>" "https://<rocketchat-domain>/file-upload/<file_id>/<file_name>"
```

The server responds with `200 OK` and serves the file, despite it being deleted.

Affected Code:
- [deleteMessage.ts:65](https://github.com/RocketChat/Rocket.Chat/blob/develop/apps/meteor/app/lib/server/functions/deleteMessage.ts#L65): When a message is deleted and `keepHistory` is enabled, the associated files are marked as hidden: `await Uploads.updateOne({ _id: file._id }, { $set: { _hidden: true } })`.
- [FileUpload.ts:478](https://github.com/RocketChat/Rocket.Chat/blob/develop/apps/meteor/app/file-upload/server/lib/FileUpload.ts#L478): When a user requests a file, `requestCanAccessFiles` is called to authorize the request.
- [FileUpload.ts:560](https://github.com/RocketChat/Rocket.Chat/blob/develop/apps/meteor/app/file-upload/server/lib/FileUpload.ts#L560): `requestCanAccessFiles` checks room access via `canAccessRoomIdAsync(file.rid, user._id)`.
- The function never checks if the file has `_hidden: true`, allowing any user with access to the room to download the deleted file.

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

@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.

Actionable comments posted: 3

🧹 Nitpick comments (1)
apps/meteor/app/apple/lib/handleIdentityToken.ts (1)

127-132: ⚡ Quick win

Verify RSA-SHA256 algorithm name is correct for Apple's RS256 JWTs.

Apple uses RS256 (RSASSA-PKCS1-v1_5 with SHA-256). Node's crypto.verify() accepts 'RSA-SHA256' as an alias for this algorithm, which is correct. However, there's no validation that the JWT header's alg field actually specifies RS256 before proceeding with verification.

A token with alg: 'none' or a different algorithm would still be verified using RSA-SHA256, which could lead to unexpected behavior if Apple ever rotates to different key types.

🔒 Proposed fix to validate algorithm
 	const header = JSON.parse(decodeBase64Url(headerB64));
 	const payload = JSON.parse(decodeBase64Url(payloadB64)) as AppleJWTPayload;

+	if (header.alg !== 'RS256') {
+		console.error(`Unexpected JWT algorithm: ${header.alg}. Expected RS256`);
+		return null;
+	}
+
 	const nowInSeconds = Math.floor(Date.now() / 1000);
🤖 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/app/apple/lib/handleIdentityToken.ts` around lines 127 - 132,
Before calling crypto.verify(...) to validate the signature, explicitly check
the JWT header's "alg" field equals "RS256" and reject the token otherwise;
update the code in handleIdentityToken (the code that parses the JWT header from
headerB64/payloadB64) to read the header's alg and throw or return an error if
alg !== 'RS256', then only proceed to call verify('RSA-SHA256', ...) for
accepted tokens.
🤖 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.

Inline comments:
In `@apps/meteor/app/apple/lib/handleIdentityToken.spec.ts`:
- Around line 32-44: The test currently fails signature verification before
audience checks; to fix it, update the test for handleIdentityToken so the JWKS
endpoint is mocked to return a public key whose kid matches 'mock-key-id' and
ensure the token is signed with the corresponding private key (instead of using
'dummySignature') so signature verification passes, then assert that
handleIdentityToken rejects due to the wrong aud (mockClientId) — reference the
mockToken construction, toBase64Url usage, and handleIdentityToken invocation
when locating where to add the JWKS mock and valid signature generation.

In `@apps/meteor/app/apple/lib/handleIdentityToken.ts`:
- Around line 73-74: The code in handleIdentityToken directly JSON.parse()s the
decoded header and payload (headerB64/payloadB64 via decodeBase64Url) which will
throw an unhandled parse error for malformed tokens; wrap each JSON.parse call
in a try/catch and throw a clear, descriptive Error (e.g., "Invalid JWT header
JSON" or "Invalid JWT payload JSON" including the raw decoded string or token
part) so the outer error handler can distinguish parse failures from
signature/validation errors and log/report them appropriately.

In `@apps/meteor/server/lib/rooms/roomTypes/livechat.ts`:
- Around line 26-28: The current roomName implementation casts the result to
string which can mislead if room.name, room.fname, and (room as any).label are
all undefined; update the roomName function to return the proper type by either
removing the explicit "as string" cast so it returns Promise<string | undefined>
or provide a safe fallback (e.g. append "|| ''") to guarantee a string; modify
the return in the roomName method accordingly to match the
IRoomTypeServerDirectives.roomName signature and avoid returning a misleading
casted value.

---

Nitpick comments:
In `@apps/meteor/app/apple/lib/handleIdentityToken.ts`:
- Around line 127-132: Before calling crypto.verify(...) to validate the
signature, explicitly check the JWT header's "alg" field equals "RS256" and
reject the token otherwise; update the code in handleIdentityToken (the code
that parses the JWT header from headerB64/payloadB64) to read the header's alg
and throw or return an error if alg !== 'RS256', then only proceed to call
verify('RSA-SHA256', ...) for accepted tokens.
🪄 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: a95a9ee0-83dd-4777-a64a-9ae8fe23de8e

📥 Commits

Reviewing files that changed from the base of the PR and between b7f28c3 and b3c635d.

📒 Files selected for processing (16)
  • .changeset/rich-bananas-shine.md
  • apps/meteor/app/apple/lib/handleIdentityToken.spec.ts
  • apps/meteor/app/apple/lib/handleIdentityToken.ts
  • apps/meteor/app/apple/server/AppleCustomOAuth.ts
  • apps/meteor/app/apple/server/appleOauthRegisterService.ts
  • apps/meteor/app/apple/server/loginHandler.spec.ts
  • apps/meteor/app/apple/server/loginHandler.ts
  • apps/meteor/app/file-upload/server/lib/FileUpload.spec.ts
  • apps/meteor/app/file-upload/server/lib/FileUpload.ts
  • apps/meteor/definition/IRoomTypeConfig.ts
  • apps/meteor/definition/externals/meteor/accounts-base.d.ts
  • apps/meteor/jest.config.ts
  • apps/meteor/server/lib/rooms/roomCoordinator.ts
  • apps/meteor/server/lib/rooms/roomTypes/livechat.ts
  • apps/meteor/server/methods/deleteFileMessage.ts
  • apps/meteor/tests/unit/server/methods/deleteFileMessage.spec.ts
✅ Files skipped from review due to trivial changes (1)
  • .changeset/rich-bananas-shine.md
📜 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). (5)
  • GitHub Check: 📦 Build Packages
  • GitHub Check: update-pr
  • GitHub Check: CodeQL-Build
  • GitHub Check: CodeQL-Build
  • GitHub Check: Hacktron Security Check
🧰 Additional context used
📓 Path-based instructions (2)
**/*.{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/jest.config.ts
  • apps/meteor/server/lib/rooms/roomCoordinator.ts
  • apps/meteor/definition/externals/meteor/accounts-base.d.ts
  • apps/meteor/app/apple/server/AppleCustomOAuth.ts
  • apps/meteor/server/lib/rooms/roomTypes/livechat.ts
  • apps/meteor/definition/IRoomTypeConfig.ts
  • apps/meteor/app/file-upload/server/lib/FileUpload.spec.ts
  • apps/meteor/app/apple/server/loginHandler.ts
  • apps/meteor/tests/unit/server/methods/deleteFileMessage.spec.ts
  • apps/meteor/server/methods/deleteFileMessage.ts
  • apps/meteor/app/apple/lib/handleIdentityToken.spec.ts
  • apps/meteor/app/file-upload/server/lib/FileUpload.ts
  • apps/meteor/app/apple/server/loginHandler.spec.ts
  • apps/meteor/app/apple/server/appleOauthRegisterService.ts
  • apps/meteor/app/apple/lib/handleIdentityToken.ts
**/*.spec.ts

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

**/*.spec.ts: Use descriptive test names that clearly communicate expected behavior in Playwright tests
Use .spec.ts extension for test files (e.g., login.spec.ts)

Files:

  • apps/meteor/app/file-upload/server/lib/FileUpload.spec.ts
  • apps/meteor/tests/unit/server/methods/deleteFileMessage.spec.ts
  • apps/meteor/app/apple/lib/handleIdentityToken.spec.ts
  • apps/meteor/app/apple/server/loginHandler.spec.ts
🧠 Learnings (6)
📚 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/jest.config.ts
  • apps/meteor/server/lib/rooms/roomCoordinator.ts
  • apps/meteor/definition/externals/meteor/accounts-base.d.ts
  • apps/meteor/app/apple/server/AppleCustomOAuth.ts
  • apps/meteor/server/lib/rooms/roomTypes/livechat.ts
  • apps/meteor/definition/IRoomTypeConfig.ts
  • apps/meteor/app/file-upload/server/lib/FileUpload.spec.ts
  • apps/meteor/app/apple/server/loginHandler.ts
  • apps/meteor/tests/unit/server/methods/deleteFileMessage.spec.ts
  • apps/meteor/server/methods/deleteFileMessage.ts
  • apps/meteor/app/apple/lib/handleIdentityToken.spec.ts
  • apps/meteor/app/file-upload/server/lib/FileUpload.ts
  • apps/meteor/app/apple/server/loginHandler.spec.ts
  • apps/meteor/app/apple/server/appleOauthRegisterService.ts
  • apps/meteor/app/apple/lib/handleIdentityToken.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/jest.config.ts
  • apps/meteor/server/lib/rooms/roomCoordinator.ts
  • apps/meteor/definition/externals/meteor/accounts-base.d.ts
  • apps/meteor/app/apple/server/AppleCustomOAuth.ts
  • apps/meteor/server/lib/rooms/roomTypes/livechat.ts
  • apps/meteor/definition/IRoomTypeConfig.ts
  • apps/meteor/app/file-upload/server/lib/FileUpload.spec.ts
  • apps/meteor/app/apple/server/loginHandler.ts
  • apps/meteor/tests/unit/server/methods/deleteFileMessage.spec.ts
  • apps/meteor/server/methods/deleteFileMessage.ts
  • apps/meteor/app/apple/lib/handleIdentityToken.spec.ts
  • apps/meteor/app/file-upload/server/lib/FileUpload.ts
  • apps/meteor/app/apple/server/loginHandler.spec.ts
  • apps/meteor/app/apple/server/appleOauthRegisterService.ts
  • apps/meteor/app/apple/lib/handleIdentityToken.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/jest.config.ts
  • apps/meteor/server/lib/rooms/roomCoordinator.ts
  • apps/meteor/definition/externals/meteor/accounts-base.d.ts
  • apps/meteor/app/apple/server/AppleCustomOAuth.ts
  • apps/meteor/server/lib/rooms/roomTypes/livechat.ts
  • apps/meteor/definition/IRoomTypeConfig.ts
  • apps/meteor/app/file-upload/server/lib/FileUpload.spec.ts
  • apps/meteor/app/apple/server/loginHandler.ts
  • apps/meteor/tests/unit/server/methods/deleteFileMessage.spec.ts
  • apps/meteor/server/methods/deleteFileMessage.ts
  • apps/meteor/app/apple/lib/handleIdentityToken.spec.ts
  • apps/meteor/app/file-upload/server/lib/FileUpload.ts
  • apps/meteor/app/apple/server/loginHandler.spec.ts
  • apps/meteor/app/apple/server/appleOauthRegisterService.ts
  • apps/meteor/app/apple/lib/handleIdentityToken.ts
📚 Learning: 2026-02-24T19:22:48.358Z
Learnt from: juliajforesti
Repo: RocketChat/Rocket.Chat PR: 38493
File: apps/meteor/tests/e2e/omnichannel/omnichannel-send-pdf-transcript.spec.ts:66-67
Timestamp: 2026-02-24T19:22:48.358Z
Learning: In Playwright end-to-end tests (e.g., under apps/meteor/tests/e2e/...), prefer locating elements by translated text (getByText) and ARIA roles (getByRole) over data-qa attributes. If translation values change, update the corresponding test locators accordingly. Never use data-qa locators. This guideline applies to all Playwright e2e test specs in the repository and helps keep tests robust to UI text changes and accessible semantics.

Applied to files:

  • apps/meteor/app/file-upload/server/lib/FileUpload.spec.ts
  • apps/meteor/tests/unit/server/methods/deleteFileMessage.spec.ts
  • apps/meteor/app/apple/lib/handleIdentityToken.spec.ts
  • apps/meteor/app/apple/server/loginHandler.spec.ts
📚 Learning: 2026-03-06T18:10:15.268Z
Learnt from: tassoevan
Repo: RocketChat/Rocket.Chat PR: 39397
File: packages/gazzodown/src/code/CodeBlock.spec.tsx:47-68
Timestamp: 2026-03-06T18:10:15.268Z
Learning: In tests (especially those using testing-library/dom/jsdom) for Rocket.Chat components, the HTML <code> element has an implicit ARIA role of 'code'. Therefore, screen.getByRole('code') or screen.findByRole('code') will locate <code> elements even without a role attribute. Do not flag findByRole('code') as invalid in reviews; prefer using the implicit role instead of adding role="code" unless necessary for accessibility.

Applied to files:

  • apps/meteor/app/file-upload/server/lib/FileUpload.spec.ts
  • apps/meteor/tests/unit/server/methods/deleteFileMessage.spec.ts
  • apps/meteor/app/apple/lib/handleIdentityToken.spec.ts
  • apps/meteor/app/apple/server/loginHandler.spec.ts
📚 Learning: 2026-03-09T18:39:14.020Z
Learnt from: Harxhit
Repo: RocketChat/Rocket.Chat PR: 39476
File: apps/meteor/server/methods/addAllUserToRoom.ts:0-0
Timestamp: 2026-03-09T18:39:14.020Z
Learning: When implementing batch processing in server methods, favor a single data pass to collect both the items and any derived fields needed for validation. Use the same dataset for both validation and processing to avoid races between validation and execution, and document the approach in code comments. Apply this pattern to similar Meteor Rocket.Chat server methods under apps/meteor/server/methods to prevent race conditions and ensure consistent batch behavior.

Applied to files:

  • apps/meteor/server/methods/deleteFileMessage.ts
🔇 Additional comments (34)
apps/meteor/app/apple/lib/handleIdentityToken.ts (2)

160-163: LGTM!


1-66: LGTM!

apps/meteor/app/apple/lib/handleIdentityToken.spec.ts (3)

46-88: LGTM!


90-133: LGTM!


1-30: LGTM!

apps/meteor/app/apple/server/appleOauthRegisterService.ts (4)

49-69: LGTM!


71-123: LGTM!


1-47: LGTM!


24-27: Apple ES256 client secret: ensure the signature is ES256/JWS (JOSE) “plain” P1363 r||s

  • Node’s crypto.sign() for ECDSA commonly yields ASN.1-DER signatures, while ES256/JWS requires the JOSE “plain” P1363 (r||s) format; since the code sets dsaEncoding: 'ieee-p1363', confirm this is honored by the runtime and that the produced signature is the expected 64-byte r||s value before JWT/base64url encoding.
  • sign('sha256', ...) is correct for the SHA-256 digest in ES256 as long as the key is an EC P-256 Apple .p8 and the verifier receives JOSE-format r||s (not DER).
apps/meteor/app/apple/server/AppleCustomOAuth.ts (1)

1-38: LGTM!

apps/meteor/app/apple/server/loginHandler.spec.ts (1)

1-124: LGTM!

apps/meteor/app/apple/server/loginHandler.ts (1)

1-46: LGTM!

apps/meteor/jest.config.ts (1)

53-54: LGTM!

apps/meteor/definition/externals/meteor/accounts-base.d.ts (1)

40-44: Confirm updateOrCreateUserFromExternalService is treated as async in this codebase. apps/meteor/app/apple/server/loginHandler.ts awaits Accounts.updateOrCreateUserFromExternalService(...), and apps/meteor/app/apple/server/loginHandler.spec.ts mocks it with mockResolvedValue(...), so Promise<Record<string, unknown>> matches the repo’s usage. The repo alone doesn’t prove Meteor’s upstream return type.

apps/meteor/app/file-upload/server/lib/FileUpload.ts (3)

100-110: LGTM!


453-476: LGTM!


478-499: LGTM!

apps/meteor/app/file-upload/server/lib/FileUpload.spec.ts (3)

291-359: LGTM!


362-416: LGTM!


418-470: LGTM!

apps/meteor/definition/IRoomTypeConfig.ts (2)

1-11: LGTM!


101-101: LGTM!

apps/meteor/server/lib/rooms/roomCoordinator.ts (2)

2-2: LGTM!


36-38: LGTM!

apps/meteor/server/lib/rooms/roomTypes/livechat.ts (1)

30-38: LGTM!

apps/meteor/server/methods/deleteFileMessage.ts (4)

1-9: LGTM!


20-32: LGTM!


41-54: LGTM!


34-39: Confirm user projection is sufficient for Upload.canDeleteFile permission checksUpload.canDeleteFile calls canDeleteMessageAsync(user, ...) with the projected user, and canDeleteMessageAsync only uses deletingUser._id plus optional deletingUser.username (for read-only-room unmuted checks). It does not read roles/other user fields, so { projection: { username: 1 } } is sufficient for the permission evaluation.

apps/meteor/tests/unit/server/methods/deleteFileMessage.spec.ts (5)

1-63: LGTM!


65-69: LGTM!


71-82: LGTM!


84-99: LGTM!


101-124: LGTM!

Comment on lines +32 to +44
it('should throw an error if the token has the wrong audience', async () => {
const header = toBase64Url({ alg: 'RS256', kid: 'mock-key-id' });
const payload = toBase64Url({
iss: 'https://appleid.apple.com',
aud: 'wrong.client.id',
exp: Math.floor(Date.now() / 1000) + 3600,
sub: 'user123',
});

const mockToken = `${header}.${payload}.dummySignature`;

await expect(handleIdentityToken(mockToken, mockClientId)).rejects.toThrow('identityToken is not a valid Apple JWT or has expired');
});

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 | 🟡 Minor | ⚡ Quick win

Test case may not be testing audience validation as intended.

This test uses 'dummySignature' without mocking the JWKS endpoint. The handleIdentityToken function will fail at signature verification before reaching audience validation, so the error "identityToken is not a valid Apple JWT or has expired" is thrown due to signature failure, not audience mismatch.

To properly test audience validation, the JWKS mock should be set up to return the test public key so signature verification passes, then audience validation fails.

🧪 Proposed fix to properly test audience validation
 	it('should throw an error if the token has the wrong audience', async () => {
-		const header = toBase64Url({ alg: 'RS256', kid: 'mock-key-id' });
-		const payload = toBase64Url({
+		const headerB64 = toBase64Url({ alg: 'RS256', kid: 'mock-key-id' });
+		const payloadB64 = toBase64Url({
 			iss: 'https://appleid.apple.com',
 			aud: 'wrong.client.id',
 			exp: Math.floor(Date.now() / 1000) + 3600,
 			sub: 'user123',
 		});

-		const mockToken = `${header}.${payload}.dummySignature`;
+		const signatureBytes = sign('RSA-SHA256', Buffer.from(`${headerB64}.${payloadB64}`), privateKey);
+		const signatureB64 = signatureBytes.toString('base64url');
+		const mockToken = `${headerB64}.${payloadB64}.${signatureB64}`;
+
+		if (!jwkPublicKey.n || !jwkPublicKey.e) {
+			throw new Error('Generated test key is missing modulus or exponent');
+		}
+
+		const mockJwksPayload = {
+			keys: [{ kty: 'RSA', kid: 'mock-key-id', use: 'sig', alg: 'RS256', n: jwkPublicKey.n, e: jwkPublicKey.e }],
+		};
+
+		jest.mocked(serverFetch).mockResolvedValue(
+			new Response(JSON.stringify(mockJwksPayload), { status: 200, headers: { 'Content-Type': 'application/json' } }),
+		);

 		await expect(handleIdentityToken(mockToken, mockClientId)).rejects.toThrow('identityToken is not a valid Apple JWT or has expired');
 	});
🤖 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/app/apple/lib/handleIdentityToken.spec.ts` around lines 32 - 44,
The test currently fails signature verification before audience checks; to fix
it, update the test for handleIdentityToken so the JWKS endpoint is mocked to
return a public key whose kid matches 'mock-key-id' and ensure the token is
signed with the corresponding private key (instead of using 'dummySignature') so
signature verification passes, then assert that handleIdentityToken rejects due
to the wrong aud (mockClientId) — reference the mockToken construction,
toBase64Url usage, and handleIdentityToken invocation when locating where to add
the JWKS mock and valid signature generation.

Comment on lines +73 to +74
const header = JSON.parse(decodeBase64Url(headerB64));
const payload = JSON.parse(decodeBase64Url(payloadB64)) as AppleJWTPayload;

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 | 🟡 Minor | ⚡ Quick win

Malformed JWT header/payload will throw unhandled JSON.parse error.

If decodeBase64Url returns invalid JSON (e.g., corrupted or tampered token), JSON.parse throws and the error propagates without a clear message. The outer handleIdentityToken catches errors but with a generic message that doesn't distinguish parse failures from signature failures.

🛡️ Proposed fix to handle parse errors explicitly
 async function verifyAppleJWT(
 	headerB64: string,
 	payloadB64: string,
 	signatureB64: string,
 	clientId: string,
 ): Promise<AppleJWTPayload | null> {
-	const header = JSON.parse(decodeBase64Url(headerB64));
-	const payload = JSON.parse(decodeBase64Url(payloadB64)) as AppleJWTPayload;
+	let header: { alg?: string; kid?: string };
+	let payload: AppleJWTPayload;
+	try {
+		header = JSON.parse(decodeBase64Url(headerB64));
+		payload = JSON.parse(decodeBase64Url(payloadB64)) as AppleJWTPayload;
+	} catch {
+		console.error('Failed to parse JWT header or payload');
+		return null;
+	}
🤖 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/app/apple/lib/handleIdentityToken.ts` around lines 73 - 74, The
code in handleIdentityToken directly JSON.parse()s the decoded header and
payload (headerB64/payloadB64 via decodeBase64Url) which will throw an unhandled
parse error for malformed tokens; wrap each JSON.parse call in a try/catch and
throw a clear, descriptive Error (e.g., "Invalid JWT header JSON" or "Invalid
JWT payload JSON" including the raw decoded string or token part) so the outer
error handler can distinguish parse failures from signature/validation errors
and log/report them appropriately.

Comment on lines 26 to 28
async roomName(room, _userId?) {
return room.name || room.fname || (room as any).label;
return (room.name || room.fname || (room as any).label) as string;
},

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 | 🟡 Minor | ⚡ Quick win

Type cast may be misleading.

The explicit as string cast could return undefined if all three properties (room.name, room.fname, room.label) are undefined. Since IRoomTypeServerDirectives.roomName returns Promise<string | undefined>, consider either removing the cast or adding a fallback like || '' to ensure a string is always returned.

🔧 Suggested fix
 async roomName(room, _userId?) {
-  return (room.name || room.fname || (room as any).label) as string;
+  return (room.name || room.fname || (room as any).label || '') as string;
 },
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
async roomName(room, _userId?) {
return room.name || room.fname || (room as any).label;
return (room.name || room.fname || (room as any).label) as string;
},
async roomName(room, _userId?) {
return (room.name || room.fname || (room as any).label || '') as string;
},
🤖 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/server/lib/rooms/roomTypes/livechat.ts` around lines 26 - 28, The
current roomName implementation casts the result to string which can mislead if
room.name, room.fname, and (room as any).label are all undefined; update the
roomName function to return the proper type by either removing the explicit "as
string" cast so it returns Promise<string | undefined> or provide a safe
fallback (e.g. append "|| ''") to guarantee a string; modify the return in the
roomName method accordingly to match the IRoomTypeServerDirectives.roomName
signature and avoid returning a misleading casted value.

@codecov

codecov Bot commented Jun 11, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 77.83251% with 90 lines in your changes missing coverage. Please review.
✅ Project coverage is 69.93%. Comparing base (d0230e1) to head (01a1846).

Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##           master   #40893      +/-   ##
==========================================
- Coverage   69.95%   69.93%   -0.02%     
==========================================
  Files        3328     3330       +2     
  Lines      126813   127220     +407     
  Branches    22143    22121      -22     
==========================================
+ Hits        88706    88976     +270     
- Misses      34805    34931     +126     
- Partials     3302     3313      +11     
Flag Coverage Δ
e2e 59.26% <26.00%> (-0.08%) ⬇️
e2e-api 46.13% <9.09%> (-0.02%) ⬇️
unit 70.01% <81.55%> (-0.02%) ⬇️

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.

dionisio-bot Bot and others added 5 commits June 11, 2026 21:56
Co-authored-by: Ricardo Garim <rswarovsky@gmail.com>
Co-authored-by: Julio Araujo <julio.araujo@rocket.chat>
Co-authored-by: Julio Araujo <julio.araujo@rocket.chat>
Co-authored-by: Yasmim Nagat <117310290+yasnagat@users.noreply.github.com>
Co-authored-by: Julio Araujo <julio.araujo@rocket.chat>
Co-authored-by: Julio Araujo <julio.araujo@rocket.chat>
dionisio-bot Bot and others added 3 commits June 12, 2026 12:13
Co-authored-by: Julio Araujo <julio.araujo@rocket.chat>
Co-authored-by: Julio Araujo <julio.araujo@rocket.chat>
Co-authored-by: Julio Araujo <julio.araujo@rocket.chat>
@julio-rocketchat
julio-rocketchat requested a review from a team as a code owner June 12, 2026 12:20
@julio-rocketchat
julio-rocketchat requested review from a team as code owners June 12, 2026 21:12

@cubic-dev-ai cubic-dev-ai 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.

3 issues found across 34 files (changes from recent commits).

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="apps/meteor/client/hooks/useDecryptedMessage.ts">

<violation number="1" location="apps/meteor/client/hooks/useDecryptedMessage.ts:23">
P2: Attachment description overwrites message text when both are present due to missing early return</violation>
</file>

<file name="apps/meteor/app/livechat/server/lib/sendTranscript.ts">

<violation number="1" location="apps/meteor/app/livechat/server/lib/sendTranscript.ts:120">
P0: The return value of `escapeHtml(messageContent)` is discarded, leaving the attachment description unescaped. This allows HTML injection into the transcript HTML output. The fix is to reassign: `messageContent = escapeHtml(messageContent);`.</violation>
</file>

<file name="apps/meteor/server/services/messages/hooks/BeforeSaveMarkdownParser.ts">

<violation number="1" location="apps/meteor/server/services/messages/hooks/BeforeSaveMarkdownParser.ts:42">
P2: Attachment description parsing is not guarded by messageMaxParseLength, unlike message.msg parsing. Long attachment descriptions could cause the same performance issues the limit was designed to prevent.</violation>
</file>

Tip: Review your code locally with the cubic CLI to iterate faster.

Re-trigger cubic


if (message.attachments && message.attachments?.length > 0) {
messageContent = message.attachments[0].description || '';
escapeHtml(messageContent);

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.

P0: The return value of escapeHtml(messageContent) is discarded, leaving the attachment description unescaped. This allows HTML injection into the transcript HTML output. The fix is to reassign: messageContent = escapeHtml(messageContent);.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At apps/meteor/app/livechat/server/lib/sendTranscript.ts, line 120:

<comment>The return value of `escapeHtml(messageContent)` is discarded, leaving the attachment description unescaped. This allows HTML injection into the transcript HTML output. The fix is to reassign: `messageContent = escapeHtml(messageContent);`.</comment>

<file context>
@@ -108,14 +108,17 @@ export async function sendTranscript({
 
 		if (message.attachments && message.attachments?.length > 0) {
+			messageContent = message.attachments[0].description || '';
+			escapeHtml(messageContent);
+
 			for await (const attachment of message.attachments) {
</file context>
Suggested change
escapeHtml(messageContent);
messageContent = escapeHtml(messageContent);


if (decryptedMsg.attachments && decryptedMsg.attachments.length > 0) {
setDecryptedMessage(t('Message_with_attachment'));
if (decryptedMsg.attachments && decryptedMsg.attachments?.length > 0) {

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.

P2: Attachment description overwrites message text when both are present due to missing early return

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At apps/meteor/client/hooks/useDecryptedMessage.ts, line 23:

<comment>Attachment description overwrites message text when both are present due to missing early return</comment>

<file context>
@@ -18,11 +18,14 @@ export const useDecryptedMessage = (message: IMessage): string => {
 
-			if (decryptedMsg.attachments && decryptedMsg.attachments.length > 0) {
-				setDecryptedMessage(t('Message_with_attachment'));
+			if (decryptedMsg.attachments && decryptedMsg.attachments?.length > 0) {
+				if (decryptedMsg.attachments[0].description) {
+					setDecryptedMessage(decryptedMsg.attachments[0].description);
</file context>

message.md = parse(message.msg, config);
}

if (message.attachments?.[0]?.description) {

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.

P2: Attachment description parsing is not guarded by messageMaxParseLength, unlike message.msg parsing. Long attachment descriptions could cause the same performance issues the limit was designed to prevent.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At apps/meteor/server/services/messages/hooks/BeforeSaveMarkdownParser.ts, line 42:

<comment>Attachment description parsing is not guarded by messageMaxParseLength, unlike message.msg parsing. Long attachment descriptions could cause the same performance issues the limit was designed to prevent.</comment>

<file context>
@@ -38,6 +38,10 @@ export class BeforeSaveMarkdownParser {
 				message.md = parse(message.msg, config);
 			}
+
+			if (message.attachments?.[0]?.description) {
+				message.attachments[0].descriptionMd = parse(message.attachments[0].description, config);
+			}
</file context>

@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

Comment on lines +198 to +199
firstAttachment.description =
typeof firstAttachment.description === 'string' ? emojione.shortnameToUnicode(firstAttachment.description) : undefined;

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 Shared Message Object Mutation in sendNotification Suppresses Attachment Notifications for Subsequent Users

In sendNotificationsOnMessage.ts, the server aggregates all subscriptions that should receive notifications (desktop, mobile, email) and loops over them using subscriptions.forEach. For each subscription, it calls sendNotification passing the shared message object by reference.

Inside sendNotification, if email notifications are enabled and the receiver has a verified email, the code attempts to format the first attachment of the message. To do this, it calls message.attachments.shift(), which directly mutates the shared message.attachments array of the message object.

Because the message object is passed by reference and shared across all subscriptions in the loop, once message.attachments.shift() is called for one subscription, the first attachment is permanently removed from the message object in memory. Consequently, any subsequent subscriptions in the loop that are processed afterwards will receive notifications (whether desktop, mobile, or email) with missing or corrupted attachments.

An attacker can exploit this behavior to selectively suppress attachment notifications for other users in a room by ensuring they receive an email notification first, thereby hiding the attachment details from subsequent notifications.

Steps to Reproduce
  1. Create a channel with multiple users.
  2. Ensure User A has email notifications enabled and a verified email.
  3. Ensure User B has desktop/mobile notifications enabled.
  4. Send a message with an attachment.
  5. In the backend, sendMessageNotifications is triggered.
  6. User A's subscription is processed, triggering sendNotification which calls message.attachments.shift().
  7. User B's subscription is processed next. Since message.attachments has been mutated, User B's notification (desktop/mobile) is sent without the attachment details.
Fix with AI

Open in Cursor Open in Claude

A security vulnerability was found by Hacktron.

File: apps/meteor/app/lib/server/lib/sendNotificationsOnMessage.ts
Lines: 198-199
Severity: medium

Vulnerability: Shared Message Object Mutation in sendNotification Suppresses Attachment Notifications for Subsequent Users

Description:
In `sendNotificationsOnMessage.ts`, the server aggregates all subscriptions that should receive notifications (desktop, mobile, email) and loops over them using `subscriptions.forEach`. For each subscription, it calls `sendNotification` passing the shared `message` object by reference.

Inside `sendNotification`, if email notifications are enabled and the receiver has a verified email, the code attempts to format the first attachment of the message. To do this, it calls `message.attachments.shift()`, which directly mutates the shared `message.attachments` array of the `message` object.

Because the `message` object is passed by reference and shared across all subscriptions in the loop, once `message.attachments.shift()` is called for one subscription, the first attachment is permanently removed from the `message` object in memory. Consequently, any subsequent subscriptions in the loop that are processed afterwards will receive notifications (whether desktop, mobile, or email) with missing or corrupted attachments.

An attacker can exploit this behavior to selectively suppress attachment notifications for other users in a room by ensuring they receive an email notification first, thereby hiding the attachment details from subsequent notifications.

Proof of Concept:
1. Create a channel with multiple users.
2. Ensure User A has email notifications enabled and a verified email.
3. Ensure User B has desktop/mobile notifications enabled.
4. Send a message with an attachment.
5. In the backend, `sendMessageNotifications` is triggered.
6. User A's subscription is processed, triggering `sendNotification` which calls `message.attachments.shift()`.
7. User B's subscription is processed next. Since `message.attachments` has been mutated, User B's notification (desktop/mobile) is sent without the attachment details.

Affected Code:
```typescript
// File: ./Rocket.Chat/apps/meteor/app/lib/server/lib/sendNotificationsOnMessage.ts

export const sendNotification = async ({
	subscription,
	sender,
	hasReplyToThread,
	hasMentionToAll,
	hasMentionToHere,
	message,
	notificationMessage,
	room,
	mentionIds,
	disableAllMessageNotifications,
}: {
...
	if (
		receiver.emails &&
		shouldNotifyEmail({
			disableAllMessageNotifications,
			statusConnection: receiver.statusConnection,
			emailNotifications,
			isHighlighted,
			hasMentionToUser,
			hasMentionToAll,
			hasReplyToThread,
			roomType,
			isThread,
		})
	) {
		const messageWithUnicode = message.msg ? emojione.shortnameToUnicode(message.msg) : message.msg;
		const firstAttachment = message.attachments?.length && message.attachments.shift(); // <--- MUTATION OF SHARED ARRAY

		if (firstAttachment) {
			firstAttachment.description =
				typeof firstAttachment.description === 'string' ? emojione.shortnameToUnicode(firstAttachment.description) : undefined;
			firstAttachment.text = typeof firstAttachment.text === 'string' ? emojione.shortnameToUnicode(firstAttachment.text) : undefined;
		}

		const attachments = firstAttachment ? [firstAttachment, ...(message.attachments ?? [])].filter(Boolean) : [];
...
```

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

@rc-layne

rc-layne Bot commented Jun 12, 2026

Copy link
Copy Markdown

Warning

These are security findings reported by the security scanners configured in Layne. Findings may contain false positives - review them and fix what makes sense.

Layne found 1 high issue in this PR.

View 1 finding(s)
Severity Scanner File Rule Description
🟠 High semgrep apps/meteor/app/apple/lib/handleIdentityToken.ts:42 app.config.semgrep.rules.rocketchat.ssrf-validation-bypass-without-justification SSRF validation is disabled. Ensure the URL is not user-controlled or is restricted to a known-safe allowlist.

@julio-rocketchat

Copy link
Copy Markdown
Member

/layne exception-approve LAYNE-2ddd92cdd5a7448f reason: justification was added to the issue

@rc-layne

rc-layne Bot commented Jun 12, 2026

Copy link
Copy Markdown

✅ Exception recorded for LAYNE-2ddd92cdd5a7448f by @julio-rocketchat: "justification was added to the issue". Re-running scan...

Co-authored-by: dougfabris <devfabris@gmail.com>

@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
HIGH 1

View full scan results

title: file.name,
type: 'file',
description: file?.description,
image_alt: file?.description,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

HIGH Trusting Client-Controlled File Metadata in sendFileMessage Meteor Method

The sendFileMessage Meteor method allows users to send a file message associated with an uploaded file. However, instead of retrieving the file's canonical metadata (such as MIME type, size, and name) from the database record associated with the file ID, the server trusts and uses the client-provided file object properties.

Specifically, in parseFileIntoMessageAttachments (./Rocket.Chat/apps/meteor/app/file-upload/server/methods/sendFileMessage.ts), the server queries the database using { projection: { _id: 1 } }, which explicitly discards all stored file metadata. It then uses the client-provided file.type, file.size, file.identify, file.name, and file.description to construct the message attachments and update the file record in the database.

An attacker can exploit this by first uploading a benign file (e.g., a small image) to obtain a valid file ID, and then invoking sendFileMessage with spoofed metadata (e.g., setting the type to text/html or application/x-msdownload, and renaming the file to a malicious extension). This allows the attacker to bypass file type restrictions, spoof file sizes, and potentially trigger Stored XSS or other client-side vulnerabilities when other users view the message attachment.

Steps to Reproduce

An attacker can call the sendFileMessage Meteor method via DDP with the following arguments:

Meteor.call('sendFileMessage', roomId, null, {
  _id: "valid_file_id_of_uploaded_png",
  name: "<script>alert(1)</script>.html",
  type: "text/html",
  size: 1337,
  identify: { format: "html" }
});

This will bypass server-side file type controls and send a message with a spoofed HTML attachment.

Fix with AI

Open in Cursor Open in Claude

A security vulnerability was found by Hacktron.

File: apps/meteor/app/file-upload/server/methods/sendFileMessage.ts
Lines: 76
Severity: high

Vulnerability: Trusting Client-Controlled File Metadata in sendFileMessage Meteor Method

Description:
The `sendFileMessage` Meteor method allows users to send a file message associated with an uploaded file. However, instead of retrieving the file's canonical metadata (such as MIME type, size, and name) from the database record associated with the file ID, the server trusts and uses the client-provided `file` object properties.

Specifically, in `parseFileIntoMessageAttachments` (`./Rocket.Chat/apps/meteor/app/file-upload/server/methods/sendFileMessage.ts`), the server queries the database using `{ projection: { _id: 1 } }`, which explicitly discards all stored file metadata. It then uses the client-provided `file.type`, `file.size`, `file.identify`, `file.name`, and `file.description` to construct the message attachments and update the file record in the database.

An attacker can exploit this by first uploading a benign file (e.g., a small image) to obtain a valid file ID, and then invoking `sendFileMessage` with spoofed metadata (e.g., setting the type to `text/html` or `application/x-msdownload`, and renaming the file to a malicious extension). This allows the attacker to bypass file type restrictions, spoof file sizes, and potentially trigger Stored XSS or other client-side vulnerabilities when other users view the message attachment.

Proof of Concept:
An attacker can call the `sendFileMessage` Meteor method via DDP with the following arguments:
```javascript
Meteor.call('sendFileMessage', roomId, null, {
  _id: "valid_file_id_of_uploaded_png",
  name: "<script>alert(1)</script>.html",
  type: "text/html",
  size: 1337,
  identify: { format: "html" }
});
```
This will bypass server-side file type controls and send a message with a spoofed HTML attachment.

Affected Code:
- In [sendFileMessage.ts](./Rocket.Chat/apps/meteor/app/file-upload/server/methods/sendFileMessage.ts):
  - Line 41: `const upload = await Uploads.findOneByIdAndUserIdAndRoomId(file._id, user._id, roomId, { projection: { _id: 1 } });`
  - Line 48-53: `const safeMetadata = { ... };` (updates name, description, typeGroup, content from client)
  - Line 61-70: `const files: FileProp[] = [ { _id: file._id, name: file.name || '', type: file.type || 'file', size: file.size || 0, ... } ];` (uses client-provided type, size, name)
  - Line 73-83: `const attachment: FileAttachmentProps = { ... image_type: file.type as string, image_size: file.size, ... }`

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

@rocketchat-github-ci
rocketchat-github-ci merged commit 01a1846 into master Jun 15, 2026
48 of 50 checks passed
@rocketchat-github-ci
rocketchat-github-ci deleted the release-8.5.1 branch June 15, 2026 22:08
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