snapshot of https://github.com/RocketChat/Rocket.Chat.git (develop, 2026-09-16; blobs > 131072B omitted)
Some checks failed
Create issues from TODOs / todos (push) Failing after 3s
Close inactive issues / close-issues (push) Has been cancelled
Deploy GitHub Pages / deploy-preview (push) Has been cancelled
CI / ⚙️ Variables Setup (push) Has been cancelled
CI / ⚙️ Test Guard (push) Has been cancelled
CI / 🚀 Notify external services - draft (push) Has been cancelled
CI / 📦 Build Packages (push) Has been cancelled
CI / 📦 Meteor Build (coverage) (push) Has been cancelled
CI / 📦 Meteor Build (production) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [account-service presence-service omnichannel-transcript-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [account-service presence-service omnichannel-transcript-service], fips) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [authorization-service queue-worker-service ddp-streamer-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [authorization-service queue-worker-service ddp-streamer-service], fips) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], coverage) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], fips) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [account-service presence-service omnichannel-transcript-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [authorization-service queue-worker-service ddp-streamer-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [rocketchat], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [rocketchat], coverage) (push) Has been cancelled
CI / 🚢 Publish Docker Images (ghcr.io) (push) Has been cancelled
CI / 📦 Track Image Sizes (push) Has been cancelled
CI / 🔎 Code Check - Action Lint (push) Has been cancelled
CI / 🔎 Code Check (push) Has been cancelled
CI / 🔨 Test Storybook (push) Has been cancelled
CI / 🔨 Test Unit (push) Has been cancelled
CI / 🔨 Test API (CE) (push) Has been cancelled
CI / 🔨 Test API Livechat (CE) (push) Has been cancelled
CI / 🔨 Test UI (CE) (push) Has been cancelled
CI / 🔨 Test API (EE) (push) Has been cancelled
CI / 🔨 Test API Livechat (EE) (push) Has been cancelled
CI / 🔨 Test API Apps (deno-runtime - EE) (push) Has been cancelled
CI / 🔨 Test UI (EE) (push) Has been cancelled
CI / 🔨 Test API (FIPS) (push) Has been cancelled
CI / 🔨 Test API Livechat (FIPS) (push) Has been cancelled
CI / 🔨 Test UI (FIPS) (push) Has been cancelled
CI / 🔨 Test Federation Matrix (push) Has been cancelled
CI / 📊 Report Coverage (push) Has been cancelled
CI / ✅ Tests Done (push) Has been cancelled
CI / 🚀 Publish build assets (push) Has been cancelled
CI / 🚀 Publish Docker Images (DockerHub) (push) Has been cancelled
CI / 🚀 Notify external services (push) Has been cancelled
CI / Update Version Durability (push) Has been cancelled
Release / Release (push) Has been cancelled
Auto-close duplicate issues / auto-close-duplicates (push) Failing after 1s
Code scanning - action / CodeQL-Build (push) Failing after 1s

This commit is contained in:
upstream-mirror
2026-09-16 01:21:02 +05:00
commit 30810eecd7
10161 changed files with 987110 additions and 0 deletions

View File

@@ -0,0 +1,35 @@
import { pino } from 'pino';
export function getLogger({ MOLECULER_LOG_LEVEL: level, NODE_ENV: mode }: Record<string, unknown> = {}) {
if (!level || typeof level !== 'string') {
return {};
}
if (!['fatal', 'error', 'warn', 'info', 'debug', 'trace'].includes(level)) {
return {};
}
return {
logger: {
type: 'Pino',
options: {
level,
pino: {
options: {
timestamp: pino.stdTimeFunctions.isoTime,
...(mode !== 'production'
? {
transport: {
target: 'pino-pretty',
options: {
colorize: true,
},
},
}
: {}),
},
},
},
},
};
}

View File

@@ -0,0 +1,17 @@
export function getTransporter({ transporter, port, extra }: { transporter?: string; port?: string; extra?: string } = {}) {
if (transporter) {
if (!transporter.match(/^(?:monolith\+)/)) {
throw new Error('invalid transporter');
}
const [, ...url] = transporter.split('+');
return url.join('');
}
return {
port: port ? port.trim() : 0,
udpDiscovery: false,
useHostname: false,
...(extra ? JSON.parse(extra) : {}),
};
}

View File

@@ -0,0 +1,257 @@
import os from 'node:os';
import type { AppStatusReport } from '@rocket.chat/core-services';
import { Apps, License, ServiceClassInternal, Settings } from '@rocket.chat/core-services';
import type { IInstanceStatus } from '@rocket.chat/core-typings';
import { InstanceStatus, defaultPingInterval, indexExpire } from '@rocket.chat/instance-status';
import { InstanceStatus as InstanceStatusRaw } from '@rocket.chat/models';
import EJSON from 'ejson';
import type { BrokerNode } from 'moleculer';
import { ServiceBroker, Transporters, Serializers } from 'moleculer';
import { getLogger } from './getLogger';
import { getTransporter } from './getTransporter';
import { SystemLogger } from '../../../../server/lib/logger/system';
import { StreamerCentral } from '../../../../server/modules/streamer/streamer.module';
import { AppsEngineNoNodesFoundError } from '../../../../server/services/apps-engine/service';
import type { IInstanceService } from '../../sdk/types/IInstanceService';
const hostIP = process.env.INSTANCE_IP ? String(process.env.INSTANCE_IP).trim() : 'localhost';
const { Base } = Serializers;
class EJSONSerializer extends Base {
override serialize(obj: any): Buffer {
return Buffer.from(EJSON.stringify(obj));
}
override deserialize(buf: Buffer): any {
return EJSON.parse(buf.toString());
}
}
export class InstanceService extends ServiceClassInternal implements IInstanceService {
protected name = 'instance';
private broadcastStarted = false;
private transporter: Transporters.TCP | Transporters.NATS;
private broker: ServiceBroker;
private troubleshootDisableInstanceBroadcast = false;
constructor() {
super();
this.onEvent('license.module', async ({ module, valid }) => {
if (module === 'scalability' && valid) {
await this.startBroadcast();
}
});
this.onSettingChanged('Troubleshoot_Disable_Instance_Broadcast', async ({ setting }): Promise<void> => {
const { value } = setting;
if (typeof value !== 'boolean') {
return;
}
if (this.troubleshootDisableInstanceBroadcast === value) {
return;
}
this.troubleshootDisableInstanceBroadcast = value;
});
}
override async created() {
const transporter = getTransporter({
transporter: process.env.TRANSPORTER,
port: process.env.TCP_PORT,
extra: process.env.TRANSPORTER_EXTRA,
});
const isTransporterTCP = typeof transporter !== 'string';
this.transporter = isTransporterTCP ? new Transporters.TCP(transporter) : new Transporters.NATS({ url: transporter });
this.broker = new ServiceBroker({
nodeID: InstanceStatus.id(),
transporter: this.transporter,
serializer: new EJSONSerializer(),
heartbeatInterval: defaultPingInterval,
heartbeatTimeout: indexExpire,
...getLogger(process.env),
});
this.broker.createService({
name: 'matrix',
events: {
broadcast(ctx: any) {
const { eventName, streamName, args } = ctx.params;
const { nodeID } = ctx;
const fromLocalNode = nodeID === InstanceStatus.id();
if (fromLocalNode) {
return;
}
const instance = StreamerCentral.instances[streamName];
if (!instance) {
// return 'stream-not-exists';
return;
}
if (instance.serverOnly) {
instance.__emit(eventName, ...args);
} else {
// @ts-expect-error not sure why it thinks _emit needs an extra argument
StreamerCentral.instances[streamName]._emit(eventName, args);
}
},
},
actions: {
getAppsStatus(_ctx) {
return Apps.getAppsStatusLocal();
},
},
});
if (isTransporterTCP) {
const changeStream = InstanceStatusRaw.watchActiveInstances();
changeStream
.on('change', (change) => {
if (change.operationType === 'update') {
return;
}
if (change.operationType === 'insert' && change.fullDocument?.extraInformation?.tcpPort) {
this.connectNode(change.fullDocument);
return;
}
if (change.operationType === 'delete') {
this.disconnectNode(change.documentKey._id);
}
})
.once('error', (err) => {
SystemLogger.error({ msg: 'Error in InstanceStatus change stream:', err });
});
}
}
private connectNode(record: IInstanceStatus) {
if (record._id === InstanceStatus.id()) {
return;
}
const { host, tcpPort } = record.extraInformation;
(this.broker?.transit?.tx as any).addOfflineNode(record._id, host, tcpPort);
}
private disconnectNode(nodeId: string) {
(this.broker.transit?.tx as any).nodes.disconnected(nodeId, false);
(this.broker.transit?.tx as any).nodes.nodes.delete(nodeId);
}
override async started() {
await this.broker.start();
const instance = {
host: hostIP,
port: String(process.env.PORT).trim(),
tcpPort: (this.broker.transit?.tx as any)?.nodes?.localNode?.port,
os: {
type: os.type(),
platform: os.platform(),
arch: os.arch(),
release: os.release(),
uptime: os.uptime(),
loadavg: os.loadavg(),
totalmem: os.totalmem(),
freemem: os.freemem(),
cpus: os.cpus().length,
},
nodeVersion: process.version,
};
await InstanceStatus.registerInstance('rocket.chat', instance);
try {
const hasLicense = await License.hasModule('scalability');
if (!hasLicense) {
return;
}
this.troubleshootDisableInstanceBroadcast = await Settings.get<boolean>('Troubleshoot_Disable_Instance_Broadcast');
await this.startBroadcast();
} catch (error) {
console.error('Instance service did not start correctly', error);
}
}
private async startBroadcast() {
if (this.broadcastStarted) {
return;
}
this.broadcastStarted = true;
StreamerCentral.on('broadcast', this.sendBroadcast.bind(this));
}
private sendBroadcast(streamName: string, eventName: string, args: unknown[]) {
if (this.troubleshootDisableInstanceBroadcast) {
return;
}
void this.broker.broadcast('broadcast', { streamName, eventName, args });
}
async getInstances(): Promise<BrokerNode[]> {
return this.broker.call('$node.list', { onlyAvailable: true });
}
async getAppsStatusInInstances(): Promise<AppStatusReport> {
const instances = await this.getInstances();
if (instances.length < 2) {
throw new AppsEngineNoNodesFoundError();
}
const control: Promise<void>[] = [];
const statusByApp: AppStatusReport = {};
instances.forEach((instance) => {
const { id: instanceId } = instance;
control.push(
(async () => {
const appsStatus = await this.broker.call<Awaited<ReturnType<(typeof Apps)['getAppsStatusLocal']>>, null>(
'matrix.getAppsStatus',
null,
{ nodeID: instanceId },
);
if (!appsStatus) {
throw new Error(`Failed to get apps status from instance ${instanceId}`);
}
appsStatus.forEach(({ status, appId }) => {
if (!statusByApp[appId]) {
statusByApp[appId] = [];
}
statusByApp[appId].push({ instanceId, isLocal: instance.local, status });
});
})(),
);
});
await Promise.all(control);
return statusByApp;
}
}

View File

@@ -0,0 +1,38 @@
import { ServiceClassInternal, type ILDAPEEService } from '@rocket.chat/core-services';
import type { IUser } from '@rocket.chat/core-typings';
import { Users } from '@rocket.chat/models';
import type { FindCursor } from 'mongodb';
import { LDAPEEManager } from '../../lib/ldap/Manager';
export class LDAPEEService extends ServiceClassInternal implements ILDAPEEService {
protected name = 'ldap-enterprise';
async sync(): Promise<void> {
return LDAPEEManager.sync();
}
async syncAvatars(): Promise<void> {
return LDAPEEManager.syncAvatars();
}
async syncAvatarAndAbacAttributes(): Promise<void> {
return LDAPEEManager.syncAvatarAndAbacAttributes();
}
async syncLogout(): Promise<void> {
return LDAPEEManager.syncLogout();
}
async syncAbacAttributes(): Promise<void> {
return LDAPEEManager.syncAbacAttributes();
}
async syncUsersAbacAttributes(users: FindCursor<IUser>): Promise<void> {
return LDAPEEManager.syncUsersAbacAttributes(users);
}
async syncUsersAbacAttributesByIds(userIds: string[]): Promise<void> {
return LDAPEEManager.syncUsersAbacAttributes(Users.findUsersByIdentifiers({ ids: userIds }));
}
}

View File

@@ -0,0 +1,51 @@
import { ServiceClassInternal, api } from '@rocket.chat/core-services';
import { Messages, MessageReads, Subscriptions } from '@rocket.chat/models';
import { MAX_ROOM_SIZE_CHECK_INDIVIDUAL_READ_RECEIPTS } from '../../lib/constants';
import { ReadReceipt } from '../../lib/message-read-receipt/ReadReceipt';
import type { IMessageReadsService } from '../../sdk/types/IMessageReadsService';
export class MessageReadsService extends ServiceClassInternal implements IMessageReadsService {
protected name = 'message-reads';
async readThread(userId: string, tmid: string): Promise<void> {
const read = await MessageReads.findOneByUserIdAndThreadId(userId, tmid);
const threadMessage = await Messages.findOneById(tmid, { projection: { ts: 1, tlm: 1, rid: 1 } });
if (!threadMessage?.tlm) {
return;
}
await MessageReads.updateReadTimestampByUserIdAndThreadId(userId, tmid);
await ReadReceipt.storeThreadMessagesReadReceipts(tmid, userId, read?.ls || threadMessage.ts);
// doesn't mark as read if not all room members have read the thread
const membersCount = await Subscriptions.countUnarchivedByRoomId(threadMessage.rid);
if (membersCount <= MAX_ROOM_SIZE_CHECK_INDIVIDUAL_READ_RECEIPTS) {
const subscriptions = await Subscriptions.findUnarchivedByRoomId(threadMessage.rid, {
projection: { 'u._id': 1 },
}).toArray();
const members = subscriptions.map((s) => s.u._id);
const totalMessageReads = await MessageReads.countByThreadAndUserIds(tmid, members);
if (totalMessageReads < membersCount) {
return;
}
} else {
// for large rooms, mark as read if there are as many reads as room members to improve performance (instead of checking each read)
const totalMessageReads = await MessageReads.countByThreadId(tmid);
if (totalMessageReads < membersCount) {
return;
}
}
const firstRead = await MessageReads.getMinimumLastSeenByThreadId(tmid);
if (firstRead?.ls) {
const result = await Messages.setThreadMessagesAsRead(threadMessage.rid, tmid, firstRead.ls);
if (result.modifiedCount > 0) {
void api.broadcast('notify.messagesRead', { rid: threadMessage.rid, tmid, until: firstRead.ls });
}
}
}
}

View File

@@ -0,0 +1,208 @@
import { ServiceClassInternal, Message } from '@rocket.chat/core-services';
import type { IOmnichannelEEService } from '@rocket.chat/core-services';
import { isOmnichannelRoom, LivechatInquiryStatus } from '@rocket.chat/core-typings';
import type { IOmnichannelRoom, IUser, ILivechatInquiryRecord, IOmnichannelSystemMessage } from '@rocket.chat/core-typings';
import { Logger } from '@rocket.chat/logger';
import { LivechatRooms, Subscriptions, LivechatInquiry } from '@rocket.chat/models';
import { callbacks } from '../../../server/lib/callbacks';
import {
notifyOnSubscriptionChangedByRoomId,
notifyOnLivechatInquiryChangedById,
notifyOnRoomChangedById,
} from '../../../server/lib/notifyListener';
import { dispatchAgentDelegated } from '../../../server/lib/omnichannel/Helper';
import { queueInquiry } from '../../../server/lib/omnichannel/QueueManager';
import { RoutingManager } from '../../../server/lib/omnichannel/RoutingManager';
import { settings } from '../../../server/settings';
export class OmnichannelEE extends ServiceClassInternal implements IOmnichannelEEService {
protected name = 'omnichannel-ee';
protected override internal = true;
logger: Logger;
constructor() {
super();
this.logger = new Logger('OmnichannelEE');
}
async placeRoomOnHold(
room: Pick<IOmnichannelRoom, '_id' | 't' | 'open' | 'onHold'>,
comment: string,
onHoldBy: Pick<IUser, '_id' | 'username' | 'name'>,
) {
this.logger.debug({ msg: 'Attempting to place room on hold', roomId: room._id, userId: onHoldBy?._id });
const { _id: roomId } = room;
if (!room || !isOmnichannelRoom(room)) {
throw new Error('error-invalid-room');
}
if (!room.open) {
throw new Error('error-room-already-closed');
}
if (room.onHold) {
throw new Error('error-room-is-already-on-hold');
}
const restrictedOnHold = settings.get('Livechat_allow_manual_on_hold_upon_agent_engagement_only');
const canRoomBePlacedOnHold = !room.onHold;
const canAgentPlaceOnHold = !room.lastMessage?.token;
const canPlaceChatOnHold = canRoomBePlacedOnHold && (!restrictedOnHold || canAgentPlaceOnHold);
if (!canPlaceChatOnHold) {
throw new Error('error-cannot-place-chat-on-hold');
}
if (!room.servedBy) {
throw new Error('error-unserved-rooms-cannot-be-placed-onhold');
}
const [roomResult, subsResult] = await Promise.all([
LivechatRooms.setOnHoldByRoomId(roomId),
Subscriptions.setOnHoldByRoomId(roomId),
Message.saveSystemMessage<IOmnichannelSystemMessage>('omnichannel_placed_chat_on_hold', roomId, '', onHoldBy, { comment }),
]);
if (roomResult.modifiedCount) {
void notifyOnRoomChangedById(roomId);
}
if (subsResult.modifiedCount) {
void notifyOnSubscriptionChangedByRoomId(roomId);
}
await callbacks.run('livechat:afterOnHold', room);
}
async resumeRoomOnHold(
room: Pick<IOmnichannelRoom, '_id' | 't' | 'open' | 'onHold' | 'servedBy'>,
comment: string,
resumeBy: Pick<IUser, '_id' | 'username' | 'name'>,
clientAction = false,
) {
this.logger.debug({ msg: 'Attempting to resume room on hold', roomId: room._id, userId: resumeBy?._id });
if (!room || !isOmnichannelRoom(room)) {
throw new Error('error-invalid-room');
}
if (!room.open) {
throw new Error('This_conversation_is_already_closed');
}
if (!room.onHold) {
throw new Error('error-room-not-on-hold');
}
const { _id: roomId, servedBy } = room;
if (!servedBy) {
this.logger.error({ msg: 'No serving agent found for room', roomId });
throw new Error('error-room-not-served');
}
const inquiry = await LivechatInquiry.findOneByRoomId(roomId, {});
if (!inquiry) {
this.logger.error({ msg: 'No inquiry found for room', roomId });
throw new Error('error-invalid-inquiry');
}
await this.attemptToAssignRoomToServingAgentElseQueueIt({
room,
inquiry,
servingAgent: servedBy,
clientAction,
});
const [roomResult, subsResult] = await Promise.all([
LivechatRooms.unsetOnHoldByRoomId(roomId),
Subscriptions.unsetOnHoldByRoomId(roomId),
Message.saveSystemMessage<IOmnichannelSystemMessage>('omnichannel_on_hold_chat_resumed', roomId, '', resumeBy, { comment }),
]);
if (roomResult.modifiedCount) {
void notifyOnRoomChangedById(roomId);
}
if (subsResult.modifiedCount) {
void notifyOnSubscriptionChangedByRoomId(roomId);
}
await callbacks.run('livechat:afterOnHoldChatResumed', room);
}
private async attemptToAssignRoomToServingAgentElseQueueIt({
room,
inquiry,
servingAgent,
clientAction,
}: {
room: Pick<IOmnichannelRoom, '_id'>;
inquiry: ILivechatInquiryRecord;
servingAgent: NonNullable<IOmnichannelRoom['servedBy']>;
clientAction: boolean;
}) {
try {
const agent = {
agentId: servingAgent._id,
username: servingAgent.username,
};
await callbacks.run('livechat.checkAgentBeforeTakeInquiry', {
agent,
inquiry,
options: {},
});
return;
} catch (e) {
this.logger.error({ msg: 'Agent is not available to take inquiry', agentId: servingAgent._id, inquiryId: inquiry._id, err: e });
if (clientAction) {
// if the action was triggered by the client, we should throw the error
// so the client can handle it and show the error message to the user
throw e;
}
}
await this.removeCurrentAgentFromRoom({ room, inquiry });
const { _id: inquiryId } = inquiry;
const newInquiry = await LivechatInquiry.findOneById(inquiryId);
if (!newInquiry) {
throw new Error('error-invalid-inquiry');
}
await queueInquiry(newInquiry);
}
private async removeCurrentAgentFromRoom({
room,
inquiry,
}: {
room: Pick<IOmnichannelRoom, '_id'>;
inquiry: ILivechatInquiryRecord;
}): Promise<void> {
this.logger.debug({ msg: 'Attempting to remove current agent from room', roomId: room._id });
const { _id: roomId } = room;
const { _id: inquiryId } = inquiry;
await Promise.all([
LivechatRooms.removeAgentByRoomId(roomId),
LivechatInquiry.queueInquiryAndRemoveDefaultAgent(inquiryId),
RoutingManager.removeAllRoomSubscriptions(room),
]);
void notifyOnLivechatInquiryChangedById(inquiryId, 'updated', {
status: LivechatInquiryStatus.QUEUED,
queuedAt: new Date(),
takenAt: undefined,
defaultAgent: undefined,
});
await dispatchAgentDelegated(roomId);
void notifyOnRoomChangedById(roomId);
}
}