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,36 @@
import type { ServerMethods } from '@rocket.chat/ddp-client';
import { OEmbedCache } from '@rocket.chat/models';
import { Meteor } from 'meteor/meteor';
import { hasPermissionAsync } from '../../lib/authorization/hasPermission';
import { settings } from '../../settings';
declare module '@rocket.chat/ddp-client' {
// eslint-disable-next-line @typescript-eslint/naming-convention
interface ServerMethods {
OEmbedCacheCleanup(): { message: string };
}
}
export const executeClearOEmbedCache = async () => {
const date = new Date();
const expirationDays = settings.get<number>('API_EmbedCacheExpirationDays');
date.setDate(date.getDate() - expirationDays);
return OEmbedCache.removeBeforeDate(date);
};
Meteor.methods<ServerMethods>({
async OEmbedCacheCleanup() {
const uid = Meteor.userId();
if (!uid || !(await hasPermissionAsync(uid, 'clear-oembed-cache'))) {
throw new Meteor.Error('error-not-allowed', 'Not allowed', {
method: 'OEmbedCacheCleanup',
});
}
await executeClearOEmbedCache();
return {
message: 'cache_cleared',
};
},
});

View File

@@ -0,0 +1,33 @@
import type { ServerMethods } from '@rocket.chat/ddp-client';
import { Users } from '@rocket.chat/models';
import { Meteor } from 'meteor/meteor';
import { methodDeprecationLogger } from '../../lib/deprecationWarningLogger';
import { notifyOnUserChange } from '../../lib/notifyListener';
declare module '@rocket.chat/ddp-client' {
// eslint-disable-next-line @typescript-eslint/naming-convention
interface ServerMethods {
'banner/dismiss'({ id }: { id: string }): void;
}
}
Meteor.methods<ServerMethods>({
async 'banner/dismiss'({ id }) {
methodDeprecationLogger.method('banner/dismiss', '9.0.0', '/v1/banners.dismiss');
const userId = Meteor.userId();
if (!userId) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'banner/dismiss' });
}
await Users.setBannerReadById(userId, id);
void notifyOnUserChange({
id: userId,
clientAction: 'updated',
diff: {
[`banners.${id}.read`]: true,
},
});
},
});

View File

@@ -0,0 +1,84 @@
import { Federation, FederationEE, Authorization } from '@rocket.chat/core-services';
import type { ServerMethods } from '@rocket.chat/ddp-client';
import { License } from '@rocket.chat/license';
import { Meteor } from 'meteor/meteor';
import { methodDeprecationLogger } from '../../lib/deprecationWarningLogger';
declare module '@rocket.chat/ddp-client' {
// eslint-disable-next-line @typescript-eslint/naming-convention
interface ServerMethods {
checkFederationConfiguration(): Promise<{ message: string }>;
}
}
Meteor.methods<ServerMethods>({
async checkFederationConfiguration() {
methodDeprecationLogger.method('checkFederationConfiguration', '9.0.0', []);
const uid = Meteor.userId();
if (!uid) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', {
method: 'checkFederationConfiguration',
});
}
if (!(await Authorization.hasPermission(uid, 'view-privileged-setting'))) {
throw new Meteor.Error('error-not-allowed', 'Action not allowed', {
method: 'checkFederationConfiguration',
});
}
const errors: string[] = [];
const successes: string[] = [];
const service = License.hasValidLicense() ? FederationEE : Federation;
const status = await service.configurationStatus();
if (status.externalReachability.ok) {
successes.push('homeserver configuration looks good');
} else {
let err = 'external reachability could not be verified';
const { error } = status.externalReachability;
if (error) {
err += `, error: ${error}`;
}
errors.push(err);
}
const {
roundTrip: { durationMs: duration },
} = status.appservice;
if (status.appservice.ok) {
successes.push(`appservice configuration looks good, total round trip time to homeserver ${duration}ms`);
} else {
errors.push(`failed to verify appservice configuration: ${status.appservice.error}`);
}
if (errors.length) {
void service.markConfigurationInvalid();
if (successes.length) {
const message = ['Configuration could only be partially verified'].concat(successes).concat(errors).join(', ');
throw new Meteor.Error('error-invalid-configuration', message, { method: 'checkFederationConfiguration' });
}
throw new Meteor.Error('error-invalid-configuration', ['Invalid configuration'].concat(errors).join(', '), {
method: 'checkFederationConfiguration',
});
}
void service.markConfigurationValid();
return {
message: ['All configuration looks good'].concat(successes).join(', '),
};
},
});

View File

@@ -0,0 +1,214 @@
import type { ServerMethods } from '@rocket.chat/ddp-client';
import { check } from 'meteor/check';
import { Meteor } from 'meteor/meteor';
import { hasPermissionAsync } from '../../lib/authorization/hasPermission';
import { buildWorkspaceRegistrationData } from '../../lib/cloud/buildRegistrationData';
import { checkUserHasCloudLogin } from '../../lib/cloud/checkUserHasCloudLogin';
import { connectWorkspace } from '../../lib/cloud/connectWorkspace';
import { finishOAuthAuthorization } from '../../lib/cloud/finishOAuthAuthorization';
import { getOAuthAuthorizationUrl } from '../../lib/cloud/getOAuthAuthorizationUrl';
import { retrieveRegistrationStatus } from '../../lib/cloud/retrieveRegistrationStatus';
import { startRegisterWorkspace } from '../../lib/cloud/startRegisterWorkspace';
import { syncWorkspace } from '../../lib/cloud/syncWorkspace';
import { userLogout } from '../../lib/cloud/userLogout';
import { methodDeprecationLogger } from '../../lib/deprecationWarningLogger';
declare module '@rocket.chat/ddp-client' {
// eslint-disable-next-line @typescript-eslint/naming-convention
interface ServerMethods {
'cloud:checkRegisterStatus': () => {
workspaceRegistered: boolean;
workspaceId: string;
uniqueId: string;
token: string;
email: string;
};
'cloud:getWorkspaceRegisterData': () => string;
'cloud:registerWorkspace': () => boolean;
'cloud:syncWorkspace': () => boolean;
'cloud:connectWorkspace': (token: string) => boolean | Error;
'cloud:getOAuthAuthorizationUrl': () => string;
'cloud:finishOAuthAuthorization': (code: string, state: string) => boolean;
'cloud:checkUserLoggedIn': () => boolean;
'cloud:logout': () => Promise<boolean | string>;
}
}
Meteor.methods<ServerMethods>({
/**
* @deprecated this method is deprecated and will be removed soon.
* Prefer using cloud.registrationStatus rest api.
*/
async 'cloud:checkRegisterStatus'() {
methodDeprecationLogger.method('cloud:checkRegisterStatus', '9.0.0', '/v1/cloud.registrationStatus');
const uid = Meteor.userId();
if (!uid) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', {
method: 'cloud:checkRegisterStatus',
});
}
if (!(await hasPermissionAsync(uid, 'manage-cloud'))) {
throw new Meteor.Error('error-not-authorized', 'Not authorized', {
method: 'cloud:checkRegisterStatus',
});
}
return retrieveRegistrationStatus();
},
/**
* @deprecated this method is deprecated and will be removed soon.
* Prefer using cloud.workspaceRegisterData rest api.
*/
async 'cloud:getWorkspaceRegisterData'() {
methodDeprecationLogger.method('cloud:getWorkspaceRegisterData', '9.0.0', '/v1/cloud.workspaceRegisterData');
const uid = Meteor.userId();
if (!uid) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', {
method: 'cloud:getWorkspaceRegisterData',
});
}
if (!(await hasPermissionAsync(uid, 'manage-cloud'))) {
throw new Meteor.Error('error-not-authorized', 'Not authorized', {
method: 'cloud:getWorkspaceRegisterData',
});
}
return Buffer.from(JSON.stringify(await buildWorkspaceRegistrationData(undefined))).toString('base64');
},
async 'cloud:registerWorkspace'() {
const uid = Meteor.userId();
if (!uid) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', {
method: 'cloud:registerWorkspace',
});
}
if (!(await hasPermissionAsync(uid, 'manage-cloud'))) {
throw new Meteor.Error('error-not-authorized', 'Not authorized', {
method: 'cloud:registerWorkspace',
});
}
return startRegisterWorkspace();
},
async 'cloud:syncWorkspace'() {
const uid = Meteor.userId();
if (!uid) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', {
method: 'cloud:syncWorkspace',
});
}
if (!(await hasPermissionAsync(uid, 'manage-cloud'))) {
throw new Meteor.Error('error-not-authorized', 'Not authorized', {
method: 'cloud:syncWorkspace',
});
}
await syncWorkspace();
return true;
},
async 'cloud:connectWorkspace'(token) {
methodDeprecationLogger.method('cloud:connectWorkspace', '9.0.0', '/v1/cloud.connectWorkspace');
check(token, String);
const uid = Meteor.userId();
if (!uid) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', {
method: 'cloud:connectWorkspace',
});
}
if (!(await hasPermissionAsync(uid, 'manage-cloud'))) {
throw new Meteor.Error('error-not-authorized', 'Not authorized', {
method: 'cloud:connectWorkspace',
});
}
if (!token) {
throw new Meteor.Error('error-invalid-payload', 'Token is required.', {
method: 'cloud:connectWorkspace',
});
}
return connectWorkspace(token);
},
// Currently unused but will link local account to Rocket.Chat Cloud account.
async 'cloud:getOAuthAuthorizationUrl'() {
const uid = Meteor.userId();
if (!uid) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', {
method: 'cloud:getOAuthAuthorizationUrl',
});
}
if (!(await hasPermissionAsync(uid, 'manage-cloud'))) {
throw new Meteor.Error('error-not-authorized', 'Not authorized', {
method: 'cloud:getOAuthAuthorizationUrl',
});
}
return getOAuthAuthorizationUrl();
},
async 'cloud:finishOAuthAuthorization'(code, state) {
check(code, String);
check(state, String);
const uid = Meteor.userId();
if (!uid) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', {
method: 'cloud:finishOAuthAuthorization',
});
}
if (!(await hasPermissionAsync(uid, 'manage-cloud'))) {
throw new Meteor.Error('error-not-authorized', 'Not authorized', {
method: 'cloud:finishOAuthAuthorization',
});
}
return finishOAuthAuthorization(code, state);
},
async 'cloud:checkUserLoggedIn'() {
const uid = Meteor.userId();
if (!uid) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', {
method: 'cloud:checkUserLoggedIn',
});
}
if (!(await hasPermissionAsync(uid, 'manage-cloud'))) {
throw new Meteor.Error('error-not-authorized', 'Not authorized', {
method: 'cloud:checkUserLoggedIn',
});
}
return checkUserHasCloudLogin(uid);
},
async 'cloud:logout'() {
const uid = Meteor.userId();
if (!uid) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', {
method: 'cloud:logout',
});
}
if (!(await hasPermissionAsync(uid, 'manage-cloud'))) {
throw new Meteor.Error('error-not-authorized', 'Not authorized', {
method: 'cloud:logout',
});
}
return userLogout(uid);
},
});

View File

@@ -0,0 +1,23 @@
import type { ServerMethods } from '@rocket.chat/ddp-client';
import { Users } from '@rocket.chat/models';
import { Meteor } from 'meteor/meteor';
import { methodDeprecationLogger } from '../../lib/deprecationWarningLogger';
declare module '@rocket.chat/ddp-client' {
// eslint-disable-next-line @typescript-eslint/naming-convention
interface ServerMethods {
'e2e.fetchMyKeys'(): { public_key?: string; private_key?: string };
}
}
Meteor.methods<ServerMethods>({
async 'e2e.fetchMyKeys'() {
methodDeprecationLogger.method('e2e.fetchMyKeys', '9.0.0', '/v1/e2e.fetchMyKeys');
const userId = Meteor.userId();
if (!userId) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'e2e.fetchMyKeys' });
}
return Users.fetchKeysByUserId(userId);
},
});

View File

@@ -0,0 +1,28 @@
import type { ServerMethods } from '@rocket.chat/ddp-client';
import { Meteor } from 'meteor/meteor';
import { TranslationProviderRegistry } from '../../lib/autotranslate/autotranslate';
declare module '@rocket.chat/ddp-client' {
// eslint-disable-next-line @typescript-eslint/naming-convention
interface ServerMethods {
'autoTranslate.getProviderUiMetadata'(): Record<string, { name: string; displayName: string }>;
}
}
Meteor.methods<ServerMethods>({
'autoTranslate.getProviderUiMetadata'() {
if (!Meteor.userId()) {
throw new Meteor.Error('error-action-not-allowed', 'Login neccessary', {
method: 'autoTranslate.getProviderUiMetadata',
});
}
return Object.fromEntries(
TranslationProviderRegistry.getProviders().map((provider) => {
const { name, displayName } = provider._getProviderMetadata();
return [name, { name, displayName }];
}),
);
},
});

View File

@@ -0,0 +1,27 @@
import type { IStats } from '@rocket.chat/core-typings';
import type { ServerMethods } from '@rocket.chat/ddp-client';
import { Meteor } from 'meteor/meteor';
import { methodDeprecationLogger } from '../../lib/deprecationWarningLogger';
import { getLastStatistics } from '../../lib/statistics/functions/getLastStatistics';
declare module '@rocket.chat/ddp-client' {
// eslint-disable-next-line @typescript-eslint/naming-convention
interface ServerMethods {
getStatistics(refresh?: boolean): IStats;
}
}
Meteor.methods<ServerMethods>({
async getStatistics(refresh) {
methodDeprecationLogger.method('getStatistics', '9.0.0', '/v1/statistics');
const uid = Meteor.userId();
if (!uid) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'getStatistics' });
}
return getLastStatistics({
userId: uid,
refresh,
});
},
});

View File

@@ -0,0 +1,39 @@
import type { ISupportedLanguage } from '@rocket.chat/core-typings';
import type { ServerMethods } from '@rocket.chat/ddp-client';
import { DDPRateLimiter } from 'meteor/ddp-rate-limiter';
import { Meteor } from 'meteor/meteor';
import { getSupportedLanguages } from '../../lib/autotranslate/functions/getSupportedLanguages';
declare module '@rocket.chat/ddp-client' {
// eslint-disable-next-line @typescript-eslint/naming-convention
interface ServerMethods {
'autoTranslate.getSupportedLanguages'(targetLanguage: string): ISupportedLanguage[] | undefined;
}
}
Meteor.methods<ServerMethods>({
async 'autoTranslate.getSupportedLanguages'(targetLanguage) {
const userId = Meteor.userId();
if (!userId) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', {
method: 'getSupportedLanguages',
});
}
return getSupportedLanguages(userId, targetLanguage);
},
});
DDPRateLimiter.addRule(
{
type: 'method',
name: 'autoTranslate.getSupportedLanguages',
userId(/* userId*/) {
return true;
},
},
5,
60000,
);

View File

@@ -0,0 +1,56 @@
import type { IRoom, IUser } from '@rocket.chat/core-typings';
import type { ServerMethods } from '@rocket.chat/ddp-client';
import { Subscriptions, Users } from '@rocket.chat/models';
import { check } from 'meteor/check';
import { Meteor } from 'meteor/meteor';
import { canAccessRoomIdAsync } from '../../lib/authorization/canAccessRoom';
declare module '@rocket.chat/ddp-client' {
// eslint-disable-next-line @typescript-eslint/naming-convention
interface ServerMethods {
'e2e.getUsersOfRoomWithoutKey'(rid: IRoom['_id']): { users: Pick<IUser, '_id' | 'e2e'>[] };
}
}
export const getUsersOfRoomWithoutKeyMethod = async (
userId: string,
rid: IRoom['_id'],
): Promise<{ users: Pick<IUser, '_id' | 'e2e'>[] }> => {
if (!(await canAccessRoomIdAsync(rid, userId))) {
throw new Meteor.Error('error-invalid-room', 'Invalid room', { method: 'e2e.getUsersOfRoomWithoutKey' });
}
const subscriptions = await Subscriptions.findByRidWithoutE2EKey(rid, {
projection: { 'u._id': 1 },
}).toArray();
const userIds = subscriptions.map((s) => s.u._id);
const options = { projection: { 'e2e.public_key': 1 } };
const users = await Users.findByIdsWithPublicE2EKey(userIds, options).toArray();
return {
users,
};
};
Meteor.methods<ServerMethods>({
async 'e2e.getUsersOfRoomWithoutKey'(rid) {
check(rid, String);
const userId = Meteor.userId();
if (!userId) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', {
method: 'e2e.getUsersOfRoomWithoutKey',
});
}
if (!rid) {
throw new Meteor.Error('error-invalid-room', 'Invalid room', {
method: 'e2e.getUsersOfRoomWithoutKey',
});
}
return getUsersOfRoomWithoutKeyMethod(userId, rid);
},
});

View File

@@ -0,0 +1,24 @@
import type { ServerMethods } from '@rocket.chat/ddp-client';
import { check } from 'meteor/check';
import { Meteor } from 'meteor/meteor';
import { getMomentLocale } from '../../lib/getMomentLocale';
declare module '@rocket.chat/ddp-client' {
// eslint-disable-next-line @typescript-eslint/naming-convention
interface ServerMethods {
loadLocale(locale: string): string | undefined;
}
}
Meteor.methods<ServerMethods>({
loadLocale(locale) {
check(locale, String);
try {
return getMomentLocale(locale);
} catch (error: any) {
throw new Meteor.Error(error.message, `Moment locale not found: ${locale}`);
}
},
});

View File

@@ -0,0 +1,80 @@
import { Push } from '@rocket.chat/core-services';
import type { IPushToken } from '@rocket.chat/core-typings';
import type { ServerMethods } from '@rocket.chat/ddp-client';
import { PushToken } from '@rocket.chat/models';
import { Accounts } from 'meteor/accounts-base';
import { Match, check } from 'meteor/check';
import { Meteor } from 'meteor/meteor';
import { methodDeprecationLogger } from '../../lib/deprecationWarningLogger';
import { logger } from '../../lib/notifications/push/logger';
import { _matchToken } from '../../lib/notifications/push/push';
type PushUpdateOptions = {
id?: string;
token: IPushToken['token'];
authToken: string;
appName: string;
userId: string | null;
metadata?: Record<string, unknown>;
};
declare module '@rocket.chat/ddp-client' {
// eslint-disable-next-line @typescript-eslint/naming-convention
interface ServerMethods {
'raix:push-update'(options: PushUpdateOptions): Promise<Omit<IPushToken, 'authToken'>>;
'raix:push-setuser'(options: { id: string; userId: string }): Promise<boolean>;
}
}
Meteor.methods<ServerMethods>({
async 'raix:push-update'(options) {
methodDeprecationLogger.method('raix:push-update', '9.0.0', '/v1/push.token');
logger.debug({ msg: 'Got push token from app', options });
check(options, {
id: Match.Optional(String),
token: _matchToken,
authToken: String,
appName: String,
userId: Match.OneOf(String, null),
metadata: Match.Optional(Object),
});
// The if user id is set then user id should match on client and connection
if (!this.userId || (options.userId && options.userId !== this.userId)) {
throw new Meteor.Error(403, 'Forbidden access');
}
// Retain old behavior: if id is not specified but userId is explicitly set, then update the user's first token
if (!options.id && options.userId) {
const firstDoc = await PushToken.findFirstByUserId(options.userId, { projection: { _id: 1 } });
if (firstDoc) {
options.id = firstDoc._id;
}
}
const authToken = Accounts._hashLoginToken(options.authToken);
return Push.registerPushToken({
...(options.id && { _id: options.id }),
token: options.token,
appName: options.appName,
authToken,
userId: this.userId,
...(options.metadata && { metadata: options.metadata }),
});
},
async 'raix:push-setuser'(id) {
methodDeprecationLogger.method('raix:push-setuser', '9.0.0', []);
check(id, String);
if (!this.userId) {
throw new Meteor.Error(403, 'Forbidden access');
}
logger.debug({ msg: 'Setting userId for app', userId: this.userId, appId: id });
const found = await PushToken.updateOne({ _id: id }, { $set: { userId: this.userId } });
return !!found;
},
});

View File

@@ -0,0 +1,123 @@
import { mkdtemp } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import path, { join } from 'node:path';
import type { IExportOperation, IUser } from '@rocket.chat/core-typings';
import type { ServerMethods } from '@rocket.chat/ddp-client';
import { ExportOperations, UserDataFiles } from '@rocket.chat/models';
import { Meteor } from 'meteor/meteor';
import * as dataExport from '../../lib/dataExport';
import { methodDeprecationLogger } from '../../lib/deprecationWarningLogger';
import { settings } from '../../settings';
declare module '@rocket.chat/ddp-client' {
// eslint-disable-next-line @typescript-eslint/naming-convention
interface ServerMethods {
requestDataDownload(params: { fullExport?: boolean }): Promise<{
requested: boolean;
exportOperation: IExportOperation;
url: string | null;
pendingOperationsBeforeMyRequest: number;
}>;
}
}
export const requestDataDownload = async ({
userData,
fullExport = false,
}: {
userData: IUser;
fullExport?: boolean;
}): Promise<{
requested: boolean;
exportOperation: IExportOperation;
url: string | null;
pendingOperationsBeforeMyRequest: number;
}> => {
const currentUserData = userData;
if (!currentUserData) {
throw new Meteor.Error('error-invalid-user', 'Invalid user');
}
const userId = currentUserData._id;
const lastOperation = await ExportOperations.findLastOperationByUser(userId, fullExport);
const requestDay = lastOperation ? lastOperation.createdAt : new Date();
const pendingOperationsBeforeMyRequestCount = await ExportOperations.countAllPendingBeforeMyRequest(requestDay);
if (lastOperation) {
const yesterday = new Date();
yesterday.setUTCDate(yesterday.getUTCDate() - 1);
if (lastOperation.createdAt > yesterday) {
if (lastOperation.status === 'completed') {
const file = lastOperation.fileId
? await UserDataFiles.findOneById(lastOperation.fileId)
: await UserDataFiles.findLastFileByUser(userId);
if (file) {
return {
requested: false,
exportOperation: lastOperation,
url: dataExport.getPath(file._id),
pendingOperationsBeforeMyRequest: pendingOperationsBeforeMyRequestCount,
};
}
}
return {
requested: false,
exportOperation: lastOperation,
url: null,
pendingOperationsBeforeMyRequest: pendingOperationsBeforeMyRequestCount,
};
}
}
const tempFolder = settings.get<string | undefined>('UserData_FileSystemPath')?.trim() || (await mkdtemp(join(tmpdir(), 'userData')));
const exportOperation = {
status: 'preparing',
userId: currentUserData._id,
roomList: undefined,
fileList: [],
generatedFile: undefined,
fullExport,
userData: currentUserData,
userNameTable: {},
} as unknown as IExportOperation; // @todo yikes!
const id = await ExportOperations.create(exportOperation);
exportOperation._id = id;
const folderName = path.join(tempFolder, id);
const assetsFolder = path.join(folderName, 'assets');
exportOperation.exportPath = folderName;
exportOperation.assetsPath = assetsFolder;
exportOperation.status = 'pending';
await ExportOperations.updateOperation(exportOperation);
return {
requested: true,
exportOperation,
url: null,
pendingOperationsBeforeMyRequest: pendingOperationsBeforeMyRequestCount,
};
};
Meteor.methods<ServerMethods>({
async requestDataDownload({ fullExport = false }) {
methodDeprecationLogger.method('requestDataDownload', '9.0.0', '/v1/users.requestDataDownload');
const currentUserData = await Meteor.userAsync();
if (!currentUserData) {
throw new Meteor.Error('error-invalid-user', 'Invalid user');
}
return requestDataDownload({ userData: currentUserData as IUser, fullExport });
},
});

View File

@@ -0,0 +1,51 @@
import { api } from '@rocket.chat/core-services';
import type { ServerMethods } from '@rocket.chat/ddp-client';
import { Subscriptions, Rooms } from '@rocket.chat/models';
import { Meteor } from 'meteor/meteor';
import { methodDeprecationLogger } from '../../lib/deprecationWarningLogger';
declare module '@rocket.chat/ddp-client' {
// eslint-disable-next-line @typescript-eslint/naming-convention
interface ServerMethods {
'e2e.requestSubscriptionKeys'(): boolean;
}
}
export const requestSubscriptionKeysMethod = async (userId: string): Promise<void> => {
// Get all encrypted rooms that the user is subscribed to and has no E2E key yet
const subscriptions = await Subscriptions.findByUserIdWithoutE2E(userId).toArray();
const roomIds = subscriptions.map((subscription) => subscription.rid);
// For all subscriptions without E2E key, get the rooms that have encryption enabled
const query = {
e2eKeyId: {
$exists: true,
},
_id: {
$in: roomIds,
},
};
const rooms = Rooms.find(query);
await rooms.forEach((room) => {
void api.broadcast('notify.e2e.keyRequest', room._id, room.e2eKeyId);
});
};
Meteor.methods<ServerMethods>({
async 'e2e.requestSubscriptionKeys'() {
methodDeprecationLogger.method('e2e.requestSubscriptionKeys', '9.0.0', '/v1/e2e.requestSubscriptionKeys');
const userId = Meteor.userId();
if (!userId) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', {
method: 'requestSubscriptionKeys',
});
}
await requestSubscriptionKeysMethod(userId);
return true;
},
});

View File

@@ -0,0 +1,34 @@
import { MeteorError } from '@rocket.chat/core-services';
import type { ServerMethods } from '@rocket.chat/ddp-client';
import { Meteor } from 'meteor/meteor';
import { twoFactorRequired } from '../../lib/2fa/twoFactorRequired';
import { methodDeprecationLogger } from '../../lib/deprecationWarningLogger';
import { resetUserE2EEncriptionKey } from '../../lib/resetUserE2EKey';
declare module '@rocket.chat/ddp-client' {
// eslint-disable-next-line @typescript-eslint/naming-convention
interface ServerMethods {
'e2e.resetOwnE2EKey'(): Promise<boolean>;
}
}
Meteor.methods<ServerMethods>({
'e2e.resetOwnE2EKey': twoFactorRequired(async () => {
methodDeprecationLogger.method('e2e.resetOwnE2EKey', '9.0.0', '/v1/users.resetE2EKey');
const userId = Meteor.userId();
if (!userId) {
throw new MeteorError('error-invalid-user', 'Invalid user', {
method: 'resetOwnE2EKey',
});
}
if (!(await resetUserE2EEncriptionKey(userId, false))) {
throw new MeteorError('failed-reset-e2e-password', 'Failed to reset E2E password', {
method: 'resetOwnE2EKey',
});
}
return true;
}),
});

View File

@@ -0,0 +1,41 @@
import type { ServerMethods } from '@rocket.chat/ddp-client';
import { Meteor } from 'meteor/meteor';
import { hasPermissionAsync } from '../../lib/authorization/hasPermission';
declare module '@rocket.chat/ddp-client' {
// eslint-disable-next-line @typescript-eslint/naming-convention
interface ServerMethods {
restart_server(): {
message: string;
params: [number];
};
}
}
Meteor.methods<ServerMethods>({
async restart_server() {
const uid = Meteor.userId();
if (!uid) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'restart_server' });
}
if ((await hasPermissionAsync(uid, 'restart-server')) !== true) {
throw new Meteor.Error('error-not-allowed', 'Not allowed', { method: 'restart_server' });
}
setTimeout(() => {
setTimeout(() => {
console.warn('Call to process.exit() timed out, aborting.');
process.abort();
}, 1000);
process.exit(1);
}, 1000);
return {
message: 'The_server_will_restart_in_s_seconds',
params: [2],
};
},
});

View File

@@ -0,0 +1,26 @@
import type { ServerMethods } from '@rocket.chat/ddp-client';
import { Meteor } from 'meteor/meteor';
import { saveAutoTranslateSettings } from '../../lib/autotranslate/functions/saveSettings';
import { methodDeprecationLogger } from '../../lib/deprecationWarningLogger';
declare module '@rocket.chat/ddp-client' {
// eslint-disable-next-line @typescript-eslint/naming-convention
interface ServerMethods {
'autoTranslate.saveSettings'(rid: string, field: string, value: string, options: { defaultLanguage: string }): boolean;
}
}
Meteor.methods<ServerMethods>({
async 'autoTranslate.saveSettings'(rid, field, value, options) {
methodDeprecationLogger.method('autoTranslate.saveSettings', '9.0.0', '/v1/autotranslate.saveSettings');
const userId = Meteor.userId();
if (!userId) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', {
method: 'saveAutoTranslateSettings',
});
}
return saveAutoTranslateSettings(userId, rid, field, value, options);
},
});

View File

@@ -0,0 +1,94 @@
import type { IMessageSearchProvider, IMessageSearchSuggestion, IRoom, IUser } from '@rocket.chat/core-typings';
import type { ServerMethods } from '@rocket.chat/ddp-client';
import { Meteor } from 'meteor/meteor';
import { SearchLogger } from '../../lib/search/logger/logger';
import type { IRawSearchResult, ISearchResult } from '../../lib/search/model/ISearchResult';
import { searchProviderService, validationService } from '../../lib/search/service';
declare module '@rocket.chat/ddp-client' {
// eslint-disable-next-line @typescript-eslint/naming-convention
interface ServerMethods {
'rocketchatSearch.getProvider'(): IMessageSearchProvider | undefined;
'rocketchatSearch.search'(text: string, context: { uid?: IUser['_id']; rid: IRoom['_id'] }, payload: unknown): Promise<ISearchResult>;
'rocketchatSearch.suggest'(
text: string,
context: { uid?: IUser['_id']; rid: IRoom['_id'] },
payload: unknown,
): Promise<IMessageSearchSuggestion[]>;
}
}
Meteor.methods<ServerMethods>({
/**
* Get the current provider with key, description, resultTemplate, suggestionItemTemplate and settings (as Map)
*/
'rocketchatSearch.getProvider'() {
const provider = searchProviderService.activeProvider;
if (!provider) {
return undefined;
}
return {
key: provider.key,
description: provider.i18nDescription,
icon: provider.iconName,
resultTemplate: provider.resultTemplate,
supportsSuggestions: provider.supportsSuggestions,
suggestionItemTemplate: provider.suggestionItemTemplate,
settings: Object.fromEntries(Object.values(provider.settingsAsMap).map((setting) => [setting.key, setting.value] as const)),
};
},
/**
* Search using the current search provider and check if results are valid for the user. The search result has
* the format `{messages:{start:0,numFound:1,docs:[{...}]},users:{...},rooms:{...}}`
* @param text the search text
* @param context the context (uid, rid)
* @param payload custom payload (e.g. for paging)
*/
async 'rocketchatSearch.search'(text, context, payload) {
payload = payload !== null ? payload : undefined; // TODO is this cleanup necessary?
if (!searchProviderService.activeProvider) {
throw new Error('Provider currently not active');
}
SearchLogger.debug({ msg: 'search', text, context, payload });
const userId = Meteor.userId();
if (!userId) {
throw new Error('User not logged in');
}
return new Promise<IRawSearchResult>((resolve, reject) => {
void searchProviderService.activeProvider?.search(userId, text, context, payload, (error, data) => {
if (error) {
return reject(error);
}
return resolve(data);
});
}).then((result) => validationService.validateSearchResult(result));
},
async 'rocketchatSearch.suggest'(text, context, payload) {
payload ??= undefined; // TODO is this cleanup necessary?
if (!searchProviderService.activeProvider) {
throw new Error('Provider currently not active');
}
SearchLogger.debug({ msg: 'suggest', text, context, payload });
return new Promise((resolve, reject) => {
searchProviderService.activeProvider?.suggest(text, context, payload, (error, data) => {
if (error) {
reject(error);
return;
}
resolve(data);
});
});
},
});

View File

@@ -0,0 +1,49 @@
import type { IRoom } from '@rocket.chat/core-typings';
import type { ServerMethods } from '@rocket.chat/ddp-client';
import { Rooms } from '@rocket.chat/models';
import { check } from 'meteor/check';
import { Meteor } from 'meteor/meteor';
import { canAccessRoomIdAsync } from '../../lib/authorization/canAccessRoom';
import { notifyOnRoomChanged } from '../../lib/notifyListener';
declare module '@rocket.chat/ddp-client' {
// eslint-disable-next-line @typescript-eslint/naming-convention
interface ServerMethods {
'e2e.setRoomKeyID'(rid: IRoom['_id'], keyID: string): void;
}
}
export const setRoomKeyIDMethod = async (userId: string, rid: IRoom['_id'], keyID: string): Promise<void> => {
if (!(await canAccessRoomIdAsync(rid, userId))) {
throw new Meteor.Error('error-invalid-room', 'Invalid room', { method: 'e2e.setRoomKeyID' });
}
const room = await Rooms.setE2eKeyId(rid, keyID);
if (!room) {
throw new Meteor.Error('error-room-e2e-key-already-exists', 'E2E Key ID already exists', {
method: 'e2e.setRoomKeyID',
});
}
void notifyOnRoomChanged(room);
};
Meteor.methods<ServerMethods>({
async 'e2e.setRoomKeyID'(rid, keyID) {
check(rid, String);
check(keyID, String);
const userId = Meteor.userId();
if (!userId) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'e2e.setRoomKeyID' });
}
if (!rid) {
throw new Meteor.Error('error-invalid-room', 'Invalid room', { method: 'e2e.setRoomKeyID' });
}
await setRoomKeyIDMethod(userId, rid, keyID);
},
});

View File

@@ -0,0 +1,63 @@
import type { ServerMethods } from '@rocket.chat/ddp-client';
import { Rooms, Users } from '@rocket.chat/models';
import { Meteor } from 'meteor/meteor';
import { methodDeprecationLogger } from '../../lib/deprecationWarningLogger';
import { notifyOnRoomChangedById } from '../../lib/notifyListener';
declare module '@rocket.chat/ddp-client' {
// eslint-disable-next-line @typescript-eslint/naming-convention
interface ServerMethods {
'e2e.setUserPublicAndPrivateKeys'({ public_key, private_key }: { public_key: string; private_key: string; force?: boolean }): void;
}
}
const isKeysResult = (result: any): result is { public_key: string; private_key: string } => {
return result.private_key && result.public_key;
};
export const setUserPublicAndPrivateKeysMethod = async (
userId: string,
keyPair: { public_key: string; private_key: string; force?: boolean },
): Promise<void> => {
if (!keyPair.force) {
const keys = await Users.fetchKeysByUserId(userId);
if (isKeysResult(keys)) {
throw new Meteor.Error('error-keys-already-set', 'Keys already set', {
method: 'e2e.setUserPublicAndPrivateKeys',
});
}
}
await Users.setE2EPublicAndPrivateKeysByUserId(userId, {
private_key: keyPair.private_key,
public_key: keyPair.public_key,
});
const subscribedRoomIds = await Rooms.getSubscribedRoomIdsWithoutE2EKeys(userId);
await Rooms.addUserIdToE2EEQueueByRoomIds(subscribedRoomIds, userId);
void notifyOnRoomChangedById(subscribedRoomIds);
};
Meteor.methods<ServerMethods>({
async 'e2e.setUserPublicAndPrivateKeys'(keyPair) {
methodDeprecationLogger.method('e2e.setUserPublicAndPrivateKeys', '9.0.0', '/v1/e2e.setUserPublicAndPrivateKeys');
const userId = Meteor.userId();
if (!userId) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', {
method: 'e2e.setUserPublicAndPrivateKeys',
});
}
if (!keyPair.public_key || !keyPair.private_key) {
throw new Meteor.Error('error-invalid-keys', 'Invalid keys', {
method: 'e2e.setUserPublicAndPrivateKeys',
});
}
await setUserPublicAndPrivateKeysMethod(userId, keyPair);
},
});

View File

@@ -0,0 +1,37 @@
import type { IMessage } from '@rocket.chat/core-typings';
import type { ServerMethods } from '@rocket.chat/ddp-client';
import { Messages, Rooms } from '@rocket.chat/models';
import { check } from 'meteor/check';
import { Meteor } from 'meteor/meteor';
import { canAccessRoomAsync } from '../../lib/authorization';
import { translateMessage } from '../../lib/autotranslate/functions/translateMessage';
declare module '@rocket.chat/ddp-client' {
// eslint-disable-next-line @typescript-eslint/naming-convention
interface ServerMethods {
'autoTranslate.translateMessage'(message: IMessage | undefined, targetLanguage: string): Promise<IMessage | undefined>;
}
}
Meteor.methods<ServerMethods>({
async 'autoTranslate.translateMessage'(message, targetLanguage) {
const userId = Meteor.userId();
if (!userId) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', {
method: 'autoTranslate.translateMessage',
});
}
check(message?._id, String);
check(targetLanguage, String);
const msg = await Messages.findOneById(message._id);
if (!msg) {
throw new Meteor.Error('error-message-not-found', 'Message not found');
}
const room = await Rooms.findOneById(msg.rid);
if (!room || !(await canAccessRoomAsync(room, { _id: userId }))) {
throw new Meteor.Error('error-not-allowed', 'Not allowed');
}
return translateMessage(targetLanguage, msg);
},
});

View File

@@ -0,0 +1,34 @@
import { Subscriptions, Rooms } from '@rocket.chat/models';
import { notifyOnSubscriptionChangedById, notifyOnSubscriptionChanged, notifyOnRoomChangedById } from '../../lib/notifyListener';
export async function updateGroupKey(rid: string, uid: string, key: string, callerUserId: string) {
// I have a subscription to this room
const mySub = await Subscriptions.findOneByRoomIdAndUserId(rid, callerUserId);
if (mySub) {
// Setting the key to myself, can set directly to the final field
if (callerUserId === uid) {
const setGroupE2EKeyResponse = await Subscriptions.setGroupE2EKey(mySub._id, key);
// Case: I create an encrypted room before setting up my keys, and I reset the e2e keys
// Next login, I'll create the keys for the room, and set them here.
// However as I reset my keys, I'm on the `usersWaitingForKeys` queue
// So I need to remove myself from the queue and notify the time i reach here
// This way, I can provide the keys to other users
const { modifiedCount } = await Rooms.removeUsersFromE2EEQueueByRoomId(mySub.rid, [callerUserId]);
if (setGroupE2EKeyResponse.modifiedCount) {
void notifyOnSubscriptionChangedById(mySub._id);
}
if (modifiedCount) {
void notifyOnRoomChangedById(mySub.rid);
}
return;
}
// uid also has subscription to this room
const value = await Subscriptions.setGroupE2ESuggestedKey(uid, rid, key);
if (value) {
void notifyOnSubscriptionChanged(value);
}
}
}