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
Code scanning - action / CodeQL-Build (push) Failing after 2s
Auto-close duplicate issues / auto-close-duplicates (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,55 @@
import type { IUser } from '@rocket.chat/core-typings';
import { Users } from '@rocket.chat/models';
import type { IPublication } from './types';
type CachedUser = IUser; // Pick<IUser, '_id' | 'roles'>;
type CacheEntry = {
user: Promise<CachedUser | null>;
timeout: NodeJS.Timeout;
};
const CACHE_PROJECTION = { _id: 1, roles: 1 } as const;
const CACHE_TIMEOUT = 1000 * 60;
const cacheByUserId = new Map<string, CacheEntry>();
export function getCachedUserForPublication(publication: IPublication): Promise<CachedUser | null> {
const userId = publication.userId ?? publication._session?.userId;
if (!userId) {
return Promise.resolve(null);
}
const existing = cacheByUserId.get(userId);
if (existing) {
return existing.user;
}
const userPromise = Users.findOneById<CachedUser>(userId, { projection: CACHE_PROJECTION });
const timeout = setTimeout(() => {
invalidate(userId);
}, CACHE_TIMEOUT);
cacheByUserId.set(userId, { user: userPromise, timeout });
userPromise.then(
(user: CachedUser | null) => {
if (!user) {
invalidate(userId);
}
},
() => invalidate(userId),
);
return userPromise;
}
export function invalidate(userId: string): void {
const entry = cacheByUserId.get(userId);
if (!entry) {
return;
}
clearTimeout(entry.timeout);
cacheByUserId.delete(userId);
}

View File

@@ -0,0 +1,348 @@
import { MeteorError } from '@rocket.chat/core-services';
import type { StreamerEvents } from '@rocket.chat/ddp-client';
import { EventEmitter } from 'eventemitter3';
import type { IPublication, Rule, Connection, DDPSubscription, IStreamer, IRules, TransformMessage } from './types';
import { SystemLogger } from '../../lib/logger/system';
class StreamerCentralClass<N extends keyof StreamerEvents> extends EventEmitter {
public instances: Record<string, Streamer<N>> = {};
constructor() {
super();
}
}
type ActivePublication = IPublication & {
_session: NonNullable<IPublication['_session']> & { socket: NonNullable<NonNullable<IPublication['_session']>['socket']> };
};
export const StreamerCentral = new StreamerCentralClass();
export abstract class Streamer<N extends keyof StreamerEvents> extends EventEmitter implements IStreamer<N> {
public subscriptions = new Set<DDPSubscription>();
protected subscriptionsByEventName = new Map<string, Set<DDPSubscription>>();
public retransmit = true;
public retransmitToSelf = false;
public serverOnly = false;
private _allowRead: IRules = {};
private _allowWrite: IRules = {};
private _allowEmit: IRules = {};
constructor(
public name: string,
{ retransmit = true, retransmitToSelf = false }: { retransmit?: boolean; retransmitToSelf?: boolean } = {},
) {
super();
if (StreamerCentral.instances[name]) {
console.warn('Streamer instance already exists:', name);
return StreamerCentral.instances[name];
}
StreamerCentral.instances[name] = this;
this.retransmit = retransmit;
this.retransmitToSelf = retransmitToSelf;
this.iniPublication();
// DDPStreamer doesn't have this
this.initMethod();
this.allowRead('none');
this.allowEmit('all');
this.allowWrite('none');
}
get subscriptionName(): string {
return `stream-${this.name}`;
}
private allow(rules: IRules, name: string) {
return (eventName: string | boolean | Rule, fn?: string | boolean | Rule): void => {
if (fn === undefined) {
fn = eventName;
eventName = '__all__';
}
if (typeof eventName !== 'string') {
return;
}
if (typeof fn === 'function') {
rules[eventName] = fn;
return;
}
if (typeof fn === 'string' && ['all', 'none', 'logged'].indexOf(fn) === -1) {
SystemLogger.error({ msg: 'shortcut is invalid', name, fn });
}
if (fn === 'all' || fn === true) {
rules[eventName] = async function (): Promise<boolean> {
return true;
};
return;
}
if (fn === 'none' || fn === false) {
rules[eventName] = async function (): Promise<boolean> {
return false;
};
return;
}
if (fn === 'logged') {
rules[eventName] = async function (): Promise<boolean> {
return Boolean(this.userId);
};
}
};
}
allowRead(eventName: string | boolean | Rule, fn?: Rule | 'all' | 'none' | 'logged'): void {
this.allow(this._allowRead, 'allowRead')(eventName, fn);
}
allowWrite(eventName: string | boolean | Rule, fn?: Rule | 'all' | 'none' | 'logged'): void {
this.allow(this._allowWrite, 'allowWrite')(eventName, fn);
}
allowEmit(eventName: string | boolean | Rule, fn?: Rule | 'all' | 'none' | 'logged'): void {
this.allow(this._allowEmit, 'allowEmit')(eventName, fn);
}
private isAllowed(rules: IRules) {
return async (scope: IPublication, eventName: string, args: any): Promise<boolean | object> => {
if (rules[eventName]) {
return rules[eventName].call(scope, eventName, ...args);
}
return rules.__all__.call(scope, eventName, ...args);
};
}
async isReadAllowed(scope: IPublication, eventName: string, args: any): Promise<boolean | object> {
return this.isAllowed(this._allowRead)(scope, eventName, args);
}
async isEmitAllowed(scope: IPublication, eventName: string, ...args: any[]): Promise<boolean | object> {
return this.isAllowed(this._allowEmit)(scope, eventName, args);
}
async isWriteAllowed(scope: IPublication, eventName: string, args: any): Promise<boolean | object> {
return this.isAllowed(this._allowWrite)(scope, eventName, args);
}
addSubscription(subscription: DDPSubscription, eventName: string): void {
this.subscriptions.add(subscription);
const subByEventName = this.subscriptionsByEventName.get(eventName) || new Set();
subByEventName.add(subscription);
this.subscriptionsByEventName.set(eventName, subByEventName);
}
removeSubscription(subscription: DDPSubscription, eventName: string): void {
this.subscriptions.delete(subscription);
const subByEventName = this.subscriptionsByEventName.get(eventName);
if (subByEventName) {
subByEventName.delete(subscription);
}
}
async _publish(
publication: IPublication,
eventName: string,
options: boolean | { useCollection?: boolean; args?: any } = false,
): Promise<void> {
let useCollection;
let args = [];
if (typeof options === 'boolean') {
useCollection = options;
} else {
if (options.useCollection) {
useCollection = options.useCollection;
}
if (options.args) {
args = options.args;
}
}
if (eventName.length === 0) {
throw new MeteorError('invalid-event-name');
}
if ((await this.isReadAllowed(publication, eventName, args)) !== true) {
throw new MeteorError('not-allowed');
}
// after meteor 3.4.1 immediately after a disconnection session becomes null (which is not wrong)
// we were just not counting on this, session is _session so we actually should not use it
// now after any await, the session can potentially be null, so we need to check for that
if (!Streamer.isPublicationActive(publication)) {
// if the client is disconnected, we don't want to do anything, it will not have an disconnect event to undo anymore
throw new MeteorError('publication-client-disconnected');
}
const subscription = {
subscription: publication,
eventName,
};
this.addSubscription(subscription, eventName);
publication.onStop(() => {
this.removeSubscription(subscription, eventName);
});
// DDPStreamer doesn't have this
if (useCollection === true) {
// Collection compatibility
publication._session.sendAdded(this.subscriptionName, 'id', {
eventName,
});
}
publication.ready();
super.emit('_afterPublish', this, publication, eventName, options);
}
abstract registerPublication(
name: string,
fn: (eventName: string, options: boolean | { useCollection?: boolean; args?: any }) => Promise<void>,
): void;
iniPublication(): void {
const _publish = this._publish.bind(this);
this.registerPublication(
this.subscriptionName,
async function (this: IPublication, eventName: string, options: boolean | { useCollection?: boolean; args?: any }) {
return _publish(this, eventName, options);
},
);
}
abstract registerMethod(methods: Record<string, (eventName: string, ...args: any[]) => any>): void;
initMethod(): void {
const isWriteAllowed = this.isWriteAllowed.bind(this);
const __emit = this.__emit.bind(this);
const _emit = this._emit.bind(this);
const { retransmit } = this;
const method: Record<string, (eventName: string, ...args: any[]) => any> = {
async [this.subscriptionName](this: IPublication, eventName, ...args): Promise<void> {
if ((await isWriteAllowed(this, eventName, args)) !== true) {
return;
}
__emit(eventName, ...args);
if (retransmit === true) {
_emit(eventName, args, this.connection, true);
}
},
};
try {
this.registerMethod(method);
} catch (err) {
SystemLogger.error({ err });
}
}
abstract changedPayload(collection: string, id: string, fields: Record<string, any>): string | false;
_emit(eventName: string, args: any[], origin: Connection | undefined, broadcast: boolean, transform?: TransformMessage): boolean {
if (broadcast === true) {
StreamerCentral.emit('broadcast', this.name, eventName, args);
}
const subscriptions = this.subscriptionsByEventName.get(eventName);
if (!subscriptions?.size) {
return false;
}
if (transform) {
void this.sendToManySubscriptions(subscriptions, origin, eventName, args, transform);
return true;
}
const msg = this.changedPayload(this.subscriptionName, 'id', {
eventName,
args,
});
if (!msg) {
return false;
}
void this.sendToManySubscriptions(subscriptions, origin, eventName, args, msg);
return true;
}
static isPublicationActive(publication: IPublication): publication is ActivePublication {
// After Meteor 3.5 the socket can become null independently of session deactivation
// (e.g. right after a disconnection), so "active" must also mean the socket is still there.
return !publication._isDeactivated() && publication._session?.socket != null;
}
async sendToManySubscriptions(
subscriptions: Set<DDPSubscription>,
origin: Connection | undefined,
eventName: string,
args: any[],
getMsg: string | TransformMessage,
): Promise<void> {
await Promise.all(
[...subscriptions].map(async (subscription) => {
try {
if (this.retransmitToSelf === false && origin && origin === subscription.subscription.connection) {
return;
}
const allowed = await this.isEmitAllowed(subscription.subscription, eventName, ...args);
if (allowed) {
const msg = typeof getMsg === 'string' ? getMsg : getMsg(this, subscription, eventName, args, allowed);
if (msg) {
subscription.subscription._session?.socket?.send(msg);
}
}
} catch (err) {
SystemLogger.error({
msg: 'Error while delivering streamer event',
eventName,
streamName: this.name,
err,
});
}
}),
);
}
override emit(eventName: string | symbol, ...args: any[]): boolean {
return this._emit(eventName as string, args, undefined, true);
}
__emit(eventName: string, ...args: any[]): boolean {
return super.emit(eventName, ...args);
}
emitWithoutBroadcast(eventName: string, ...args: any[]): void {
this._emit(eventName, args, undefined, false);
}
}

View File

@@ -0,0 +1,107 @@
import type { StreamNames, StreamKeys, StreamerCallbackArgs } from '@rocket.chat/ddp-client';
export type Connection = any;
export interface IPublication {
connection: Connection;
_isDeactivated(): this is IPublication & { _session: null };
_session: {
sendAdded(publicationName: string, id: string, fields: Record<string, any>): void;
userId: string | undefined;
socket: {
send: (payload: string) => void;
} | null;
} | null;
client: {
meteorClient: boolean;
ws: any;
userId?: string;
send: (payload: string) => void;
};
onStop(func: () => void): void;
/**
* Call inside the publish function. Informs the subscriber that an initial, complete snapshot of the record set has been sent. This will trigger a call on the client to the `onReady`
* callback passed to `Meteor.subscribe`, if any.
*/
ready(): void;
/**
* Call inside the publish function. Informs the subscriber that a document has been removed from the record set.
* @param collection The name of the collection that the document has been removed from.
* @param id The ID of the document that has been removed.
*/
removed(collection: string, id: string): void;
/**
* Access inside the publish function. The incoming connection for this subscription.
*/
stop(): void;
/**
* Call inside the publish function. Allows subsequent methods or subscriptions for the client of this subscription
* to begin running without waiting for the publishing to become ready.
*/
unblock(): void;
/** Access inside the publish function. The id of the logged-in user, or `null` if no user is logged in. */
userId: string | null;
}
export type Rule<K extends string = string> = (this: IPublication, eventName: K, ...args: any) => Promise<boolean | object>;
export interface IRules {
[k: string]: Rule;
}
export type DDPSubscription = {
eventName: string;
subscription: IPublication;
};
export type TransformMessage = (
streamer: IStreamer<StreamNames>,
subscription: DDPSubscription,
eventName: string,
args: any[],
allowed: boolean | object,
) => string | false;
export interface IStreamer<N extends StreamNames> {
serverOnly: boolean;
subscriptions: Set<DDPSubscription>;
subscriptionName: string;
allowEmit<K extends StreamKeys<N>>(eventName: K, fn?: Rule | 'all' | 'none' | 'logged'): void;
allowEmit(rule: Rule<StreamKeys<N>> | 'all' | 'none' | 'logged'): void;
allowWrite<K extends StreamKeys<N>>(eventName: K | boolean, fn: Rule | 'all' | 'none' | 'logged'): void;
allowWrite(rule: Rule<StreamKeys<N>> | 'all' | 'none' | 'logged'): void;
allowRead<K extends StreamKeys<N>>(eventName: K | boolean, fn: Rule | 'all' | 'none' | 'logged'): void;
allowRead(rule: Rule<StreamKeys<N>> | 'all' | 'none' | 'logged'): void;
emit<K extends StreamKeys<N>>(event: K, ...data: StreamerCallbackArgs<N, K>): void;
on<K extends StreamKeys<N>>(event: K, fn: (...data: any[]) => void): void;
on(event: '_afterPublish', fn: (streamer: this, publication: IPublication, eventName: string, ...data: any[]) => void): void;
removeSubscription(subscription: DDPSubscription, eventName: string): void;
removeListener(event: string, fn: (...data: any[]) => void): void;
removeAllListeners(event: string): void;
__emit(...data: any[]): void;
_emit(eventName: string, args: any[], origin: Connection | undefined, broadcast: boolean, transform?: TransformMessage): boolean;
emitWithoutBroadcast<K extends StreamKeys<N>>(event: K, ...data: StreamerCallbackArgs<N, K>): void;
changedPayload(collection: string, id: string, fields: Record<string, any>): string | false;
_publish(publication: IPublication, eventName: string, options: boolean | { useCollection?: boolean; args?: any }): Promise<void>;
}
export interface IStreamerConstructor {
new <N extends StreamNames>(name: N, options?: { retransmit?: boolean; retransmitToSelf?: boolean }): IStreamer<N>;
}