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,4 @@
import type { BehaviorWithContext, LicenseBehavior } from '@rocket.chat/core-typings';
export const filterBehaviorsResult = (result: BehaviorWithContext[], expectedBehaviors: LicenseBehavior[]) =>
result.filter(({ behavior }) => expectedBehaviors.includes(behavior));

View File

@@ -0,0 +1,37 @@
import type { LicenseLimitKind, LimitContext } from '@rocket.chat/core-typings';
import type { LicenseManager } from '../license';
import { logger } from '../logger';
import { applyPendingLicense, hasPendingLicense } from '../pendingLicense';
export function setLicenseLimitCounter<T extends LicenseLimitKind>(
this: LicenseManager,
limitKey: T,
fn: (context?: LimitContext<T>) => Promise<number> | number,
) {
this.dataCounters.set(limitKey, fn as (context?: LimitContext<LicenseLimitKind>) => Promise<number>);
if (hasPendingLicense.call(this) && hasAllDataCounters.call(this)) {
void applyPendingLicense.call(this);
}
}
export async function getCurrentValueForLicenseLimit<T extends LicenseLimitKind>(
this: LicenseManager,
limitKey: T,
context?: Partial<LimitContext<T>>,
): Promise<number> {
const counterFn = this.dataCounters.get(limitKey);
if (!counterFn) {
logger.error({ msg: 'Unable to validate license limit due to missing data counter.', limitKey });
throw new Error(`Unable to validate license limit due to missing ${limitKey} data counter`);
}
return counterFn(context as LimitContext<LicenseLimitKind> | undefined);
}
export function hasAllDataCounters(this: LicenseManager) {
return (
['activeUsers', 'guestUsers', 'roomsPerGuest', 'privateApps', 'marketplaceApps', 'monthlyActiveContacts'] as LicenseLimitKind[]
).every((limitKey) => this.dataCounters.has(limitKey));
}

View File

@@ -0,0 +1,14 @@
import type { BehaviorWithContext, LicenseBehavior, LicenseModule } from '@rocket.chat/core-typings';
const filterValidationResult = (result: BehaviorWithContext[], expectedBehavior: LicenseBehavior) =>
result.filter(({ behavior }) => behavior === expectedBehavior) as BehaviorWithContext[];
export const getModulesToDisable = (validationResult: BehaviorWithContext[]): LicenseModule[] => {
return [
...new Set([
...filterValidationResult(validationResult, 'disable_modules')
.map(({ modules }) => modules || [])
.flat(),
]),
];
};

View File

@@ -0,0 +1,25 @@
import type { LicenseLimitKind, BehaviorWithContext, LicenseLimit, LicensePeriod } from '@rocket.chat/core-typings';
export const getResultingBehavior = (
data: LicenseLimit | LicensePeriod | Partial<Omit<BehaviorWithContext, 'reason'>>,
{ reason, limit }: { reason: BehaviorWithContext['reason']; limit?: LicenseLimitKind },
): BehaviorWithContext => {
const behavior = 'invalidBehavior' in data ? data.invalidBehavior : data.behavior;
switch (behavior) {
case 'disable_modules':
return {
behavior,
modules: ('modules' in data && data.modules) || [],
reason,
limit,
};
default:
return {
behavior,
reason,
limit,
} as BehaviorWithContext;
}
};

View File

@@ -0,0 +1,4 @@
import type { BehaviorWithContext, LicenseBehavior } from '@rocket.chat/core-typings';
export const isBehaviorsInResult = (result: BehaviorWithContext[], expectedBehaviors: LicenseBehavior[]) =>
result.some(({ behavior }) => expectedBehaviors.includes(behavior));

View File

@@ -0,0 +1,7 @@
import type { LicenseManager } from '../license';
import { hasAllDataCounters } from './getCurrentValueForLicenseLimit';
// Can only validate licenses once the workspace URL and the data counter functions are set
export function isReadyForValidation(this: LicenseManager) {
return Boolean(this.getWorkspaceUrl() && hasAllDataCounters.call(this));
}

View File

@@ -0,0 +1,11 @@
import type { LicenseBehavior } from '@rocket.chat/core-typings';
export const logKind = (behavior: LicenseBehavior) => {
switch (behavior) {
case 'prevent_installation':
case 'invalidate_license':
return 'error';
default:
return 'info';
}
};

View File

@@ -0,0 +1,38 @@
/**
* @jest-environment node
*/
import { runValidation } from './runValidation';
import { MockedLicenseBuilder, getReadyLicenseManager } from '../../__tests__/MockedLicenseBuilder';
describe('Validation behaviors', () => {
it('should return a behavior if the license period is invalid', async () => {
const licenseManager = await getReadyLicenseManager();
// two days ago
const validFrom = new Date(new Date().setDate(new Date().getDate() - 2));
// one day ago
const validUntil = new Date(new Date().setDate(new Date().getDate() - 1));
const license = await new MockedLicenseBuilder().resetValidPeriods().withValidPeriod({
validFrom: validFrom.toISOString(),
validUntil: validUntil.toISOString(),
invalidBehavior: 'disable_modules',
modules: ['livechat-enterprise'],
});
await expect(
runValidation.call(licenseManager, await license.build(), {
behaviors: ['invalidate_license', 'prevent_installation', 'start_fair_policy', 'disable_modules'],
suppressLog: true,
}),
).resolves.toStrictEqual([
{
behavior: 'disable_modules',
limit: undefined,
modules: ['livechat-enterprise'],
reason: 'period',
},
]);
});
});

View File

@@ -0,0 +1,18 @@
import type { ILicenseV3, BehaviorWithContext, LicenseValidationOptions } from '@rocket.chat/core-typings';
import type { LicenseManager } from '../license';
import { validateLicenseLimits } from './validateLicenseLimits';
import { validateLicensePeriods } from './validateLicensePeriods';
import { validateLicenseUrl } from './validateLicenseUrl';
export async function runValidation(
this: LicenseManager,
license: ILicenseV3,
options: LicenseValidationOptions,
): Promise<BehaviorWithContext[]> {
return [
...validateLicenseUrl.call(this, license, options),
...validateLicensePeriods(license, options),
...(await validateLicenseLimits.call(this, license, options)),
];
}

View File

@@ -0,0 +1,27 @@
import type { BehaviorWithContext, LicenseLimit, LicenseValidationOptions } from '@rocket.chat/core-typings';
import type { LicenseManager } from '../license';
import { validateLimits } from './validateLimits';
export const defaultLimits: {
privateApps: LicenseLimit[];
marketplaceApps: LicenseLimit[];
// monthlyActiveContacts?: LicenseLimit[];
} = {
privateApps: [
{
behavior: 'prevent_action',
max: 0,
},
],
marketplaceApps: [
{
behavior: 'prevent_action',
max: 5,
},
],
};
export async function validateDefaultLimits(this: LicenseManager, options: LicenseValidationOptions): Promise<BehaviorWithContext[]> {
return validateLimits.call(this, defaultLimits, options);
}

View File

@@ -0,0 +1,16 @@
import { InvalidLicenseError } from '../errors/InvalidLicenseError';
import { decrypt } from '../token';
export const validateFormat = async (encryptedLicense: string): Promise<boolean> => {
if (!encryptedLicense || String(encryptedLicense).trim() === '') {
throw new InvalidLicenseError('Empty license');
}
try {
await decrypt(encryptedLicense);
} catch (e) {
throw new InvalidLicenseError();
}
return true;
};

View File

@@ -0,0 +1,38 @@
import { MockedLicenseBuilder, getReadyLicenseManager } from '../../__tests__/MockedLicenseBuilder';
describe('validateLicenseLimits', () => {
describe('limit max: -1', () => {
it('should return prevent_action when the limit is reached', async () => {
const licenseManager = await getReadyLicenseManager();
const license = await new MockedLicenseBuilder().withLimits('activeUsers', [
{
max: -1,
behavior: 'prevent_action',
},
]);
await expect(licenseManager.setLicense(await license.sign())).resolves.toBe(true);
licenseManager.setLicenseLimitCounter('activeUsers', () => 99999999);
await expect(licenseManager.shouldPreventAction('activeUsers')).resolves.toBe(false);
});
});
describe('limit max: 0', () => {
it('should return prevent_action when the limit is reached', async () => {
const licenseManager = await getReadyLicenseManager();
const license = await new MockedLicenseBuilder().withLimits('activeUsers', [
{
max: 0,
behavior: 'prevent_action',
},
]);
await expect(licenseManager.setLicense(await license.sign())).resolves.toBe(true);
licenseManager.setLicenseLimitCounter('activeUsers', () => 99999999);
await expect(licenseManager.shouldPreventAction('activeUsers')).resolves.toBe(true);
});
});
});

View File

@@ -0,0 +1,14 @@
import type { ILicenseV3, BehaviorWithContext, LicenseValidationOptions } from '@rocket.chat/core-typings';
import type { LicenseManager } from '../license';
import { validateLimits } from './validateLimits';
export async function validateLicenseLimits(
this: LicenseManager,
license: ILicenseV3,
options: LicenseValidationOptions,
): Promise<BehaviorWithContext[]> {
const { limits } = license;
return validateLimits.call(this, limits, options);
}

View File

@@ -0,0 +1,40 @@
import type { ILicenseV3, BehaviorWithContext, LicenseValidationOptions } from '@rocket.chat/core-typings';
import { isBehaviorAllowed } from '../isItemAllowed';
import { logger } from '../logger';
import { getResultingBehavior } from './getResultingBehavior';
export const isPeriodInvalid = (from: string | undefined, until: string | undefined) => {
const now = new Date();
if (from && now < new Date(from)) {
return true;
}
if (until && now > new Date(until)) {
return true;
}
return false;
};
export const validateLicensePeriods = (license: ILicenseV3, options: LicenseValidationOptions): BehaviorWithContext[] => {
const {
validation: { validPeriods },
} = license;
return validPeriods
.filter(
({ validFrom, validUntil, invalidBehavior }) => isBehaviorAllowed(invalidBehavior, options) && isPeriodInvalid(validFrom, validUntil),
)
.map((period) => {
if (!options.suppressLog) {
logger.error({
msg: 'Period validation failed',
period,
});
}
return getResultingBehavior(period, { reason: 'period' });
});
};

View File

@@ -0,0 +1,163 @@
/**
* @jest-environment node
*/
import crypto from 'node:crypto';
import { validateLicenseUrl } from './validateLicenseUrl';
import { MockedLicenseBuilder, getReadyLicenseManager } from '../../__tests__/MockedLicenseBuilder';
describe('Url Validation', () => {
describe('url method', () => {
it('should return a behavior if the license url is invalid', async () => {
const licenseManager = await getReadyLicenseManager();
const license = await new MockedLicenseBuilder().withServerUrls({
value: 'localhost:3001',
type: 'url',
});
await expect(
validateLicenseUrl.call(licenseManager, await license.build(), {
behaviors: ['invalidate_license', 'prevent_installation', 'start_fair_policy', 'disable_modules'],
suppressLog: true,
}),
).toStrictEqual([
{
behavior: 'invalidate_license',
limit: undefined,
reason: 'url',
},
]);
});
it('should return an empty array if the license url is valid', async () => {
const licenseManager = await getReadyLicenseManager();
const license = await new MockedLicenseBuilder().withServerUrls({
value: 'localhost:3000',
type: 'url',
});
await expect(
validateLicenseUrl.call(licenseManager, await license.build(), {
behaviors: ['invalidate_license', 'prevent_installation', 'start_fair_policy', 'disable_modules'],
suppressLog: true,
}),
).toStrictEqual([]);
});
});
describe('regex method', () => {
it('should return a behavior if the license does not match the regex', async () => {
const licenseManager = await getReadyLicenseManager();
const license = await new MockedLicenseBuilder().withServerUrls({
value: 'unstable.rocket.*',
type: 'regex',
});
await expect(
validateLicenseUrl.call(licenseManager, await license.build(), {
behaviors: ['invalidate_license', 'prevent_installation', 'start_fair_policy', 'disable_modules'],
suppressLog: true,
}),
).toStrictEqual([
{
behavior: 'invalidate_license',
limit: undefined,
reason: 'url',
},
]);
});
it('should return an empty array if the license matches the regex', async () => {
const licenseManager = await getReadyLicenseManager();
const license = await new MockedLicenseBuilder().withServerUrls({
value: 'localhost:300*',
type: 'regex',
});
await expect(
validateLicenseUrl.call(licenseManager, await license.build(), {
behaviors: ['invalidate_license', 'prevent_installation', 'start_fair_policy', 'disable_modules'],
suppressLog: true,
}),
).toStrictEqual([]);
});
});
describe('hash method', () => {
it('should return a behavior if the license does not match the hash', async () => {
const licenseManager = await getReadyLicenseManager();
const hash = crypto.createHash('sha256').update('localhost:3001').digest('hex');
const license = await new MockedLicenseBuilder().withServerUrls({
value: hash,
type: 'hash',
});
await expect(
validateLicenseUrl.call(licenseManager, await license.build(), {
behaviors: ['invalidate_license', 'prevent_installation', 'start_fair_policy', 'disable_modules'],
suppressLog: true,
}),
).toStrictEqual([
{
behavior: 'invalidate_license',
limit: undefined,
reason: 'url',
},
]);
});
it('should return an empty array if the license matches the hash', async () => {
const licenseManager = await getReadyLicenseManager();
const hash = crypto.createHash('sha256').update('localhost:3000').digest('hex');
const license = await new MockedLicenseBuilder().withServerUrls({
value: hash,
type: 'hash',
});
await expect(
validateLicenseUrl.call(licenseManager, await license.build(), {
behaviors: ['invalidate_license', 'prevent_installation', 'start_fair_policy', 'disable_modules'],
suppressLog: true,
}),
).toStrictEqual([]);
});
});
describe('type mismatch', () => {
it('should validate as hash if the type is url but the value looks like a hash', async () => {
const licenseManager = await getReadyLicenseManager();
const hash = crypto.createHash('sha256').update('localhost:3000').digest('hex');
const license = await new MockedLicenseBuilder().withServerUrls({
value: hash,
type: 'url',
});
await expect(
validateLicenseUrl.call(licenseManager, await license.build(), {
behaviors: ['invalidate_license', 'prevent_installation', 'start_fair_policy', 'disable_modules'],
suppressLog: false,
}),
).toStrictEqual([]);
});
it('should validate as url if the type is hash but the value looks like a url', async () => {
const licenseManager = await getReadyLicenseManager();
const license = await new MockedLicenseBuilder().withServerUrls({
value: 'localhost:3000',
type: 'hash',
});
await expect(
validateLicenseUrl.call(licenseManager, await license.build(), {
behaviors: ['invalidate_license', 'prevent_installation', 'start_fair_policy', 'disable_modules'],
suppressLog: false,
}),
).toStrictEqual([]);
});
});
});

View File

@@ -0,0 +1,88 @@
import type { ILicenseV3, BehaviorWithContext, LicenseValidationOptions } from '@rocket.chat/core-typings';
import { isBehaviorAllowed } from '../isItemAllowed';
import type { LicenseManager } from '../license';
import { logger } from '../logger';
import { getResultingBehavior } from './getResultingBehavior';
const validateRegex = (licenseURL: string, url: string) => {
licenseURL = licenseURL
.replace(/\./g, '\\.') // convert dots to literal
.replace(/\*/g, '.*'); // convert * to .*
const regex = new RegExp(`^${licenseURL}$`, 'i');
return !!regex.exec(url);
};
const validateUrl = (licenseURL: string, url: string) => {
return licenseURL.toLowerCase() === url.toLowerCase();
};
const validateHash = (licenseURL: string, hashedUrl: string) => {
return licenseURL === hashedUrl;
};
export function validateLicenseUrl(this: LicenseManager, license: ILicenseV3, options: LicenseValidationOptions): BehaviorWithContext[] {
if (!isBehaviorAllowed('invalidate_license', options)) {
return [];
}
const {
validation: { serverUrls },
} = license;
const workspaceUrl = this.getWorkspaceUrl();
if (!workspaceUrl) {
logger.error('Unable to validate license URL without knowing the workspace URL.');
return [getResultingBehavior({ behavior: 'invalidate_license' }, { reason: 'url' })];
}
const hashedWorkspaceUrl = this.hashWorkspaceUrl(workspaceUrl);
return serverUrls
.filter((url) => {
if (
url.type === 'url' &&
url.value.length === 64 &&
/^[a-f0-9]{64}$/i.test(url.value) &&
validateHash(url.value, hashedWorkspaceUrl)
) {
// If the url type is 'url' but the value looks like a hash, validate it as a hash to avoid invalidating licenses unnecessarily.
logger.warn(
`License URL with type 'url' is actually a hash. Validating as hash to avoid invalidating license unnecessarily. url: ${url.value}`,
);
return false;
}
if (url.type === 'hash' && !/^[a-f0-9]{64}$/i.test(url.value) && validateUrl(url.value, workspaceUrl)) {
// If the url type is 'hash' but the value looks like a url, validate it as a url to avoid invalidating licenses unnecessarily.
logger.warn(
`License URL with type 'hash' does not look like a hash. Validating as url to avoid invalidating license unnecessarily. url: ${url.value}`,
);
return false;
}
switch (url.type) {
case 'regex':
return !validateRegex(url.value, workspaceUrl);
case 'hash':
return !validateHash(url.value, hashedWorkspaceUrl);
case 'url':
return !validateUrl(url.value, workspaceUrl);
default:
return true; // If the type is unknown, consider it invalid to be safe.
}
})
.map((url) => {
if (!options.suppressLog) {
logger.error({
msg: 'Url validation failed',
licenseUrl: url,
workspaceUrl,
hashedWorkspaceUrl,
});
}
return getResultingBehavior({ behavior: 'invalidate_license' }, { reason: 'url' });
});
}

View File

@@ -0,0 +1,62 @@
import type { LicenseBehavior } from '@rocket.chat/core-typings';
/**
* The difference between validateLimit and validateWarnLimit is that the first one
* is used to trigger the client so for start_fair_policy we trigger as soon the limit is reached
* for the visual warning we trigger when the limit is reached + 1
/**
* Validates if the current value is over the limit
* @param max The maximum value allowed
* @param currentValue The current value
* @param behavior The behavior to be applied if the limit is reached
* @param extraCount The extra count to be added to the current value
* @returns
* - true if the limit is reached
* - false if the limit is not reached
*/
export function validateLimit(max: number, currentValue: number, behavior: LicenseBehavior, extraCount = 0) {
switch (behavior) {
case 'invalidate_license':
case 'prevent_installation':
case 'disable_modules':
default:
return currentValue > max;
case 'start_fair_policy':
return currentValue >= max;
case 'prevent_action':
/**
* if we are validating the current count the limit should be equal or over the max, if we are validating the future count the limit should be over the max
*/
return extraCount ? currentValue > max : currentValue >= max;
}
}
/**
* Validates if the current value is over the limit
* @param max The maximum value allowed
* @param currentValue The current value
* @param behavior The behavior to be applied if the limit is reached
* @param extraCount The extra count to be added to the current value
* @returns
* - true if the limit is reached
* - false if the limit is not reached
*/
export function validateWarnLimit(max: number, currentValue: number, behavior: LicenseBehavior, extraCount = 0) {
switch (behavior) {
case 'invalidate_license':
case 'prevent_installation':
case 'disable_modules':
case 'start_fair_policy':
default:
return currentValue > max;
case 'prevent_action':
/**
* if we are validating the current count the limit should be equal or over the max, if we are validating the future count the limit should be over the max
*/
return extraCount ? currentValue > max : currentValue >= max;
}
}

View File

@@ -0,0 +1,55 @@
import type { ILicenseV3, LicenseLimitKind, BehaviorWithContext, LicenseValidationOptions } from '@rocket.chat/core-typings';
import { isLimitAllowed, isBehaviorAllowed } from '../isItemAllowed';
import type { LicenseManager } from '../license';
import { logger } from '../logger';
import { getCurrentValueForLicenseLimit } from './getCurrentValueForLicenseLimit';
import { getResultingBehavior } from './getResultingBehavior';
import { logKind } from './logKind';
import { validateLimit } from './validateLimit';
export async function validateLimits(
this: LicenseManager,
limits: ILicenseV3['limits'],
options: LicenseValidationOptions,
): Promise<BehaviorWithContext[]> {
const limitKeys = (Object.keys(limits) as LicenseLimitKind[]).filter((limit) => isLimitAllowed(limit, options));
return (
await Promise.all(
limitKeys.map(async (limitKey) => {
// Filter the limit list before running any query in the database so we don't end up loading some value we won't use.
const limitList = limits[limitKey]?.filter(({ behavior, max }) => max >= 0 && isBehaviorAllowed(behavior, options));
if (!limitList?.length) {
return [];
}
const extraCount = options.context?.[limitKey]?.extraCount ?? 0;
const currentValue = (await getCurrentValueForLicenseLimit.call(this, limitKey, options.context?.[limitKey])) + extraCount;
return limitList
.filter(({ max, behavior }) => validateLimit(max, currentValue, behavior, extraCount))
.map((limit) => {
if (!options.suppressLog) {
switch (logKind(limit.behavior)) {
case 'error':
logger.error({
msg: 'Limit validation failed',
kind: limitKey,
limit,
});
break;
case 'info':
logger.info({
msg: 'Limit validation failed',
kind: limitKey,
limit,
});
break;
}
}
return getResultingBehavior(limit, { reason: 'limit', limit: limitKey });
});
}),
)
).flat();
}