feat: (poc) Unified AI Search#40890
Conversation
There was a problem hiding this comment.
♻️ Duplicate comments (1)
apps/meteor/app/api/server/v1/ai-search.ts (1)
404-417:⚠️ Potential issue | 🟠 Major | 🏗️ Heavy lift
search.answerstill trusts client-provided messages without authorization bindingLine 405 and Line 408-416 still pass user-supplied
messagesdirectly toAISearch.answerwithout verifying those messages exist and are visible to the caller. This keeps spoofed-context answer generation possible and should be fixed at the endpoint boundary (e.g., accept message IDs and resolve authorized messages server-side before LLM call).🤖 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/api/server/v1/ai-search.ts` around lines 404 - 417, The action() function currently accepts user-supplied messages from this.bodyParams and passes them directly to AISearch.answer without verifying the messages exist or that the caller has permission to access them. Instead of passing full message objects from the client, modify the endpoint to accept message IDs, then resolve those IDs server-side by fetching the actual messages from the database and verifying the current user has authorization to view them before passing the authorized messages to AISearch.answer.
🤖 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.
Duplicate comments:
In `@apps/meteor/app/api/server/v1/ai-search.ts`:
- Around line 404-417: The action() function currently accepts user-supplied
messages from this.bodyParams and passes them directly to AISearch.answer
without verifying the messages exist or that the caller has permission to access
them. Instead of passing full message objects from the client, modify the
endpoint to accept message IDs, then resolve those IDs server-side by fetching
the actual messages from the database and verifying the current user has
authorization to view them before passing the authorized messages to
AISearch.answer.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: a3e482fb-cda3-4ee3-8b8e-e868242d3395
📒 Files selected for processing (16)
apps/meteor/app/api/server/v1/ai-search.tsapps/meteor/client/navbar/NavBarSearch/NavBarSearchMessageRow.tsxapps/meteor/client/navbar/NavBarSearch/hooks/useSearchItems.tsapps/meteor/client/views/admin/aiCenter/AICenterRoute.tsxapps/meteor/client/views/search/SearchPage.tsxapps/meteor/server/methods/messageSearch.tsapps/meteor/server/services/ai-search/service.tsapps/meteor/server/settings/ai.tsapps/meteor/tests/unit/server/services/ai-search/service.tests.tsdocs/intelligent-search-core-vs-apps-engine.mdpackages/ai-search/src/intelligentSearch.spec.tspackages/ai-search/src/intelligentSearch.tspackages/ai-search/src/llm.spec.tspackages/ai-search/src/llm.tspackages/i18n/src/locales/en.i18n.jsonpackages/rest-typings/src/v1/misc.ts
💤 Files with no reviewable changes (1)
- apps/meteor/server/settings/ai.ts
✅ Files skipped from review due to trivial changes (1)
- docs/intelligent-search-core-vs-apps-engine.md
🚧 Files skipped from review as they are similar to previous changes (11)
- apps/meteor/client/navbar/NavBarSearch/NavBarSearchMessageRow.tsx
- packages/rest-typings/src/v1/misc.ts
- packages/ai-search/src/llm.spec.ts
- packages/ai-search/src/intelligentSearch.spec.ts
- apps/meteor/tests/unit/server/services/ai-search/service.tests.ts
- packages/ai-search/src/llm.ts
- apps/meteor/client/navbar/NavBarSearch/hooks/useSearchItems.ts
- packages/ai-search/src/intelligentSearch.ts
- apps/meteor/client/views/search/SearchPage.tsx
- apps/meteor/server/services/ai-search/service.ts
- packages/i18n/src/locales/en.i18n.json
📜 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: cubic · AI code reviewer
- GitHub Check: CodeQL-Build
- 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/methods/messageSearch.tsapps/meteor/client/views/admin/aiCenter/AICenterRoute.tsxapps/meteor/app/api/server/v1/ai-search.ts
🧠 Learnings (7)
📚 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/methods/messageSearch.tsapps/meteor/app/api/server/v1/ai-search.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/methods/messageSearch.tsapps/meteor/app/api/server/v1/ai-search.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/messageSearch.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/methods/messageSearch.tsapps/meteor/client/views/admin/aiCenter/AICenterRoute.tsxapps/meteor/app/api/server/v1/ai-search.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:
apps/meteor/client/views/admin/aiCenter/AICenterRoute.tsx
📚 Learning: 2026-02-23T17:53:06.802Z
Learnt from: ggazzo
Repo: RocketChat/Rocket.Chat PR: 35995
File: apps/meteor/app/api/server/v1/rooms.ts:1107-1112
Timestamp: 2026-02-23T17:53:06.802Z
Learning: During PR reviews that touch endpoint files under apps/meteor/app/api/server/v1, enforce strict scope: if a PR targets a specific endpoint (e.g., rooms.favorite), do not propose changes to unrelated endpoints (e.g., rooms.invite) unless maintainers explicitly request them. Focus feedback on the touched endpoint's behavior, API surface, and related tests; avoid broad cross-endpoint changes in the same PR unless requested.
Applied to files:
apps/meteor/app/api/server/v1/ai-search.ts
📚 Learning: 2026-02-24T19:09:01.522Z
Learnt from: ahmed-n-abdeltwab
Repo: RocketChat/Rocket.Chat PR: 38974
File: apps/meteor/app/api/server/v1/im.ts:220-221
Timestamp: 2026-02-24T19:09:01.522Z
Learning: In Rocket.Chat OpenAPI migration PRs for endpoints under apps/meteor/app/api/server/v1, avoid introducing logic changes. Only perform scope-tight changes that preserve behavior; style-only cleanups (e.g., removing inline comments) may be deferred to follow-ups to keep the migration PR focused.
Applied to files:
apps/meteor/app/api/server/v1/ai-search.ts
🔇 Additional comments (3)
apps/meteor/server/methods/messageSearch.ts (1)
24-31: LGTM!Also applies to: 33-84, 148-149, 153-158, 161-174, 177-177
apps/meteor/app/api/server/v1/ai-search.ts (1)
214-221: LGTM!Also applies to: 251-251, 271-280
apps/meteor/client/views/admin/aiCenter/AICenterRoute.tsx (1)
55-66: LGTM!Also applies to: 73-73
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 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/api/server/v1/ai-search.ts`:
- Around line 235-270: The getSearchAnswerMessagesForUser function lacks
room-level authorization checks and only verifies message visibility, allowing
users to access AI summaries of content from rooms they cannot access. After
retrieving the room map using getRoomMap, add authorization validation by
calling canAccessRoomIdAsync for each unique room ID present in the messages
array, similar to the authorization pattern used in the messageSearch flow. If a
user lacks access to any room, throw an appropriate Meteor.Error before
proceeding with message normalization and answer generation.
🪄 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: bd7bb85b-e652-4d88-b2b1-b0984e99c5fc
📒 Files selected for processing (3)
apps/meteor/app/api/server/v1/ai-search.tsapps/meteor/client/views/search/SearchPage.tsxpackages/rest-typings/src/v1/misc.ts
🚧 Files skipped from review as they are similar to previous changes (2)
- apps/meteor/client/views/search/SearchPage.tsx
- packages/rest-typings/src/v1/misc.ts
📜 Review details
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (4)
- GitHub Check: 📦 Build Packages
- GitHub Check: cubic · AI code reviewer
- GitHub Check: CodeQL-Build
- GitHub Check: CodeQL-Build
🧰 Additional context used
📓 Path-based instructions (1)
**/*.{ts,tsx,js}
📄 CodeRabbit inference engine (.cursor/rules/playwright.mdc)
**/*.{ts,tsx,js}: Write concise, technical TypeScript/JavaScript with accurate typing in Playwright tests
Avoid code comments in the implementation
Files:
apps/meteor/app/api/server/v1/ai-search.ts
🧠 Learnings (5)
📚 Learning: 2026-02-23T17:53:06.802Z
Learnt from: ggazzo
Repo: RocketChat/Rocket.Chat PR: 35995
File: apps/meteor/app/api/server/v1/rooms.ts:1107-1112
Timestamp: 2026-02-23T17:53:06.802Z
Learning: During PR reviews that touch endpoint files under apps/meteor/app/api/server/v1, enforce strict scope: if a PR targets a specific endpoint (e.g., rooms.favorite), do not propose changes to unrelated endpoints (e.g., rooms.invite) unless maintainers explicitly request them. Focus feedback on the touched endpoint's behavior, API surface, and related tests; avoid broad cross-endpoint changes in the same PR unless requested.
Applied to files:
apps/meteor/app/api/server/v1/ai-search.ts
📚 Learning: 2026-02-24T19:09:01.522Z
Learnt from: ahmed-n-abdeltwab
Repo: RocketChat/Rocket.Chat PR: 38974
File: apps/meteor/app/api/server/v1/im.ts:220-221
Timestamp: 2026-02-24T19:09:01.522Z
Learning: In Rocket.Chat OpenAPI migration PRs for endpoints under apps/meteor/app/api/server/v1, avoid introducing logic changes. Only perform scope-tight changes that preserve behavior; style-only cleanups (e.g., removing inline comments) may be deferred to follow-ups to keep the migration PR focused.
Applied to files:
apps/meteor/app/api/server/v1/ai-search.ts
📚 Learning: 2026-02-26T19:25:44.063Z
Learnt from: gabriellsh
Repo: RocketChat/Rocket.Chat PR: 38778
File: packages/ui-voip/src/providers/useMediaSession.ts:192-192
Timestamp: 2026-02-26T19:25:44.063Z
Learning: In the Rocket.Chat repository, do not reference Biome lint rules in code review feedback. Biome is not used even if biome.json exists; only reference Biome rules if there is explicit, project-wide usage documented. For TypeScript files, review lint implications without Biome guidance unless the project enables Biome rules.
Applied to files:
apps/meteor/app/api/server/v1/ai-search.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/app/api/server/v1/ai-search.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/app/api/server/v1/ai-search.ts
🔇 Additional comments (4)
apps/meteor/app/api/server/v1/ai-search.ts (4)
1-27: LGTM!
272-403: LGTM!
405-424: LGTM!
441-466: LGTM!
There was a problem hiding this comment.
1 issue found across 16 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/server/settings/index.ts">
<violation number="1" location="apps/meteor/server/settings/index.ts:43">
P3: AI settings now include `AI_Thread_Summarization`, but the AI Center UI only routes to Intelligent_Search and AI_LLM_Provider. That leaves the new section unreachable from the feature preview entrypoint.</violation>
</file>
<file name="apps/meteor/app/api/server/v1/ai-search.ts">
<violation number="1" location="apps/meteor/app/api/server/v1/ai-search.ts:242">
P1: `search.answer` now trusts `findVisibleByIds` results without checking the caller can access each message room, enabling private message content to be used in generated answers.</violation>
</file>
Tip: Review your code locally with the cubic CLI to iterate faster.
Re-trigger cubic
# Conflicts: # apps/meteor/client/navbar/NavBarSearch/NavBarSearch.tsx # apps/meteor/client/navbar/NavBarSearch/NavBarSearchListbox.tsx # apps/meteor/client/navbar/NavBarSearch/hooks/useSearchItems.ts
- i18n: localize NavBar filter suggestions (room/user/date) — remove hardcoded English; add Search_in_this_room and Search_messages_from_* - SearchPage: abort in-flight search.answer on query/source change and decouple the answer source set from pagination so "Show more" no longer retriggers a costly LLM generation (tie page size + answer slice to one constant) - search.answer: gate on AI Search license/feature availability before any DB work, and clamp client-supplied relevance scores to [0,1] - service: log the high-room-count unscoped-pipeline degraded path; move the default answer system prompt out of an indented template literal - a11y: wrap source results in a role="list" container - cleanup: drop the unused useFocusManager; document the deliberate helper duplication across the REST layer and AISearchService - tests: extend SearchPage source-row coverage (score clamping, non-link rendering) in the existing mockAppRoot style - docs: reframe completed work and clearly scope remaining items as future enhancements rather than open TODOs
There was a problem hiding this comment.
1 issue found across 8 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/server/settings/index.ts">
<violation number="1" location="apps/meteor/server/settings/index.ts:43">
P3: AI settings now include `AI_Thread_Summarization`, but the AI Center UI only routes to Intelligent_Search and AI_LLM_Provider. That leaves the new section unreachable from the feature preview entrypoint.</violation>
</file>
Tip: Review your code locally with the cubic CLI to iterate faster.
Re-trigger cubic
cardoso
left a comment
There was a problem hiding this comment.
Initial review (backend only)
| export const trimTrailingSlashes = (url: string): string => { | ||
| let end = url.length; | ||
|
|
||
| while (end > 0 && url.charCodeAt(end - 1) === 47) { | ||
| end--; | ||
| } | ||
|
|
||
| return url.slice(0, end); | ||
| }; |
There was a problem hiding this comment.
Is this file needed?
In service.ts:90 you use const normalizedBaseUrl = asString(baseUrl).replace(/\/+$/, '');. This separate function looks cryptic in comparison.
There was a problem hiding this comment.
Followed up in 474dd46c0e: removed the separate url.ts helper entirely. The package now builds endpoint URLs directly with new URL(path, baseUrl.endsWith("/") ? baseUrl : ${baseUrl}/), which avoids the cryptic manual trimming helper and also avoids reintroducing the previous slow-regex CodeQL warning.
| "For formatting the answer, use markdown. For code snippets, use markdown code blocks with the appropriate language specified. Keep the answers as concise as possible, while still providing a complete answer to the user's question, and everything in a single column, without using tables or other formatting that may be hard to read in the Rocket.Chat client.", | ||
| ].join('\n'); | ||
|
|
||
| const aiServiceFetch: AIServiceFetch = (url, options) => fetch(url, options as Parameters<typeof fetch>[1]); |
There was a problem hiding this comment.
Why have this AIServiceFetch type and cast the options param instead of using server-fetch directly?
There was a problem hiding this comment.
Updated in 9249be6e03: removed the local AIServiceFetch adapter/cast. The Meteor service now uses a small serverFetch wrapper that explicitly enforces SSRF validation with an empty allowlist before passing it into the pure package functions.
| async models(): Promise<AISearchModelOption[]> { | ||
| const [baseUrl, apiKey, selectedModel] = await Promise.all([ | ||
| Settings.get<string>('AI_LLM_OpenAI_Base_URL'), | ||
| Settings.get<string>('AI_LLM_OpenAI_API_Key'), | ||
| Settings.get<string>('AI_LLM_OpenAI_Model'), | ||
| ]); | ||
|
|
||
| return listOpenAICompatibleModels({ | ||
| provider: { | ||
| baseUrl: asString(baseUrl).replace(/\/+$/, ''), | ||
| apiKey: asString(apiKey), | ||
| }, | ||
| selectedModel: asString(selectedModel), | ||
| fetch: aiServiceFetch, | ||
| logger: SystemLogger, | ||
| }); | ||
| } | ||
| } |
There was a problem hiding this comment.
In lines 109-130, you read the same settings:
private async getAnswerProviderConfig(): Promise<OpenAICompatibleProviderConfig | undefined> {
const [baseUrl, apiKey, model] = await Promise.all([
Settings.get<string>('AI_LLM_OpenAI_Base_URL'),
Settings.get<string>('AI_LLM_OpenAI_API_Key'),
Settings.get<string>('AI_LLM_OpenAI_Model'),
]);
const normalizedBaseUrl = asString(baseUrl).replace(/\/+$/, '');
const normalizedApiKey = asString(apiKey);
const normalizedModel = asString(model);
if (!normalizedBaseUrl || !normalizedApiKey || !normalizedModel) {
return undefined;
}
return {
name: 'OpenAI compatible',
baseUrl: normalizedBaseUrl,
apiKey: normalizedApiKey,
model: normalizedModel,
};
}
Maybe reuse this code?
There was a problem hiding this comment.
Updated in 9249be6e03: added a shared getAnswerProviderSettings() helper. Answer generation still requires a selected model, while /models can reuse the same base URL/API key settings before a model is selected.
There was a problem hiding this comment.
Addressed in 9249be6e03: getAnswerProviderSettings() now centralizes the shared OpenAI-compatible base URL/API key/model reads. Answer generation still requires a selected model, while model listing can reuse the same base URL/API key before a model is selected.
| '@rocket.chat/meteor': minor | ||
| --- | ||
|
|
||
| Adds native Intelligent Search to the Rocket.Chat core — a semantic, vector-based search experience powered by an external AI pipeline and an optional LLM answer layer, accessible from the NavBar. |
There was a problem hiding this comment.
| Adds native Intelligent Search to the Rocket.Chat core — a semantic, vector-based search experience powered by an external AI pipeline and an optional LLM answer layer, accessible from the NavBar. | |
| Adds native Intelligent Search to the Rocket.Chat |
| properties: { | ||
| _id: { type: 'string' }, | ||
| t: { type: 'string' }, | ||
| name: { type: 'string', nullable: true }, |
There was a problem hiding this comment.
| name: { type: 'string', nullable: true }, | |
| name: { type: 'string' }, |
nullable is generally for required props that may accept null. This doesn't seem your case so you can remove. (from other props too)
| return value === true || value === 'true'; | ||
| }; | ||
|
|
||
| const parseQueryDate = (value: string | undefined): Date | undefined => { |
There was a problem hiding this comment.
We have a date ajv type that does this. no need for custom made parsers
| return Number.isNaN(date.getTime()) ? undefined : date; | ||
| }; | ||
|
|
||
| const requireNonEmptyQuery = (value: string): string => { |
There was a problem hiding this comment.
you can achieve the same by using minLength on the ajv schema for the props you use this for
| const getSearchAnswerMessagesForUser = async (userId: string, messages: SearchAnswer['messages']) => { | ||
| const messageIds = [...new Set(messages.map(({ _id }) => _id).filter(Boolean))]; | ||
| if (!messageIds.length) { | ||
| throw new Meteor.Error('error-invalid-search-answer-sources', 'Search answer sources are not available'); |
There was a problem hiding this comment.
use normal errors and add translations to them.
error-invalid... is enough and the UI should be able to show the human-way if you add translations for it.
same with other errors
|
|
||
| const rooms = await Promise.all(normalizedRoomNames.map((roomName) => Rooms.findOneByNameOrFname(roomName, { projection: { _id: 1 } }))); | ||
|
|
||
| return rooms.map((room) => room?._id).filter((roomId): roomId is string => Boolean(roomId)); |
There was a problem hiding this comment.
mongo won't return optional _id for rooms. you can map the cursor and avoid the ?._id as it's impossible.
| ...(filters?.fromUsernames || []), | ||
| ...(filters?.fromUsername ? [filters.fromUsername] : []), | ||
| ]); | ||
| if (filterUserIds) { |
There was a problem hiding this comment.
what about
if !filterUserIds?.length {
return { ... }
}
| const msgs = await Messages.findVisibleByIds(msgIds, { | ||
| projection: { _id: 1, rid: 1, msg: 1, ts: 1, u: 1 }, | ||
| }).toArray(); | ||
| for (const message of msgs) { |
There was a problem hiding this comment.
Fixed in 99a369931a: the subscription cursors now map in the cursor chain, e.g. Subscriptions.findByUserId(...).map(({ rid }) => rid).toArray() and the same pattern for findByUserIdAndRoomIds.
| for (const message of msgs) { | ||
| messageMap.set(String(message._id), message); | ||
| } | ||
| SystemLogger.debug({ msg: 'AI search messages fetched from DB', requested: msgIds.length, found: messageMap.size }); |
There was a problem hiding this comment.
create your own logger for service.
|
|
||
| private async getPipelineConfig(): Promise<IntelligentSearchPipelineConfig | undefined> { | ||
| const [baseUrl, pipelineId, apiKey, apiKeySecret, queryTemplate, minimumSimilarityPercent] = await Promise.all([ | ||
| Settings.get<string>('AI_Intelligent_Search_Pipeline_Base_URL'), |
There was a problem hiding this comment.
every call is a roundtrip. So:
- since this is not a micro service, you can use the regular cached settings here
- if you plan to run this as a micro service in the near future, then cache the settings calls and use the same pattern the microservices do: fetch once and listen for changes on event.
| const getSearchAnswerMessagesForUser = async (userId: string, messages: SearchAnswer['messages']) => { | ||
| const messageIds = [...new Set(messages.map(({ _id }) => _id).filter(Boolean))]; | ||
| if (!messageIds.length) { | ||
| throw new Meteor.Error('error-invalid-search-answer-sources'); | ||
| } | ||
|
|
||
| const clampScore = (score: number | undefined): number | undefined => | ||
| typeof score === 'number' && Number.isFinite(score) ? Math.min(1, Math.max(0, score)) : undefined; | ||
| const scoreByMessageId = new Map(messages.map(({ _id, score }) => [_id, clampScore(score)])); | ||
| const docs = await Messages.findVisibleByIds(messageIds, { | ||
| projection: { _id: 1, rid: 1, msg: 1, ts: 1, u: 1 }, | ||
| }).toArray(); | ||
| const subscribedRoomIds = await getSubscribedRoomIds( | ||
| userId, | ||
| docs.map((message) => message.rid), | ||
| ); | ||
| const subscribedDocs = docs.filter((message) => subscribedRoomIds.has(message.rid)); | ||
| if (subscribedDocs.length !== docs.length) { | ||
| throw new Meteor.Error('error-invalid-search-answer-sources'); | ||
| } | ||
|
|
||
| const normalizedDocs = await normalizeMessagesForUser(subscribedDocs, userId); | ||
| const docsById = new Map(normalizedDocs.map((message: IMessage) => [message._id, message])); | ||
| const rooms = await getRoomMap(normalizedDocs.map((message: IMessage) => message.rid)); | ||
|
|
||
| const answerMessages = messageIds | ||
| .map((messageId) => docsById.get(messageId)) | ||
| .filter((message): message is IMessage => Boolean(message?.msg)) | ||
| .map((message) => { | ||
| const room = rooms.get(message.rid); | ||
| const score = scoreByMessageId.get(message._id); | ||
|
|
||
| return { | ||
| text: message.msg, | ||
| username: message.u?.username, | ||
| roomName: room?.fname || room?.name, | ||
| ts: message.ts?.toISOString(), | ||
| ...(Number.isFinite(score) && { score }), | ||
| }; | ||
| }); | ||
|
|
||
| if (!answerMessages.length) { | ||
| throw new Meteor.Error('error-invalid-search-answer-sources'); | ||
| } | ||
|
|
||
| return answerMessages; | ||
| }; |
There was a problem hiding this comment.
Cross-Room Message Existence Oracle in search.answer API Endpoint
The newly introduced search.answer POST API endpoint is vulnerable to a cross-room message existence oracle. When a user requests an AI-generated answer based on a list of message IDs, the backend verifies if the user has access to all retrieved messages in getSearchAnswerMessagesForUser by comparing the number of found-and-subscribed messages to the number of found messages (subscribedDocs.length !== docs.length).
Because docs only contains messages that actually exist in the database (retrieved via Messages.findVisibleByIds), an attacker can supply a non-existent message ID alongside an accessible message ID, and the check will pass (since the non-existent message is not found, both subscribedDocs and docs will only contain the accessible message, making their lengths equal).
Conversely, if the attacker supplies a message ID that exists but belongs to a room they are not subscribed to, the message is found by Messages.findVisibleByIds (which does not check permissions) but filtered out of subscribedDocs, causing their lengths to differ and triggering an error-invalid-search-answer-sources exception.
By observing whether the API throws this error or succeeds, an attacker can determine whether any arbitrary message ID exists in the database, even if it belongs to a private room or direct message they do not have access to.
Preconditions
- The attacker must have a registered account on the Rocket.Chat instance.
- The AI Search and Answer Generation features must be licensed and enabled on the workspace.
Exploitation Path
- The attacker registers or logs into a standard user account.
- The attacker sends a POST request to
/api/v1/search.answerwith the following payload:{ "query": "any query", "messages": [ { "_id": "TARGET_MESSAGE_ID" }, { "_id": "ATTACKER_OWN_MESSAGE_ID" } ] } - If
TARGET_MESSAGE_IDexists in the database (in a room the attacker is not subscribed to), the server returns a400error witherror-invalid-search-answer-sources. - If
TARGET_MESSAGE_IDdoes not exist in the database, the server does not throw this error and proceeds to process the request (returning a200or a different error if the LLM provider fails). - The attacker repeats this to probe for the existence of arbitrary message IDs across the workspace.
Steps to Reproduce
Send a request with a non-existent message ID and an owned message ID
curl -X POST -H "X-Auth-Token: " -H "X-User-Id: "
-H "Content-Type: application/json"
-d '{"query": "test", "messages": [{"_id": "NON_EXISTENT_ID"}, {"_id": "OWN_MSG_ID"}]}'
http://localhost:3000/api/v1/search.answer
Response: 200 OK (or LLM error, but NOT error-invalid-search-answer-sources)
Send a request with a valid message ID from an inaccessible private room and an owned message ID
curl -X POST -H "X-Auth-Token: " -H "X-User-Id: "
-H "Content-Type: application/json"
-d '{"query": "test", "messages": [{"_id": "PRIVATE_ROOM_MSG_ID"}, {"_id": "OWN_MSG_ID"}]}'
http://localhost:3000/api/v1/search.answer
Response: 400 Bad Request {"success":false,"error":"error-invalid-search-answer-sources"}
Fix with AI
A security vulnerability was found by Hacktron.
File: apps/meteor/app/api/server/v1/ai-search.ts
Lines: 231-277
Severity: medium
Vulnerability: Cross-Room Message Existence Oracle in search.answer API Endpoint
Description:
The newly introduced `search.answer` POST API endpoint is vulnerable to a cross-room message existence oracle. When a user requests an AI-generated answer based on a list of message IDs, the backend verifies if the user has access to all retrieved messages in `getSearchAnswerMessagesForUser` by comparing the number of found-and-subscribed messages to the number of found messages (`subscribedDocs.length !== docs.length`).
Because `docs` only contains messages that actually exist in the database (retrieved via `Messages.findVisibleByIds`), an attacker can supply a non-existent message ID alongside an accessible message ID, and the check will pass (since the non-existent message is not found, both `subscribedDocs` and `docs` will only contain the accessible message, making their lengths equal).
Conversely, if the attacker supplies a message ID that exists but belongs to a room they are not subscribed to, the message is found by `Messages.findVisibleByIds` (which does not check permissions) but filtered out of `subscribedDocs`, causing their lengths to differ and triggering an `error-invalid-search-answer-sources` exception.
By observing whether the API throws this error or succeeds, an attacker can determine whether any arbitrary message ID exists in the database, even if it belongs to a private room or direct message they do not have access to.
### Preconditions
- The attacker must have a registered account on the Rocket.Chat instance.
- The AI Search and Answer Generation features must be licensed and enabled on the workspace.
### Exploitation Path
1. The attacker registers or logs into a standard user account.
2. The attacker sends a POST request to `/api/v1/search.answer` with the following payload:
```json
{
"query": "any query",
"messages": [
{ "_id": "TARGET_MESSAGE_ID" },
{ "_id": "ATTACKER_OWN_MESSAGE_ID" }
]
}
```
3. If `TARGET_MESSAGE_ID` exists in the database (in a room the attacker is not subscribed to), the server returns a `400` error with `error-invalid-search-answer-sources`.
4. If `TARGET_MESSAGE_ID` does not exist in the database, the server does not throw this error and proceeds to process the request (returning a `200` or a different error if the LLM provider fails).
5. The attacker repeats this to probe for the existence of arbitrary message IDs across the workspace.
Proof of Concept:
# Send a request with a non-existent message ID and an owned message ID
curl -X POST -H "X-Auth-Token: <token>" -H "X-User-Id: <uid>" \
-H "Content-Type: application/json" \
-d '{"query": "test", "messages": [{"_id": "NON_EXISTENT_ID"}, {"_id": "OWN_MSG_ID"}]}' \
http://localhost:3000/api/v1/search.answer
# Response: 200 OK (or LLM error, but NOT error-invalid-search-answer-sources)
# Send a request with a valid message ID from an inaccessible private room and an owned message ID
curl -X POST -H "X-Auth-Token: <token>" -H "X-User-Id: <uid>" \
-H "Content-Type: application/json" \
-d '{"query": "test", "messages": [{"_id": "PRIVATE_ROOM_MSG_ID"}, {"_id": "OWN_MSG_ID"}]}' \
http://localhost:3000/api/v1/search.answer
# Response: 400 Bad Request {"success":false,"error":"error-invalid-search-answer-sources"}
Affected Code:
- [ai-search.ts:240](https://github.com/RocketChat/Rocket.Chat/blob/main/apps/meteor/app/api/server/v1/ai-search.ts#L240): `const docs = await Messages.findVisibleByIds(messageIds, ...)` fetches all messages matching the requested IDs from the database, without enforcing room-level authorization.
- [ai-search.ts:247-248](https://github.com/RocketChat/Rocket.Chat/blob/main/apps/meteor/app/api/server/v1/ai-search.ts#L247-L248): `const subscribedDocs = docs.filter((message) => subscribedRoomIds.has(message.rid)); if (subscribedDocs.length !== docs.length) { throw new Meteor.Error('error-invalid-search-answer-sources'); }` compares the number of authorized messages found to the total number of messages found.
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), !accepted_risk <reason>, or !fixed (resolved). Any other reply is saved as a triage note.
Reason is optional but improves future scans — e.g. !fp internal endpoint, not user-facing.
There was a problem hiding this comment.
!fixed Confirmed valid as an existence-oracle edge case. Fixed in 561cbbe6c9 by rejecting when the number of DB-visible source messages does not exactly match the unique requested source IDs, using the same generic error-invalid-search-answer-sources response as the unsubscribed-room case. That makes missing IDs and inaccessible existing IDs indistinguishable before any LLM call is made.
There was a problem hiding this comment.
3 issues found across 13 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/server/settings/index.ts">
<violation number="1" location="apps/meteor/server/settings/index.ts:43">
P3: AI settings now include `AI_Thread_Summarization`, but the AI Center UI only routes to Intelligent_Search and AI_LLM_Provider. That leaves the new section unreachable from the feature preview entrypoint.</violation>
</file>
Tip: Review your code locally with the cubic CLI to iterate faster.
Re-trigger cubic
There was a problem hiding this comment.
1 issue found across 2 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/app/api/server/v1/ai-search.ts">
<violation number="1" location="apps/meteor/app/api/server/v1/ai-search.ts:411">
P2: Logging raw error objects from AISearch operations can leak sensitive user search filters, query text, or provider configuration into server logs, and will spam logs during provider outages.</violation>
</file>
Tip: Review your code locally with the cubic CLI to iterate faster.
Re-trigger cubic
| limit: intelligentLimit, | ||
| }); | ||
| } catch (error) { | ||
| this.logger.warn({ msg: 'AI search request failed', err: error }); |
There was a problem hiding this comment.
P2: Logging raw error objects from AISearch operations can leak sensitive user search filters, query text, or provider configuration into server logs, and will spam logs during provider outages.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At apps/meteor/app/api/server/v1/ai-search.ts, line 411:
<comment>Logging raw error objects from AISearch operations can leak sensitive user search filters, query text, or provider configuration into server logs, and will spam logs during provider outages.</comment>
<file context>
@@ -399,7 +407,8 @@ API.v1.get(
});
- } catch {
+ } catch (error) {
+ this.logger.warn({ msg: 'AI search request failed', err: error });
intelligentResults = [];
}
</file context>
Proposed changes (including videos or screenshots)
Screen.Recording.2026-06-16.at.7.29.42.PM.mov
Issue(s)
Steps to test or reproduce
Further comments
AI-53
Summary by CodeRabbit