Skip to content

perf: quick wins on hot paths without behavior changes#41548

Draft
KevLehman wants to merge 1 commit into
developfrom
claude/perf-optimization-quick-wins-ga1nvw
Draft

perf: quick wins on hot paths without behavior changes#41548
KevLehman wants to merge 1 commit into
developfrom
claude/perf-optimization-quick-wins-ga1nvw

Conversation

@KevLehman

@KevLehman KevLehman commented Jul 24, 2026

Copy link
Copy Markdown
Member
  • Random.id/secret (server): generate all randomness with a single
    crypto.randomBytes call instead of one per character (~15x faster,
    identical output distribution)
  • Markdown original/filtered parsers: hoist constant regexes and cache
    the schemes-derived link regexes instead of recompiling per message
  • MentionsParser: cache user/channel mention regexes keyed on the
    configured pattern; avoid a duplicate channels.find per mention
  • AutoTranslate tokenizers: compile constant regexes once at module load
  • MentionsServer: skip the empty channel-mention DB query on messages
    with no channel mentions; fetch the room member count at most once per
    message when handling @all/@here
  • API response shaping: replace O(n*m) Array.find/includes scans with
    Map/Set lookups (channels/groups/im files, im.members, browseChannels,
    Team.findBySubscribedUserIds, LDAP role sync)
  • Replace quadratic reduce+spread accumulators with Object.assign,
    Object.fromEntries and flatMap (i18n namespace merge, license v2->v3
    conversion, settings $unset build, GenericMenu items)
  • Avoid repeated settings.get calls in parseUrlsInMessage and
    getMarkdownConfig

Co-Authored-By: Claude Fable 5 noreply@anthropic.com
Claude-Session: https://claude.ai/code/session_01ETnjqyMsf3b8LAeQ8fYCbG

Review in cubic

Summary by CodeRabbit

  • Performance
    • Improved responsiveness across message processing, Markdown parsing, mentions, channel browsing, team visibility, menus, and user lookups.
    • Reduced repeated data queries and optimized large-list processing.
    • Improved random value generation efficiency while preserving existing behavior.
  • Bug Fixes
    • Preserved existing Markdown, link parsing, mention handling, subscriptions, and configuration behavior while improving processing efficiency.

- Random.id/secret (server): generate all randomness with a single
  crypto.randomBytes call instead of one per character (~15x faster,
  identical output distribution)
- Markdown original/filtered parsers: hoist constant regexes and cache
  the schemes-derived link regexes instead of recompiling per message
- MentionsParser: cache user/channel mention regexes keyed on the
  configured pattern; avoid a duplicate channels.find per mention
- AutoTranslate tokenizers: compile constant regexes once at module load
- MentionsServer: skip the empty channel-mention DB query on messages
  with no channel mentions; fetch the room member count at most once per
  message when handling @all/@here
- API response shaping: replace O(n*m) Array.find/includes scans with
  Map/Set lookups (channels/groups/im files, im.members, browseChannels,
  Team.findBySubscribedUserIds, LDAP role sync)
- Replace quadratic reduce+spread accumulators with Object.assign,
  Object.fromEntries and flatMap (i18n namespace merge, license v2->v3
  conversion, settings $unset build, GenericMenu items)
- Avoid repeated settings.get calls in parseUrlsInMessage and
  getMarkdownConfig

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ETnjqyMsf3b8LAeQ8fYCbG
@KevLehman
KevLehman requested a review from a team as a code owner July 24, 2026 13:32
@dionisio-bot

dionisio-bot Bot commented Jul 24, 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
  • This PR has an invalid title

Please fix the issues and try again

If you have any trouble, please check the PR guidelines

@changeset-bot

changeset-bot Bot commented Jul 24, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: dd5758b

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

This PR includes changesets to release 11 packages
Name Type
@rocket.chat/random Patch
@rocket.chat/i18n Patch
@rocket.chat/license Patch
@rocket.chat/ui-client Patch
@rocket.chat/meteor Patch
@rocket.chat/cron Patch
@rocket.chat/livechat Patch
@rocket.chat/models Patch
@rocket.chat/ui-composer 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

@KevLehman
KevLehman marked this pull request as draft July 24, 2026 13:32
@coderabbitai

coderabbitai Bot commented Jul 24, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

This PR applies behavior-preserving performance optimizations across random generation, markdown and mention parsing, messaging, API enrichment, LDAP role syncing, collection transformations, and UI list construction. A Changesets entry marks patch releases for affected packages.

Changes

Performance optimizations

Layer / File(s) Summary
Batched random generation
packages/random/src/NodeRandomGenerator.ts
Random string generation uses one byte buffer, while hexadecimal generation shares centralized cryptographic byte handling with fallback support.
Parser regular-expression caching
apps/meteor/app/markdown/..., apps/meteor/app/mentions/..., apps/meteor/server/lib/autotranslate/...
Markdown, mention, and auto-translation paths reuse compiled regular expressions instead of constructing them per call.
Message and lookup path optimization
apps/meteor/server/lib/messages/..., apps/meteor/server/lib/messaging/..., apps/meteor/server/api/..., apps/meteor/server/services/team/...
Site settings and member counts are reused, empty channel lookups are skipped, and repeated array searches are replaced with Map or Set lookups.
Allocation and transformation cleanup
apps/meteor/ee/..., apps/meteor/server/services/..., apps/meteor/server/settings/..., ee/packages/license/..., packages/i18n/..., packages/ui-client/..., .changeset/...
Role resolution and collection transformations use indexed lookups or direct flattening and assignment operations; related package patch metadata is added.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Suggested labels: type: chore

Suggested reviewers: sampaiodiego, tassoevan

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the performance-focused hot-path optimizations and the no-behavior-change intent.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 Biome (2.5.3)
apps/meteor/app/markdown/lib/parser/filtered/filtered.js

File contains syntax errors that prevent linting: Line 24: Illegal use of an export declaration outside of a module

apps/meteor/app/markdown/lib/parser/original/markdown.js

File contains syntax errors that prevent linting: Line 1: Illegal use of an import declaration outside of a module; Line 207: Illegal use of an export declaration outside of a module


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.

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

🧹 Nitpick comments (2)
packages/random/src/NodeRandomGenerator.ts (1)

28-29: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Remove the newly added implementation comments.

  • packages/random/src/NodeRandomGenerator.ts#L28-L29: remove the hex-trimming explanation.
  • packages/random/src/NodeRandomGenerator.ts#L34-L37: remove the random-string batching explanation.
  • packages/random/src/NodeRandomGenerator.ts#L48-L54: remove the fallback explanation and XXX comment.
  • apps/meteor/app/markdown/lib/parser/filtered/filtered.js#L3-L5: remove the cache explanation.
  • apps/meteor/app/markdown/lib/parser/filtered/filtered.js#L33-L33: remove the block-code comment.
  • apps/meteor/app/markdown/lib/parser/filtered/filtered.js#L36-L36: remove the inline-code comment.
  • apps/meteor/app/markdown/lib/parser/filtered/filtered.js#L39-L39: remove the markdown-link comment.
  • apps/meteor/app/markdown/lib/parser/filtered/filtered.js#L42-L42: remove the piped-link comment.
  • apps/meteor/app/markdown/lib/parser/original/markdown.js#L34-L36: remove the regex-cache explanation.
  • apps/meteor/app/markdown/lib/parser/original/markdown.js#L68-L70: remove the link-cache explanation.
  • apps/meteor/app/mentions/lib/MentionsParser.ts#L50-L54: remove the mention-cache explanation.
  • apps/meteor/server/lib/autotranslate/autotranslate.ts#L23-L25: remove the tokenizer-pattern explanation.
  • apps/meteor/server/lib/messaging/mentions/Mentions.ts#L62-L63: remove the member-count cache explanation.
  • apps/meteor/server/lib/messaging/mentions/Mentions.ts#L107-L108: remove the empty-query explanation.

As per coding guidelines: “Avoid code comments in the implementation.”

🤖 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 `@packages/random/src/NodeRandomGenerator.ts` around lines 28 - 29, Remove the
newly added implementation comments without changing behavior: in
packages/random/src/NodeRandomGenerator.ts, remove comments at lines 28-29,
34-37, and 48-54; in apps/meteor/app/markdown/lib/parser/filtered/filtered.js,
remove comments at lines 3-5, 33, 36, 39, and 42; in
apps/meteor/app/markdown/lib/parser/original/markdown.js, remove comments at
lines 34-36 and 68-70; in apps/meteor/app/mentions/lib/MentionsParser.ts, remove
lines 50-54; in apps/meteor/server/lib/autotranslate/autotranslate.ts, remove
lines 23-25; and in apps/meteor/server/lib/messaging/mentions/Mentions.ts,
remove lines 62-63 and 107-108. Preserve all surrounding implementation code.

Source: Coding guidelines

apps/meteor/ee/server/lib/ldap/Manager.ts (1)

369-372: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Remove the new implementation comments.

These explanatory comments are inside a TypeScript implementation. As per coding guidelines, **/*.{ts,tsx,js} should avoid code comments in implementation; keep this context in the PR description or rely on the descriptive identifiers.

🤖 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/ee/server/lib/ldap/Manager.ts` around lines 369 - 372, Remove the
explanatory comments describing role indexing, lookup order, and
first-occurrence behavior near the role-mapping implementation; leave the
surrounding TypeScript logic unchanged.

Source: Coding guidelines

🤖 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/server/lib/autotranslate/autotranslate.ts`:
- Around line 26-28: Update the urlSchemes constant used by markdownLinkRegex
and pipedLinkRegex so interpolation produces a regular-expression alternation
between http and https rather than a comma-separated literal. Preserve both
regexes’ existing URL-matching behavior for standard http:// and https:// links.

---

Nitpick comments:
In `@apps/meteor/ee/server/lib/ldap/Manager.ts`:
- Around line 369-372: Remove the explanatory comments describing role indexing,
lookup order, and first-occurrence behavior near the role-mapping
implementation; leave the surrounding TypeScript logic unchanged.

In `@packages/random/src/NodeRandomGenerator.ts`:
- Around line 28-29: Remove the newly added implementation comments without
changing behavior: in packages/random/src/NodeRandomGenerator.ts, remove
comments at lines 28-29, 34-37, and 48-54; in
apps/meteor/app/markdown/lib/parser/filtered/filtered.js, remove comments at
lines 3-5, 33, 36, 39, and 42; in
apps/meteor/app/markdown/lib/parser/original/markdown.js, remove comments at
lines 34-36 and 68-70; in apps/meteor/app/mentions/lib/MentionsParser.ts, remove
lines 50-54; in apps/meteor/server/lib/autotranslate/autotranslate.ts, remove
lines 23-25; and in apps/meteor/server/lib/messaging/mentions/Mentions.ts,
remove lines 62-63 and 107-108. Preserve all surrounding implementation code.
🪄 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 Plus

Run ID: 52ff827e-1e72-48f8-8dce-600966a8ae3d

📥 Commits

Reviewing files that changed from the base of the PR and between a27dd2f and dd5758b.

📒 Files selected for processing (18)
  • .changeset/perf-quick-wins.md
  • apps/meteor/app/markdown/lib/parser/filtered/filtered.js
  • apps/meteor/app/markdown/lib/parser/original/markdown.js
  • apps/meteor/app/mentions/lib/MentionsParser.ts
  • apps/meteor/ee/server/lib/ldap/Manager.ts
  • apps/meteor/server/api/lib/addUserToFileObj.ts
  • apps/meteor/server/api/v1/im.ts
  • apps/meteor/server/lib/autotranslate/autotranslate.ts
  • apps/meteor/server/lib/messages/parseUrlsInMessage.ts
  • apps/meteor/server/lib/messaging/mentions/Mentions.ts
  • apps/meteor/server/meteor-methods/rooms/browseChannels.ts
  • apps/meteor/server/services/messages/service.ts
  • apps/meteor/server/services/team/service.ts
  • apps/meteor/server/settings/SettingsRegistry.ts
  • ee/packages/license/src/v2/convertToV3.ts
  • packages/i18n/src/index.ts
  • packages/random/src/NodeRandomGenerator.ts
  • packages/ui-client/src/components/GenericMenu/GenericMenu.tsx
📜 Review details
⏰ Context from checks skipped due to timeout. (4)
  • GitHub Check: cubic · AI code reviewer
  • GitHub Check: 📦 Build Packages
  • GitHub Check: Hacktron Security Check
  • GitHub Check: CodeQL-Build
🧰 Additional context used
📓 Path-based instructions (1)
**/*.{ts,tsx,js}

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

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

Files:

  • apps/meteor/server/settings/SettingsRegistry.ts
  • ee/packages/license/src/v2/convertToV3.ts
  • apps/meteor/server/lib/messages/parseUrlsInMessage.ts
  • packages/ui-client/src/components/GenericMenu/GenericMenu.tsx
  • apps/meteor/server/services/messages/service.ts
  • apps/meteor/ee/server/lib/ldap/Manager.ts
  • apps/meteor/server/api/lib/addUserToFileObj.ts
  • apps/meteor/server/lib/messaging/mentions/Mentions.ts
  • apps/meteor/app/mentions/lib/MentionsParser.ts
  • apps/meteor/server/meteor-methods/rooms/browseChannels.ts
  • packages/i18n/src/index.ts
  • apps/meteor/server/api/v1/im.ts
  • apps/meteor/app/markdown/lib/parser/filtered/filtered.js
  • apps/meteor/server/lib/autotranslate/autotranslate.ts
  • apps/meteor/server/services/team/service.ts
  • apps/meteor/app/markdown/lib/parser/original/markdown.js
  • packages/random/src/NodeRandomGenerator.ts
🧠 Learnings (5)
📚 Learning: 2026-03-16T21:50:37.589Z
Learnt from: amitb0ra
Repo: RocketChat/Rocket.Chat PR: 39676
File: .changeset/migrate-users-register-openapi.md:3-3
Timestamp: 2026-03-16T21:50:37.589Z
Learning: For changes related to OpenAPI migrations in Rocket.Chat/OpenAPI, when removing endpoint types and validators from rocket.chat/rest-typings (e.g., UserRegisterParamsPOST, /v1/users.register) document this as a minor changeset (not breaking) per RocketChat/Rocket.Chat-Open-API#150 Rule 7. Note that the endpoint type is re-exposed via a module augmentation .d.ts in the consuming package (e.g., packages/web-ui-registration/src/users-register.d.ts). In reviews, ensure the changeset clearly states: this is a non-breaking change, the major version should not be bumped, and the changeset reflects a minor version bump. Do not treat this as a breaking change during OpenAPI migrations.

Applied to files:

  • .changeset/perf-quick-wins.md
📚 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/server/settings/SettingsRegistry.ts
  • ee/packages/license/src/v2/convertToV3.ts
  • apps/meteor/server/lib/messages/parseUrlsInMessage.ts
  • apps/meteor/server/services/messages/service.ts
  • apps/meteor/ee/server/lib/ldap/Manager.ts
  • apps/meteor/server/api/lib/addUserToFileObj.ts
  • apps/meteor/server/lib/messaging/mentions/Mentions.ts
  • apps/meteor/app/mentions/lib/MentionsParser.ts
  • apps/meteor/server/meteor-methods/rooms/browseChannels.ts
  • packages/i18n/src/index.ts
  • apps/meteor/server/api/v1/im.ts
  • apps/meteor/server/lib/autotranslate/autotranslate.ts
  • apps/meteor/server/services/team/service.ts
  • packages/random/src/NodeRandomGenerator.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/server/settings/SettingsRegistry.ts
  • ee/packages/license/src/v2/convertToV3.ts
  • apps/meteor/server/lib/messages/parseUrlsInMessage.ts
  • apps/meteor/server/services/messages/service.ts
  • apps/meteor/ee/server/lib/ldap/Manager.ts
  • apps/meteor/server/api/lib/addUserToFileObj.ts
  • apps/meteor/server/lib/messaging/mentions/Mentions.ts
  • apps/meteor/app/mentions/lib/MentionsParser.ts
  • apps/meteor/server/meteor-methods/rooms/browseChannels.ts
  • packages/i18n/src/index.ts
  • apps/meteor/server/api/v1/im.ts
  • apps/meteor/server/lib/autotranslate/autotranslate.ts
  • apps/meteor/server/services/team/service.ts
  • packages/random/src/NodeRandomGenerator.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/server/settings/SettingsRegistry.ts
  • ee/packages/license/src/v2/convertToV3.ts
  • apps/meteor/server/lib/messages/parseUrlsInMessage.ts
  • packages/ui-client/src/components/GenericMenu/GenericMenu.tsx
  • apps/meteor/server/services/messages/service.ts
  • apps/meteor/ee/server/lib/ldap/Manager.ts
  • apps/meteor/server/api/lib/addUserToFileObj.ts
  • apps/meteor/server/lib/messaging/mentions/Mentions.ts
  • apps/meteor/app/mentions/lib/MentionsParser.ts
  • apps/meteor/server/meteor-methods/rooms/browseChannels.ts
  • packages/i18n/src/index.ts
  • apps/meteor/server/api/v1/im.ts
  • apps/meteor/server/lib/autotranslate/autotranslate.ts
  • apps/meteor/server/services/team/service.ts
  • packages/random/src/NodeRandomGenerator.ts
📚 Learning: 2026-03-27T14:52:56.865Z
Learnt from: dougfabris
Repo: RocketChat/Rocket.Chat PR: 39892
File: apps/meteor/client/views/room/contextualBar/Threads/Thread.tsx:150-155
Timestamp: 2026-03-27T14:52:56.865Z
Learning: In Rocket.Chat, there are two different `ModalBackdrop` components with different prop APIs. During review, confirm the import source: (1) `rocket.chat/fuselage` `ModalBackdrop` uses `ModalBackdropProps` based on `BoxProps` (so it supports `onClick` and other Box/DOM props) and does not have an `onDismiss` prop; (2) `rocket.chat/ui-client` `ModalBackdrop` uses a narrower props interface like `{ children?: ReactNode; onDismiss?: () => void }` and handles Escape keypress and outside mouse-up, and it does not forward arbitrary DOM props such as `onClick`. Flag mismatched props (e.g., `onDismiss` passed to the fuselage component or `onClick` passed to the ui-client component) and ensure the usage matches the correct component being imported.

Applied to files:

  • packages/ui-client/src/components/GenericMenu/GenericMenu.tsx
🪛 ast-grep (0.44.1)
apps/meteor/app/mentions/lib/MentionsParser.ts

[warning] 64-64: Regular expression constructed from variable input detected. This can lead to Regular Expression Denial of Service (ReDoS) attacks if the variable contains malicious patterns. Use libraries like 'recheck' to validate regex safety or use static patterns.
Context: new RegExp((^|\\s|>)@(${pattern}(@(${pattern}))?(:([0-9a-zA-Z-_.]+))?), 'gm')
Note: [CWE-1333] Inefficient Regular Expression Complexity

(regexp-from-variable)


[warning] 65-65: Regular expression constructed from variable input detected. This can lead to Regular Expression Denial of Service (ReDoS) attacks if the variable contains malicious patterns. Use libraries like 'recheck' to validate regex safety or use static patterns.
Context: new RegExp((^|\\s|>)#(${pattern}(@(${pattern}))?), 'gm')
Note: [CWE-1333] Inefficient Regular Expression Complexity

(regexp-from-variable)

apps/meteor/app/markdown/lib/parser/filtered/filtered.js

[warning] 11-11: Detects non-literal values in regular expressions
Context: new RegExp(!?\\[([^\\]]+)\\]\\((?:${schemes}):\\/\\/[^\\)]+\\), 'gm')
Note: [CWE-1333] Inefficient Regular Expression Complexity (ReDoS via non-literal RegExp).

(detect-non-literal-regexp)


[warning] 12-12: Detects non-literal values in regular expressions
Context: new RegExp((?:<|&lt;)(?:${schemes}):\\/\\/[^\\|]+\\|(.+?)(?=>|&gt;)(?:>|&gt;), 'gm')
Note: [CWE-1333] Inefficient Regular Expression Complexity (ReDoS via non-literal RegExp).

(detect-non-literal-regexp)

apps/meteor/server/lib/autotranslate/autotranslate.ts

[warning] 26-26: Regular expression constructed from variable input detected. This can lead to Regular Expression Denial of Service (ReDoS) attacks if the variable contains malicious patterns. Use libraries like 'recheck' to validate regex safety or use static patterns.
Context: new RegExp((!?\\[)([^\\]]+)(\\]\\((?:${urlSchemes}):\\/\\/[^\\)]+\\)), 'gm')
Note: [CWE-1333] Inefficient Regular Expression Complexity

(regexp-from-variable)


[warning] 27-27: Regular expression constructed from variable input detected. This can lead to Regular Expression Denial of Service (ReDoS) attacks if the variable contains malicious patterns. Use libraries like 'recheck' to validate regex safety or use static patterns.
Context: new RegExp(((?:<|&lt;)(?:${urlSchemes}):\\/\\/[^\\|]+\\|)(.+?)(?=>|&gt;)((?:>|&gt;)), 'gm')
Note: [CWE-1333] Inefficient Regular Expression Complexity

(regexp-from-variable)

apps/meteor/app/markdown/lib/parser/original/markdown.js

[warning] 76-76: Detects non-literal values in regular expressions
Context: new RegExp(!\\[([^\\]]+)\\]\\(((?:${schemes}):\\/\\/[^\\s]+)\\), 'gm')
Note: [CWE-1333] Inefficient Regular Expression Complexity (ReDoS via non-literal RegExp).

(detect-non-literal-regexp)


[warning] 77-77: Detects non-literal values in regular expressions
Context: new RegExp(\\[([^\\]]+)\\]\\(((?:${schemes}):\\/\\/[^\\s]+)\\), 'gm')
Note: [CWE-1333] Inefficient Regular Expression Complexity (ReDoS via non-literal RegExp).

(detect-non-literal-regexp)


[warning] 78-78: Detects non-literal values in regular expressions
Context: new RegExp((?:<|&lt;)((?:${schemes}):\\\/\\\/[^\\|]+)\\|(.+?)(?=>|&gt;)(?:>|&gt;), 'gm')
Note: [CWE-1333] Inefficient Regular Expression Complexity (ReDoS via non-literal RegExp).

(detect-non-literal-regexp)

🔇 Additional comments (17)
packages/random/src/NodeRandomGenerator.ts (1)

26-27: LGTM!

Also applies to: 30-31, 33-33, 38-45, 47-47, 50-52, 54-55

apps/meteor/app/markdown/lib/parser/filtered/filtered.js (1)

1-1: LGTM!

Also applies to: 6-17, 31-31, 37-37, 40-40, 43-43

apps/meteor/app/markdown/lib/parser/original/markdown.js (1)

37-38: LGTM!

Also applies to: 71-83, 85-92, 155-155, 173-173, 193-193

apps/meteor/app/mentions/lib/MentionsParser.ts (1)

55-77: LGTM!

Also applies to: 128-136

apps/meteor/server/lib/autotranslate/autotranslate.ts (1)

234-234: LGTM!

apps/meteor/server/lib/messaging/mentions/Mentions.ts (1)

64-64: LGTM!

Also applies to: 79-85, 109-111

packages/i18n/src/index.ts (1)

110-110: LGTM!

packages/ui-client/src/components/GenericMenu/GenericMenu.tsx (1)

39-39: LGTM!

.changeset/perf-quick-wins.md (1)

1-9: LGTM!

apps/meteor/server/lib/messages/parseUrlsInMessage.ts (2)

8-12: LGTM!


14-17: 🎯 Functional Correctness

Confirm that URL deduplication is intentional.

prepareUrls now removes duplicate entries, and MessageService.beforeSave assigns the result directly to message.urls at Line 249. If repeated URLs were previously preserved, this is a behavior change despite the PR objective; retain the Set only if message.urls is contractually unique.

apps/meteor/server/services/team/service.ts (1)

180-195: LGTM!

apps/meteor/ee/server/lib/ldap/Manager.ts (1)

373-393: LGTM!

Also applies to: 406-413

apps/meteor/server/services/messages/service.ts (1)

285-286: LGTM!

apps/meteor/server/settings/SettingsRegistry.ts (1)

288-288: LGTM!

ee/packages/license/src/v2/convertToV3.ts (1)

54-55: LGTM!

apps/meteor/server/meteor-methods/rooms/browseChannels.ts (1)

101-101: 🎯 Functional Correctness

Clarify whether these Map constructors are still failing TypeScript.

new Map(arr.map((...) => [k, v])) is valid with TypeScript’s Map entries overload when the mapped callback returns a 2-element tuple. Array.map already returns an array, so adding as const to the [team._id, team] expression would make the callback return a readonly tuple, but it is not required unless the constructor is currently rejected.

			> Likely an incorrect or invalid review comment.

Comment on lines +26 to +28
const urlSchemes = 'http,https';
const markdownLinkRegex = new RegExp(`(!?\\[)([^\\]]+)(\\]\\((?:${urlSchemes}):\\/\\/[^\\)]+\\))`, 'gm');
const pipedLinkRegex = new RegExp(`((?:<|&lt;)(?:${urlSchemes}):\\/\\/[^\\|]+\\|)(.+?)(?=>|&gt;)((?:>|&gt;))`, 'gm');

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.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Restore the URL-scheme alternation.

urlSchemes is interpolated directly, so (?:http,https) matches only the literal http,https: scheme. Standard http:// and https:// links stop being protected from translation.

Proposed fix
-const urlSchemes = 'http,https';
+const urlSchemes = 'http|https';
📝 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
const urlSchemes = 'http,https';
const markdownLinkRegex = new RegExp(`(!?\\[)([^\\]]+)(\\]\\((?:${urlSchemes}):\\/\\/[^\\)]+\\))`, 'gm');
const pipedLinkRegex = new RegExp(`((?:<|&lt;)(?:${urlSchemes}):\\/\\/[^\\|]+\\|)(.+?)(?=>|&gt;)((?:>|&gt;))`, 'gm');
const urlSchemes = 'http|https';
const markdownLinkRegex = new RegExp(`(!?\\[)([^\\]]+)(\\]\\((?:${urlSchemes}):\\/\\/[^\\)]+\\))`, 'gm');
const pipedLinkRegex = new RegExp(`((?:<|&lt;)(?:${urlSchemes}):\\/\\/[^\\|]+\\|)(.+?)(?=>|&gt;)((?:>|&gt;))`, 'gm');
🧰 Tools
🪛 ast-grep (0.44.1)

[warning] 26-26: Regular expression constructed from variable input detected. This can lead to Regular Expression Denial of Service (ReDoS) attacks if the variable contains malicious patterns. Use libraries like 'recheck' to validate regex safety or use static patterns.
Context: new RegExp((!?\\[)([^\\]]+)(\\]\\((?:${urlSchemes}):\\/\\/[^\\)]+\\)), 'gm')
Note: [CWE-1333] Inefficient Regular Expression Complexity

(regexp-from-variable)


[warning] 27-27: Regular expression constructed from variable input detected. This can lead to Regular Expression Denial of Service (ReDoS) attacks if the variable contains malicious patterns. Use libraries like 'recheck' to validate regex safety or use static patterns.
Context: new RegExp(((?:<|&lt;)(?:${urlSchemes}):\\/\\/[^\\|]+\\|)(.+?)(?=>|&gt;)((?:>|&gt;)), 'gm')
Note: [CWE-1333] Inefficient Regular Expression Complexity

(regexp-from-variable)

🤖 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/autotranslate/autotranslate.ts` around lines 26 - 28,
Update the urlSchemes constant used by markdownLinkRegex and pipedLinkRegex so
interpolation produces a regular-expression alternation between http and https
rather than a comma-separated literal. Preserve both regexes’ existing
URL-matching behavior for standard http:// and https:// links.

@codecov

codecov Bot commented Jul 24, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 74.28571% with 27 lines in your changes missing coverage. Please review.
✅ Project coverage is 68.67%. Comparing base (a27dd2f) to head (dd5758b).

Additional details and impacted files

Impacted file tree graph

@@           Coverage Diff            @@
##           develop   #41548   +/-   ##
========================================
  Coverage    68.66%   68.67%           
========================================
  Files         4138     4138           
  Lines       159082   159127   +45     
  Branches     27942    27889   -53     
========================================
+ Hits        109238   109280   +42     
- Misses       44696    44703    +7     
+ Partials      5148     5144    -4     
Flag Coverage Δ
unit 70.66% <74.28%> (-0.01%) ⬇️

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.

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

2 issues found across 18 files

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/server/lib/messages/parseUrlsInMessage.ts">

<violation number="1" location="apps/meteor/server/lib/messages/parseUrlsInMessage.ts:15">
P3: Messages without `previewUrls` now perform an unnecessary settings lookup on every URL-parsing call. Keep the lookup conditional so the hot path retains its former no-settings-read behavior when no preview filtering is requested.</violation>
</file>

<file name="packages/random/src/NodeRandomGenerator.ts">

<violation number="1" location="packages/random/src/NodeRandomGenerator.ts:38">
P3: `Random.id`/`Random.secret` now throw for negative or fractional counts, whereas the inherited implementation returned an empty string or rounded up through its loop. Normalize the byte request and loop bound so this server override preserves the established API behavior.</violation>
</file>

Reply with feedback, questions, or to request a fix.

Re-trigger cubic


const prepareUrls = (urls: string[], previewUrls?: string[]) => [...new Set(urls)].map((url) => prepareUrl(url, previewUrls));
const prepareUrls = (urls: string[], previewUrls?: string[]) => {
const siteUrl = settings.get<string>('Site_Url');

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.

P3: Messages without previewUrls now perform an unnecessary settings lookup on every URL-parsing call. Keep the lookup conditional so the hot path retains its former no-settings-read behavior when no preview filtering is requested.

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

<comment>Messages without `previewUrls` now perform an unnecessary settings lookup on every URL-parsing call. Keep the lookup conditional so the hot path retains its former no-settings-read behavior when no preview filtering is requested.</comment>

<file context>
@@ -5,13 +5,16 @@ import { getMessageUrlRegex } from '../../../lib/getMessageUrlRegex';
 
-const prepareUrls = (urls: string[], previewUrls?: string[]) => [...new Set(urls)].map((url) => prepareUrl(url, previewUrls));
+const prepareUrls = (urls: string[], previewUrls?: string[]) => {
+	const siteUrl = settings.get<string>('Site_Url');
+	return [...new Set(urls)].map((url) => prepareUrl(url, previewUrls, siteUrl));
+};
</file context>
Suggested change
const siteUrl = settings.get<string>('Site_Url');
const siteUrl = previewUrls ? settings.get<string>('Site_Url') : '';

Comment on lines +38 to +40
const bytes = this.randomBytes(charsCount * 4);
let result = '';
for (let i = 0; i < charsCount; i++) {

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.

P3: Random.id/Random.secret now throw for negative or fractional counts, whereas the inherited implementation returned an empty string or rounded up through its loop. Normalize the byte request and loop bound so this server override preserves the established API behavior.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At packages/random/src/NodeRandomGenerator.ts, line 38:

<comment>`Random.id`/`Random.secret` now throw for negative or fractional counts, whereas the inherited implementation returned an empty string or rounded up through its loop. Normalize the byte request and loop bound so this server override preserves the established API behavior.</comment>

<file context>
@@ -23,19 +23,36 @@ export class NodeRandomGenerator extends RandomGenerator {
+		// crypto.randomBytes() call per character. Each character consumes 4
+		// bytes read as a big-endian uint32, matching what fraction() would
+		// have produced, so the output distribution is unchanged.
+		const bytes = this.randomBytes(charsCount * 4);
+		let result = '';
+		for (let i = 0; i < charsCount; i++) {
</file context>
Suggested change
const bytes = this.randomBytes(charsCount * 4);
let result = '';
for (let i = 0; i < charsCount; i++) {
const count = Number.isNaN(charsCount) ? 0 : Math.max(0, Math.ceil(charsCount));
const bytes = this.randomBytes(count * 4);
let result = '';
for (let i = 0; i < count; i++) {

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