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,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: [],
};
}
};