RocketChat/Rocket.Chat · error · Meteor.Error

error-invalid-sort

error-invalid-sort

Error message

Invalid sort parameter provided: "${params.sort}"

What it means

parseJsonQuery (apps/meteor/server/api/lib/parseJsonQuery.ts) runs on every list-style REST v1 endpoint and parses the sort query param with JSON.parse. Every value must be exactly the number 1 or -1; anything else throws an inner error-invalid-sort-parameter which is caught, logged as a warning, and rethrown as Meteor error-invalid-sort with the raw param in the message. Note this check is not gated by ALLOW_UNSAFE_QUERY_AND_FIELDS_API_PARAMS — the sort param is always parsed when supplied.

Source

Thrown at apps/meteor/server/api/lib/parseJsonQuery.ts:52

	let sort;
	if (typeof params?.sort === 'string') {
		try {
			sort = JSON.parse(params.sort);
			Object.entries(sort).forEach(([key, value]) => {
				if (value !== 1 && value !== -1) {
					throw new Meteor.Error('error-invalid-sort-parameter', `Invalid sort parameter: ${key}`, {
						helperMethod: 'parseJsonQuery',
					});
				}
			});
		} catch (e) {
			logger.warn({
				msg: 'Invalid sort parameter provided',
				sort: params.sort,
				err: e,
			});
			throw new Meteor.Error('error-invalid-sort', `Invalid sort parameter provided: \"${params.sort}\"`, {
				helperMethod: 'parseJsonQuery',
			});
		}
	}

	const isUnsafeQueryParamsAllowed = process.env.ALLOW_UNSAFE_QUERY_AND_FIELDS_API_PARAMS?.toUpperCase() === 'TRUE';
	const messageGenerator = ({ endpoint, version, parameter }: { endpoint: string; version: string; parameter: string }): string =>
		`The usage of the "${parameter}" parameter in endpoint "${endpoint}" breaks the security of the API and can lead to data exposure. It has been deprecated and will be removed in the version ${version}.`;

	let fields: Record<string, 0 | 1> | undefined;
	if (typeof params?.fields === 'string' && isUnsafeQueryParamsAllowed) {
		try {
			apiDeprecationLogger.parameter(route, 'fields', '9.0.0', response, messageGenerator);
			fields = JSON.parse(params.fields) as Record<string, 0 | 1>;
			Object.entries(fields).forEach(([key, value]) => {
				if (value !== 1 && value !== 0) {
					throw new Meteor.Error('error-invalid-sort-parameter', `Invalid fields parameter: ${key}`, {
						helperMethod: 'parseJsonQuery',

View on GitHub (pinned to b2c16d5842)

Solutions

  1. Send strict JSON with numeric values: sort={"ts":-1} (and URL-encode it: sort=%7B%22ts%22%3A-1%7D)
  2. Build the param programmatically: JSON.stringify({ ts: -1 })
  3. Drop the sort param entirely to accept the endpoint default (usually {ts: -1})

Example fix

// before
GET /api/v1/channels.list?sort={"name":"asc"}

// after
GET /api/v1/channels.list?sort={"name":1}
Defensive patterns

Strategy: validation

Validate before calling

type SortDir = 1 | -1;
function buildSortParam(sort: Record<string, SortDir>): string {
  for (const [k, v] of Object.entries(sort)) {
    if (v !== 1 && v !== -1) throw new Error(`sort.${k} must be 1 or -1, got ${JSON.stringify(v)}`);
  }
  return JSON.stringify(sort); // e.g. '{"ts":-1}' — strict JSON, numeric values
}

Type guard

const isSortSpec = (v: unknown): v is Record<string, 1 | -1> =>
  typeof v === 'object' && v !== null && !Array.isArray(v) &&
  Object.values(v).every((x) => x === 1 || x === -1);

Try / catch

try {
  await client.get('/api/v1/channels.list', { params: { sort: JSON.stringify(sort) } });
} catch (e: any) {
  if (e?.response?.data?.errorType === 'error-invalid-sort') {
    throw new ValidationError(`bad sort param: ${e.response.data.message}`);
  }
  throw e;
}

Prevention

When it happens

Trigger: Sending sort={"ts":"-1"} (string values), sort=name (bare field, not JSON), sort={"ts":0}/{"ts":2}, or any malformed JSON such as unescaped quotes in the query string. Any endpoint calling parseJsonQuery (e.g. chat.getMentionedMessages, users.list, channels.list) reproduces it.

Common situations: Copy-pasting Mongo shell syntax ({ts:-1} is fine but {ts:'asc'} is not); URL encoding that mangles quotes into &quot;; older clients sending 'asc'/'desc' strings; hand-built query strings concatenating sort=name directly.

Related errors


AI-assisted analysis of RocketChat/Rocket.Chat@b2c16d5842 (2026-08-18). Data as JSON: /api/errors/92b264dcaa4b5715. Report an issue: GitHub.