Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: implement middleware for handling EE endpoints #35625

Merged
merged 8 commits into from
Mar 26, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion apps/meteor/app/api/server/api.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { IMethodConnection, IUser, IRoom } from '@rocket.chat/core-typings';
import { License } from '@rocket.chat/license';
import { Logger } from '@rocket.chat/logger';
import { Users } from '@rocket.chat/models';
import { Random } from '@rocket.chat/random';
Expand Down Expand Up @@ -42,6 +43,7 @@ import { metricsMiddleware } from './middlewares/metrics';
import { tracerSpanMiddleware } from './middlewares/tracer';
import type { Route } from './router';
import { Router } from './router';
import { license } from '../../../ee/app/api-enterprise/server/middlewares/license';
import { isObject } from '../../../lib/utils/isObject';
import { getNestedProp } from '../../../server/lib/getNestedProp';
import { shouldBreakInVersion } from '../../../server/lib/shouldBreakInVersion';
Expand Down Expand Up @@ -897,12 +899,12 @@ export class APIClass<

return result;
} as InnerAction<any, any, any>;

// Allow the endpoints to make usage of the logger which respects the user's settings
(operations[method as keyof Operations<TPathPattern, TOptions>] as Record<string, any>).logger = logger;
this.router[method.toLowerCase() as 'get' | 'post' | 'put' | 'delete'](
`/${route}`.replaceAll('//', '/'),
_options as TypedOptions,
license(_options as TypedOptions, License),
(operations[method as keyof Operations<TPathPattern, TOptions>] as Record<string, any>).action as any,
);
this._routes.push({
Expand Down
3 changes: 2 additions & 1 deletion apps/meteor/app/api/server/definition.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { IUser } from '@rocket.chat/core-typings';
import type { IUser, LicenseModule } from '@rocket.chat/core-typings';
import type { Logger } from '@rocket.chat/logger';
import type { Method, MethodOf, OperationParams, OperationResult, PathPattern, UrlParams } from '@rocket.chat/rest-typings';
import type { ValidateFunction } from 'ajv';
Expand Down Expand Up @@ -250,6 +250,7 @@ export type TypedOptions = {
body?: ValidateFunction;
tags?: string[];
typed?: boolean;
license?: LicenseModule[];
} & Options;

export type TypedThis<TOptions extends TypedOptions, TPath extends string = ''> = {
Expand Down
35 changes: 25 additions & 10 deletions apps/meteor/app/api/server/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,19 @@ import express from 'express';

import type { TypedAction, TypedOptions } from './definition';

type MiddlewareHandler = (req: express.Request, res: express.Response, next: express.NextFunction) => void;

type MiddlewareHandlerListAndActionHandler<TOptions extends TypedOptions, TSubPathPattern extends string> = [
...MiddlewareHandler[],
TypedAction<TOptions, TSubPathPattern>,
];

function splitArray<T, U>(arr: [...T[], U]): [T[], U] {
const last = arr[arr.length - 1];
const rest = arr.slice(0, -1) as T[];
return [rest, last as U];
}

export type Route = {
responses: Record<
number,
Expand Down Expand Up @@ -107,7 +120,7 @@ export class Router<
method: Method,
subpath: TSubPathPattern,
options: TOptions,
action: TypedAction<TOptions, TSubPathPattern>,
...actions: MiddlewareHandlerListAndActionHandler<TOptions, TSubPathPattern>
): Router<
TBasePath,
| TOperations
Expand All @@ -116,10 +129,12 @@ export class Router<
path: TPathPattern;
} & Omit<TOptions, 'response'>)
> {
const [middlewares, action] = splitArray(actions);

const prev = this.middleware;
this.middleware = (router: express.Router) => {
prev(router);
router[method.toLowerCase() as Lowercase<Method>](`/${subpath}`.replace('//', '/'), async (req, res) => {
router[method.toLowerCase() as Lowercase<Method>](`/${subpath}`.replace('//', '/'), ...middlewares, async (req, res) => {
if (options.query) {
const validatorFn = options.query;
if (typeof options.query === 'function' && !validatorFn(req.query)) {
Expand Down Expand Up @@ -196,7 +211,7 @@ export class Router<
get<TSubPathPattern extends string, TOptions extends TypedOptions, TPathPattern extends `${TBasePath}/${TSubPathPattern}`>(
subpath: TSubPathPattern,
options: TOptions,
action: TypedAction<TOptions, TSubPathPattern>,
...action: MiddlewareHandlerListAndActionHandler<TOptions, TSubPathPattern>
): Router<
TBasePath,
| TOperations
Expand All @@ -205,13 +220,13 @@ export class Router<
path: TPathPattern;
} & Omit<TOptions, 'response'>)
> {
return this.method('GET', subpath, options, action);
return this.method('GET', subpath, options, ...action);
}

post<TSubPathPattern extends string, TOptions extends TypedOptions, TPathPattern extends `${TBasePath}/${TSubPathPattern}`>(
subpath: TSubPathPattern,
options: TOptions,
action: TypedAction<TOptions, TSubPathPattern>,
...action: MiddlewareHandlerListAndActionHandler<TOptions, TSubPathPattern>
): Router<
TBasePath,
| TOperations
Expand All @@ -220,13 +235,13 @@ export class Router<
path: TPathPattern;
} & Omit<TOptions, 'response'>)
> {
return this.method('POST', subpath, options, action);
return this.method('POST', subpath, options, ...action);
}

put<TSubPathPattern extends string, TOptions extends TypedOptions, TPathPattern extends `${TBasePath}/${TSubPathPattern}`>(
subpath: TSubPathPattern,
options: TOptions,
action: TypedAction<TOptions, TSubPathPattern>,
...action: MiddlewareHandlerListAndActionHandler<TOptions, TSubPathPattern>
): Router<
TBasePath,
| TOperations
Expand All @@ -235,13 +250,13 @@ export class Router<
path: TPathPattern;
} & Omit<TOptions, 'response'>)
> {
return this.method('PUT', subpath, options, action);
return this.method('PUT', subpath, options, ...action);
}

delete<TSubPathPattern extends string, TOptions extends TypedOptions, TPathPattern extends `${TBasePath}/${TSubPathPattern}`>(
subpath: TSubPathPattern,
options: TOptions,
action: TypedAction<TOptions, TSubPathPattern>,
...action: MiddlewareHandlerListAndActionHandler<TOptions, TSubPathPattern>
): Router<
TBasePath,
| TOperations
Expand All @@ -250,7 +265,7 @@ export class Router<
path: TPathPattern;
} & Omit<TOptions, 'response'>)
> {
return this.method('DELETE', subpath, options, action);
return this.method('DELETE', subpath, options, ...action);
}

use<FN extends (req: express.Request, res: express.Response, next: express.NextFunction) => void>(fn: FN): Router<TBasePath, TOperations>;
Expand Down
5 changes: 3 additions & 2 deletions apps/meteor/ee/app/api-enterprise/server/canned-responses.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ declare module '@rocket.chat/rest-typings' {

API.v1.addRoute(
'canned-responses.get',
{ authRequired: true, permissionsRequired: ['view-canned-responses'] },
{ authRequired: true, permissionsRequired: ['view-canned-responses'], license: ['canned-responses'] },
{
async get() {
return API.v1.success({
Expand All @@ -60,6 +60,7 @@ API.v1.addRoute(
authRequired: true,
permissionsRequired: { GET: ['view-canned-responses'], POST: ['save-canned-responses'], DELETE: ['remove-canned-responses'] },
validateParams: { POST: isPOSTCannedResponsesProps, DELETE: isDELETECannedResponsesProps, GET: isCannedResponsesProps },
license: ['canned-responses'],
},
{
async get() {
Expand Down Expand Up @@ -113,7 +114,7 @@ API.v1.addRoute(

API.v1.addRoute(
'canned-responses/:_id',
{ authRequired: true, permissionsRequired: ['view-canned-responses'] },
{ authRequired: true, permissionsRequired: ['view-canned-responses'], license: ['canned-responses'] },
{
async get() {
const { _id } = this.urlParams;
Expand Down
11 changes: 2 additions & 9 deletions apps/meteor/ee/app/api-enterprise/server/index.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,2 @@
import { License } from '@rocket.chat/license';

await License.onLicense('canned-responses', async () => {
await import('./canned-responses');
});

License.onValidateLicense(async () => {
await import('./voip-freeswitch');
});
import './canned-responses';
import './voip-freeswitch';
38 changes: 38 additions & 0 deletions apps/meteor/ee/app/api-enterprise/server/middlewares/license.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import type { LicenseManager } from '@rocket.chat/license';
import type { Request, Response, NextFunction } from 'express';

import type { FailureResult, TypedOptions } from '../../../../../app/api/server/definition';

type ExpressMiddleware = (req: Request, res: Response, next: NextFunction) => void;

export const license =
(options: TypedOptions, licenseManager: LicenseManager): ExpressMiddleware =>
async (_req, res, next) => {
if (!options.license) {
return next();
}

const license = options.license.every((license) => licenseManager.hasModule(license));

const failure: FailureResult<{
error: string;
errorType: string;
}> = {
statusCode: 400,
body: {
success: false,
error: 'This is an enterprise feature [error-action-not-allowed]',
errorType: 'error-action-not-allowed',
},
};

if (!license) {
// Explicitly set the content type to application/json to avoid the following issue:
// https://github.com/expressjs/express/issues/2238
res.writeHead(failure.statusCode, { 'Content-Type': 'application/json' });
res.write(JSON.stringify(failure.body));
return res.end();
}

return next();
};
28 changes: 24 additions & 4 deletions apps/meteor/ee/app/api-enterprise/server/voip-freeswitch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,12 @@ import { settings } from '../../../../app/settings/server/cached';

API.v1.addRoute(
'voip-freeswitch.extension.list',
{ authRequired: true, permissionsRequired: ['manage-voip-extensions'], validateParams: isVoipFreeSwitchExtensionListProps },
{
authRequired: true,
permissionsRequired: ['manage-voip-extensions'],
validateParams: isVoipFreeSwitchExtensionListProps,
license: ['voip-enterprise'],
},
{
async get() {
if (!settings.get('VoIP_TeamCollab_Enabled')) {
Expand Down Expand Up @@ -59,7 +64,12 @@ API.v1.addRoute(

API.v1.addRoute(
'voip-freeswitch.extension.assign',
{ authRequired: true, permissionsRequired: ['manage-voip-extensions'], validateParams: isVoipFreeSwitchExtensionAssignProps },
{
authRequired: true,
permissionsRequired: ['manage-voip-extensions'],
validateParams: isVoipFreeSwitchExtensionAssignProps,
license: ['voip-enterprise'],
},
{
async post() {
if (!settings.get('VoIP_TeamCollab_Enabled')) {
Expand Down Expand Up @@ -94,7 +104,12 @@ API.v1.addRoute(

API.v1.addRoute(
'voip-freeswitch.extension.getDetails',
{ authRequired: true, permissionsRequired: ['view-voip-extension-details'], validateParams: isVoipFreeSwitchExtensionGetDetailsProps },
{
authRequired: true,
permissionsRequired: ['view-voip-extension-details'],
validateParams: isVoipFreeSwitchExtensionGetDetailsProps,
license: ['voip-enterprise'],
},
{
async get() {
if (!settings.get('VoIP_TeamCollab_Enabled')) {
Expand Down Expand Up @@ -124,7 +139,12 @@ API.v1.addRoute(

API.v1.addRoute(
'voip-freeswitch.extension.getRegistrationInfoByUserId',
{ authRequired: true, permissionsRequired: ['view-user-voip-extension'], validateParams: isVoipFreeSwitchExtensionGetInfoProps },
{
authRequired: true,
permissionsRequired: ['view-user-voip-extension'],
validateParams: isVoipFreeSwitchExtensionGetInfoProps,
license: ['voip-enterprise'],
},
{
async get() {
if (!settings.get('VoIP_TeamCollab_Enabled')) {
Expand Down
15 changes: 13 additions & 2 deletions apps/meteor/ee/app/livechat-enterprise/server/api/agents.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,12 @@ import {

API.v1.addRoute(
'livechat/analytics/agents/average-service-time',
{ authRequired: true, permissionsRequired: ['view-livechat-manager'], validateParams: isLivechatAnalyticsAgentsAverageServiceTimeProps },
{
authRequired: true,
permissionsRequired: ['view-livechat-manager'],
validateParams: isLivechatAnalyticsAgentsAverageServiceTimeProps,
license: ['livechat-enterprise'],
},
{
async get() {
const { offset, count } = await getPaginationItems(this.queryParams);
Expand Down Expand Up @@ -47,7 +52,12 @@ API.v1.addRoute(

API.v1.addRoute(
'livechat/analytics/agents/total-service-time',
{ authRequired: true, permissionsRequired: ['view-livechat-manager'], validateParams: isLivechatAnalyticsAgentsTotalServiceTimeProps },
{
authRequired: true,
permissionsRequired: ['view-livechat-manager'],
validateParams: isLivechatAnalyticsAgentsTotalServiceTimeProps,
license: ['livechat-enterprise'],
},
{
async get() {
const { offset, count } = await getPaginationItems(this.queryParams);
Expand Down Expand Up @@ -84,6 +94,7 @@ API.v1.addRoute(
authRequired: true,
permissionsRequired: ['view-livechat-manager'],
validateParams: isLivechatAnalyticsAgentsAvailableForServiceHistoryProps,
license: ['livechat-enterprise'],
},
{
async get() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ declare module '@rocket.chat/rest-typings' {

API.v1.addRoute(
'livechat/business-hours',
{ authRequired: true, permissionsRequired: ['view-livechat-business-hours'] },
{ authRequired: true, permissionsRequired: ['view-livechat-business-hours'], license: ['livechat-enterprise'] },
{
async get() {
const { offset, count } = await getPaginationItems(this.queryParams);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ API.v1.addRoute(
authRequired: true,
permissionsRequired: ['block-livechat-contact'],
validateParams: isBlockContactProps,
license: ['livechat-enterprise'],
},
{
async post() {
Expand All @@ -69,6 +70,7 @@ API.v1.addRoute(
authRequired: true,
permissionsRequired: ['unblock-livechat-contact'],
validateParams: isBlockContactProps,
license: ['livechat-enterprise'],
},
{
async post() {
Expand Down
Loading
Loading