Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/bump-patch-1766148726545.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@rocket.chat/meteor': patch
---

Bump @rocket.chat/meteor version.
5 changes: 5 additions & 0 deletions .changeset/fast-ligers-unite.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@rocket.chat/meteor': patch
---

Security Hotfix (https://docs.rocket.chat/docs/security-fixes-and-updates)
8 changes: 8 additions & 0 deletions .changeset/spicy-nails-design.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
"@rocket.chat/meteor": patch
"@rocket.chat/core-services": patch
"@rocket.chat/ddp-streamer": patch
"@rocket.chat/presence": patch
---

Ensures presence stays accurate by refreshing connections on heartbeats and removing stale sessions.
10 changes: 9 additions & 1 deletion .github/actions/build-docker/action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -75,14 +75,22 @@ runs:
set -o xtrace
export DENO_VERSION="${{ inputs.deno-version }}"

# Removes unnecessary swc cores to reduce image sized
# Removes unnecessary swc cores and sharp binaries to reduce image size
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Update comment to include all removed binaries.

The comment mentions only "swc cores and sharp binaries" but the code also removes pinyin (line 89) and esbuild binaries (lines 91, 93). Update the comment to reflect all removal operations for clarity.

🔎 Suggested fix
-        # Removes unnecessary swc cores and sharp binaries to reduce image size
+        # Removes unnecessary swc cores, sharp, pinyin, and esbuild binaries to reduce image size
📝 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
# Removes unnecessary swc cores and sharp binaries to reduce image size
# Removes unnecessary swc cores, sharp, pinyin, and esbuild binaries to reduce image size
🤖 Prompt for AI Agents
.github/actions/build-docker/action.yml around line 78: the existing comment
only mentions "swc cores and sharp binaries" but the removal block also removes
pinyin and esbuild binaries; update the comment to list all removed items (swc
cores, sharp, pinyin, and esbuild binaries) or use a generic phrase like
"unnecessary native binaries (swc cores, sharp, pinyin, esbuild)" so the comment
accurately reflects the cleanup operations.

swc_arch='x64'
if [[ "${{ inputs.service }}" == 'rocketchat' ]]; then
if [[ "${{ inputs.arch }}" == 'arm64' ]]; then
swc_arch='arm64'
fi

find /tmp/build/bundle/programs/server/npm/node_modules/meteor/babel-compiler/node_modules/@meteorjs/swc-core/.swc/node_modules/@swc -type d -name 'core-*' -not -name "*linux-${swc_arch}-gnu*" -exec rm -rf {} +

find /tmp/build/bundle/programs/server/npm/node_modules/@img -type d -name 'sharp-*' -not -name "*-linuxmusl-${swc_arch}" -exec rm -rf {} +

find /tmp/build/bundle/programs/server/npm/node_modules/@napi-rs -type d -name 'pinyin-linux-*' -not -name "*-linux-${swc_arch}-*" -exec rm -rf {} +

find /tmp/build/bundle/programs/server/npm/node_modules/@esbuild -type d -name 'linux-*' -not -name "*-${swc_arch}" -exec rm -rf {} +

find /tmp/build/bundle/programs/server/npm/node_modules/@rocket.chat/apps-engine/node_modules/@esbuild -type d -name 'linux-*' -not -name "*-${swc_arch}" -exec rm -rf {} +
fi

if [[ "${{ inputs.publish-image }}" == 'true' ]]; then
Expand Down
10 changes: 8 additions & 2 deletions .github/actions/setup-node/action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,8 @@ runs:
apps/meteor/ee/server/services/node_modules
packages/apps-engine/node_modules
packages/apps-engine/.deno-cache
key: node-modules-${{ inputs.type }}-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('package.json') }}-${{ hashFiles('yarn.lock') }}-deno-v${{ inputs.deno-version }}-${{ hashFiles('packages/apps-engine/deno-runtime/deno.lock') }}-v3
# key: node-modules-${{ inputs.type }}-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('package.json') }}-${{ hashFiles('yarn.lock') }}-deno-v${{ inputs.deno-version }}-${{ hashFiles('packages/apps-engine/deno-runtime/deno.lock') }}-v${{ github.run_id }}
key: node-modules-${{ inputs.type }}-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('package.json') }}-${{ hashFiles('yarn.lock') }}-${{ hashFiles('.yarnrc.yml') }}-deno-v${{ inputs.deno-version }}-${{ hashFiles('packages/apps-engine/deno-runtime/deno.lock') }}-v5
# key: node-modules-${{ inputs.type }}-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('package.json') }}-${{ hashFiles('yarn.lock') }}-${{ hashFiles('.yarnrc.yml') }}-deno-v${{ inputs.deno-version }}-${{ hashFiles('packages/apps-engine/deno-runtime/deno.lock') }}-v${{ github.run_id }}
#
# Could use this command to list all paths to save:
# find . -name 'node_modules' -prune | grep -v "/\.meteor/" | grep -v "/meteor/packages/"
Expand All @@ -75,6 +75,12 @@ runs:
run: |
echo "//registry.npmjs.org/:_authToken=${{ inputs.NPM_TOKEN }}" > ~/.npmrc

- name: yarn config
if: inputs.install
shell: bash
run: |
yarn config set supportedArchitectures --json '{"os": ["linux"], "cpu": ["arm64", "x64"], "libc": ["glibc", "musl"]}'

- name: yarn install
if: inputs.install && inputs.type == 'development'
shell: bash
Expand Down
9 changes: 1 addition & 8 deletions apps/meteor/.docker/Dockerfile.alpine
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,7 @@ COPY . /app
ENV NODE_ENV=production

RUN cd /app/bundle/programs/server \
&& npm install --omit=dev \
# Re install sharp dependencies to ensure proper binary for architecture
# We only need the @img folder from sharp dependencies
&& cd /app/bundle/programs/server/npm/node_modules/sharp \
&& npm install --omit=dev \
&& rm -rf ../@img \
&& mv node_modules/@img ../@img \
&& rm -rf node_modules
&& npm install --omit=dev

FROM node:22.16.0-alpine3.20

Expand Down
20 changes: 13 additions & 7 deletions apps/meteor/app/api/server/lib/isValidQuery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,16 +23,22 @@ export const isValidQuery: {
const verifyQuery = (query: Query, allowedAttributes: string[], allowedOperations: string[], parent = ''): boolean => {
return Object.entries(removeDangerousProps(query)).every(([key, value]) => {
const path = parent ? `${parent}.${key}` : key;
if (parent === '' && path.startsWith('$')) {
if (!allowedOperations.includes(path)) {
isValidQuery.errors.push(`Invalid operation: ${path}`);
if (key.startsWith('$')) {
if (!allowedOperations.includes(key)) {
isValidQuery.errors.push(`Invalid operation: ${key}`);
return false;
}
if (!Array.isArray(value)) {
isValidQuery.errors.push(`Invalid parameter for operation: ${path} : ${value}`);
return false;

if (Array.isArray(value)) {
return value.every((v) => verifyQuery(v, allowedAttributes, allowedOperations));
}
return value.every((v) => verifyQuery(v, allowedAttributes, allowedOperations));

if (value instanceof Object) {
return verifyQuery(value, allowedAttributes, allowedOperations, path);
}

// handles primitive values (strings, numbers, booleans, etc.)
return true;
}

if (
Expand Down
20 changes: 15 additions & 5 deletions apps/meteor/app/api/server/v1/users.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ import {
} from '../../../lib/server/functions/checkUsernameAvailability';
import { deleteUser } from '../../../lib/server/functions/deleteUser';
import { getAvatarSuggestionForUser } from '../../../lib/server/functions/getAvatarSuggestionForUser';
import { getFullUserDataByIdOrUsernameOrImportId } from '../../../lib/server/functions/getFullUserData';
import { getFullUserDataByIdOrUsernameOrImportId, defaultFields, fullFields } from '../../../lib/server/functions/getFullUserData';
import { generateUsernameSuggestion } from '../../../lib/server/functions/getUsernameSuggestion';
import { saveCustomFields } from '../../../lib/server/functions/saveCustomFields';
import { saveCustomFieldsWithoutValidation } from '../../../lib/server/functions/saveCustomFieldsWithoutValidation';
Expand Down Expand Up @@ -503,13 +503,18 @@ API.v1.addRoute(
const { offset, count } = await getPaginationItems(this.queryParams);
const { sort, fields, query } = await this.parseJsonQuery();

const nonEmptyQuery = getNonEmptyQuery(query, await hasPermissionAsync(this.userId, 'view-full-other-user-info'));
const nonEmptyFields = getNonEmptyFields(fields);

const inclusiveFields = getInclusiveFields(nonEmptyFields);

const inclusiveFieldsKeys = Object.keys(inclusiveFields);

const hasUserQuery = query && Object.keys(query).length > 0;

const nonEmptyQuery = getNonEmptyQuery(query, await hasPermissionAsync(this.userId, 'view-full-other-user-info'));

// if user provided a query, validate it with their allowed operators
// otherwise we use the default query (with $regex and $options)
if (
!isValidQuery(
nonEmptyQuery,
Expand All @@ -521,7 +526,7 @@ API.v1.addRoute(
inclusiveFieldsKeys.includes('type') && 'type.*',
inclusiveFieldsKeys.includes('customFields') && 'customFields.*',
].filter(Boolean) as string[],
this.queryOperations,
hasUserQuery ? this.queryOperations : [...this.queryOperations, '$regex', '$options'],
)
) {
throw new Meteor.Error('error-invalid-query', isValidQuery.errors.join('\n'));
Expand Down Expand Up @@ -1144,8 +1149,13 @@ API.v1.addRoute(
const selector: { exceptions: Required<IUser>['username'][]; conditions: Filter<IUser>; term: string } = JSON.parse(selectorRaw);

try {
if (selector?.conditions && !isValidQuery(selector.conditions, ['*'], ['$or', '$and'])) {
throw new Error('error-invalid-query');
if (selector?.conditions) {
const canViewFullInfo = await hasPermissionAsync(this.userId, 'view-full-other-user-info');
const allowedFields = canViewFullInfo ? [...Object.keys(defaultFields), ...Object.keys(fullFields)] : Object.keys(defaultFields);

if (!isValidQuery(selector.conditions, allowedFields, ['$and', '$ne', '$exists'])) {
throw new Error('error-invalid-query');
}
}
} catch (e) {
return API.v1.failure(e);
Expand Down
4 changes: 2 additions & 2 deletions apps/meteor/app/lib/server/functions/getFullUserData.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { settings } from '../../../settings/server';

const logger = new Logger('getFullUserData');

const defaultFields = {
export const defaultFields = {
name: 1,
username: 1,
nickname: 1,
Expand All @@ -24,7 +24,7 @@ const defaultFields = {
statusLivechat: 1,
} as const;

const fullFields = {
export const fullFields = {
emails: 1,
phone: 1,
statusConnection: 1,
Expand Down
64 changes: 64 additions & 0 deletions apps/meteor/definition/externals/meteor/ddp-common.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,5 +14,69 @@ declare module 'meteor/ddp-common' {
userId?: string;
});
}

/**
* Heartbeat options
*/
type HeartbeatOptions = {
/**
* interval to send pings, in milliseconds
*/
heartbeatInterval: number;
/**
* timeout to close the connection if a reply isn't received, in milliseconds.
*/
heartbeatTimeout: number;
/**
* function to call to send a ping on the connection.
*/
sendPing: () => void;
/**
* function to call to close the connection
*/
onTimeout: () => void;
};

class Heartbeat {
heartbeatInterval: number;

heartbeatTimeout: number;

_sendPing: () => void;

_onTimeout: () => void;

_seenPacket: boolean;

_heartbeatIntervalHandle: ReturnType<typeof setTimeout> | null;

_heartbeatTimeoutHandle: ReturnType<typeof setTimeout> | null;

constructor(options: HeartbeatOptions);

stop(): void;

start(): void;

_startHeartbeatIntervalTimer(): void;

_startHeartbeatTimeoutTimer(): void;

_clearHeartbeatIntervalTimer(): void;

_clearHeartbeatTimeoutTimer(): void;

/**
* The heartbeat interval timer is fired when we should send a ping.
*/
_heartbeatIntervalFired(): void;

/**
* The heartbeat timeout timer is fired when we sent a ping, but we timed out waiting for the pong.
*/
_heartbeatTimeoutFired(): void;

messageReceived(): void;
}
}
}
9 changes: 7 additions & 2 deletions apps/meteor/definition/externals/meteor/meteor.d.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import 'meteor/meteor';
import type { ServerMethods } from '@rocket.chat/ddp-client';
import type { IStreamerConstructor, IStreamer } from 'meteor/rocketchat:streamer';
import type { DDPCommon, IStreamerConstructor, IStreamer } from 'meteor/ddp-common';

type StringifyBuffers<T extends unknown[]> = {
[P in keyof T]: T[P] extends Buffer ? string : T[P];
Expand Down Expand Up @@ -39,7 +39,12 @@ declare module 'meteor/meteor' {
isDesktop: () => boolean;
}

const server: any;
const server: {
sessions: Map<string, { userId: string; heartbeat: DDPCommon.Heartbeat }>;
publish_handlers: {
meteor_autoupdate_clientVersions(): void;
};
};

const runAsUser: <T>(userId: string, scope: () => T) => T;

Expand Down
10 changes: 10 additions & 0 deletions apps/meteor/ee/server/startup/presence.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,16 @@ Meteor.startup(() => {
return;
}

const _messageReceived = session.heartbeat.messageReceived.bind(session.heartbeat);
session.heartbeat.messageReceived = function messageReceived() {
if (this._seenPacket === false) {
void Presence.updateConnection(login.user._id, login.connection.id).catch((err) => {
console.error('Error updating connection presence on heartbeat:', err);
});
}
return _messageReceived();
};

void (async function () {
await Presence.newConnection(login.user._id, login.connection.id, nodeId);
updateConns();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ describe('isValidQuery', () => {
},
},
};
expect(isValidQuery(query, props, ['$or'])).to.be.true;
expect(isValidQuery(query, props, ['$or', '$regex'])).to.be.true;
expect(isValidQuery.errors.length).to.be.equals(0);
});

Expand Down Expand Up @@ -212,5 +212,15 @@ describe('isValidQuery', () => {
),
).to.be.false;
});

it('should return false if the query contains nested conditions with disallowed operators', () => {
const props = ['username'];
const allowedOps = ['$and', '$ne'];
const query = {
$and: [{ username: { $exists: true } }, { username: { $ne: '1000' } }],
};
expect(isValidQuery(query, props, allowedOps)).to.be.false;
expect(isValidQuery.errors.length).to.be.equals(1);
});
});
});
15 changes: 15 additions & 0 deletions ee/apps/ddp-streamer/src/Client.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import { EventEmitter } from 'events';
import type { IncomingMessage } from 'http';

import { Presence } from '@rocket.chat/core-services';
import type { ISocketConnection } from '@rocket.chat/core-typings';
import { throttle } from 'underscore';
import { v1 as uuidv1 } from 'uuid';
import type WebSocket from 'ws';

Expand Down Expand Up @@ -73,6 +75,18 @@ export class Client extends EventEmitter {

public userToken?: string;

private updatePresence = throttle(
() => {
if (this.userId) {
void Presence.updateConnection(this.userId, this.connection.id).catch((err) => {
console.error('Error updating connection presence:', err);
});
}
},
TIMEOUT,
{ leading: true, trailing: false },
);

constructor(
public ws: WebSocket,
public meteorClient = false,
Expand Down Expand Up @@ -200,6 +214,7 @@ export class Client extends EventEmitter {
handler = async (payload: WebSocket.Data, isBinary: boolean): Promise<void> => {
try {
const packet = server.parse(payload, isBinary);
this.updatePresence();
this.emit('message', packet);
if (this.wait) {
return new Promise((resolve) => this.once(DDP_EVENTS.LOGGED, () => resolve(this.process(packet.msg, packet))));
Expand Down
Loading
Loading