Skip to content
Draft
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
6 changes: 6 additions & 0 deletions .changeset/flat-stingrays-complain.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@rocket.chat/rest-typings': minor
'@rocket.chat/meteor': minor
---

Migration of groups.memebers added ajv validation for request and response, schema changes for request.
167 changes: 118 additions & 49 deletions apps/meteor/app/api/server/v1/groups.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,17 @@
import { Team, isMeteorError } from '@rocket.chat/core-services';
import type { IIntegration, IUser, IRoom, RoomType, UserStatus } from '@rocket.chat/core-typings';
import { Integrations, Messages, Rooms, Subscriptions, Uploads, Users } from '@rocket.chat/models';
import { isGroupsOnlineProps, isGroupsMessagesProps, isGroupsFilesProps } from '@rocket.chat/rest-typings';
import {
isGroupsOnlineProps,
isGroupsMessagesProps,
isGroupsFilesProps,
ajv,
validateBadRequestErrorResponse,
validateUnauthorizedErrorResponse,
validateForbiddenErrorResponse,
withGroupBaseProperties,
} from '@rocket.chat/rest-typings';
import type { PaginatedRequest, GroupsBaseProps } from '@rocket.chat/rest-typings';
import { isTruthy } from '@rocket.chat/tools';
import { check, Match } from 'meteor/check';
import { Meteor } from 'meteor/meteor';
Expand Down Expand Up @@ -31,12 +41,112 @@ import { executeGetRoomRoles } from '../../../lib/server/methods/getRoomRoles';
import { leaveRoomMethod } from '../../../lib/server/methods/leaveRoom';
import { executeUnarchiveRoom } from '../../../lib/server/methods/unarchiveRoom';
import { normalizeMessagesForUser } from '../../../utils/server/lib/normalizeMessagesForUser';
import type { ExtractRoutesFromAPI } from '../ApiClass';
import { API } from '../api';
import { addUserToFileObj } from '../helpers/addUserToFileObj';
import { composeRoomWithLastMessage } from '../helpers/composeRoomWithLastMessage';
import { getPaginationItems } from '../helpers/getPaginationItems';
import { getUserFromParams, getUserListFromParams } from '../helpers/getUserFromParams';

type GroupsMembersProps = PaginatedRequest<GroupsBaseProps & { filter?: string; status?: string[] }>;

const GroupsMembersPropsSchema = withGroupBaseProperties({
offset: {
type: 'string',
},
count: {
type: 'string',
},
filter: {
type: 'string',
},
query: {
type: 'string',
nullable: true,
},
sort: {
type: 'string',
nullable: true,
},
status: {
type: 'array',
items: { type: 'string' },
},
});

const isGroupsMembersProps = ajv.compile<GroupsMembersProps>(GroupsMembersPropsSchema);

const isGroupsMembersResponse = ajv.compile({
type: 'object',
properties: {
members: {
type: 'array',
items: { $ref: '#/components/schemas/IUser' },
},
count: { type: 'integer' },
offset: { type: 'integer' },
total: { type: 'integer' },
success: { type: 'boolean', enum: [true] },
},
required: ['members', 'success','count','offset','total'],
additionalProperties: false,
});
Comment on lines +79 to +93
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

# Examine the groups.ts file to see the current state and patterns
cat -n apps/meteor/app/api/server/v1/groups.ts | head -150

Repository: RocketChat/Rocket.Chat

Length of output: 6668


🏁 Script executed:

# Look for similar response schema patterns in rooms.ts to confirm the convention
rg "ajv\.compile" apps/meteor/app/api/server/v1/rooms.ts -A 10 | head -100

Repository: RocketChat/Rocket.Chat

Length of output: 2266


🏁 Script executed:

# Check if there's a changeset describing this as an OpenAPI migration
fd -e md apps/meteor/app/api/server/v1/ | head -20

Repository: RocketChat/Rocket.Chat

Length of output: 491


🏁 Script executed:

# Search for pagination-field patterns in other migrated endpoints
rg "count.*offset.*total" apps/meteor/app/api/server/v1/ --type ts -B 2 | head -80

Repository: RocketChat/Rocket.Chat

Length of output: 3920


🏁 Script executed:

# Check if there's a changeset or PR context for this groups.ts file
find apps/meteor/app/api/server/v1 -name "*.md" -o -name "changeset*" | head -10

Repository: RocketChat/Rocket.Chat

Length of output: 48


🏁 Script executed:

# Verify by examining rooms.ts more closely to see the pattern distinction
rg "rooms\.delete|rooms\.leave|rooms\.favorite" apps/meteor/app/api/server/v1/rooms.ts -B 5 -A 15 | head -80

Repository: RocketChat/Rocket.Chat

Length of output: 1381


🏁 Script executed:

# Check the context around groups.ts to verify it's an OpenAPI migration
rg "GroupsHistoryEndpoints|GroupsMembersEndpoints" apps/meteor/app/api/server/v1/groups.ts -A 3 -B 3

Repository: RocketChat/Rocket.Chat

Length of output: 364


🏁 Script executed:

# Confirm the pattern: compare groups.members (paginated) vs a simple groups endpoint
rg "groups\.(delete|leave|archive)" apps/meteor/app/api/server/v1/groups.ts -B 5 -A 15 | head -100

Repository: RocketChat/Rocket.Chat

Length of output: 1159


Explicitly type the 200 response schema and require all pagination fields.

The groups.members endpoint is paginated; the handler always returns members, count, offset, total, and success (lines 141–146). The response schema must reflect this contract. Leaving the generic type unspecified and omitting pagination fields from required weakens both the exported endpoint type and runtime validation. All similar paginated endpoints across the codebase (settings, videoConference, moderation, etc.) explicitly include these fields in their required array.

Suggested fix
+type GroupsMembersResponse = {
+	members: IUser[];
+	count: number;
+	offset: number;
+	total: number;
+	success: true;
+};
+
-const isGroupsMembersResponse = ajv.compile({
+const isGroupsMembersResponse = ajv.compile<GroupsMembersResponse>({
 	type: 'object',
 	properties: {
 		members: {
 			type: 'array',
 			items: { $ref: '#/components/schemas/IUser' },
 		},
 		count: { type: 'integer' },
 		offset: { type: 'integer' },
 		total: { type: 'integer' },
 		success: { type: 'boolean', enum: [true] },
 	},
-	required: ['members', 'success'],
+	required: ['members', 'count', 'offset', 'total', 'success'],
 	additionalProperties: false,
 });
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/meteor/app/api/server/v1/groups.ts` around lines 80 - 94, Update the
isGroupsMembersResponse AJV schema so the 200 response is fully typed and
enforces all pagination fields: ensure the schema for members remains an array
of items with $ref '#/components/schemas/IUser', keep success as boolean enum
[true], and add "count", "offset", and "total" to the schema's required array
(i.e., required: ['members','count','offset','total','success']) so runtime
validation and the exported endpoint types reflect the actual handler contract;
make no other structural changes to the object shape or additionalProperties
setting.


const groupsEndPoints = API.v1.get(
'groups.members',
{
authRequired: true,
query: isGroupsMembersProps,
response: {
200: isGroupsMembersResponse,
400: validateBadRequestErrorResponse,
401: validateUnauthorizedErrorResponse,
403: validateForbiddenErrorResponse,
},
},
async function action() {
const findResult = await findPrivateGroupByIdOrName({
params: this.queryParams,
userId: this.userId,
});

if (findResult.broadcast && !(await hasPermissionAsync(this.userId, 'view-broadcast-member-list', findResult.rid))) {
return API.v1.forbidden('User does not have the permissions required for this action');
}

const { offset: skip, count: limit } = await getPaginationItems(this.queryParams);
const { sort = {} } = await this.parseJsonQuery();

check(
this.queryParams,
Match.ObjectIncluding({
status: Match.Maybe([String]),
filter: Match.Maybe(String),
}),
);

const { status, filter } = this.queryParams;

const { cursor, totalCount } = await findUsersOfRoom({
rid: findResult.rid,
...(status && { status: { $in: status as UserStatus[] } }),
skip,
limit,
filter,
...(sort?.username && { sort: { username: sort.username } }),
});

const [members, total] = await Promise.all([cursor.toArray(), totalCount]);

return API.v1.success({
members,
count: members.length,
offset: skip,
total,
});
},
);

async function getRoomFromParams(params: { roomId?: string } | { roomName?: string }): Promise<IRoom> {
if (
(!('roomId' in params) && !('roomName' in params)) ||
Expand Down Expand Up @@ -718,54 +828,6 @@ API.v1.addRoute(
},
);

API.v1.addRoute(
'groups.members',
{ authRequired: true },
{
async get() {
const findResult = await findPrivateGroupByIdOrName({
params: this.queryParams,
userId: this.userId,
});

if (findResult.broadcast && !(await hasPermissionAsync(this.userId, 'view-broadcast-member-list', findResult.rid))) {
return API.v1.forbidden();
}

const { offset: skip, count: limit } = await getPaginationItems(this.queryParams);
const { sort = {} } = await this.parseJsonQuery();

check(
this.queryParams,
Match.ObjectIncluding({
status: Match.Maybe([String]),
filter: Match.Maybe(String),
}),
);

const { status, filter } = this.queryParams;

const { cursor, totalCount } = await findUsersOfRoom({
rid: findResult.rid,
...(status && { status: { $in: status as UserStatus[] } }),
skip,
limit,
filter,
...(sort?.username && { sort: { username: sort.username } }),
});

const [members, total] = await Promise.all([cursor.toArray(), totalCount]);

return API.v1.success({
members,
count: members.length,
offset: skip,
total,
});
},
},
);

API.v1.addRoute(
'groups.messages',
{ authRequired: true, validateParams: isGroupsMessagesProps },
Expand Down Expand Up @@ -1300,3 +1362,10 @@ API.v1.addRoute(
},
},
);

export type GroupsHistoryEndpoints = ExtractRoutesFromAPI<typeof groupsEndPoints>;

declare module '@rocket.chat/rest-typings' {
// eslint-disable-next-line @typescript-eslint/naming-convention, @typescript-eslint/no-empty-interface
interface Endpoints extends GroupsHistoryEndpoints {}
}
28 changes: 0 additions & 28 deletions packages/rest-typings/src/v1/groups/GroupsMembersProps.ts

This file was deleted.

9 changes: 0 additions & 9 deletions packages/rest-typings/src/v1/groups/groups.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ import type { GroupsInviteProps } from './GroupsInviteProps';
import type { GroupsKickProps } from './GroupsKickProps';
import type { GroupsLeaveProps } from './GroupsLeaveProps';
import type { GroupsListProps } from './GroupsListProps';
import type { GroupsMembersProps } from './GroupsMembersProps';
import type { GroupsMessagesProps } from './GroupsMessagesProps';
import type { GroupsModeratorsProps } from './GroupsModeratorsProps';
import type { GroupsOnlineProps } from './GroupsOnlineProps';
Expand Down Expand Up @@ -46,14 +45,6 @@ export type GroupsEndpoints = {
files: IUploadWithUser[];
}>;
};
'/v1/groups.members': {
GET: (params: GroupsMembersProps) => {
count: number;
offset: number;
members: IUser[];
total: number;
};
};
'/v1/groups.history': {
GET: (params: GroupsHistoryProps) => PaginatedResult<{
messages: IMessage[];
Expand Down
2 changes: 1 addition & 1 deletion packages/rest-typings/src/v1/groups/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
export type * from './groups';

export * from './BaseProps';
export * from './GroupsArchiveProps';
export * from './GroupsCloseProps';
export * from './GroupsConvertToTeamProps';
Expand All @@ -9,7 +10,6 @@ export * from './GroupsDeleteProps';
export * from './GroupsFilesProps';
export * from './GroupsKickProps';
export * from './GroupsLeaveProps';
export * from './GroupsMembersProps';
export * from './GroupsMessagesProps';
export * from './GroupsRolesProps';
export * from './GroupsUnarchiveProps';
Expand Down