Skip to content

Conversation

@ricardogarim
Copy link
Contributor

@ricardogarim ricardogarim commented Oct 10, 2025

As per FDR-169, this PR adds the ability to send and receive user name changes in federated rooms.

Depends on RocketChat/homeserver#291 and RocketChat/homeserver#298.

Screen.Recording.2025-10-29.at.00.53.49.mov

Summary by CodeRabbit:

  • Display name changes are tracked and synchronized to federated rooms; system messages announce display-name updates.
  • New federation API to update a user’s profile/display name across federated rooms.

Summary by CodeRabbit

  • New Features

    • User display name changes are now tracked and displayed in federated rooms as system messages, showing both old and new display names.
  • Refactoring

    • Enhanced Matrix ID construction, validation, and user identification utilities to improve federation consistency and reliability across the platform.

@changeset-bot
Copy link

changeset-bot bot commented Oct 10, 2025

⚠️ No Changeset found

Latest commit: def9191

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

@dionisio-bot
Copy link
Contributor

dionisio-bot bot commented Oct 10, 2025

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
Copy link
Contributor

coderabbitai bot commented Oct 10, 2025

Walkthrough

Adds propagation of user display-name changes to federation: captures prior user state when real name updates, invokes an afterSaveUser callback, introduces Matrix ID helpers and tests, extends FederationMatrix with updateUserProfile, handles member displayname changes, and registers a system message type and translation for display-name changes.

Changes

Cohort / File(s) Summary
Core real-name change hook
apps/meteor/app/lib/server/functions/setRealName.ts
Capture oldUser, make the transaction callback async, and invoke an afterSaveUser(user, oldUser) callback after broadcasting name-change events.
Federation hooks integration
apps/meteor/ee/server/hooks/federation/index.ts
Add native-federation-after-user-profile-update afterSaveUser callback that early-exits on no-change, finds federated subscriptions, calls FederationMatrix.updateUserProfile, and sends per-room user-display-name-changed system messages; note: callback appears inserted twice.
Matrix ID helpers & tests
ee/packages/federation-matrix/src/helpers/matrixId.ts, ee/packages/federation-matrix/src/helpers/matrixId.spec.ts
New helpers: sanitizeForMatrixLocalpart, validateServerNameFormat, constructMatrixId, validateFederatedUsername, getUserMatrixId; comprehensive unit tests for validation, construction, and edge cases.
FederationMatrix refactor & API
ee/packages/federation-matrix/src/FederationMatrix.ts, packages/core-services/src/types/IFederationMatrixService.ts
Replace inline Matrix ID logic with helper usage, pass owner/creator display names to room creation, improve DM invite and leave/kick flows, and add public updateUserProfile(userId: string, displayName: string): Promise<void> (and update service interface).
Member join / displayname handling
ee/packages/federation-matrix/src/events/member.ts
Detect displayname changes for local and federated joins; when changed and user is subscribed, update local DB directly (bypassing loop-prone flows), broadcast watch.users, and post in-room system message.
Message type, registration & i18n
packages/core-typings/src/IMessage/IMessage.ts, packages/message-types/src/registrations/common.ts, packages/i18n/src/locales/en.i18n.json
Add 'user-display-name-changed' message type, register system message rendering that parses `old_name

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant setRealName
    participant Callbacks
    participant FederationHook
    participant FederationMatrix
    participant Room

    Client->>setRealName: request real-name update
    setRealName->>setRealName: capture oldUser
    setRealName->>Room: broadcast user.nameChanged / user.realNameChanged
    setRealName->>Callbacks: onceTransactionCommittedSuccessfully (async)
    Callbacks->>Callbacks: afterSaveUser(user, oldUser)
    Callbacks->>FederationHook: native-federation-after-user-profile-update

    alt displayName changed
        FederationHook->>FederationMatrix: updateUserProfile(userId, newDisplayName)
        loop per federated room
            FederationMatrix->>Room: update member profile
            FederationHook->>Room: send system message (user-display-name-changed)
        end
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

  • Areas needing extra attention:
    • correctness and error handling in FederationMatrix.updateUserProfile.
    • sanitization, validation, and edge cases in matrixId helpers and their tests.
    • duplicate afterSaveUser registration in apps/meteor/ee/server/hooks/federation/index.ts.
    • direct DB writes in member events and potential notification/loop interaction.

Possibly related PRs

Suggested labels

stat: ready to merge, stat: QA assured

Suggested reviewers

  • ggazzo
  • sampaiodiego

Poem

🐰 I stored the old name in a cozy nook,

nudged the matrix IDs and changed the book,
hopped through rooms where federated friends play,
sent a tiny note: "old → new" on its way,
a rabbit's cheer — names updated, hip hooray!

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 14.29% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ 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 'feat(federation): add support for user renames' clearly and concisely summarizes the main change—adding federation support for user display name changes.
Linked Issues check ✅ Passed The PR implements support for federated user renames (FDR-169), including display-name change tracking, synchronization to federated rooms, system messages, and a federation API for profile updates.
Out of Scope Changes check ✅ Passed All changes directly support user rename functionality: real-name capture and callbacks, federation hooks for display-name updates, Matrix ID utilities, message type registration, and i18n translations.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/federation-rename-user

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Jira integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between ec28f38 and def9191.

📒 Files selected for processing (1)
  • apps/meteor/app/lib/server/functions/setRealName.ts (4 hunks)
🧰 Additional context used
🧠 Learnings (1)
📓 Common learnings
Learnt from: ricardogarim
Repo: RocketChat/Rocket.Chat PR: 37377
File: apps/meteor/ee/server/hooks/federation/index.ts:86-88
Timestamp: 2025-11-04T16:49:19.107Z
Learning: In Rocket.Chat's federation system (apps/meteor/ee/server/hooks/federation/), permission checks follow two distinct patterns: (1) User-initiated federation actions (creating rooms, adding users to federated rooms, joining from invites) should throw MeteorError to inform users they lack 'access-federation' permission. (2) Remote server-initiated federation events should silently skip/ignore when users lack permission. The beforeAddUserToRoom hook only executes for local user-initiated actions, so throwing an error there is correct. Remote federation events are handled separately by the federation Matrix package with silent skipping logic.
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: rodrigok
Repo: RocketChat/Rocket.Chat PR: 36991
File: apps/meteor/server/services/federation/infrastructure/rocket-chat/adapters/Settings.ts:219-221
Timestamp: 2025-09-19T15:15:04.642Z
Learning: The Federation_Matrix_homeserver_domain setting in apps/meteor/server/services/federation/infrastructure/rocket-chat/adapters/Settings.ts is part of the old federation system and is being deprecated/removed, so configuration issues with this setting should not be flagged for improvement.
🧬 Code graph analysis (1)
apps/meteor/app/lib/server/functions/setRealName.ts (1)
apps/meteor/lib/callbacks.ts (1)
  • callbacks (252-260)
⏰ 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). (3)
  • GitHub Check: 📦 Build Packages
  • GitHub Check: CodeQL-Build
  • GitHub Check: CodeQL-Build
🔇 Additional comments (4)
apps/meteor/app/lib/server/functions/setRealName.ts (4)

8-8: LGTM: Import added to support federation callback.

The import is correctly added to enable the afterSaveUser callback invocation for federation support.


38-39: LGTM: Old user state captured correctly.

The shallow copy captures the user state before the name field is updated on line 52, which is exactly what's needed for the afterSaveUser callback. Since only the name primitive is modified, a shallow copy is sufficient here.


54-54: LGTM: Transaction callback now supports async operations.

Converting the transaction callback to async is a good practice that enables async operations within the callback, making it forward-compatible with future enhancements.


67-67: LGTM: Federation callback integration looks good.

The afterSaveUser callback is correctly invoked with both the updated user and the previous state, enabling federation to track and propagate display-name changes. The fire-and-forget pattern is consistent with the existing broadcast operations.


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.

Base automatically changed from release-7.11.0 to master October 17, 2025 18:29
@ricardogarim ricardogarim changed the base branch from master to develop October 28, 2025 11:06
@ricardogarim ricardogarim force-pushed the feat/federation-rename-user branch from cfe2740 to 3180191 Compare October 28, 2025 14:40
@ricardogarim ricardogarim marked this pull request as ready for review October 28, 2025 14:59
@ricardogarim ricardogarim requested a review from a team as a code owner October 28, 2025 14:59
Copy link
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: 4

🧹 Nitpick comments (8)
apps/meteor/app/lib/server/functions/setRealName.ts (1)

54-68: Emit hook after commit: prefer awaiting the callback to surface errors.

Use an async run to catch failures from downstream handlers (federation propagation, system messages) while still running post-commit.

-  await onceTransactionCommitedSuccessfully(async () => {
+  await onceTransactionCommitedSuccessfully(async () => {
     if (settings.get('UI_Use_Real_Name') === true) {
       void api.broadcast('user.nameChanged', {
         _id: user._id,
         name: user.name,
         username: user.username,
       });
     }
     void api.broadcast('user.realNameChanged', {
       _id: user._id,
       name,
       username: user.username,
     });
-    void callbacks.run('afterSaveUser', { user, oldUser });
+    // Prefer awaiting async callbacks chain
+    await callbacks.run?.('afterSaveUser', { user, oldUser });
+    // If the async variant exists in this codebase, use it instead:
+    // await callbacks.runAsync('afterSaveUser', { user, oldUser });
   }, session);

Please confirm whether callbacks.runAsync exists in this package so we can switch to it; otherwise, keeping run but awaiting its Promise-capable return is fine.

packages/message-types/src/registrations/common.ts (1)

118-127: Make payload parsing robust; avoid brittle '|' split.

Guard against missing delimiter and names containing '|'. Prefer JSON payload with fallback to a bounded split.

 instance.registerType({
   id: 'user-display-name-changed',
   system: true,
-  text: (t, message) =>
-    t('User_changed_display_name', {
-      username: message.u.username,
-      old_name: message.msg.split('|')[0],
-      new_name: message.msg.split('|')[1],
-    }),
+  text: (t, message) => {
+    const raw = String(message.msg ?? '');
+    // Prefer JSON payload: {"old_name":"...","new_name":"..."}
+    let oldName = '';
+    let newName = '';
+    try {
+      const p = JSON.parse(raw);
+      oldName = p.old_name ?? p.oldName ?? '';
+      newName = p.new_name ?? p.newName ?? '';
+    } catch {
+      const [o = '', n = ''] = raw.split('|', 2);
+      oldName = o;
+      newName = n;
+    }
+    return t('User_changed_display_name', {
+      username: message.u.username,
+      old_name: oldName,
+      new_name: newName,
+    });
+  },
 });

If we switch the producer to send JSON (see hook comment), this will render correctly and remain backward-compatible with existing 'old|new' payloads.

ee/packages/federation-matrix/src/helpers/matrixId.spec.ts (1)

18-21: Add IPv6 MXID validation tests.

Current tests don’t cover IPv6 homeserver forms. Add cases like:

  • Valid: @user:[2001:db8::1], @user:[2001:db8::1]:8448
  • Invalid: missing closing bracket, empty host inside brackets

Also applies to: 30-34

ee/packages/federation-matrix/src/events/member.ts (2)

60-91: Loop-free local rename handling looks good; minor resiliency nits.

Solid approach avoiding afterSave loop and broadcasting directly. Consider:

  • Wrap Users.updateOne with projection of name conflicts (rare) and log the old value from DB for traceability.
  • Guard against over-notifying if Matrix sends redundant events (debounce by comparing current DB name to new value before write).

103-147: Non-local rename detection is correct; add IPv6-safe parsing dependency.

Works as intended when prev_content.membership === 'join'. Ensure getUsernameServername remains IPv6-safe (see validator fix), otherwise state_key parsing could mis-identify server names.

ee/packages/federation-matrix/src/FederationMatrix.ts (2)

721-726: Prefer indexed helper for subscription lookup.

Use existing helper to leverage indexes and avoid magic field paths.

- const subscription = await Subscriptions.findOne({ 'rid': room._id, 'u._id': user._id });
+ const subscription = await Subscriptions.findOneByRoomIdAndUserId(room._id, user._id);

959-1013: updateUserProfile: good shape; add small hardening.

  • Early-return on identical current name to reduce Matrix calls.
  • Consider batching per-room updates (if SDK supports) to reduce round-trips on large accounts.
ee/packages/federation-matrix/src/helpers/matrixId.ts (1)

10-12: Address CodeQL regex warning by trimming without regex.

Replace the underscore-trim regex with index-based slicing to avoid potential backtracking flags.

- sanitized = sanitized.replace(/^_+|_+$/g, '');
+ // trim leading/trailing underscores without regex (avoids backtracking warnings)
+ let start = 0;
+ while (start < sanitized.length && sanitized.charCodeAt(start) === 95 /* '_' */) start++;
+ let end = sanitized.length;
+ while (end > start && sanitized.charCodeAt(end - 1) === 95 /* '_' */) end--;
+ sanitized = sanitized.slice(start, end);
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Jira integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 688786a and 3180191.

📒 Files selected for processing (10)
  • apps/meteor/app/lib/server/functions/setRealName.ts (4 hunks)
  • apps/meteor/ee/server/hooks/federation/index.ts (2 hunks)
  • ee/packages/federation-matrix/src/FederationMatrix.ts (20 hunks)
  • ee/packages/federation-matrix/src/events/member.ts (3 hunks)
  • ee/packages/federation-matrix/src/helpers/matrixId.spec.ts (1 hunks)
  • ee/packages/federation-matrix/src/helpers/matrixId.ts (1 hunks)
  • packages/core-services/src/types/IFederationMatrixService.ts (1 hunks)
  • packages/core-typings/src/IMessage/IMessage.ts (1 hunks)
  • packages/i18n/src/locales/en.i18n.json (1 hunks)
  • packages/message-types/src/registrations/common.ts (1 hunks)
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2025-09-19T15:15:04.642Z
Learnt from: rodrigok
PR: RocketChat/Rocket.Chat#36991
File: apps/meteor/server/services/federation/infrastructure/rocket-chat/adapters/Settings.ts:219-221
Timestamp: 2025-09-19T15:15:04.642Z
Learning: The Federation_Matrix_homeserver_domain setting in apps/meteor/server/services/federation/infrastructure/rocket-chat/adapters/Settings.ts is part of the old federation system and is being deprecated/removed, so configuration issues with this setting should not be flagged for improvement.

Applied to files:

  • apps/meteor/ee/server/hooks/federation/index.ts
🧬 Code graph analysis (7)
ee/packages/federation-matrix/src/helpers/matrixId.ts (1)
packages/core-typings/src/IUser.ts (2)
  • IUser (186-255)
  • isUserNativeFederated (276-277)
ee/packages/federation-matrix/src/events/member.ts (1)
ee/packages/federation-matrix/src/FederationMatrix.ts (2)
  • getUsernameServername (41-53)
  • createOrUpdateFederatedUser (63-106)
ee/packages/federation-matrix/src/FederationMatrix.ts (2)
ee/packages/federation-matrix/src/helpers/matrixId.ts (3)
  • validateFederatedUsername (33-65)
  • constructMatrixId (24-31)
  • getUserMatrixId (67-83)
packages/core-typings/src/IUser.ts (1)
  • isUserNativeFederated (276-277)
ee/packages/federation-matrix/src/helpers/matrixId.spec.ts (2)
ee/packages/federation-matrix/src/helpers/matrixId.ts (3)
  • validateFederatedUsername (33-65)
  • constructMatrixId (24-31)
  • getUserMatrixId (67-83)
packages/core-typings/src/IUser.ts (1)
  • IUser (186-255)
packages/message-types/src/registrations/common.ts (2)
packages/message-types/src/registrations/e2ee.ts (1)
  • instance (3-21)
packages/message-types/src/registrations/omnichannel.ts (1)
  • instance (5-63)
apps/meteor/app/lib/server/functions/setRealName.ts (1)
apps/meteor/lib/callbacks.ts (1)
  • callbacks (252-260)
apps/meteor/ee/server/hooks/federation/index.ts (3)
apps/meteor/lib/callbacks.ts (1)
  • callbacks (252-260)
packages/core-typings/src/IRoom.ts (1)
  • isRoomNativeFederated (124-125)
ee/packages/federation-matrix/src/FederationMatrix.ts (1)
  • FederationMatrix (110-1031)
🪛 GitHub Actions: CI
ee/packages/federation-matrix/src/FederationMatrix.ts

[error] 213-213: TS2554: Expected 3 arguments, but got 4. TypeScript compile error in FederationMatrix.ts: function call with 4 args when 3 expected.

🪛 GitHub Check: CodeQL
ee/packages/federation-matrix/src/helpers/matrixId.ts

[failure] 11-11: Polynomial regular expression used on uncontrolled data
This regular expression that depends on library input may run slow on strings with many repetitions of ''.
This regular expression that depends on library input may run slow on strings with many repetitions of '
'.
This regular expression that depends on library input may run slow on strings with many repetitions of ''.
This regular expression that depends on library input may run slow on strings with many repetitions of '
'.
This regular expression that depends on library input may run slow on strings with many repetitions of ''.
This regular expression that depends on library input may run slow on strings with many repetitions of '
'.
This regular expression that depends on library input may run slow on strings with many repetitions of ''.
This regular expression that depends on library input may run slow on strings with many repetitions of '
'.
This regular expression that depends on library input may run slow on strings with many repetitions of ''.
This regular expression that depends on library input may run slow on strings with many repetitions of '
'.
This regular expression that depends on library input may run slow on strings with many repetitions of '_'.

🔇 Additional comments (6)
packages/i18n/src/locales/en.i18n.json (1)

5550-5550: JSON breakage: unescaped quotes around placeholders (and add trailing comma).

The string includes raw " characters around {{old_name}} and {{new_name}}, which invalidates JSON. Also ensure the entry ends with a comma to keep the object valid.

Apply this fix:

-  "User_changed_display_name": "changed display name from "{{old_name}}" to "{{new_name}}"",
+  "User_changed_display_name": "changed display name from {{old_name}} to {{new_name}}",

Optional: for consistency with existing wording like “Room name changed to …”, consider “changed name from {{old_name}} to {{new_name}}”.

Likely an incorrect or invalid review comment.

packages/core-typings/src/IMessage/IMessage.ts (1)

92-92: Type addition looks good.

The new message type value integrates cleanly with MessageTypesValues.

apps/meteor/ee/server/hooks/federation/index.ts (1)

219-264: Remove JSON serialization suggestion; remote-origin guard pattern is incorrect.

The review comment contains two critical incompatibilities:

  1. JSON serialization breaks message rendering: The parser in packages/message-types/src/registrations/common.ts (line 123–125) hardcodes pipe-splitting: message.msg.split('|')[0] and message.msg.split('|')[1]. Existing producers in ee/packages/federation-matrix/src/events/member.ts (lines 85, 140) and current PR code (line 255) all use pipe format. Changing only the PR code to JSON would cause the parser to fail and display garbled messages. A coordinated format change across all three producers AND the parser would be required—this is not a localized improvement.

  2. Remote-origin guard pattern is incorrect: The suggestion to check user.username?.includes(':') does not reliably identify federated users. Federated users store their identity in the federation object (federation.origin, federation.mui), not in the username field. The correct guard would be if (user.federation?.origin) to skip remote-origin updates, not a username string match.

The review comment should be disregarded as written.

Likely an incorrect or invalid review comment.

ee/packages/federation-matrix/src/helpers/matrixId.spec.ts (1)

61-66: Align validator with constructor for '=' handling.

constructMatrixId preserves '=', but validateFederatedUsername may reject MXIDs containing raw '='. Add a positive test (e.g., @user=123:example.com) and update the validator to accept it, or sanitize to encode '=' consistently. See proposed validator fix in matrixId.ts review.

Also applies to: 73-76

ee/packages/federation-matrix/src/helpers/matrixId.ts (1)

24-31: Ensure helpers accept what we construct.

Given constructMatrixId preserves '=', validateFederatedUsername must not reject such MXIDs; and getUserMatrixId should keep returning mui for native federated users even if their RC username changes (tests already cover). No code change needed here after the validator fix; just re-run tests.

Also applies to: 67-83

ee/packages/federation-matrix/src/FederationMatrix.ts (1)

312-320: Verify invite.inviteUserToRoom signature before passing extra flags.

You’re passing five args (invitee, roomId, inviter, boolean, displayName). If the SDK expects three, this will also fail at runtime/compile-time. Align with SDK or stage a typed overload.

Also applies to: 590-597

Copy link
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: 2

♻️ Duplicate comments (1)
ee/packages/federation-matrix/src/helpers/matrixId.ts (1)

33-65: IPv6 and '=' handling issues remain unresolved.

The issues previously identified in the past review comment are still present:

  1. IPv6 parsing bug (line 46): Splitting domain and port on ':' breaks IPv6 addresses like @user:[2001:db8::1]:8448. The host must be extracted first (detecting bracketed IPv6 [...] before parsing the port).

  2. Localpart inconsistency (line 43): The localpart regex requires encoded form =[0-9a-fA-F]{2} but sanitizeForMatrixLocalpart (line 10) preserves raw '=' characters. This means validateFederatedUsername will reject MXIDs created by constructMatrixId.

Please refer to the previous review comment for the detailed fix. These are critical correctness issues that will cause valid Matrix IDs to be rejected.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Jira integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 3180191 and 76a73cd.

📒 Files selected for processing (1)
  • ee/packages/federation-matrix/src/helpers/matrixId.ts (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
ee/packages/federation-matrix/src/helpers/matrixId.ts (1)
packages/core-typings/src/IUser.ts (2)
  • IUser (186-255)
  • isUserNativeFederated (276-277)
🪛 GitHub Check: CodeQL
ee/packages/federation-matrix/src/helpers/matrixId.ts

[failure] 11-11: Polynomial regular expression used on uncontrolled data
This regular expression that depends on library input may run slow on strings with many repetitions of ''.
This regular expression that depends on library input may run slow on strings with many repetitions of '
'.
This regular expression that depends on library input may run slow on strings with many repetitions of ''.
This regular expression that depends on library input may run slow on strings with many repetitions of '
'.
This regular expression that depends on library input may run slow on strings with many repetitions of ''.
This regular expression that depends on library input may run slow on strings with many repetitions of '
'.
This regular expression that depends on library input may run slow on strings with many repetitions of ''.
This regular expression that depends on library input may run slow on strings with many repetitions of '
'.
This regular expression that depends on library input may run slow on strings with many repetitions of ''.
This regular expression that depends on library input may run slow on strings with many repetitions of '
'.
This regular expression that depends on library input may run slow on strings with many repetitions of '_'.

🔇 Additional comments (1)
ee/packages/federation-matrix/src/helpers/matrixId.ts (1)

67-80: LGTM! Clean user Matrix ID resolution.

The logic correctly handles both native federated users (returning their existing mui) and local users (constructing a new Matrix ID). Error handling is appropriate with clear messages for missing required fields.

Copy link
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

♻️ Duplicate comments (1)
ee/packages/federation-matrix/src/helpers/matrixId.ts (1)

10-11: ReDoS vulnerability remains unaddressed.

The polynomial regex /_+$/ flagged by CodeQL and previous reviews has not been mitigated. This pattern can cause catastrophic backtracking on strings with many consecutive underscores.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Jira integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 76a73cd and ec28f38.

📒 Files selected for processing (2)
  • ee/packages/federation-matrix/src/helpers/matrixId.spec.ts (1 hunks)
  • ee/packages/federation-matrix/src/helpers/matrixId.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • ee/packages/federation-matrix/src/helpers/matrixId.spec.ts
🧰 Additional context used
🧬 Code graph analysis (1)
ee/packages/federation-matrix/src/helpers/matrixId.ts (1)
packages/core-typings/src/IUser.ts (2)
  • IUser (186-255)
  • isUserNativeFederated (276-277)
⏰ 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). (3)
  • GitHub Check: ✅ Tests Done
  • GitHub Check: CodeQL-Build
  • GitHub Check: CodeQL-Build
🔇 Additional comments (3)
ee/packages/federation-matrix/src/helpers/matrixId.ts (3)

24-65: LGTM!

The server name validation correctly handles IPv6 (with brackets), IPv4, hostnames, and optional ports. The logic properly distinguishes between IPv6's colons and port separators.


67-108: Thorough validation added as requested.

The function now validates serverName format comprehensively, including whitespace, port ranges, and overall structure. The port validation duplication (lines 82-100 and within validateServerNameFormat) is acceptable for providing clearer error messages.


126-139: LGTM!

The function correctly distinguishes native federated users (returning existing mui) from local users (constructing Matrix ID), with appropriate error handling for missing fields.

Copy link
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.

Understood, resolving this thread. The 4-argument createRoom signature is correct for the upcoming @rocket.chat/federation-sdk version.

@ricardogarim ricardogarim force-pushed the feat/federation-rename-user branch from ec28f38 to def9191 Compare November 10, 2025 12:17
@ricardogarim ricardogarim marked this pull request as draft January 19, 2026 23:23
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants