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,110 @@
import { LivechatContacts, Statistics, Users } from '@rocket.chat/models';
import moment from 'moment';
import { LICENSE_VERSION } from './license';
import { Info } from '../../../app/utils/rocketchat.info';
import { settings } from '../../settings';
import { statistics } from '../statistics';
export type WorkspaceRegistrationData<T> = {
uniqueId: string;
deploymentFingerprintHash: string;
deploymentFingerprintVerified: boolean;
workspaceId: string;
address: string;
contactName: string;
contactEmail: T;
seats: number;
organizationType: string;
industry: string;
orgSize: string;
country: string;
language: string;
allowMarketing: string;
accountName: string;
agreePrivacyTerms: string;
website: string;
siteName: string;
workspaceType: unknown;
deploymentMethod: string;
deploymentPlatform: string;
version: string;
licenseVersion: number;
license?: string;
enterpriseReady: boolean;
setupComplete: boolean;
connectionDisable: boolean;
npsEnabled: string;
// TODO: Evaluate naming
MAC: number;
// activeContactsBillingMonth: number;
// activeContactsYesterday: number;
statsToken?: string;
};
export async function buildWorkspaceRegistrationData<T extends string | undefined>(contactEmail: T): Promise<WorkspaceRegistrationData<T>> {
const stats = (await Statistics.findLast()) || (await statistics.get());
const address = settings.get<string>('Site_Url');
const siteName = settings.get<string>('Site_Name');
const workspaceId = settings.get<string>('Cloud_Workspace_Id');
const allowMarketing = settings.get<string>('Allow_Marketing_Emails');
const accountName = settings.get<string>('Organization_Name');
const website = settings.get<string>('Website');
const npsEnabled = settings.get<string>('NPS_survey_enabled');
const agreePrivacyTerms = settings.get<string>('Cloud_Service_Agree_PrivacyTerms');
const setupWizardState = settings.get<string>('Show_Setup_Wizard');
const deploymentFingerprintHash = settings.get<string>('Deployment_FingerPrint_Hash');
const deploymentFingerprintVerified = settings.get<boolean>('Deployment_FingerPrint_Verified');
const firstUser = await Users.getOldest({ projection: { name: 1, emails: 1 } });
const contactName = firstUser?.name || '';
const country = settings.get<string>('Country');
const language = settings.get<string>('Language');
const organizationType = settings.get<string>('Organization_Type');
const industry = settings.get<string>('Industry');
const orgSize = settings.get<string>('Size');
const workspaceType = settings.get<string>('Server_Type');
const seats = await Users.getActiveLocalUserCount();
const MAC = await LivechatContacts.countContactsOnPeriod(moment.utc().format('YYYY-MM'));
const license = settings.get<string>('Enterprise_License');
return {
uniqueId: stats.uniqueId,
deploymentFingerprintHash,
deploymentFingerprintVerified,
workspaceId,
address,
contactName,
contactEmail,
seats,
allowMarketing,
accountName,
organizationType: String(organizationType),
industry: String(industry),
orgSize: String(orgSize),
country: String(country),
language: String(language),
agreePrivacyTerms,
website,
siteName,
workspaceType: String(workspaceType),
deploymentMethod: stats.deploy.method,
deploymentPlatform: stats.deploy.platform,
version: stats.version ?? Info.version,
licenseVersion: LICENSE_VERSION,
...(license && { license }),
enterpriseReady: true,
setupComplete: setupWizardState === 'completed',
connectionDisable: false,
npsEnabled,
MAC,
// activeContactsBillingMonth: stats.omnichannelContactsBySource.contactsCount,
// activeContactsYesterday: stats.uniqueContactsOfYesterday.contactsCount,
statsToken: stats.statsToken,
};
}

View File

@@ -0,0 +1,23 @@
import { Users } from '@rocket.chat/models';
import { retrieveRegistrationStatus } from './retrieveRegistrationStatus';
export async function checkUserHasCloudLogin(userId: string) {
const { workspaceRegistered } = await retrieveRegistrationStatus();
if (!workspaceRegistered) {
return false;
}
if (!userId) {
return false;
}
const user = await Users.findOneById(userId);
if (user?.services?.cloud?.accessToken) {
return true;
}
return false;
}

View File

@@ -0,0 +1,84 @@
import { serverFetch as fetch } from '@rocket.chat/server-fetch';
import { getRedirectUri } from './getRedirectUri';
import { assertNotOfflineLicense } from './offlineLicense';
import { saveRegistrationData } from './saveRegistrationData';
import { CloudWorkspaceConnectionError } from '../../../lib/errors/CloudWorkspaceConnectionError';
import { settings } from '../../settings';
import { SystemLogger } from '../logger/system';
const fetchRegistrationDataPayload = async ({
token,
body,
}: {
token: string;
body: {
email: string;
client_name: string;
redirect_uris: string[];
};
}) => {
const cloudUrl = settings.get<string>('Cloud_Url');
const response = await fetch(`${cloudUrl}/api/oauth/clients`, {
method: 'POST',
headers: {
Authorization: `Bearer ${token}`,
},
body,
// SECURITY: the URL is a default hardcoded value or an envvar/setting set by an admin. It's safe to disable this check.
ignoreSsrfValidation: true,
});
if (!response.ok) {
try {
const { error } = await response.json();
throw new CloudWorkspaceConnectionError(`Failed to connect to Rocket.Chat Cloud: ${error}`);
} catch (error) {
throw new CloudWorkspaceConnectionError(`Failed to connect to Rocket.Chat Cloud: ${response.statusText}`);
}
}
const payload = await response.json();
if (!payload) {
return undefined;
}
return payload;
};
export async function connectWorkspace(token: string) {
assertNotOfflineLicense();
if (!token) {
throw new CloudWorkspaceConnectionError('Invalid registration token');
}
try {
const redirectUri = getRedirectUri();
const body = {
email: settings.get<string>('Organization_Email'),
client_name: settings.get<string>('Site_Name'),
redirect_uris: [redirectUri],
};
const payload = await fetchRegistrationDataPayload({ token, body });
if (!payload) {
return false;
}
await saveRegistrationData(payload);
return true;
} catch (err) {
SystemLogger.error({
msg: 'Failed to Connect with Rocket.Chat Cloud',
url: '/api/oauth/clients',
err,
});
return false;
}
}

View File

@@ -0,0 +1,84 @@
import { Users } from '@rocket.chat/models';
import { serverFetch as fetch } from '@rocket.chat/server-fetch';
import { Meteor } from 'meteor/meteor';
import { getRedirectUri } from './getRedirectUri';
import { userScopes } from './oauthScopes';
import { assertNotOfflineLicense } from './offlineLicense';
import { settings } from '../../settings';
import { SystemLogger } from '../logger/system';
export async function finishOAuthAuthorization(code: string, state: string) {
assertNotOfflineLicense();
if (settings.get<string>('Cloud_Workspace_Registration_State') !== state) {
throw new Meteor.Error('error-invalid-state', 'Invalid state provided', {
method: 'cloud:finishOAuthAuthorization',
});
}
const clientId = settings.get<string>('Cloud_Workspace_Client_Id');
const clientSecret = settings.get<string>('Cloud_Workspace_Client_Secret');
const scope = userScopes.join(' ');
let payload;
try {
const cloudUrl = settings.get<string>('Cloud_Url');
const response = await fetch(`${cloudUrl}/api/oauth/token`, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
params: new URLSearchParams({
client_id: clientId,
client_secret: clientSecret,
grant_type: 'authorization_code',
scope,
code,
redirect_uri: getRedirectUri(),
}),
// SECURITY: the URL is a default hardcoded value or an envvar/setting set by an admin. It's safe to disable this check.
ignoreSsrfValidation: true,
});
if (!response.ok) {
throw new Error((await response.json()).error);
}
payload = await response.json();
} catch (err) {
SystemLogger.error({
msg: 'Failed to finish OAuth authorization with Rocket.Chat Cloud',
url: '/api/oauth/token',
err,
});
return false;
}
const expiresAt = new Date();
expiresAt.setSeconds(expiresAt.getSeconds() + payload.expires_in);
const uid = Meteor.userId();
if (!uid) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', {
method: 'cloud:finishOAuthAuthorization',
});
}
await Users.updateOne(
{ _id: uid },
{
$set: {
'services.cloud': {
accessToken: payload.access_token,
expiresAt,
scope: payload.scope,
tokenType: payload.token_type,
refreshToken: payload.refresh_token,
},
},
},
);
return true;
}

View File

@@ -0,0 +1,56 @@
import { serverFetch as fetch } from '@rocket.chat/server-fetch';
import { getWorkspaceAccessTokenOrThrow } from './getWorkspaceAccessToken';
import { syncWorkspace } from './syncWorkspace';
import { settings } from '../../settings';
import { SystemLogger } from '../logger/system';
import { getURL } from '../utils/getURL';
export const fallback = 'https://go.rocket.chat/i/contact-sales';
export const getCheckoutUrl = async (): Promise<{
url: string;
}> => {
try {
await syncWorkspace();
const token = await getWorkspaceAccessTokenOrThrow(true, 'workspace:billing', false);
const subscriptionURL = getURL('admin/subscription', {
full: true,
});
const body = {
okCallback: `${subscriptionURL}?subscriptionSuccess=true`,
cancelCallback: subscriptionURL,
};
const billingUrl = settings.get<string>('Cloud_Billing_Url');
const response = await fetch(`${billingUrl}/api/v2/checkout`, {
method: 'POST',
headers: {
Authorization: `Bearer ${token}`,
},
body,
// SECURITY: the URL is a default hardcoded value or an envvar/setting set by an admin. It's safe to disable this check.
ignoreSsrfValidation: true,
});
if (!response.ok) {
throw new Error(await response.json());
}
return response.json();
} catch (err: any) {
SystemLogger.error({
msg: 'Failed to get Checkout URL with Rocket.Chat Billing Service',
url: '/api/v2/checkout',
err,
});
return {
url: fallback,
};
}
};

View File

@@ -0,0 +1,37 @@
import type { CloudConfirmationPollData } from '@rocket.chat/core-typings';
import { serverFetch as fetch } from '@rocket.chat/server-fetch';
import { assertNotOfflineLicense } from './offlineLicense';
import { settings } from '../../settings';
import { SystemLogger } from '../logger/system';
export async function getConfirmationPoll(deviceCode: string): Promise<CloudConfirmationPollData> {
assertNotOfflineLicense();
try {
const cloudUrl = settings.get<string>('Cloud_Url');
const response = await fetch(`${cloudUrl}/api/v2/register/workspace/poll`, {
params: { token: deviceCode },
// SECURITY: the URL is a default hardcoded value or an envvar/setting set by an admin. It's safe to disable this check.
ignoreSsrfValidation: true,
});
try {
if (!response.ok) {
throw new Error((await response.json()).error);
}
return await response.json();
} catch (err) {
throw new Error(`Failed to retrieve registration confirmation poll data: ${response.statusText}`);
}
} catch (err: any) {
SystemLogger.error({
msg: 'Failed to get confirmation poll from Rocket.Chat Cloud',
url: '/api/v2/register/workspace/poll',
err,
});
throw err;
}
}

View File

@@ -0,0 +1,29 @@
import { Settings } from '@rocket.chat/models';
import { Random } from '@rocket.chat/random';
import { getRedirectUri } from './getRedirectUri';
import { userScopes } from './oauthScopes';
import { assertNotOfflineLicense } from './offlineLicense';
import { settings } from '../../settings';
import { updateAuditedBySystem } from '../../settings/lib/auditedSettingUpdates';
import { notifyOnSettingChangedById } from '../notifyListener';
export async function getOAuthAuthorizationUrl() {
assertNotOfflineLicense();
const state = Random.id();
await updateAuditedBySystem({
reason: 'getOAuthAuthorizationUrl',
})(Settings.updateValueById, 'Cloud_Workspace_Registration_State', state);
void notifyOnSettingChangedById('Cloud_Workspace_Registration_State');
const cloudUrl = settings.get('Cloud_Url');
const clientId = settings.get('Cloud_Workspace_Client_Id');
const redirectUri = getRedirectUri();
const scope = userScopes.join(' ');
return `${cloudUrl}/authorize?response_type=code&client_id=${clientId}&redirect_uri=${redirectUri}&scope=${scope}&state=${state}`;
}

View File

@@ -0,0 +1,5 @@
import { settings } from '../../settings';
export function getRedirectUri() {
return `${settings.get<string>('Site_Url')}/admin/cloud/oauth-callback`.replace(/\/\/admin+/g, '/admin');
}

View File

@@ -0,0 +1,122 @@
import type { IWorkspaceCredentials } from '@rocket.chat/core-typings';
import { License } from '@rocket.chat/license';
import { WorkspaceCredentials } from '@rocket.chat/models';
import { getWorkspaceAccessTokenWithScope } from './getWorkspaceAccessTokenWithScope';
import { workspaceScopes } from './oauthScopes';
import { retrieveRegistrationStatus } from './retrieveRegistrationStatus';
import { SystemLogger } from '../logger/system';
const hasWorkspaceAccessTokenExpired = (credentials: IWorkspaceCredentials): boolean => new Date() >= credentials.expirationDate;
/**
* Returns the access token for the workspace, if it is expired or forceNew is true, it will get a new one
* and save it to the database, therefore if this function does not throw an error, it will always return a valid token.
*
* @param {boolean} forceNew - If true, it will get a new token even if the current one is not expired
* @param {string} scope - The scope of the token to get
* @param {boolean} save - If true, it will save the new token to the database
* @throws {CloudWorkspaceAccessTokenError} If the workspace is not registered (no credentials in the database)
*
* @returns string - A valid access token for the workspace
*/
export async function getWorkspaceAccessToken(forceNew = false, scope = '', save = true, throwOnError = false): Promise<string> {
const { workspaceRegistered } = await retrieveRegistrationStatus();
if (!workspaceRegistered) {
return '';
}
if (License.hasOfflineLicense()) {
return '';
}
// Note: If no scope is given, it means we should assume the default scope, we store the default scopes
// in the global variable workspaceScopes.
if (scope === '') {
scope = workspaceScopes.join(' ');
}
const workspaceCredentials = await WorkspaceCredentials.getCredentialByScope(scope);
if (workspaceCredentials && !hasWorkspaceAccessTokenExpired(workspaceCredentials) && !forceNew) {
SystemLogger.debug({
msg: 'Workspace credentials cache hit. Avoiding generating a new access token from cloud services.',
scope,
});
return workspaceCredentials.accessToken;
}
SystemLogger.debug({
msg: 'Workspace credentials cache miss, fetching new access token from cloud services.',
scope,
});
const accessToken = await getWorkspaceAccessTokenWithScope({ scope, throwOnError });
if (save) {
await WorkspaceCredentials.updateCredentialByScope({
scope: accessToken.scope,
accessToken: accessToken.token,
expirationDate: accessToken.expiresAt,
});
}
return accessToken.token;
}
export class CloudWorkspaceAccessTokenError extends Error {
constructor() {
super('Could not get workspace access token');
}
}
export const isAbortError = (error: unknown): error is { type: 'AbortError' } => {
if (typeof error !== 'object' || error === null) {
return false;
}
return 'type' in error && error.type === 'AbortError';
};
export class CloudWorkspaceAccessTokenEmptyError extends Error {
constructor() {
super('Workspace access token is empty');
}
}
export async function getWorkspaceAccessTokenOrThrow(forceNew = false, scope = '', save = true): Promise<string> {
const token = await getWorkspaceAccessToken(forceNew, scope, save, true);
if (!token) {
throw new CloudWorkspaceAccessTokenEmptyError();
}
return token;
}
export const generateWorkspaceBearerHttpHeaderOrThrow = async (
forceNew = false,
scope = '',
save = true,
): Promise<{ Authorization: string }> => {
const token = await getWorkspaceAccessTokenOrThrow(forceNew, scope, save);
return {
Authorization: `Bearer ${token}`,
};
};
export const generateWorkspaceBearerHttpHeader = async (
forceNew = false,
scope = '',
save = true,
): Promise<{ Authorization: string } | undefined> => {
const token = await getWorkspaceAccessToken(forceNew, scope, save);
if (!token) {
return undefined;
}
return {
Authorization: `Bearer ${token}`,
};
};

View File

@@ -0,0 +1,98 @@
import { License } from '@rocket.chat/license';
import { serverFetch as fetch } from '@rocket.chat/server-fetch';
import { getRedirectUri } from './getRedirectUri';
import { CloudWorkspaceAccessTokenError } from './getWorkspaceAccessToken';
import { workspaceScopes } from './oauthScopes';
import { removeWorkspaceRegistrationInfo } from './removeWorkspaceRegistrationInfo';
import { retrieveRegistrationStatus } from './retrieveRegistrationStatus';
import { settings } from '../../settings';
import { SystemLogger } from '../logger/system';
type WorkspaceAccessTokenWithScope = {
token: string;
expiresAt: Date;
scope: string;
};
type GetWorkspaceAccessTokenWithScopeParams = {
scope?: string;
throwOnError?: boolean;
};
export async function getWorkspaceAccessTokenWithScope({
scope = '',
throwOnError = false,
}: GetWorkspaceAccessTokenWithScopeParams): Promise<WorkspaceAccessTokenWithScope> {
const { workspaceRegistered } = await retrieveRegistrationStatus();
const tokenResponse = { token: '', expiresAt: new Date(), scope: '' };
if (!workspaceRegistered) {
return tokenResponse;
}
if (License.hasOfflineLicense()) {
return tokenResponse;
}
// eslint-disable-next-line @typescript-eslint/naming-convention
const client_id = settings.get<string>('Cloud_Workspace_Client_Id');
if (!client_id) {
return tokenResponse;
}
if (scope === '') {
scope = workspaceScopes.join(' ');
}
// eslint-disable-next-line @typescript-eslint/naming-convention
const client_secret = settings.get<string>('Cloud_Workspace_Client_Secret');
const redirectUri = getRedirectUri();
let payload;
try {
const body = new URLSearchParams();
body.append('client_id', client_id);
body.append('client_secret', client_secret);
body.append('scope', scope);
body.append('grant_type', 'client_credentials');
body.append('redirect_uri', redirectUri);
const cloudUrl = settings.get<string>('Cloud_Url');
const response = await fetch(`${cloudUrl}/api/oauth/token`, {
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
method: 'POST',
body,
// SECURITY: the URL is a default hardcoded value or an envvar/setting set by an admin. It's safe to disable this check.
ignoreSsrfValidation: true,
timeout: 5000,
});
payload = await response.json();
if (response.status >= 400) {
if (payload.error === 'oauth_invalid_client_credentials') {
throw new CloudWorkspaceAccessTokenError();
}
}
const expiresAt = new Date();
expiresAt.setSeconds(expiresAt.getSeconds() + payload.expires_in);
return {
token: payload.access_token,
expiresAt,
scope: payload.scope,
};
} catch (err: any) {
if (err instanceof CloudWorkspaceAccessTokenError) {
SystemLogger.error('Server has been unregistered from cloud');
void removeWorkspaceRegistrationInfo();
if (throwOnError) {
throw err;
}
}
}
return tokenResponse;
}

View File

@@ -0,0 +1,18 @@
import { retrieveRegistrationStatus } from './retrieveRegistrationStatus';
import { settings } from '../../settings';
export async function getWorkspaceKey() {
const { workspaceRegistered } = await retrieveRegistrationStatus();
if (!workspaceRegistered) {
return false;
}
const publicKey = settings.get<string>('Cloud_Workspace_PublicKey');
if (!publicKey) {
return false;
}
return publicKey;
}

View File

@@ -0,0 +1,78 @@
import { Cloud } from '@rocket.chat/core-typings';
import { Settings } from '@rocket.chat/models';
import { serverFetch as fetch } from '@rocket.chat/server-fetch';
import * as z from 'zod';
import { getWorkspaceAccessToken } from './getWorkspaceAccessToken';
import { LICENSE_VERSION } from './license';
import { CloudWorkspaceConnectionError } from '../../../lib/errors/CloudWorkspaceConnectionError';
import { CloudWorkspaceLicenseError } from '../../../lib/errors/CloudWorkspaceLicenseError';
import { settings } from '../../settings';
import { callbacks } from '../callbacks';
import { SystemLogger } from '../logger/system';
const fetchCloudWorkspaceLicensePayload = async ({ token }: { token: string }): Promise<Cloud.WorkspaceLicensePayload> => {
const workspaceRegistrationClientUri = settings.get<string>('Cloud_Workspace_Registration_Client_Uri');
const response = await fetch(`${workspaceRegistrationClientUri}/license`, {
headers: {
Authorization: `Bearer ${token}`,
},
params: {
version: LICENSE_VERSION,
},
// SECURITY: the URL is a default hardcoded value or an envvar/setting set by an admin. It's safe to disable this check.
ignoreSsrfValidation: true,
});
if (!response.ok) {
try {
const { error } = await response.json();
throw new CloudWorkspaceConnectionError(`Failed to connect to Rocket.Chat Cloud: ${error}`);
} catch (error) {
throw new CloudWorkspaceConnectionError(`Failed to connect to Rocket.Chat Cloud: ${response.statusText}`);
}
}
const payload = await response.json();
const result = Cloud.WorkspaceLicensePayloadSchema.safeParse(payload);
if (!result.success) {
throw new CloudWorkspaceLicenseError('failed type validation', {
cause: z.prettifyError(result.error),
});
}
return result.data;
};
export async function getWorkspaceLicense() {
const currentLicense = await Settings.findOne('Cloud_Workspace_License');
// it should never happen, since even if the license is not found, it will return an empty settings
if (!currentLicense?._updatedAt) {
throw new CloudWorkspaceLicenseError('Failed to retrieve current license');
}
try {
const token = await getWorkspaceAccessToken();
if (!token) {
return;
}
const payload = await fetchCloudWorkspaceLicensePayload({ token });
if (currentLicense.value && payload.updatedAt.getTime() <= currentLicense._updatedAt.getTime()) {
return;
}
await callbacks.run('workspaceLicenseChanged', payload.license);
return { updated: true, license: payload.license };
} catch (err) {
SystemLogger.error({
msg: 'Failed to update license from Rocket.Chat Cloud',
url: '/license',
err,
});
}
}

View File

@@ -0,0 +1,59 @@
import { cronJobs } from '@rocket.chat/cron';
import { Meteor } from 'meteor/meteor';
import { connectWorkspace } from './connectWorkspace';
import { CloudWorkspaceAccessTokenEmptyError, getWorkspaceAccessToken } from './getWorkspaceAccessToken';
import { getWorkspaceAccessTokenWithScope } from './getWorkspaceAccessTokenWithScope';
import { retrieveRegistrationStatus } from './retrieveRegistrationStatus';
import { syncWorkspace } from './syncWorkspace';
import { SystemLogger } from '../logger/system';
const licenseCronName = 'Cloud Workspace Sync';
Meteor.startup(async () => {
const { workspaceRegistered } = await retrieveRegistrationStatus();
if (process.env.REG_TOKEN && process.env.REG_TOKEN !== '' && !workspaceRegistered) {
try {
SystemLogger.info('REG_TOKEN Provided. Attempting to register');
if (!(await connectWorkspace(process.env.REG_TOKEN))) {
throw new Error("Couldn't register with token. Please make sure token is valid or hasn't already been used");
}
SystemLogger.info('Successfully registered with token provided by REG_TOKEN!');
} catch (err: any) {
SystemLogger.error({ msg: 'An error occurred registering with token.', err });
}
}
setImmediate(async () => {
try {
await syncWorkspace();
} catch (err: any) {
if (err instanceof CloudWorkspaceAccessTokenEmptyError) {
return;
}
if (err.type && err.type === 'AbortError') {
return;
}
SystemLogger.error({ msg: 'An error occurred syncing workspace.', err });
}
});
const minute = Math.floor(Math.random() * 60);
await cronJobs.add(licenseCronName, `${minute} */12 * * *`, async () => {
try {
await syncWorkspace();
} catch (err: any) {
if (err instanceof CloudWorkspaceAccessTokenEmptyError) {
return;
}
if (err.type && err.type === 'AbortError') {
return;
}
SystemLogger.error({ msg: 'An error occurred syncing workspace.', err });
}
});
});
export { getWorkspaceAccessToken, getWorkspaceAccessTokenWithScope };

View File

@@ -0,0 +1 @@
export const LICENSE_VERSION = 3 as const;

View File

@@ -0,0 +1,5 @@
import { makeFunction } from '@rocket.chat/patch-injection';
export const applyAirGappedRestrictionsValidation = makeFunction(async <T>(fn: () => Promise<T>): Promise<T> => {
return fn();
});

View File

@@ -0,0 +1,13 @@
// These are the scopes we by default request access to
export const workspaceScopes = [
'workspace:license:read',
'workspace:client:write',
'workspace:stats:write',
'workspace:push:send',
'marketplace:read',
'marketplace:download',
'fedhub:register',
] as const;
// These are the scopes we use for the user
export const userScopes = ['openid', 'offline_access'] as const;

View File

@@ -0,0 +1,13 @@
import { License } from '@rocket.chat/license';
import { CloudOfflineLicenseError } from '../../../lib/errors/CloudOfflineLicenseError';
/**
* Guard for interactive cloud flows (registration, OAuth, billing). Background
* jobs should instead skip silently by checking {@link License.hasOfflineLicense}.
*/
export function assertNotOfflineLicense(): void {
if (License.hasOfflineLicense()) {
throw new CloudOfflineLicenseError('Cloud connectivity is disabled by the offline license applied to this workspace');
}
}

View File

@@ -0,0 +1,53 @@
import type { IUser } from '@rocket.chat/core-typings';
import { License } from '@rocket.chat/license';
import { Users } from '@rocket.chat/models';
import { serverFetch as fetch } from '@rocket.chat/server-fetch';
import { buildWorkspaceRegistrationData } from './buildRegistrationData';
import { settings } from '../../settings';
import { SystemLogger } from '../logger/system';
export async function registerPreIntentWorkspaceWizard(): Promise<boolean> {
if (License.hasOfflineLicense()) {
return false;
}
const firstUser = (await Users.getOldest({ projection: { name: 1, emails: 1 } })) as IUser | undefined;
const email = firstUser?.emails?.find((address) => address)?.address;
if (!email) {
return false;
}
const regInfo = await buildWorkspaceRegistrationData(email);
// Re-validated at dispatch time: an offline license applied while the
// registration data was being built must still suppress the request.
if (License.hasOfflineLicense()) {
return false;
}
try {
const cloudUrl = settings.get<string>('Cloud_Url');
const response = await fetch(`${cloudUrl}/api/v2/register/workspace/pre-intent`, {
method: 'POST',
body: regInfo,
timeout: 3 * 1000,
// SECURITY: the URL is a default hardcoded value or an envvar/setting set by an admin. It's safe to disable this check.
ignoreSsrfValidation: true,
});
if (!response.ok) {
throw new Error((await response.json()).error);
}
return true;
} catch (err: any) {
SystemLogger.error({
msg: 'Failed to register workspace pre-intent with Rocket.Chat Cloud',
url: '/api/v2/register/workspace/pre-intent',
err,
});
return false;
}
}

View File

@@ -0,0 +1,54 @@
import { serverFetch as fetch } from '@rocket.chat/server-fetch';
import { CloudWorkspaceAccessTokenEmptyError, getWorkspaceAccessToken } from './getWorkspaceAccessToken';
import { retrieveRegistrationStatus } from './retrieveRegistrationStatus';
import { syncWorkspace } from './syncWorkspace';
import { CloudWorkspaceConnectionError } from '../../../lib/errors/CloudWorkspaceConnectionError';
import { CloudWorkspaceRegistrationError } from '../../../lib/errors/CloudWorkspaceRegistrationError';
import { settings } from '../../settings';
import { callbacks } from '../callbacks';
export async function removeLicense() {
try {
const { workspaceRegistered } = await retrieveRegistrationStatus();
if (!workspaceRegistered) {
throw new CloudWorkspaceRegistrationError('Workspace is not registered');
}
const token = await getWorkspaceAccessToken(true);
if (!token) {
throw new CloudWorkspaceAccessTokenEmptyError();
}
const workspaceRegistrationClientUri = settings.get<string>('Cloud_Workspace_Registration_Client_Uri');
const response = await fetch(`${workspaceRegistrationClientUri}/client/downgrade`, {
method: 'POST',
headers: {
Authorization: `Bearer ${token}`,
},
// SECURITY: the URL is a default hardcoded value or an envvar/setting set by an admin. It's safe to disable this check.
ignoreSsrfValidation: true,
});
if (!response.ok) {
try {
const { error } = await response.json();
throw new CloudWorkspaceConnectionError(`Failed to connect to Rocket.Chat Cloud: ${error}`);
} catch (error) {
throw new CloudWorkspaceConnectionError(`Failed to connect to Rocket.Chat Cloud: ${response.statusText}`);
}
}
await syncWorkspace();
} catch (err) {
switch (true) {
case err instanceof CloudWorkspaceConnectionError:
case err instanceof CloudWorkspaceRegistrationError:
case err instanceof CloudWorkspaceAccessTokenEmptyError:
await callbacks.run('workspaceLicenseRemoved');
break;
default:
throw err;
}
}
}

View File

@@ -0,0 +1,43 @@
import { Settings, WorkspaceCredentials } from '@rocket.chat/models';
import { retrieveRegistrationStatus } from './retrieveRegistrationStatus';
import { updateAuditedBySystem } from '../../settings/lib/auditedSettingUpdates';
import { notifyOnSettingChangedById } from '../notifyListener';
export async function removeWorkspaceRegistrationInfo() {
const { workspaceRegistered } = await retrieveRegistrationStatus();
if (!workspaceRegistered) {
return true;
}
await WorkspaceCredentials.removeAllCredentials();
const settingsIds = [
'Cloud_Workspace_Id',
'Cloud_Workspace_Name',
'Cloud_Workspace_Client_Id',
'Cloud_Workspace_Client_Secret',
'Cloud_Workspace_Client_Secret_Expires_At',
'Cloud_Workspace_PublicKey',
'Cloud_Workspace_Registration_Client_Uri',
'Show_Setup_Wizard',
];
const promises = settingsIds.map((settingId) => {
if (settingId === 'Show_Setup_Wizard') {
return updateAuditedBySystem({
reason: 'removeWorkspaceRegistrationInfo',
})(Settings.updateValueById, 'Show_Setup_Wizard', 'in_progress');
}
return updateAuditedBySystem({ reason: 'removeWorkspaceRegistrationInfo' })(Settings.resetValueById, settingId, null);
});
(await Promise.all(promises)).forEach((value, index) => {
if (value?.modifiedCount) {
void notifyOnSettingChangedById(settingsIds[index]);
}
});
return true;
}

View File

@@ -0,0 +1,26 @@
import { Users } from '@rocket.chat/models';
import { settings } from '../../settings';
export async function retrieveRegistrationStatus(): Promise<{
workspaceRegistered: boolean;
workspaceId: string;
uniqueId: string;
token: string;
email: string;
}> {
const info = {
workspaceRegistered: !!settings.get('Cloud_Workspace_Client_Id') && !!settings.get('Cloud_Workspace_Client_Secret'),
workspaceId: settings.get<string>('Cloud_Workspace_Id'),
uniqueId: settings.get<string>('uniqueID'),
token: '',
email: settings.get<string>('Organization_Email') || '',
};
if (!info.email) {
const firstUser = await Users.getOldest({ projection: { emails: 1 } });
info.email = firstUser?.emails?.[0]?.address || info.email;
}
return info;
}

View File

@@ -0,0 +1,124 @@
import { applyLicense } from '@rocket.chat/license';
import { Settings } from '@rocket.chat/models';
import { settings } from '../../settings';
import { syncCloudData } from './syncWorkspace/syncCloudData';
import { updateAuditedBySystem } from '../../settings/lib/auditedSettingUpdates';
import { notifyOnSettingChangedById } from '../notifyListener';
type SaveRegistrationDataDTO = {
workspaceId: string;
client_name: string;
client_id: string;
client_secret: string;
client_secret_expires_at: number;
publicKey: string;
registration_client_uri: string;
};
type ManualSaveRegistrationDataDTO = SaveRegistrationDataDTO & { licenseData: { license: string } };
export async function saveRegistrationData({
workspaceId,
client_name,
client_id,
client_secret,
client_secret_expires_at,
publicKey,
registration_client_uri,
}: SaveRegistrationDataDTO) {
await saveRegistrationDataBase({
workspaceId,
client_name,
client_id,
client_secret,
client_secret_expires_at,
publicKey,
registration_client_uri,
});
await syncCloudData();
}
async function saveRegistrationDataBase({
workspaceId,
client_name,
client_id,
client_secret,
client_secret_expires_at,
publicKey,
registration_client_uri,
}: SaveRegistrationDataDTO) {
const settingsData = [
{ _id: 'Register_Server', value: true },
{ _id: 'Cloud_Workspace_Id', value: workspaceId },
{ _id: 'Cloud_Workspace_Name', value: client_name },
{ _id: 'Cloud_Workspace_Client_Id', value: client_id },
{ _id: 'Cloud_Workspace_Client_Secret', value: client_secret },
{ _id: 'Cloud_Workspace_Client_Secret_Expires_At', value: client_secret_expires_at },
{ _id: 'Cloud_Workspace_PublicKey', value: publicKey },
{ _id: 'Cloud_Workspace_Registration_Client_Uri', value: registration_client_uri },
];
const promises = [
...settingsData.map(({ _id, value }) =>
updateAuditedBySystem({
reason: 'saveRegistrationDataBase',
})(Settings.updateValueById, _id, value),
),
];
(await Promise.all(promises)).forEach((value, index) => {
if (value?.modifiedCount) {
void notifyOnSettingChangedById(settingsData[index]._id);
}
});
// Question: Why is this taking so long that needs a timeout?
// Answer: we use cache that requires a 'roundtrip' through the db and the application
// we need to make sure that the cache is updated before we continue the procedures
// we don't actually need to wait a whole second for this, but look this is just a retry mechanism it doesn't mean that actually takes all this time
for (const retry of Array.from({ length: 10 })) {
const isSettingsUpdated =
settings.get('Register_Server') === true &&
settings.get('Cloud_Workspace_Id') === workspaceId &&
settings.get('Cloud_Workspace_Name') === client_name &&
settings.get('Cloud_Workspace_Client_Id') === client_id &&
settings.get('Cloud_Workspace_Client_Secret') === client_secret &&
settings.get('Cloud_Workspace_Client_Secret_Expires_At') === client_secret_expires_at &&
settings.get('Cloud_Workspace_PublicKey') === publicKey &&
settings.get('Cloud_Workspace_Registration_Client_Uri') === registration_client_uri;
if (isSettingsUpdated) {
return;
}
if (retry === 9) {
throw new Error('Failed to save registration data');
}
await new Promise((resolve) => setTimeout(resolve, 1000));
}
}
export async function saveRegistrationDataManual({
workspaceId,
client_name,
client_id,
client_secret,
client_secret_expires_at,
publicKey,
registration_client_uri,
licenseData,
}: ManualSaveRegistrationDataDTO) {
await saveRegistrationDataBase({
workspaceId,
client_name,
client_id,
client_secret,
client_secret_expires_at,
publicKey,
registration_client_uri,
});
await applyLicense(licenseData.license, true);
}

View File

@@ -0,0 +1,61 @@
import { Settings } from '@rocket.chat/models';
import { serverFetch as fetch } from '@rocket.chat/server-fetch';
import { buildWorkspaceRegistrationData } from './buildRegistrationData';
import { assertNotOfflineLicense } from './offlineLicense';
import { retrieveRegistrationStatus } from './retrieveRegistrationStatus';
import { syncWorkspace } from './syncWorkspace';
import { settings } from '../../settings';
import { updateAuditedBySystem } from '../../settings/lib/auditedSettingUpdates';
import { SystemLogger } from '../logger/system';
import { notifyOnSettingChangedById } from '../notifyListener';
export async function startRegisterWorkspace(resend = false) {
assertNotOfflineLicense();
const { workspaceRegistered } = await retrieveRegistrationStatus();
if (workspaceRegistered || process.env.TEST_MODE) {
await syncWorkspace();
return true;
}
(await Settings.updateValueById('Register_Server', true)).modifiedCount && void notifyOnSettingChangedById('Register_Server');
const regInfo = await buildWorkspaceRegistrationData(undefined);
let payload;
try {
const cloudUrl = settings.get<string>('Cloud_Url');
const response = await fetch(`${cloudUrl}/api/v2/register/workspace`, {
method: 'POST',
body: regInfo,
params: {
resend,
},
// SECURITY: the URL is a default hardcoded value or an envvar/setting set by an admin. It's safe to disable this check.
ignoreSsrfValidation: true,
});
if (!response.ok) {
throw new Error((await response.json()).error);
}
payload = await response.json();
} catch (err: any) {
SystemLogger.error({
msg: 'Failed to register with Rocket.Chat Cloud',
url: '/api/v2/register/workspace',
err,
});
return false;
}
if (!payload) {
return false;
}
await updateAuditedBySystem({
reason: 'startRegisterWorkspace',
})(Settings.updateValueById, 'Cloud_Workspace_Id', payload.id);
return true;
}

View File

@@ -0,0 +1,46 @@
import type { CloudRegistrationIntentData } from '@rocket.chat/core-typings';
import { serverFetch as fetch } from '@rocket.chat/server-fetch';
import { buildWorkspaceRegistrationData } from './buildRegistrationData';
import { assertNotOfflineLicense } from './offlineLicense';
import { settings } from '../../settings';
import { SystemLogger } from '../logger/system';
export async function startRegisterWorkspaceSetupWizard(resend = false, email: string): Promise<CloudRegistrationIntentData> {
assertNotOfflineLicense();
const regInfo = await buildWorkspaceRegistrationData(email);
let payload;
try {
const cloudUrl = settings.get<string>('Cloud_Url');
const response = await fetch(`${cloudUrl}/api/v2/register/workspace/intent`, {
body: regInfo,
method: 'POST',
params: {
resent: resend,
},
// SECURITY: the URL is a default hardcoded value or an envvar/setting set by an admin. It's safe to disable this check.
ignoreSsrfValidation: true,
});
if (!response.ok) {
throw new Error((await response.json()).error);
}
payload = await response.json();
} catch (err: any) {
SystemLogger.error({
msg: 'Failed to register workspace intent with Rocket.Chat Cloud',
url: '/api/v2/register/workspace',
err,
});
throw err;
}
if (!payload) {
throw new Error('Failed to fetch registration intent endpoint');
}
return payload;
}

View File

@@ -0,0 +1,23 @@
import type { SignedSupportedVersions } from '@rocket.chat/server-cloud-communication';
import { supportedVersionsChooseLatest } from './supportedVersionsChooseLatest';
describe('supportedVersionsChooseLatest', () => {
test('should return the latest version', async () => {
const versionFromLicense: SignedSupportedVersions = {
signed: 'signed____',
timestamp: '2021-08-31T18:00:00.000Z',
versions: [],
};
const versionFromCloud: SignedSupportedVersions = {
signed: 'signed_------',
timestamp: '2021-08-31T19:00:00.000Z',
versions: [],
};
const result = await supportedVersionsChooseLatest(versionFromLicense, versionFromCloud);
expect(result.timestamp).toBe(versionFromCloud.timestamp);
});
});

View File

@@ -0,0 +1,9 @@
import type { SignedSupportedVersions } from '@rocket.chat/server-cloud-communication';
export const supportedVersionsChooseLatest = async (...tokens: (SignedSupportedVersions | undefined)[]) => {
const [token] = (tokens.filter((r) => r?.timestamp != null) as SignedSupportedVersions[]).sort((a, b) => {
return new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime();
});
return token;
};

View File

@@ -0,0 +1,208 @@
import type { SettingValue } from '@rocket.chat/core-typings';
import { License } from '@rocket.chat/license';
import { Settings } from '@rocket.chat/models';
import type { SignedSupportedVersions, SupportedVersions } from '@rocket.chat/server-cloud-communication';
import type { Response } from '@rocket.chat/server-fetch';
import { serverFetch as fetch } from '@rocket.chat/server-fetch';
import { supportedVersionsChooseLatest } from './supportedVersionsChooseLatest';
import { supportedVersions as supportedVersionsFromBuild } from '../../../../app/utils/rocketchat-supported-versions.info';
import { settings } from '../../../settings';
import { updateAuditedBySystem } from '../../../settings/lib/auditedSettingUpdates';
import { SystemLogger } from '../../logger/system';
import { notifyOnSettingChangedById } from '../../notifyListener';
import { generateWorkspaceBearerHttpHeader } from '../getWorkspaceAccessToken';
import { buildVersionUpdateMessage } from '../version-check/functions/buildVersionUpdateMessage';
declare module '@rocket.chat/core-typings' {
interface ILicenseV3 {
supportedVersions?: SignedSupportedVersions;
}
}
/** HELPERS */
export const wrapPromise = <T>(
promise: Promise<T>,
): Promise<
| {
success: true;
result: T;
}
| {
success: false;
error: any;
}
> =>
promise
.then((result) => ({ success: true, result }) as const)
.catch((error) => ({
success: false,
error,
}));
export const handleResponse = async <T>(promise: Promise<Response>) => {
return wrapPromise<T>(
(async () => {
const request = await promise;
if (!request.ok) {
if (request.size > 0) {
throw new Error((await request.json()).error);
}
throw new Error(request.statusText);
}
return request.json();
})(),
);
};
const cacheValueInSettings = <T extends SettingValue>(
key: string,
fn: (retry?: number) => Promise<T>,
): (() => Promise<T>) & {
reset: (retry?: number) => Promise<T>;
} => {
const reset = async (retry?: number) => {
SystemLogger.debug({
msg: 'Resetting cached value in settings',
key,
});
const value = await fn(retry);
if (
(
await updateAuditedBySystem({
reason: 'cacheValueInSettings reset',
})(Settings.updateValueById, key, value)
).modifiedCount
) {
void notifyOnSettingChangedById(key);
}
return value;
};
return Object.assign(
async () => {
const storedValue = settings.get<T>(key);
if (storedValue) {
return storedValue;
}
return reset();
},
{
reset,
},
);
};
const releaseEndpoint = process.env.OVERWRITE_INTERNAL_RELEASE_URL?.trim()
? process.env.OVERWRITE_INTERNAL_RELEASE_URL.trim()
: 'https://releases.rocket.chat/v2/server/supportedVersions';
const getSupportedVersionsFromCloud = async () => {
if (process.env.CLOUD_SUPPORTED_VERSIONS_TOKEN) {
return {
success: true,
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
result: JSON.parse(process.env.CLOUD_SUPPORTED_VERSIONS!),
};
}
const headers = await generateWorkspaceBearerHttpHeader();
// Re-validated at dispatch time: an offline license applied while this async
// operation was in flight must still suppress the request.
if (License.hasOfflineLicense()) {
return { success: true, result: undefined } as const;
}
const response = await handleResponse<SupportedVersions>(
fetch(releaseEndpoint, {
headers,
timeout: 5000,
// SECURITY: the URL is a default hardcoded value or an envvar set by an admin. It's safe to disable this check.
ignoreSsrfValidation: true,
}),
);
if (!response.success) {
SystemLogger.error({
msg: 'Failed to communicate with Rocket.Chat Cloud',
url: releaseEndpoint,
err: response.error,
});
}
return response;
};
const getSupportedVersionsToken = async (retry = 0) => {
/**
* Gets the supported versions from the license
* Gets the supported versions from the cloud
* Gets the latest version
* return the token
*/
const [versionsFromLicense, cloudResponse] = await Promise.all([
License.getLicense(),
License.hasOfflineLicense() ? ({ success: true, result: undefined } as const) : getSupportedVersionsFromCloud(),
]);
const supportedVersions = await supportedVersionsChooseLatest(
supportedVersionsFromBuild,
versionsFromLicense?.supportedVersions,
(cloudResponse.success && cloudResponse.result) || undefined,
);
SystemLogger.debug({
msg: 'Supported versions',
supportedVersionsFromBuild: supportedVersionsFromBuild.timestamp,
versionsFromLicense: versionsFromLicense?.supportedVersions?.timestamp,
response: cloudResponse.success && cloudResponse.result?.timestamp,
});
switch (supportedVersions) {
case supportedVersionsFromBuild:
SystemLogger.info({
msg: 'Using supported versions from build',
});
break;
case versionsFromLicense?.supportedVersions:
SystemLogger.info({
msg: 'Using supported versions from license',
});
break;
case cloudResponse.success && cloudResponse.result:
SystemLogger.info({
msg: 'Using supported versions from cloud',
});
break;
}
// to avoid a possibly wrong message, we only send the message if the cloud response was successful
if (cloudResponse.success) {
await buildVersionUpdateMessage(supportedVersions?.versions);
} else if (retry < 5) {
// in case of failure we'll try again later
setTimeout(
async () => {
await getCachedSupportedVersionsToken.reset(retry + 1);
},
5000 * Math.pow(2, retry),
);
} else {
SystemLogger.error({
msg: 'Failed to get supported versions from cloud after retries.',
retry,
});
await buildVersionUpdateMessage(supportedVersions?.versions);
}
return supportedVersions?.signed;
};
export const getCachedSupportedVersionsToken = cacheValueInSettings('Cloud_Workspace_Supported_Versions_Token', getSupportedVersionsToken);

View File

@@ -0,0 +1,104 @@
import { Cloud } from '@rocket.chat/core-typings';
import { serverFetch as fetch } from '@rocket.chat/server-fetch';
import * as z from 'zod';
import { handleAnnouncementsOnWorkspaceSync, handleNpsOnWorkspaceSync } from './handleCommsSync';
import { CloudWorkspaceConnectionError } from '../../../../lib/errors/CloudWorkspaceConnectionError';
import { CloudWorkspaceRegistrationError } from '../../../../lib/errors/CloudWorkspaceRegistrationError';
import { settings } from '../../../settings';
import { SystemLogger } from '../../logger/system';
import { buildWorkspaceRegistrationData } from '../buildRegistrationData';
import { CloudWorkspaceAccessTokenEmptyError, getWorkspaceAccessToken } from '../getWorkspaceAccessToken';
import { retrieveRegistrationStatus } from '../retrieveRegistrationStatus';
const fetchCloudAnnouncementsSync = async ({
token,
data,
}: {
token: string;
data: Cloud.WorkspaceSyncRequestPayload;
}): Promise<Cloud.WorkspaceCommsResponsePayload> => {
const cloudUrl = settings.get<string>('Cloud_Url');
const response = await fetch(`${cloudUrl}/api/v3/comms/workspace`, {
method: 'POST',
headers: {
Authorization: `Bearer ${token}`,
},
body: data,
// SECURITY: the URL is a default hardcoded value or an envvar/setting set by an admin. It's safe to disable this check.
ignoreSsrfValidation: true,
});
if (!response.ok) {
try {
const { error } = await response.json();
throw new CloudWorkspaceConnectionError(`Failed to connect to Rocket.Chat Cloud: ${error}`);
} catch (error) {
throw new CloudWorkspaceConnectionError(`Failed to connect to Rocket.Chat Cloud: ${response.statusText}`);
}
}
const payload = await response.json();
const result = Cloud.WorkspaceCommsResponsePayloadSchema.safeParse(payload);
if (!result.success) {
throw new CloudWorkspaceConnectionError('failed type validation', {
cause: z.prettifyError(result.error),
});
}
return result.data;
};
export async function announcementSync() {
try {
const { workspaceRegistered } = await retrieveRegistrationStatus();
if (!workspaceRegistered) {
throw new CloudWorkspaceRegistrationError('Workspace is not registered');
}
const token = await getWorkspaceAccessToken(true);
if (!token) {
throw new CloudWorkspaceAccessTokenEmptyError();
}
const workspaceRegistrationData = await buildWorkspaceRegistrationData(undefined);
const { nps, announcements } = await fetchCloudAnnouncementsSync({
token,
data: workspaceRegistrationData,
});
if (nps) {
await handleNpsOnWorkspaceSync(nps);
}
if (announcements) {
await handleAnnouncementsOnWorkspaceSync(announcements);
}
return true;
} catch (err) {
switch (true) {
case err instanceof CloudWorkspaceConnectionError:
case err instanceof CloudWorkspaceRegistrationError:
case err instanceof CloudWorkspaceAccessTokenEmptyError: {
SystemLogger.info({
msg: 'Failed to sync with Rocket.Chat Cloud',
function: 'announcementSync',
err,
});
break;
}
default: {
SystemLogger.error({
msg: 'Error during workspace sync',
function: 'announcementSync',
err,
});
}
}
throw err;
}
}

View File

@@ -0,0 +1,42 @@
import { Cloud } from '@rocket.chat/core-typings';
import { serverFetch as fetch } from '@rocket.chat/server-fetch';
import * as z from 'zod';
import { CloudWorkspaceConnectionError } from '../../../../lib/errors/CloudWorkspaceConnectionError';
import { settings } from '../../../settings';
export async function fetchWorkspaceSyncPayload({
token,
data,
}: {
token: string;
data: Cloud.WorkspaceSyncRequestPayload;
}): Promise<Cloud.WorkspaceSyncResponse> {
const workspaceRegistrationClientUri = settings.get<string>('Cloud_Workspace_Registration_Client_Uri');
const response = await fetch(`${workspaceRegistrationClientUri}/sync`, {
method: 'POST',
headers: {
Authorization: `Bearer ${token}`,
},
body: data,
// SECURITY: the URL is a default hardcoded value or an envvar/setting set by an admin. It's safe to disable this check.
ignoreSsrfValidation: true,
});
if (!response.ok) {
const { error } = await response.json();
throw new CloudWorkspaceConnectionError(`Failed to connect to Rocket.Chat Cloud: ${error}`);
}
const payload = await response.json();
const result = Cloud.WorkspaceSyncResponseSchema.safeParse(payload);
if (!result.success) {
throw new CloudWorkspaceConnectionError('failed type validation', {
cause: z.prettifyError(result.error),
});
}
return result.data;
}

View File

@@ -0,0 +1,56 @@
import { NPS, Banner } from '@rocket.chat/core-services';
import type { Cloud, IBanner, Optional } from '@rocket.chat/core-typings';
import { getAndCreateNpsSurvey } from '../../../services/nps/getAndCreateNpsSurvey';
export const handleNpsOnWorkspaceSync = async (nps: Cloud.NpsSurveyAnnouncement) => {
const { id: npsId, startAt, expireAt } = nps;
await NPS.create({
npsId,
startAt,
expireAt,
createdBy: {
_id: 'rocket.cat',
username: 'rocket.cat',
},
});
const now = new Date();
if (startAt.getFullYear() === now.getFullYear() && startAt.getMonth() === now.getMonth() && startAt.getDate() === now.getDate()) {
await getAndCreateNpsSurvey(npsId);
}
};
export const handleBannerOnWorkspaceSync = async (banners: Optional<IBanner, '_updatedAt'>[]) => {
for (const banner of banners) {
await Banner.create(banner);
}
};
export const handleAnnouncementsOnWorkspaceSync = async (announcements: {
create: Cloud.Announcement[];
delete?: Cloud.Announcement['_id'][];
}) => {
const { create, delete: deleteIds } = announcements;
if (deleteIds) {
await Promise.all(deleteIds.map((announcementId) => Banner.disable(announcementId)));
}
await Promise.all(
create.map((announcement) => {
const { view, selector } = announcement;
return Banner.create({
...announcement,
...(selector?.roles ? { roles: selector.roles } : {}),
view: {
...view,
appId: 'cloud-announcements-core',
},
});
}),
);
};

View File

@@ -0,0 +1,64 @@
import { License } from '@rocket.chat/license';
import { CloudWorkspaceRegistrationError } from '../../../../lib/errors/CloudWorkspaceRegistrationError';
import { SystemLogger } from '../../logger/system';
import { CloudWorkspaceAccessTokenEmptyError, CloudWorkspaceAccessTokenError, isAbortError } from '../getWorkspaceAccessToken';
import { announcementSync } from './announcementSync';
import { legacySyncWorkspace } from './legacySyncWorkspace';
import { syncCloudData } from './syncCloudData';
import { getCachedSupportedVersionsToken } from '../supportedVersionsToken/supportedVersionsToken';
/**
* Syncs the workspace with the cloud
* @returns {Promise<void>}
* @throws {Error} - If there is an unexpected error during sync like a network error
*/
export async function syncWorkspace() {
if (License.hasOfflineLicense()) {
SystemLogger.debug({ msg: 'Skipping cloud sync: workspace has an offline license', function: 'syncWorkspace' });
await getCachedSupportedVersionsToken.reset();
return;
}
try {
await announcementSync();
await syncCloudData();
} catch (err) {
switch (true) {
case err instanceof CloudWorkspaceRegistrationError:
case err instanceof CloudWorkspaceAccessTokenError: {
// There is no access token, so we can't sync
SystemLogger.info('Workspace does not have a valid access token, sync aborted');
break;
}
default: {
if (!(err instanceof CloudWorkspaceAccessTokenEmptyError) && !isAbortError(err)) {
SystemLogger.error({ msg: 'Error during workspace sync', err });
}
SystemLogger.info({
msg: 'Falling back to legacy sync',
function: 'syncCloudData',
});
try {
await legacySyncWorkspace();
} catch (err) {
switch (true) {
case err instanceof CloudWorkspaceRegistrationError:
case err instanceof CloudWorkspaceAccessTokenError: {
// There is no access token, so we can't sync
break;
}
default: {
if (!(err instanceof CloudWorkspaceAccessTokenEmptyError) && !isAbortError(err)) {
SystemLogger.error({ msg: 'Error during fallback workspace sync', err });
}
throw err;
}
}
}
}
}
} finally {
await getCachedSupportedVersionsToken.reset();
}
}

View File

@@ -0,0 +1,108 @@
import { Cloud } from '@rocket.chat/core-typings';
import { Settings } from '@rocket.chat/models';
import { serverFetch as fetch } from '@rocket.chat/server-fetch';
import * as z from 'zod';
import { CloudWorkspaceConnectionError } from '../../../../lib/errors/CloudWorkspaceConnectionError';
import { CloudWorkspaceRegistrationError } from '../../../../lib/errors/CloudWorkspaceRegistrationError';
import { settings } from '../../../settings';
import { notifyOnSettingChangedById } from '../../notifyListener';
import type { WorkspaceRegistrationData } from '../buildRegistrationData';
import { buildWorkspaceRegistrationData } from '../buildRegistrationData';
import { CloudWorkspaceAccessTokenEmptyError, getWorkspaceAccessToken } from '../getWorkspaceAccessToken';
import { getWorkspaceLicense } from '../getWorkspaceLicense';
import { retrieveRegistrationStatus } from '../retrieveRegistrationStatus';
import { handleBannerOnWorkspaceSync, handleNpsOnWorkspaceSync } from './handleCommsSync';
/** @deprecated */
const fetchWorkspaceClientPayload = async ({
token,
workspaceRegistrationData,
}: {
token: string;
workspaceRegistrationData: WorkspaceRegistrationData<undefined>;
}): Promise<Cloud.WorkspaceSyncPayload | undefined> => {
const workspaceRegistrationClientUri = settings.get<string>('Cloud_Workspace_Registration_Client_Uri');
const response = await fetch(`${workspaceRegistrationClientUri}/client`, {
method: 'POST',
headers: {
Authorization: `Bearer ${token}`,
},
body: workspaceRegistrationData,
timeout: 5000,
// SECURITY: the URL is a default hardcoded value or an envvar/setting set by an admin. It's safe to disable this check.
ignoreSsrfValidation: true,
});
if (!response.ok) {
try {
const { error } = await response.json();
throw new CloudWorkspaceConnectionError(`Failed to connect to Rocket.Chat Cloud: ${error}`);
} catch (error) {
throw new CloudWorkspaceConnectionError(`Failed to connect to Rocket.Chat Cloud: ${response.statusText}`);
}
}
const payload = await response.json();
if (!payload) {
return undefined;
}
const result = Cloud.WorkspaceSyncPayloadSchema.safeParse(payload);
if (!result.success) {
throw new CloudWorkspaceConnectionError('Invalid response from Rocket.Chat Cloud', {
cause: z.prettifyError(result.error),
});
}
return result.data;
};
/** @deprecated */
const consumeWorkspaceSyncPayload = async (result: Cloud.WorkspaceSyncPayload) => {
if (result.publicKey) {
(await Settings.updateValueById('Cloud_Workspace_PublicKey', result.publicKey)).modifiedCount &&
void notifyOnSettingChangedById('Cloud_Workspace_PublicKey');
}
if (result.trial?.trialID) {
(await Settings.updateValueById('Cloud_Workspace_Had_Trial', true)).modifiedCount &&
void notifyOnSettingChangedById('Cloud_Workspace_Had_Trial');
}
// add banners
if (result.banners) {
await handleBannerOnWorkspaceSync(result.banners);
}
if (result.nps) {
await handleNpsOnWorkspaceSync(result.nps);
}
};
/** @deprecated */
export async function legacySyncWorkspace() {
const { workspaceRegistered } = await retrieveRegistrationStatus();
if (!workspaceRegistered) {
throw new CloudWorkspaceRegistrationError('Workspace is not registered');
}
const token = await getWorkspaceAccessToken(true);
if (!token) {
throw new CloudWorkspaceAccessTokenEmptyError();
}
const workspaceRegistrationData = await buildWorkspaceRegistrationData(undefined);
const payload = await fetchWorkspaceClientPayload({ token, workspaceRegistrationData });
if (payload) {
await consumeWorkspaceSyncPayload(payload);
}
await getWorkspaceLicense();
return true;
}

View File

@@ -0,0 +1,78 @@
import { DuplicatedLicenseError } from '@rocket.chat/license';
import { Settings } from '@rocket.chat/models';
import { fetchWorkspaceSyncPayload } from './fetchWorkspaceSyncPayload';
import { CloudWorkspaceAccessError } from '../../../../lib/errors/CloudWorkspaceAccessError';
import { CloudWorkspaceRegistrationError } from '../../../../lib/errors/CloudWorkspaceRegistrationError';
import { callbacks } from '../../callbacks';
import { SystemLogger } from '../../logger/system';
import { buildWorkspaceRegistrationData } from '../buildRegistrationData';
import { CloudWorkspaceAccessTokenEmptyError, getWorkspaceAccessToken } from '../getWorkspaceAccessToken';
import { retrieveRegistrationStatus } from '../retrieveRegistrationStatus';
export async function syncCloudData() {
try {
const { workspaceRegistered } = await retrieveRegistrationStatus();
if (!workspaceRegistered) {
throw new CloudWorkspaceRegistrationError('Workspace is not registered');
}
const token = await getWorkspaceAccessToken(true);
if (!token) {
throw new CloudWorkspaceAccessTokenEmptyError();
}
const workspaceRegistrationData = await buildWorkspaceRegistrationData(undefined);
const {
license,
removeLicense = false,
cloudSyncAnnouncement,
} = await fetchWorkspaceSyncPayload({
token,
data: workspaceRegistrationData,
});
await Settings.updateValueById('Cloud_Sync_Announcement_Payload', JSON.stringify(cloudSyncAnnouncement ?? null));
if (removeLicense) {
await callbacks.run('workspaceLicenseRemoved');
} else {
await callbacks.run('workspaceLicenseChanged', license);
}
SystemLogger.info({
msg: 'Synced with Rocket.Chat Cloud',
function: 'syncCloudData',
});
return true;
} catch (err) {
/**
* If some of CloudWorkspaceAccessError and CloudWorkspaceRegistrationError happens, makes no sense to run the legacySyncWorkspace
* because it will fail too.
* The DuplicatedLicenseError license error is also ignored because it is not a problem. the Cloud is allowed to send the same license twice.
*/
switch (true) {
case err instanceof DuplicatedLicenseError:
return;
case err instanceof CloudWorkspaceAccessError:
case err instanceof CloudWorkspaceRegistrationError:
case err instanceof CloudWorkspaceAccessTokenEmptyError:
SystemLogger.info({
msg: 'Failed to sync with Rocket.Chat Cloud',
function: 'syncCloudData',
err,
});
break;
default:
SystemLogger.error({
msg: 'Failed to sync with Rocket.Chat Cloud',
function: 'syncCloudData',
err,
});
}
throw err;
}
}

View File

@@ -0,0 +1,22 @@
import { Users } from '@rocket.chat/models';
export async function userLoggedOut(userId: string) {
if (!userId) {
return false;
}
const user = await Users.findOneById(userId);
if (user?.services?.cloud) {
await Users.updateOne(
{ _id: user._id },
{
$unset: {
'services.cloud': 1,
},
},
);
}
return true;
}

View File

@@ -0,0 +1,63 @@
import { License } from '@rocket.chat/license';
import { Users } from '@rocket.chat/models';
import { serverFetch as fetch } from '@rocket.chat/server-fetch';
import { retrieveRegistrationStatus } from './retrieveRegistrationStatus';
import { userLoggedOut } from './userLoggedOut';
import { settings } from '../../settings';
import { SystemLogger } from '../logger/system';
export async function userLogout(userId: string): Promise<string | boolean> {
const { workspaceRegistered } = await retrieveRegistrationStatus();
if (!workspaceRegistered) {
return '';
}
if (!userId) {
return '';
}
// Offline (air-gapped) licenses forbid the outbound token-revocation call, but
// the local cloud credentials must still be destroyed on logout.
if (License.hasOfflineLicense()) {
return userLoggedOut(userId);
}
const user = await Users.findOneById(userId);
if (user?.services?.cloud?.refreshToken) {
try {
const clientId = settings.get<string>('Cloud_Workspace_Client_Id');
if (!clientId) {
return '';
}
const clientSecret = settings.get('Cloud_Workspace_Client_Secret');
const { refreshToken } = user.services.cloud;
const cloudUrl = settings.get<string>('Cloud_Url');
await fetch(`${cloudUrl}/api/oauth/revoke`, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
params: {
client_id: clientId,
client_secret: clientSecret,
token: refreshToken,
token_type_hint: 'refresh_token',
},
// SECURITY: the URL is a default hardcoded value or an envvar/setting set by an admin. It's safe to disable this check.
ignoreSsrfValidation: true,
});
} catch (err) {
SystemLogger.error({
msg: 'Failed to get Revoke refresh token to logout of Rocket.Chat Cloud',
url: '/api/oauth/revoke',
err,
});
}
}
return userLoggedOut(userId);
}

View File

@@ -0,0 +1,123 @@
import { buildVersionUpdateMessage } from './buildVersionUpdateMessage';
import { sendMessagesToAdmins } from '../../../sendMessagesToAdmins';
const originalTestMode = process.env.TEST_MODE;
const mockInfoVersion = jest.fn(() => '7.5.0');
jest.mock('../../../../../app/utils/rocketchat.info', () => ({
Info: {
get version() {
return mockInfoVersion();
},
},
}));
const mockSetBannersInBulk = jest.fn();
const mockFindUsersInRolesWithQuery = jest.fn();
jest.mock('@rocket.chat/models', () => ({
Settings: {
updateValueById: jest.fn().mockResolvedValue({ modifiedCount: 0 }),
},
Users: {
findUsersInRolesWithQuery: () => mockFindUsersInRolesWithQuery(),
setBannersInBulk: (updates: unknown) => mockSetBannersInBulk(updates),
},
}));
const mockSettingsGet = jest.fn();
jest.mock('../../../../settings', () => ({
settings: {
get: (key: string) => mockSettingsGet(key),
},
}));
jest.mock('../../../i18n', () => ({
i18n: {
t: jest.fn((key) => key),
},
}));
jest.mock('../../../sendMessagesToAdmins', () => ({
sendMessagesToAdmins: jest.fn(),
}));
jest.mock('../../../../settings/lib/auditedSettingUpdates', () => ({
updateAuditedBySystem: jest.fn(() => () => Promise.resolve({ modifiedCount: 0 })),
}));
jest.mock('../../../notifyListener', () => ({
notifyOnSettingChangedById: jest.fn(),
}));
describe('buildVersionUpdateMessage', () => {
// Delete the TEST_MODE environment variable so buildVersionUpdateMessage()
// doesn't return early (see line 40 in buildVersionUpdateMessage.ts)
beforeAll(() => {
delete process.env.TEST_MODE;
});
afterAll(() => {
process.env.TEST_MODE = originalTestMode;
});
beforeEach(() => {
jest.clearAllMocks();
mockInfoVersion.mockReturnValue('7.5.0');
mockSettingsGet.mockReturnValue('7.0.0');
});
describe('cleanupOutdatedVersionUpdateBanners', () => {
it('should remove outdated version banners (<= current installed)', async () => {
const admin = { _id: 'admin1', banners: { 'versionUpdate-6_2_0': { id: 'versionUpdate-6_2_0' } } };
mockFindUsersInRolesWithQuery.mockReturnValue([admin]);
await buildVersionUpdateMessage([]);
expect(mockSetBannersInBulk).toHaveBeenCalledWith([{ userId: 'admin1', banners: {} }]);
});
it('should keep version banners > current installed', async () => {
const admin = { _id: 'admin1', banners: { 'versionUpdate-8_0_0': { id: 'versionUpdate-8_0_0' } } };
mockFindUsersInRolesWithQuery.mockReturnValue([admin]);
await buildVersionUpdateMessage([]);
expect(mockSetBannersInBulk).not.toHaveBeenCalled();
});
it('should remove banners with invalid semver version IDs', async () => {
const admin = { _id: 'admin1', banners: { 'versionUpdate-invalid_version': { id: 'versionUpdate-invalid_version' } } };
mockFindUsersInRolesWithQuery.mockReturnValue([admin]);
await buildVersionUpdateMessage([]);
expect(mockSetBannersInBulk).toHaveBeenCalledWith([{ userId: 'admin1', banners: {} }]);
});
});
describe('version sorting', () => {
it('should process versions in descending order (highest first)', async () => {
mockFindUsersInRolesWithQuery.mockReturnValue([]);
await buildVersionUpdateMessage([
{ version: '7.6.0', security: false, infoUrl: 'https://example.com/7.6.0' },
{ version: '8.0.0', security: false, infoUrl: 'https://example.com/8.0.0' },
{ version: '7.8.0', security: false, infoUrl: 'https://example.com/7.8.0' },
]);
expect(sendMessagesToAdmins).toHaveBeenCalledTimes(1);
expect(sendMessagesToAdmins).toHaveBeenCalledWith(
expect.objectContaining({
banners: expect.arrayContaining([
expect.objectContaining({
id: 'versionUpdate-8_0_0',
}),
]),
}),
);
});
});
});

View File

@@ -0,0 +1,111 @@
import type { IUser } from '@rocket.chat/core-typings';
import { Settings, Users } from '@rocket.chat/models';
import semver from 'semver';
import { Info } from '../../../../../app/utils/rocketchat.info';
import { settings } from '../../../../settings';
import { updateAuditedBySystem } from '../../../../settings/lib/auditedSettingUpdates';
import { i18n } from '../../../i18n';
import { notifyOnSettingChangedById } from '../../../notifyListener';
import { sendMessagesToAdmins } from '../../../sendMessagesToAdmins';
const cleanupOutdatedVersionUpdateBanners = async (): Promise<void> => {
const admins = Users.findUsersInRolesWithQuery('admin', { banners: { $exists: true } }, { projection: { _id: 1, banners: 1 } });
const updates: { userId: IUser['_id']; banners: NonNullable<IUser['banners']> }[] = [];
for await (const admin of admins) {
if (!admin.banners) {
continue;
}
const filteredBanners = Object.fromEntries(
Object.entries(admin.banners).filter(([bannerId]) => {
if (!bannerId.startsWith('versionUpdate-')) {
return true;
}
const version = bannerId.replace('versionUpdate-', '').replace(/_/g, '.');
if (!semver.valid(version) || semver.lte(version, Info.version)) {
return false;
}
return true;
}),
);
if (Object.keys(filteredBanners).length !== Object.keys(admin.banners).length) {
updates.push({ userId: admin._id, banners: filteredBanners });
}
}
if (updates.length > 0) {
await Users.setBannersInBulk(updates);
}
};
export const buildVersionUpdateMessage = async (
versions: {
version: string;
security: boolean;
infoUrl: string;
}[] = [],
) => {
if (process.env.TEST_MODE) {
return;
}
const lastCheckedVersion = settings.get<string>('Update_LatestAvailableVersion');
if (!lastCheckedVersion) {
return;
}
const sortedVersions = [...versions].sort((a, b) => semver.rcompare(a.version, b.version));
await cleanupOutdatedVersionUpdateBanners();
for await (const version of sortedVersions) {
if (semver.prerelease(version.version)) {
continue;
}
if (semver.lte(version.version, lastCheckedVersion)) {
continue;
}
if (semver.lte(version.version, Info.version)) {
continue;
}
(
await updateAuditedBySystem({
reason: 'buildVersionUpdateMessage',
})(Settings.updateValueById, 'Update_LatestAvailableVersion', version.version)
).modifiedCount && void notifyOnSettingChangedById('Update_LatestAvailableVersion');
await sendMessagesToAdmins({
msgs: async ({ adminUser }) => [
{
msg: `*${i18n.t('Update_your_RocketChat', { ...(adminUser.language && { lng: adminUser.language }) })}*\n${i18n.t(
'New_version_available_(s)',
{
postProcess: 'sprintf',
sprintf: [version.version],
},
)}\n${version.infoUrl}`,
},
],
banners: [
{
id: `versionUpdate-${version.version}`.replace(/\./g, '_'),
priority: 10,
title: 'Update_your_RocketChat',
text: 'New_version_available_(s)',
textArguments: [version.version],
link: version.infoUrl,
modifiers: [],
},
],
});
break;
}
};

View File

@@ -0,0 +1,86 @@
import type { IUser } from '@rocket.chat/core-typings';
import { License } from '@rocket.chat/license';
import { Users } from '@rocket.chat/models';
import { i18n } from '../../../i18n';
import { sendMessagesToAdmins } from '../../../sendMessagesToAdmins';
import logger from '../logger';
import { buildVersionUpdateMessage } from './buildVersionUpdateMessage';
import { getNewUpdates } from './getNewUpdates';
const getMessagesToSendToAdmins = async (
alerts: {
id: string;
priority: number;
title: string;
text: string;
textArguments?: string[];
modifiers: string[];
infoUrl: string;
}[],
adminUser: IUser,
): Promise<{ msg: string }[]> => {
const msgs = [];
for await (const alert of alerts) {
if (!(await Users.bannerExistsById(adminUser._id, `alert-${alert.id}`))) {
continue;
}
msgs.push({
msg: `*${i18n.t('Rocket_Chat_Alert', { ...(adminUser.language && { lng: adminUser.language }) })}:*\n\n*${i18n.t(alert.title, {
...(adminUser.language && { lng: adminUser.language }),
})}*\n${i18n.t(alert.text, {
...(adminUser.language && { lng: adminUser.language }),
...(Array.isArray(alert.textArguments) && {
postProcess: 'sprintf',
sprintf: alert.textArguments,
}),
...((!Array.isArray(alert.textArguments) && alert.textArguments) || {}), // bien dormido
})}\n${alert.infoUrl}`,
});
}
return msgs;
};
/**
* @deprecated
*/
export const checkVersionUpdate = async () => {
if (License.hasOfflineLicense()) {
return;
}
logger.info('Checking for version updates');
const { versions, alerts } = await getNewUpdates();
await buildVersionUpdateMessage(versions);
await showAlertsFromCloud(alerts);
};
const showAlertsFromCloud = async (
alerts?: {
id: string;
priority: number;
title: string;
text: string;
textArguments?: string[];
modifiers: string[];
infoUrl: string;
}[],
) => {
if (!alerts?.length) {
return;
}
return sendMessagesToAdmins({
msgs: async ({ adminUser }) => getMessagesToSendToAdmins(alerts, adminUser),
banners: alerts.map((alert) => ({
id: `alert-${alert.id}`.replace(/\./g, '_'),
priority: 10,
title: alert.title,
text: alert.text,
textArguments: alert.textArguments,
modifiers: alert.modifiers,
link: alert.infoUrl,
})),
});
};

View File

@@ -0,0 +1,97 @@
import os from 'node:os';
import { Settings } from '@rocket.chat/models';
import { serverFetch as fetch } from '@rocket.chat/server-fetch';
import { check, Match } from 'meteor/check';
import { getWorkspaceAccessToken } from '../..';
import { Info } from '../../../../../app/utils/rocketchat.info';
/** @deprecated */
export const getNewUpdates = async () => {
try {
const uniqueID = await Settings.findOne('uniqueID');
if (!uniqueID) {
throw new Error('uniqueID not found');
}
const params = {
uniqueId: String(uniqueID.value),
installedAt: uniqueID.createdAt.toJSON(),
version: Info.version,
osType: os.type(),
osPlatform: os.platform(),
osArch: os.arch(),
osRelease: os.release(),
nodeVersion: process.version,
deployMethod: process.env.DEPLOY_METHOD || 'tar',
deployPlatform: process.env.DEPLOY_PLATFORM || 'selfinstall',
};
const token = await getWorkspaceAccessToken();
const headers = {
...(token && { Authorization: `Bearer ${token}` }),
};
const url = 'https://releases.rocket.chat/updates/check';
const response = await fetch(url, {
headers,
params,
// SECURITY: the URL is a default hardcoded value or an envvar/setting set by an admin. It's safe to disable this check.
ignoreSsrfValidation: true,
});
const data = await response.json();
check(
data,
Match.ObjectIncluding({
versions: [
Match.ObjectIncluding({
version: String,
security: Match.Optional(Boolean),
infoUrl: String,
}),
],
alerts: Match.Optional([
Match.ObjectIncluding({
id: String,
title: String,
text: String,
textArguments: [Match.Any],
modifiers: [String] as [StringConstructor],
infoUrl: String,
}),
]),
}),
);
return data as {
versions: {
version: string;
security: boolean;
infoUrl: string;
}[];
alerts: {
id: string;
priority: number;
title: string;
text: string;
textArguments?: string[];
modifiers: string[];
infoUrl: string;
}[];
};
} catch (error) {
// There's no need to log this error
// as it's pointless and the user
// can't do anything about it anyways
return {
versions: [],
alerts: [],
};
}
};

View File

@@ -0,0 +1,38 @@
import { cronJobs } from '@rocket.chat/cron';
import { Meteor } from 'meteor/meteor';
import { checkVersionUpdate } from './functions/checkVersionUpdate';
import { settings } from '../../../settings';
const jobName = 'version_check';
if (await cronJobs.has(jobName)) {
await cronJobs.remove(jobName);
}
const addVersionCheckJob = async () => {
await cronJobs.add(jobName, '0 2 * * *', async () => checkVersionUpdate());
};
Meteor.startup(() => {
setImmediate(() => {
if (settings.get('Update_EnableChecker')) {
void checkVersionUpdate();
}
});
});
settings.watch('Update_EnableChecker', async () => {
const checkForUpdates = settings.get('Update_EnableChecker');
if (checkForUpdates && (await cronJobs.has(jobName))) {
return;
}
if (checkForUpdates) {
await addVersionCheckJob();
return;
}
await cronJobs.remove(jobName);
});

View File

@@ -0,0 +1,3 @@
import { Logger } from '@rocket.chat/logger';
export default new Logger('VersionCheck');