From 28be5aba08e842e3f661ea13810116cafb47a00c Mon Sep 17 00:00:00 2001 From: h1pp0X Date: Fri, 19 Jul 2024 15:07:55 +0400 Subject: [PATCH 01/10] feat : added the possibility to directly log errors/infos via the send method --- packages/utils/src/utils.ts | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/packages/utils/src/utils.ts b/packages/utils/src/utils.ts index 2fb061ed..0efb9dc8 100644 --- a/packages/utils/src/utils.ts +++ b/packages/utils/src/utils.ts @@ -17,10 +17,19 @@ export type expressAppHandler = ( export const send = ( res: Response | http.ServerResponse, status: number, - body: string | object + body: string | object, + logger?: TwakeLogger ): void => { /* istanbul ignore next */ const content = typeof body === 'string' ? body : JSON.stringify(body) + if (logger != null) { + const logMessage = `Sending status ${status} with content ${content}` + if (status >= 200 && status < 300) { + logger.info(logMessage) + } else { + logger.error(logMessage) + } + } res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8', 'Content-Length': Buffer.byteLength(content, 'utf-8'), From 60fd1e0de0fce25d4428a37ebe843cdbbdd63bed Mon Sep 17 00:00:00 2001 From: h1pp0X Date: Fri, 19 Jul 2024 15:13:50 +0400 Subject: [PATCH 02/10] feat : integrated logger in send for /room directory --- .../src/rooms/roomId/getEventId.ts | 25 ++++++----- .../src/rooms/roomId/getJoinedMembers.ts | 11 ++--- .../src/rooms/roomId/getTimestampToEvent.ts | 21 ++++++---- .../room_information/get_joined_rooms.ts | 11 +++-- .../rooms/room_information/room_aliases.ts | 16 +++++--- .../src/rooms/room_information/room_tags.ts | 20 ++++----- .../rooms/room_information/room_visibilty.ts | 41 +++++++++++++------ 7 files changed, 85 insertions(+), 60 deletions(-) diff --git a/packages/matrix-client-server/src/rooms/roomId/getEventId.ts b/packages/matrix-client-server/src/rooms/roomId/getEventId.ts index c3c9eb4a..8609be4c 100644 --- a/packages/matrix-client-server/src/rooms/roomId/getEventId.ts +++ b/packages/matrix-client-server/src/rooms/roomId/getEventId.ts @@ -32,9 +32,12 @@ const GetEventId = (ClientServer: MatrixClientServer): expressAppHandler => { ) .then((rows) => { if (rows.length === 0) { - /* istanbul ignore next */ - ClientServer.logger.error('Event not found') - send(res, 404, errMsg('notFound', 'Cannot retrieve event')) + send( + res, + 404, + errMsg('notFound', 'Cannot retrieve event : event not found'), + ClientServer.logger + ) return } // Check if the user has permission to retrieve this event @@ -60,11 +63,15 @@ const GetEventId = (ClientServer: MatrixClientServer): expressAppHandler => { rows2.length === 0 || rows2[0].room_memberships_membership !== 'join' ) { - /* istanbul ignore next */ - ClientServer.logger.error( - 'User not in the room at the time of the event' + send( + res, + 404, + errMsg( + 'notFound', + 'Cannot retrieve event : User not in the room at the time of the event' + ), + ClientServer.logger ) - send(res, 404, errMsg('notFound', 'Cannot retrieve event')) return } const event = rows[0] @@ -85,15 +92,11 @@ const GetEventId = (ClientServer: MatrixClientServer): expressAppHandler => { send(res, 200, response) }) .catch((err) => { - /* istanbul ignore next */ - ClientServer.logger.error(err) /* istanbul ignore next */ send(res, 500, errMsg('unknown', err)) }) }) .catch((err) => { - /* istanbul ignore next */ - ClientServer.logger.error(err) /* istanbul ignore next */ send(res, 500, errMsg('unknown', err)) }) diff --git a/packages/matrix-client-server/src/rooms/roomId/getJoinedMembers.ts b/packages/matrix-client-server/src/rooms/roomId/getJoinedMembers.ts index d8b742c4..e846a621 100644 --- a/packages/matrix-client-server/src/rooms/roomId/getJoinedMembers.ts +++ b/packages/matrix-client-server/src/rooms/roomId/getJoinedMembers.ts @@ -32,7 +32,8 @@ const GetJoinedMembers = ( errMsg( 'notFound', 'User not in the room - cannot retrieve members' - ) + ), + ClientServer.logger ) return } @@ -62,16 +63,12 @@ const GetJoinedMembers = ( }) .catch((err) => { /* istanbul ignore next */ - ClientServer.logger.error(err) - /* istanbul ignore next */ - send(res, 500, errMsg('unknown', err)) + send(res, 500, errMsg('unknown', err), ClientServer.logger) }) }) .catch((err) => { /* istanbul ignore next */ - ClientServer.logger.error(err) - /* istanbul ignore next */ - send(res, 500, errMsg('unknown', err)) + send(res, 500, errMsg('unknown', err), ClientServer.logger) }) }) } diff --git a/packages/matrix-client-server/src/rooms/roomId/getTimestampToEvent.ts b/packages/matrix-client-server/src/rooms/roomId/getTimestampToEvent.ts index 02e3a7ff..352e77ae 100644 --- a/packages/matrix-client-server/src/rooms/roomId/getTimestampToEvent.ts +++ b/packages/matrix-client-server/src/rooms/roomId/getTimestampToEvent.ts @@ -17,7 +17,12 @@ const GetTimestampToEvent = ( // @ts-expect-error const params: query_parameters = (req as Request).query if (params.dir !== 'b' && params.dir !== 'f') { - send(res, 400, errMsg('invalidParam', 'Invalid parameters')) + send( + res, + 400, + errMsg('invalidParam', 'Invalid parameters'), + ClientServer.logger + ) return } ClientServer.authenticate(req, res, (data, id) => { @@ -42,7 +47,8 @@ const GetTimestampToEvent = ( errMsg( 'notFound', `Unable to find event from ${params.ts} in backward direction` - ) + ), + ClientServer.logger ) return } @@ -50,9 +56,7 @@ const GetTimestampToEvent = ( }) .catch((err) => { /* istanbul ignore next */ - ClientServer.logger.error(err) - /* istanbul ignore next */ - send(res, 500, errMsg('unknown', err)) + send(res, 500, errMsg('unknown', err), ClientServer.logger) }) } if (params.dir === 'f') { @@ -74,7 +78,8 @@ const GetTimestampToEvent = ( errMsg( 'notFound', `Unable to find event from ${params.ts} in forward direction` - ) + ), + ClientServer.logger ) return } @@ -82,9 +87,7 @@ const GetTimestampToEvent = ( }) .catch((err) => { /* istanbul ignore next */ - ClientServer.logger.error(err) - /* istanbul ignore next */ - send(res, 500, errMsg('unknown', err)) + send(res, 500, errMsg('unknown', err), ClientServer.logger) }) } }) diff --git a/packages/matrix-client-server/src/rooms/room_information/get_joined_rooms.ts b/packages/matrix-client-server/src/rooms/room_information/get_joined_rooms.ts index 4aadd39b..1033a6b3 100644 --- a/packages/matrix-client-server/src/rooms/room_information/get_joined_rooms.ts +++ b/packages/matrix-client-server/src/rooms/room_information/get_joined_rooms.ts @@ -15,13 +15,16 @@ export const getJoinedRooms = ( }) .then((roomsResult) => { const roomIds = roomsResult.map((row) => row.room_id) as string[] - send(res, 200, { joined_rooms: roomIds }) + send(res, 200, { joined_rooms: roomIds }, clientServer.logger) }) .catch((e) => { /* istanbul ignore next */ - clientServer.logger.error('Error querying joined rooms:', e) - /* istanbul ignore next */ - send(res, 500, errMsg('unknown', 'Error querying joined rooms')) + send( + res, + 500, + errMsg('unknown', 'Error querying joined rooms'), + clientServer.logger + ) }) }) } diff --git a/packages/matrix-client-server/src/rooms/room_information/room_aliases.ts b/packages/matrix-client-server/src/rooms/room_information/room_aliases.ts index e969bdc2..802b91ae 100644 --- a/packages/matrix-client-server/src/rooms/room_information/room_aliases.ts +++ b/packages/matrix-client-server/src/rooms/room_information/room_aliases.ts @@ -20,7 +20,12 @@ export const getRoomAliases = ( ) if (historyResponse.length === 0) { - send(res, 400, errMsg('invalidParam', 'Invalid room id')) + send( + res, + 400, + errMsg('invalidParam', 'Invalid room id'), + clientServer.logger + ) return } @@ -52,7 +57,8 @@ export const getRoomAliases = ( errMsg( 'forbidden', 'The user is not permitted to retrieve the list of local aliases for the room' - ) + ), + clientServer.logger ) } else { // Fetch the room aliases @@ -62,13 +68,11 @@ export const getRoomAliases = ( { room_id: roomId } ) const roomAliases = aliasRows.map((row) => row.room_alias) - send(res, 200, { aliases: roomAliases }) + send(res, 200, { aliases: roomAliases }, clientServer.logger) } } catch (e) { /* istanbul ignore next */ - clientServer.logger.error(e) - /* istanbul ignore next */ - send(res, 500, errMsg('unknown', e as string)) + send(res, 500, errMsg('unknown', e as string), clientServer.logger) } }) } diff --git a/packages/matrix-client-server/src/rooms/room_information/room_tags.ts b/packages/matrix-client-server/src/rooms/room_information/room_tags.ts index 4a0e0633..2cab67a0 100644 --- a/packages/matrix-client-server/src/rooms/room_information/room_tags.ts +++ b/packages/matrix-client-server/src/rooms/room_information/room_tags.ts @@ -33,27 +33,25 @@ export const getUserRoomTags = ( _tags[row.tag as string] = {} } } catch (error) { - /* istanbul ignore next */ - clientServer.logger.error( - 'Error parsing room tag content:', - error - ) /* istanbul ignore next */ send( res, 500, - errMsg('unknown', 'Error parsing room tag content') + errMsg('unknown', 'Error parsing room tag content'), + clientServer.logger ) } }) - - send(res, 200, { tags: _tags }) + send(res, 200, { tags: _tags }, clientServer.logger) }) .catch((e) => { /* istanbul ignore next */ - clientServer.logger.error('Error querying room tags:', e) - /* istanbul ignore next */ - send(res, 500, errMsg('unknown', 'Error querying room tags')) + send( + res, + 500, + errMsg('unknown', 'Error querying room tags'), + clientServer.logger + ) }) }) } diff --git a/packages/matrix-client-server/src/rooms/room_information/room_visibilty.ts b/packages/matrix-client-server/src/rooms/room_information/room_visibilty.ts index cf0b46b0..b8e5a838 100644 --- a/packages/matrix-client-server/src/rooms/room_information/room_visibilty.ts +++ b/packages/matrix-client-server/src/rooms/room_information/room_visibilty.ts @@ -20,7 +20,12 @@ export const getRoomVisibility = ( }) .then((roomsResult) => { if (roomsResult.length === 0) { - send(res, 404, errMsg('notFound', 'Room not found')) + send( + res, + 404, + errMsg('notFound', 'Room not found'), + clientServer.logger + ) } else { const roomInfo = roomsResult[0] @@ -28,16 +33,24 @@ export const getRoomVisibility = ( roomInfo.is_public !== null && roomInfo.is_public === 1 ? 'public' : 'private' - send(res, 200, { - visibility: _visibility - }) + send( + res, + 200, + { + visibility: _visibility + }, + clientServer.logger + ) } }) .catch((e) => { /* istanbul ignore next */ - clientServer.logger.error('Error querying room directory info:', e) - /* istanbul ignore next */ - send(res, 500, errMsg('unknown', 'Error querying room directory info')) + send( + res, + 500, + errMsg('unknown', 'Error querying room directory info'), + clientServer.logger + ) }) } } @@ -68,19 +81,23 @@ export const setRoomVisibility = ( ]) .then((rows) => { if (rows.length === 0) { - send(res, 404, errMsg('notFound', 'Room not found')) + send( + res, + 404, + errMsg('notFound', 'Room not found'), + clientServer.logger + ) } else { - send(res, 200, {}) + send(res, 200, {}, clientServer.logger) } }) .catch((e) => { - /* istanbul ignore next */ - clientServer.logger.error('Error updating room visibility:', e) /* istanbul ignore next */ send( res, 500, - errMsg('unknown', 'Error updating room visibility') + errMsg('unknown', 'Error updating room visibility'), + clientServer.logger ) }) } From ee5ada43af74a80f5d52e97a845e4e1e0c5c27aa Mon Sep 17 00:00:00 2001 From: h1pp0X Date: Fri, 19 Jul 2024 15:32:29 +0400 Subject: [PATCH 03/10] fix : updated send for /user directory --- .../src/user/account_data/getAccountData.ts | 40 +++++++++++-------- .../src/user/account_data/putAccountData.ts | 25 +++++++----- .../src/user/rooms/getRoomAccountData.ts | 40 +++++++++++-------- .../src/user/rooms/putRoomAccountData.ts | 25 +++++++----- 4 files changed, 76 insertions(+), 54 deletions(-) diff --git a/packages/matrix-client-server/src/user/account_data/getAccountData.ts b/packages/matrix-client-server/src/user/account_data/getAccountData.ts index fae1bf1c..8a7e8a2d 100644 --- a/packages/matrix-client-server/src/user/account_data/getAccountData.ts +++ b/packages/matrix-client-server/src/user/account_data/getAccountData.ts @@ -20,17 +20,22 @@ const getAccountData = ( !matrixIdRegex.test(parameters.userId) || !eventTypeRegex.test(parameters.type) ) { - send(res, 400, errMsg('invalidParam')) + send(res, 400, errMsg('invalidParam'), clientServer.logger) return } clientServer.authenticate(req, res, (data, token) => { if (parameters.userId !== data.sub) { // The config is only visible to the user that set the account data - send(res, 403, { - errcode: 'M_FORBIDDEN', - error: - 'The access token provided is not authorized to update this user’s account data.' - }) + send( + res, + 403, + { + errcode: 'M_FORBIDDEN', + error: + 'The access token provided is not authorized to update this user’s account data.' + }, + clientServer.logger + ) return } clientServer.matrixDb @@ -40,22 +45,25 @@ const getAccountData = ( }) .then((rows) => { if (rows.length === 0) { - send(res, 404, { - errcode: 'M_NOT_FOUND', - error: - 'No account data has been provided for this user with the given type.' - }) + send( + res, + 404, + { + errcode: 'M_NOT_FOUND', + error: + 'No account data has been provided for this user with the given type.' + }, + clientServer.logger + ) } else { const body: Record = {} body[parameters.type] = rows[0].content as string - send(res, 200, body) + send(res, 200, body, clientServer.logger) } }) .catch((e) => { - // istanbul ignore next - clientServer.logger.error("Error retrieving user's account data", e) - // istanbul ignore next - send(res, 500, errMsg('unknown')) + /* istanbul ignore next */ + send(res, 500, errMsg('unknown', e), clientServer.logger) }) }) } diff --git a/packages/matrix-client-server/src/user/account_data/putAccountData.ts b/packages/matrix-client-server/src/user/account_data/putAccountData.ts index fdf6f046..4b44cc81 100644 --- a/packages/matrix-client-server/src/user/account_data/putAccountData.ts +++ b/packages/matrix-client-server/src/user/account_data/putAccountData.ts @@ -34,7 +34,7 @@ const putAccountData = ( !matrixIdRegex.test(parameters.userId) || !eventTypeRegex.test(parameters.type) ) { - send(res, 400, errMsg('invalidParam')) + send(res, 400, errMsg('invalidParam'), clientServer.logger) return } clientServer.authenticate(req, res, (data, token) => { @@ -42,11 +42,16 @@ const putAccountData = ( validateParameters(res, schema, obj, clientServer.logger, (obj) => { if (parameters.userId !== data.sub) { // The config is only visible to the user that set the account data - send(res, 403, { - errcode: 'M_FORBIDDEN', - error: - 'The access token provided is not authorized to update this user’s account data.' - }) + send( + res, + 403, + { + errcode: 'M_FORBIDDEN', + error: + 'The access token provided is not authorized to update this user’s account data.' + }, + clientServer.logger + ) return } clientServer.matrixDb @@ -59,13 +64,11 @@ const putAccountData = ( ] ) .then(() => { - send(res, 200, {}) + send(res, 200, {}, clientServer.logger) }) .catch((e) => { - // istanbul ignore next - clientServer.logger.error("Error updating user's account data", e) - // istanbul ignore next - send(res, 500, errMsg('unknown')) + /* istanbul ignore next */ + send(res, 500, errMsg('unknown', e), clientServer.logger) }) }) }) diff --git a/packages/matrix-client-server/src/user/rooms/getRoomAccountData.ts b/packages/matrix-client-server/src/user/rooms/getRoomAccountData.ts index fc25d810..59d55e9c 100644 --- a/packages/matrix-client-server/src/user/rooms/getRoomAccountData.ts +++ b/packages/matrix-client-server/src/user/rooms/getRoomAccountData.ts @@ -23,16 +23,21 @@ const getRoomAccountData = ( !eventTypeRegex.test(parameters.type) || !roomIdRegex.test(parameters.roomId) ) { - send(res, 400, errMsg('invalidParam')) + send(res, 400, errMsg('invalidParam'), clientServer.logger) return } clientServer.authenticate(req, res, (data, token) => { if (parameters.userId !== data.sub) { - send(res, 403, { - errcode: 'M_FORBIDDEN', - error: - 'The access token provided is not authorized to update this user’s account data.' - }) + send( + res, + 403, + { + errcode: 'M_FORBIDDEN', + error: + 'The access token provided is not authorized to update this user’s account data.' + }, + clientServer.logger + ) return } clientServer.matrixDb @@ -43,22 +48,25 @@ const getRoomAccountData = ( }) .then((rows) => { if (rows.length === 0) { - send(res, 404, { - errcode: 'M_NOT_FOUND', - error: - 'No account data has been provided for this user and this room with the given type.' - }) + send( + res, + 404, + { + errcode: 'M_NOT_FOUND', + error: + 'No account data has been provided for this user and this room with the given type.' + }, + clientServer.logger + ) } else { const body: Record = {} body[parameters.type] = rows[0].content as string - send(res, 200, body) + send(res, 200, body, clientServer.logger) } }) .catch((e) => { - // istanbul ignore next - clientServer.logger.error("Error retrieving user's account data", e) - // istanbul ignore next - send(res, 500, errMsg('unknown')) + /* istanbul ignore next */ + send(res, 500, errMsg('unknown', e), clientServer.logger) }) }) } diff --git a/packages/matrix-client-server/src/user/rooms/putRoomAccountData.ts b/packages/matrix-client-server/src/user/rooms/putRoomAccountData.ts index c532f0f4..ebd80e1f 100644 --- a/packages/matrix-client-server/src/user/rooms/putRoomAccountData.ts +++ b/packages/matrix-client-server/src/user/rooms/putRoomAccountData.ts @@ -38,18 +38,23 @@ const putRoomAccountData = ( !eventTypeRegex.test(parameters.type) || !roomIdRegex.test(parameters.roomId) ) { - send(res, 400, errMsg('invalidParam')) + send(res, 400, errMsg('invalidParam'), clientServer.logger) return } clientServer.authenticate(req, res, (data, token) => { jsonContent(req, res, clientServer.logger, (obj) => { validateParameters(res, schema, obj, clientServer.logger, (obj) => { if (parameters.userId !== data.sub) { - send(res, 403, { - errcode: 'M_FORBIDDEN', - error: - 'The access token provided is not authorized to update this user’s account data.' - }) + send( + res, + 403, + { + errcode: 'M_FORBIDDEN', + error: + 'The access token provided is not authorized to update this user’s account data.' + }, + clientServer.logger + ) return } clientServer.matrixDb @@ -63,13 +68,11 @@ const putRoomAccountData = ( ] ) .then(() => { - send(res, 200, {}) + send(res, 200, {}, clientServer.logger) }) .catch((e) => { - // istanbul ignore next - clientServer.logger.error("Error updating user's account data", e) - // istanbul ignore next - send(res, 500, errMsg('unknown')) + /* istanbul ignore next */ + send(res, 500, errMsg('unknown', e), clientServer.logger) }) }) }) From 3a9776bbcd1eb70c569872b8c88992dcd42f0426 Mon Sep 17 00:00:00 2001 From: h1pp0X Date: Fri, 19 Jul 2024 15:40:01 +0400 Subject: [PATCH 04/10] feat : updated /utils directory for send --- .../src/utils/authenticate.ts | 7 +- .../utils/userInteractiveAuthentication.ts | 80 ++++++++++++------- 2 files changed, 54 insertions(+), 33 deletions(-) diff --git a/packages/matrix-client-server/src/utils/authenticate.ts b/packages/matrix-client-server/src/utils/authenticate.ts index 6718a7f3..b1ad93a4 100644 --- a/packages/matrix-client-server/src/utils/authenticate.ts +++ b/packages/matrix-client-server/src/utils/authenticate.ts @@ -69,7 +69,8 @@ const Authenticate = ( errMsg( 'forbidden', 'The appservice cannot masquerade as the user or has not registered them.' - ) + ), + logger ) return } @@ -90,11 +91,11 @@ const Authenticate = ( }) .catch((e) => { logger.warn('Access tried with an unkown token', req.headers) - send(res, 401, errMsg('unknownToken')) + send(res, 401, errMsg('unknownToken'), logger) }) } else { logger.warn('Access tried without token', req.headers) - send(res, 401, errMsg('missingToken')) + send(res, 401, errMsg('missingToken'), logger) } } } diff --git a/packages/matrix-client-server/src/utils/userInteractiveAuthentication.ts b/packages/matrix-client-server/src/utils/userInteractiveAuthentication.ts index 9475f607..772b2093 100644 --- a/packages/matrix-client-server/src/utils/userInteractiveAuthentication.ts +++ b/packages/matrix-client-server/src/utils/userInteractiveAuthentication.ts @@ -324,10 +324,15 @@ const UiAuthenticate = ( jsonContent(req, res, logger, (obj) => { // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions if (!(obj as requestBody).auth) { - send(res, 401, { - ...allowedFlows, - session: randomString(12) // Chose 12 arbitrarily according to a spec example - }) + send( + res, + 401, + { + ...allowedFlows, + session: randomString(12) // Chose 12 arbitrarily according to a spec example + }, + logger + ) } else { const auth = (obj as requestBody).auth as AuthenticationData checkAuthentication(auth, matrixDb, conf, req) @@ -359,40 +364,50 @@ const UiAuthenticate = ( if (authOver) { callback(obj, userId) // Arguments of callback are subject to change } else { - send(res, 401, { - ...allowedFlows, - session: auth.session, - completed - }) + send( + res, + 401, + { + ...allowedFlows, + session: auth.session, + completed + }, + logger + ) } }) .catch((e) => { - // istanbul ignore next + /* istanbul ignore next */ logger.error( 'Error while retrieving session credentials from the database during User-Interactive Authentication', e ) - // istanbul ignore next - send(res, 400, e) + /* istanbul ignore next */ + send(res, 400, e, logger) }) }) .catch((e) => { - // istanbul ignore next + /* istanbul ignore next */ logger.error( 'Error while inserting session credentials into the database during User-Interactive Authentication', e ) - // istanbul ignore next - send(res, 400, e) + /* istanbul ignore next */ + send(res, 400, e, logger) }) }) .catch((e) => { if (auth.type === 'm.login.application_service') { - send(res, 401, { - errcode: e.errcode, - error: e.error, - ...allowedFlows - }) + send( + res, + 401, + { + errcode: e.errcode, + error: e.error, + ...allowedFlows + }, + logger + ) return } db.get('ui_auth_sessions', ['stage_type'], { @@ -402,22 +417,27 @@ const UiAuthenticate = ( const completed: string[] = rows.map( (row) => row.stage_type as string ) - send(res, 401, { - errcode: e.errcode, - error: e.error, - completed, - ...allowedFlows, - session: auth.session - }) + send( + res, + 401, + { + errcode: e.errcode, + error: e.error, + completed, + ...allowedFlows, + session: auth.session + }, + logger + ) }) .catch((e) => { - // istanbul ignore next + /* istanbul ignore next */ logger.error( 'Error while retrieving session credentials from the database during User-Interactive Authentication', e ) - // istanbul ignore next - send(res, 400, e) + /* istanbul ignore next */ + send(res, 400, e, logger) }) }) } From 6d7755b12f959c5f3efa61146a568be40760836b Mon Sep 17 00:00:00 2001 From: h1pp0X Date: Fri, 19 Jul 2024 15:54:26 +0400 Subject: [PATCH 05/10] fix : added logger to send calls in /register directory --- .../src/register/email/requestToken.ts | 59 +++++++++------ .../src/register/email/submitToken.ts | 26 ++++--- .../src/register/index.ts | 38 ++++++---- .../src/register/msisdn/requestToken.ts | 71 +++++++++++++------ 4 files changed, 131 insertions(+), 63 deletions(-) diff --git a/packages/matrix-client-server/src/register/email/requestToken.ts b/packages/matrix-client-server/src/register/email/requestToken.ts index ed0c8a99..4d4e77cd 100644 --- a/packages/matrix-client-server/src/register/email/requestToken.ts +++ b/packages/matrix-client-server/src/register/email/requestToken.ts @@ -117,20 +117,21 @@ export const fillTable = ( last_send_attempt: sendAttempt }) .then(() => { - send(res, 200, { sid, submit_url: getSubmitUrl(clientServer.conf) }) + send( + res, + 200, + { sid, submit_url: getSubmitUrl(clientServer.conf) }, + clientServer.logger + ) }) .catch((err) => { // istanbul ignore next - clientServer.logger.error('Insertion error', err) - // istanbul ignore next - send(res, 500, errMsg('unknown', err)) + send(res, 500, errMsg('unknown', err), clientServer.logger) }) }) .catch((err) => { /* istanbul ignore next */ - clientServer.logger.error('Token error', err) - /* istanbul ignore next */ - send(res, 500, errMsg('unknown', err)) + send(res, 500, errMsg('unknown', err), clientServer.logger) }) } @@ -151,18 +152,28 @@ const RequestToken = (clientServer: MatrixClientServer): expressAppHandler => { const dst = (obj as RequestTokenArgs).email const nextLink = (obj as RequestTokenArgs).next_link if (!clientSecretRe.test(clientSecret)) { - send(res, 400, errMsg('invalidParam', 'invalid client_secret')) + send( + res, + 400, + errMsg('invalidParam', 'invalid client_secret'), + clientServer.logger + ) } else if (!validEmailRe.test(dst)) { - send(res, 400, errMsg('invalidEmail')) + send(res, 400, errMsg('invalidEmail'), clientServer.logger) // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions } else if (nextLink && !isValidUrl(nextLink)) { - send(res, 400, errMsg('invalidParam', 'invalid next_link')) + send( + res, + 400, + errMsg('invalidParam', 'invalid next_link'), + clientServer.logger + ) } else { clientServer.matrixDb .get('user_threepids', ['user_id'], { address: dst }) .then((rows) => { if (rows.length > 0) { - send(res, 400, errMsg('threepidInUse')) + send(res, 400, errMsg('threepidInUse'), clientServer.logger) } else { clientServer.matrixDb .get( @@ -176,10 +187,15 @@ const RequestToken = (clientServer: MatrixClientServer): expressAppHandler => { .then((rows) => { if (rows.length > 0) { if (sendAttempt === rows[0].last_send_attempt) { - send(res, 200, { - sid: rows[0].session_id, - submit_url: getSubmitUrl(clientServer.conf) - }) + send( + res, + 200, + { + sid: rows[0].session_id, + submit_url: getSubmitUrl(clientServer.conf) + }, + clientServer.logger + ) } else { clientServer.matrixDb .deleteWhere('threepid_validation_session', [ @@ -210,9 +226,12 @@ const RequestToken = (clientServer: MatrixClientServer): expressAppHandler => { }) .catch((err) => { // istanbul ignore next - clientServer.logger.error('Deletion error', err) - // istanbul ignore next - send(res, 500, errMsg('unknown', err)) + send( + res, + 500, + errMsg('unknown', err), + clientServer.logger + ) }) } } else { @@ -234,7 +253,7 @@ const RequestToken = (clientServer: MatrixClientServer): expressAppHandler => { /* istanbul ignore next */ clientServer.logger.error('Send_attempt error', err) /* istanbul ignore next */ - send(res, 500, errMsg('unknown', err)) + send(res, 500, errMsg('unknown', err), clientServer.logger) }) } }) @@ -242,7 +261,7 @@ const RequestToken = (clientServer: MatrixClientServer): expressAppHandler => { /* istanbul ignore next */ clientServer.logger.error('Error getting userID :', err) /* istanbul ignore next */ - send(res, 500, errMsg('unknown', err)) + send(res, 500, errMsg('unknown', err), clientServer.logger) }) } }) diff --git a/packages/matrix-client-server/src/register/email/submitToken.ts b/packages/matrix-client-server/src/register/email/submitToken.ts index 9730cd94..326f91a8 100644 --- a/packages/matrix-client-server/src/register/email/submitToken.ts +++ b/packages/matrix-client-server/src/register/email/submitToken.ts @@ -68,7 +68,7 @@ const SubmitToken = (clientServer: MatrixClientServer): expressAppHandler => { res.end() return } - send(res, 200, { success: true }) + send(res, 200, { success: true }, clientServer.logger) }) .catch((e) => { // istanbul ignore next @@ -77,33 +77,38 @@ const SubmitToken = (clientServer: MatrixClientServer): expressAppHandler => { e ) // istanbul ignore next - send(res, 500, e) + send(res, 500, e, clientServer.logger) }) }) .catch((e) => { // istanbul ignore next clientServer.logger.error('Error while deleting the token', e) // istanbul ignore next - send(res, 500, e) + send(res, 500, e, clientServer.logger) }) } else { /* istanbul ignore next */ - send(res, 400, errMsg('invalidParam', 'sid or secret mismatch')) + send( + res, + 400, + errMsg('invalidParam', 'sid or secret mismatch'), + clientServer.logger + ) } }) .catch((e) => { - clientServer.logger.error('Token error', e) send( res, 400, errMsg( 'invalidParam', 'Unknown or expired token ' + (e as string) - ) + ), + clientServer.logger ) }) } else { - send(res, 400, errMsg('missingParams')) + send(res, 400, errMsg('missingParams'), clientServer.logger) } } if (req.method === 'GET') { @@ -116,7 +121,12 @@ const SubmitToken = (clientServer: MatrixClientServer): expressAppHandler => { }) } else { /* istanbul ignore next */ - send(res, 400, errMsg('unAuthorized', 'Unauthorized method')) + send( + res, + 400, + errMsg('unAuthorized', 'Unauthorized method'), + clientServer.logger + ) } } } diff --git a/packages/matrix-client-server/src/register/index.ts b/packages/matrix-client-server/src/register/index.ts index c8b998f5..48dcd9fc 100644 --- a/packages/matrix-client-server/src/register/index.ts +++ b/packages/matrix-client-server/src/register/index.ts @@ -61,30 +61,40 @@ const createUser = ( Promise.all([otherPromise, userPromise, userIpPromise]) .then(() => { if (body.inhibit_login) { - send(res, 200, { user_id: userId }) + send(res, 200, { user_id: userId }, clientServer.logger) } else { - send(res, 200, { - access_token: accessToken, - device_id: deviceId, - user_id: userId, - expires_in_ms: 60000 // Arbitrary value, should probably be defined in the server config - }) + send( + res, + 200, + { + access_token: accessToken, + device_id: deviceId, + user_id: userId, + expires_in_ms: 60000 // Arbitrary value, should probably be defined in the server config + }, + clientServer.logger + ) } }) .catch((e) => { // istanbul ignore next clientServer.logger.error('Error while registering a user', e) // istanbul ignore next - send(res, 500, { - error: 'Error while registering a user' - }) + send( + res, + 500, + { + error: 'Error while registering a user' + }, + clientServer.logger + ) }) } const register = (clientServer: MatrixClientServer): expressAppHandler => { if (!clientServer.conf.is_registration_enabled) { return (req, res) => { - send(res, 404, { error: 'Registration is disabled' }) + send(res, 404, { error: 'Registration is disabled' }, clientServer.logger) } } return (req, res) => { @@ -107,7 +117,7 @@ const register = (clientServer: MatrixClientServer): expressAppHandler => { }) .then((rows) => { if (rows.length > 0) { - send(res, 400, errMsg('userInUse')) + send(res, 400, errMsg('userInUse'), clientServer.logger) } else { clientServer.matrixDb .get('devices', ['display_name', 'user_id'], { @@ -152,7 +162,7 @@ const register = (clientServer: MatrixClientServer): expressAppHandler => { e ) // istanbul ignore next - send(res, 500, e) + send(res, 500, e, clientServer.logger) }) } }) @@ -163,7 +173,7 @@ const register = (clientServer: MatrixClientServer): expressAppHandler => { e ) // istanbul ignore next - send(res, 500, e) + send(res, 500, e, clientServer.logger) }) }) } else { diff --git a/packages/matrix-client-server/src/register/msisdn/requestToken.ts b/packages/matrix-client-server/src/register/msisdn/requestToken.ts index 724d8f01..f5ae656b 100644 --- a/packages/matrix-client-server/src/register/msisdn/requestToken.ts +++ b/packages/matrix-client-server/src/register/msisdn/requestToken.ts @@ -119,20 +119,21 @@ export const fillTable = ( last_send_attempt: sendAttempt }) .then(() => { - send(res, 200, { sid, submit_url: getSubmitUrl(clientServer.conf) }) + send( + res, + 200, + { sid, submit_url: getSubmitUrl(clientServer.conf) }, + clientServer.logger + ) }) .catch((err) => { // istanbul ignore next - console.error('Insertion error:', err) - // istanbul ignore next - send(res, 500, errMsg('unknown', err)) + send(res, 500, errMsg('unknown', err), clientServer.logger) }) }) .catch((err) => { /* istanbul ignore next */ - console.error('Token error:', err) - /* istanbul ignore next */ - send(res, 500, errMsg('unknown', err)) + send(res, 500, errMsg('unknown', err), clientServer.logger) }) } @@ -155,20 +156,40 @@ const RequestToken = (clientServer: MatrixClientServer): expressAppHandler => { const dst = formatPhoneNumber(phoneNumber, country) const nextLink = (obj as RequestTokenArgs).next_link if (!clientSecretRegex.test(clientSecret)) { - send(res, 400, errMsg('invalidParam', 'Invalid client_secret')) + send( + res, + 400, + errMsg('invalidParam', 'Invalid client_secret'), + clientServer.logger + ) } else if (!validCountryRegex.test(country)) { - send(res, 400, errMsg('invalidParam', 'Invalid country')) + send( + res, + 400, + errMsg('invalidParam', 'Invalid country'), + clientServer.logger + ) // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions } else if (nextLink && !isValidUrl(nextLink)) { - send(res, 400, errMsg('invalidParam', 'Invalid next_link')) + send( + res, + 400, + errMsg('invalidParam', 'Invalid next_link'), + clientServer.logger + ) } else if (!validPhoneNumberRegex.test(dst)) { - send(res, 400, errMsg('invalidParam', 'Invalid phone number')) + send( + res, + 400, + errMsg('invalidParam', 'Invalid phone number'), + clientServer.logger + ) } else { clientServer.matrixDb .get('user_threepids', ['user_id'], { address: dst }) .then((rows) => { if (rows.length > 0) { - send(res, 400, errMsg('threepidInUse')) + send(res, 400, errMsg('threepidInUse'), clientServer.logger) } else { clientServer.matrixDb .get( @@ -182,10 +203,15 @@ const RequestToken = (clientServer: MatrixClientServer): expressAppHandler => { .then((rows) => { if (rows.length > 0) { if (sendAttempt === rows[0].last_send_attempt) { - send(res, 200, { - sid: rows[0].session_id, - submit_url: getSubmitUrl(clientServer.conf) - }) + send( + res, + 200, + { + sid: rows[0].session_id, + submit_url: getSubmitUrl(clientServer.conf) + }, + clientServer.logger + ) } else { clientServer.matrixDb .deleteWhere('threepid_validation_session', [ @@ -216,9 +242,12 @@ const RequestToken = (clientServer: MatrixClientServer): expressAppHandler => { }) .catch((err) => { // istanbul ignore next - console.error('Deletion error:', err) - // istanbul ignore next - send(res, 500, errMsg('unknown', err)) + send( + res, + 500, + errMsg('unknown', err), + clientServer.logger + ) }) } } else { @@ -240,7 +269,7 @@ const RequestToken = (clientServer: MatrixClientServer): expressAppHandler => { /* istanbul ignore next */ console.error('Send_attempt error:', err) /* istanbul ignore next */ - send(res, 500, errMsg('unknown', err)) + send(res, 500, errMsg('unknown', err), clientServer.logger) }) } }) @@ -248,7 +277,7 @@ const RequestToken = (clientServer: MatrixClientServer): expressAppHandler => { /* istanbul ignore next */ console.error('Error getting userID :', err) /* istanbul ignore next */ - send(res, 500, errMsg('unknown', err)) + send(res, 500, errMsg('unknown', err), clientServer.logger) }) } }) From 7b9c22dcd22534e04cdf490800e8f2a35c11b287 Mon Sep 17 00:00:00 2001 From: h1pp0X Date: Fri, 19 Jul 2024 17:02:12 +0400 Subject: [PATCH 06/10] fix : updated fix for /profiles directory --- .../src/profiles/changeProfiles.ts | 56 +++++--- .../src/profiles/getProfiles.ts | 131 +++++++++++++----- 2 files changed, 132 insertions(+), 55 deletions(-) diff --git a/packages/matrix-client-server/src/profiles/changeProfiles.ts b/packages/matrix-client-server/src/profiles/changeProfiles.ts index 95343dfa..081db8f5 100644 --- a/packages/matrix-client-server/src/profiles/changeProfiles.ts +++ b/packages/matrix-client-server/src/profiles/changeProfiles.ts @@ -71,9 +71,12 @@ export const changeAvatarUrl = ( byAdmin = response[0].admin as number } catch (e) { /* istanbul ignore next */ - clientServer.logger.error('Error checking admin:', e) - /* istanbul ignore next */ - send(res, 500, errMsg('unknown', 'Error checking admin')) + send( + res, + 500, + errMsg('unknown', 'Error checking admin'), + clientServer.logger + ) } jsonContent(req, res, clientServer.logger, (obj) => { @@ -86,7 +89,8 @@ export const changeAvatarUrl = ( send( res, 400, - errMsg('unknown', 'Cannot change displayname of a remote user') + errMsg('unknown', 'Cannot change displayname of a remote user'), + clientServer.logger ) return } @@ -98,7 +102,8 @@ export const changeAvatarUrl = ( errMsg( 'forbidden', 'Cannot change displayname of another user when not admin' - ) + ), + clientServer.logger ) return } @@ -112,7 +117,8 @@ export const changeAvatarUrl = ( errMsg( 'invalidParam', `Avatar url too long. Max length is + ${MAX_AVATAR_URL_LEN}` - ) + ), + clientServer.logger ) return } @@ -123,13 +129,16 @@ export const changeAvatarUrl = ( ]) .then(() => { clientServer.logger.debug('AvatarUrl updated') - send(res, 200, {}) + send(res, 200, {}, clientServer.logger) }) .catch((e) => { /* istanbul ignore next */ - clientServer.logger.error('Error querying profiles:', e) - /* istanbul ignore next */ - send(res, 500, errMsg('unknown', 'Error querying profiles')) + send( + res, + 500, + errMsg('unknown', 'Error querying profiles'), + clientServer.logger + ) }) }) }) @@ -171,7 +180,12 @@ export const changeDisplayname = ( /* istanbul ignore next */ clientServer.logger.error('Error checking admin:', e) /* istanbul ignore next */ - send(res, 500, errMsg('unknown', 'Error checking admin')) + send( + res, + 500, + errMsg('unknown', 'Error checking admin'), + clientServer.logger + ) } jsonContent(req, res, clientServer.logger, (obj) => { @@ -189,7 +203,8 @@ export const changeDisplayname = ( send( res, 400, - errMsg('unknown', 'Cannot change displayname of a remote user') + errMsg('unknown', 'Cannot change displayname of a remote user'), + clientServer.logger ) return } @@ -201,7 +216,8 @@ export const changeDisplayname = ( errMsg( 'forbidden', 'Cannot change displayname of another user when not admin' - ) + ), + clientServer.logger ) return } @@ -215,7 +231,8 @@ export const changeDisplayname = ( errMsg( 'invalidParam', `Displayname too long. Max length is + ${MAX_DISPLAYNAME_LEN}` - ) + ), + clientServer.logger ) return } @@ -228,13 +245,16 @@ export const changeDisplayname = ( ) .then(() => { clientServer.logger.debug('Displayname updated') - send(res, 200, {}) + send(res, 200, {}, clientServer.logger) }) .catch((e) => { /* istanbul ignore next */ - clientServer.logger.error('Error querying profiles:', e) - /* istanbul ignore next */ - send(res, 500, errMsg('unknown', 'Error querying profiles')) + send( + res, + 500, + errMsg('unknown', 'Error querying profiles'), + clientServer.logger + ) }) } ) diff --git a/packages/matrix-client-server/src/profiles/getProfiles.ts b/packages/matrix-client-server/src/profiles/getProfiles.ts index 4475ba6c..a25f6284 100644 --- a/packages/matrix-client-server/src/profiles/getProfiles.ts +++ b/packages/matrix-client-server/src/profiles/getProfiles.ts @@ -28,29 +28,44 @@ export const getProfile = ( }) .then((rows) => { if (rows.length === 0) { - clientServer.logger.info('Profile not found') - send(res, 404, errMsg('notFound', 'Profile not found')) + send( + res, + 404, + errMsg('notFound', 'Profile not found'), + clientServer.logger + ) } else { - // logger.info('Profile found:', rows[0]) - send(res, 200, { - avatar_url: rows[0].avatar_url, - displayname: rows[0].displayname - }) + send( + res, + 200, + { + avatar_url: rows[0].avatar_url, + displayname: rows[0].displayname + }, + clientServer.logger + ) } }) .catch((e) => { /* istanbul ignore next */ - send(res, 500, errMsg('unknown', e)) - /* istanbul ignore next */ - clientServer.logger.error('Error querying profiles:', e) + send(res, 500, errMsg('unknown', e), clientServer.logger) }) } else { // TODO : Have a look on remote server via federation - send(res, 500, errMsg('unknown', 'Cannot get profile of a remote user')) + send( + res, + 500, + errMsg('unknown', 'Cannot get profile of a remote user'), + clientServer.logger + ) } } else { - send(res, 400, errMsg('missingParams', 'No user ID provided')) - clientServer.logger.debug('No user ID provided') + send( + res, + 400, + errMsg('missingParams', 'No user ID provided'), + clientServer.logger + ) } } } @@ -73,31 +88,52 @@ export const getAvatarUrl = ( }) .then((rows) => { if (rows.length === 0) { - clientServer.logger.info('User not found') - send(res, 404, errMsg('notFound', 'User not found')) + send( + res, + 404, + errMsg('notFound', 'User not found'), + clientServer.logger + ) } else { if (rows[0].avatar_url === null) { - send(res, 404, errMsg('notFound', 'Avatar not found')) + send( + res, + 404, + errMsg('notFound', 'Avatar not found'), + clientServer.logger + ) } else { - send(res, 200, { - avatar_url: rows[0].avatar_url - }) + send( + res, + 200, + { + avatar_url: rows[0].avatar_url + }, + clientServer.logger + ) } } }) .catch((e) => { /* istanbul ignore next */ - send(res, 500, errMsg('unknown', e)) - /* istanbul ignore next */ - clientServer.logger.error('Error querying profiles:', e) + send(res, 500, errMsg('unknown', e), clientServer.logger) }) } else { // TODO : Have a look on remote server via federation - send(res, 500, errMsg('unknown', 'Cannot get profile of a remote user')) + send( + res, + 500, + errMsg('unknown', 'Cannot get profile of a remote user'), + clientServer.logger + ) } } else { - send(res, 400, errMsg('missingParams', 'No user ID provided')) - clientServer.logger.debug('No user ID provided') + send( + res, + 400, + errMsg('missingParams', 'No user ID provided'), + clientServer.logger + ) } } } @@ -120,31 +156,52 @@ export const getDisplayname = ( }) .then((rows) => { if (rows.length === 0) { - clientServer.logger.info('User not found') - send(res, 404, errMsg('notFound', 'User not found')) + send( + res, + 404, + errMsg('notFound', 'User not found'), + clientServer.logger + ) } else { if (rows[0].displayname === null) { - send(res, 404, errMsg('notFound', 'Displayname not found')) + send( + res, + 404, + errMsg('notFound', 'Displayname not found'), + clientServer.logger + ) } else { - send(res, 200, { - displayname: rows[0].displayname - }) + send( + res, + 200, + { + displayname: rows[0].displayname + }, + clientServer.logger + ) } } }) .catch((e) => { /* istanbul ignore next */ - send(res, 500, errMsg('unknown', e)) - /* istanbul ignore next */ - clientServer.logger.error('Error querying profiles:', e) + send(res, 500, errMsg('unknown', e), clientServer.logger) }) } else { // TODO : Have a look on remote server via federation - send(res, 500, errMsg('unknown', 'Cannot get profile of a remote user')) + send( + res, + 500, + errMsg('unknown', 'Cannot get profile of a remote user'), + clientServer.logger + ) } } else { - send(res, 400, errMsg('missingParams', 'No user ID provided')) - clientServer.logger.debug('No user ID provided') + send( + res, + 400, + errMsg('missingParams', 'No user ID provided'), + clientServer.logger + ) } } } From b211098cdb162c00bfdc53c3ee13d9d6116fa119 Mon Sep 17 00:00:00 2001 From: h1pp0X Date: Mon, 22 Jul 2024 09:21:01 +0400 Subject: [PATCH 07/10] fix : updated send for the /presence directory --- .../src/presence/getStatus.ts | 48 +++++++++++-------- .../src/presence/putStatus.ts | 17 ++++--- 2 files changed, 39 insertions(+), 26 deletions(-) diff --git a/packages/matrix-client-server/src/presence/getStatus.ts b/packages/matrix-client-server/src/presence/getStatus.ts index b997957e..27ec5d1c 100644 --- a/packages/matrix-client-server/src/presence/getStatus.ts +++ b/packages/matrix-client-server/src/presence/getStatus.ts @@ -10,8 +10,12 @@ const getStatus = (clientServer: MatrixClientServer): expressAppHandler => { // @ts-expect-error const userId: string = req.params.userId as string if (!matrixIdRegex.test(userId)) { - clientServer.logger.warn('Invalid user ID') - send(res, 400, errMsg('invalidParam')) + send( + res, + 400, + errMsg('invalidParam', 'Invalid user ID'), + clientServer.logger + ) } else { clientServer.authenticate(req, res, (data, id) => { clientServer.matrixDb @@ -20,29 +24,35 @@ const getStatus = (clientServer: MatrixClientServer): expressAppHandler => { }) .then((rows) => { if (rows.length === 0) { - clientServer.logger.error('No presence state for this user') - send(res, 404, { - errcode: 'M_UNKNOWN', - error: - 'There is no presence state for this user. This user may not exist or isn’t exposing presence information to you.' - }) + send( + res, + 404, + { + errcode: 'M_UNKNOWN', + error: + 'There is no presence state for this user. This user may not exist or isn’t exposing presence information to you.' + }, + clientServer.logger + ) } else { - send(res, 200, { - currently_active: rows[0].state === 'online', - last_active_ts: epoch() - (rows[0].mtime as number), // TODO : Check if mtime corresponds to last_active_ts, not clear in the spec - state: rows[0].state, - status_msg: rows[0].status_msg - }) + send( + res, + 200, + { + currently_active: rows[0].state === 'online', + last_active_ts: epoch() - (rows[0].mtime as number), // TODO : Check if mtime corresponds to last_active_ts, not clear in the spec + state: rows[0].state, + status_msg: rows[0].status_msg + }, + clientServer.logger + ) } }) .catch((e) => { // istanbul ignore next - clientServer.logger.error( - "Error retrieving user's presence state", - e - ) + clientServer.logger.error("Error retrieving user's presence state") // istanbul ignore next - send(res, 500, errMsg('unknown')) + send(res, 500, errMsg('unknown', e), clientServer.logger) }) }) } diff --git a/packages/matrix-client-server/src/presence/putStatus.ts b/packages/matrix-client-server/src/presence/putStatus.ts index f69db571..1b235b20 100644 --- a/packages/matrix-client-server/src/presence/putStatus.ts +++ b/packages/matrix-client-server/src/presence/putStatus.ts @@ -27,8 +27,12 @@ const putStatus = (clientServer: MatrixClientServer): expressAppHandler => { // @ts-expect-error const userId: string = req.params.userId as string if (!matrixIdRegex.test(userId)) { - clientServer.logger.warn('Invalid user ID') - send(res, 400, errMsg('invalidParam')) + send( + res, + 400, + errMsg('invalidParam', 'Invalid user ID'), + clientServer.logger + ) } else { clientServer.authenticate(req, res, (data, id) => { jsonContent(req, res, clientServer.logger, (obj) => { @@ -37,7 +41,7 @@ const putStatus = (clientServer: MatrixClientServer): expressAppHandler => { clientServer.logger.warn( 'You cannot set the presence state of another user' ) - send(res, 403, errMsg('forbidden')) + send(res, 403, errMsg('forbidden'), clientServer.logger) return } clientServer.matrixDb @@ -50,16 +54,15 @@ const putStatus = (clientServer: MatrixClientServer): expressAppHandler => { [{ field: 'user_id', value: userId }] ) .then(() => { - send(res, 200, {}) + send(res, 200, {}, clientServer.logger) }) .catch((e) => { // istanbul ignore next clientServer.logger.error( - "Error updating user's presence state", - e + "Error updating user's presence state" ) // istanbul ignore next - send(res, 500, errMsg('unknown')) + send(res, 500, errMsg('unknown', e), clientServer.logger) }) }) }) From 538c210ef08140852ce5dca59ba7c439334a0a10 Mon Sep 17 00:00:00 2001 From: h1pp0X Date: Mon, 22 Jul 2024 09:25:12 +0400 Subject: [PATCH 08/10] fix : added tests for send method --- packages/utils/src/index.test.ts | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/packages/utils/src/index.test.ts b/packages/utils/src/index.test.ts index a4775c00..23a39913 100644 --- a/packages/utils/src/index.test.ts +++ b/packages/utils/src/index.test.ts @@ -26,7 +26,8 @@ describe('Utility Functions', () => { mockLogger = { error: jest.fn(), warn: jest.fn(), - log: jest.fn() + log: jest.fn(), + info: jest.fn() } as unknown as TwakeLogger }) @@ -47,6 +48,22 @@ describe('Utility Functions', () => { ) expect(mockResponse.end).toHaveBeenCalled() }) + + it('should log the response status with info if status code in 200-299', () => { + send(mockResponse as Response, 200, { message: 'ok' }, mockLogger) + + expect(mockLogger.info).toHaveBeenCalledWith( + 'Sending status 200 with content {"message":"ok"}' + ) + }) + + it('should log the response status with error if status code not in 200-299', () => { + send(mockResponse as Response, 400, { message: 'error' }, mockLogger) + + expect(mockLogger.error).toHaveBeenCalledWith( + 'Sending status 400 with content {"message":"error"}' + ) + }) }) describe('jsonContent', () => { From 1a3a7ba1f7361fc7a9d8de3f837d7f3624bdf712 Mon Sep 17 00:00:00 2001 From: h1pp0X Date: Mon, 22 Jul 2024 09:34:00 +0400 Subject: [PATCH 09/10] fix : updated send calls for /admin /devices and /login directories --- .../matrix-client-server/src/admin/whois.ts | 22 ++++++++------ .../src/devices/changeDevices.ts | 9 +++--- .../src/devices/getDevices.ts | 30 ++++++++++++------- .../src/login/getLogin.ts | 2 +- .../src/login/postLogin.ts | 12 +++++--- 5 files changed, 46 insertions(+), 29 deletions(-) diff --git a/packages/matrix-client-server/src/admin/whois.ts b/packages/matrix-client-server/src/admin/whois.ts index 72873cad..0ee6aef4 100644 --- a/packages/matrix-client-server/src/admin/whois.ts +++ b/packages/matrix-client-server/src/admin/whois.ts @@ -60,23 +60,27 @@ const whois = (clientServer: MatrixClientServer): expressAppHandler => { } devices[deviceId].sessions.push(sessions[mappings[deviceId]]) }) - send(res, 200, { - user_id: prms.userId, - devices - }) + send( + res, + 200, + { + user_id: prms.userId, + devices + }, + clientServer.logger + ) }) - .catch((err) => { + .catch((e) => { // istanbul ignore next clientServer.logger.error( - 'Error retrieving user informations from the MatrixDB', - err + 'Error retrieving user informations from the MatrixDB' ) // istanbul ignore next - send(res, 500, errMsg('unknown')) + send(res, 500, errMsg('unknown', e), clientServer.logger) }) }) } else { - send(res, 400, errMsg('missingParams')) + send(res, 400, errMsg('missingParams'), clientServer.logger) } } } diff --git a/packages/matrix-client-server/src/devices/changeDevices.ts b/packages/matrix-client-server/src/devices/changeDevices.ts index 66346e25..c1d1eacd 100644 --- a/packages/matrix-client-server/src/devices/changeDevices.ts +++ b/packages/matrix-client-server/src/devices/changeDevices.ts @@ -52,18 +52,19 @@ export const changeDeviceName = ( errMsg( 'notFound', 'The current user has no device with the given ID' - ) + ), + clientServer.logger ) } else { clientServer.logger.debug('Device Name updated') - send(res, 200, {}) + send(res, 200, {}, clientServer.logger) } }) .catch((e) => { /* istanbul ignore next */ - clientServer.logger.error('Error querying profiles:', e) + clientServer.logger.error('Error querying profiles:') /* istanbul ignore next */ - send(res, 500, errMsg('unknown', 'Error querying profiles')) + send(res, 500, errMsg('unknown', e), clientServer.logger) }) }) }) diff --git a/packages/matrix-client-server/src/devices/getDevices.ts b/packages/matrix-client-server/src/devices/getDevices.ts index 763a8c8d..f9cb4f4f 100644 --- a/packages/matrix-client-server/src/devices/getDevices.ts +++ b/packages/matrix-client-server/src/devices/getDevices.ts @@ -34,11 +34,13 @@ export const getDevices = ( last_seen_ts: row.last_seen } }) - send(res, 200, { devices: _devices }) + send(res, 200, { devices: _devices }, clientServer.logger) }) .catch((e) => { /* istanbul ignore next */ - clientServer.logger.error('Error querying devices:', e) + clientServer.logger.error('Error querying devices') + /* istanbul ignore next */ + send(res, 500, errMsg('unknown', e), clientServer.logger) }) }) } @@ -65,22 +67,28 @@ export const getDeviceInfo = ( errMsg( 'notFound', 'The current user has no device with the given ID' - ) + ), + clientServer.logger ) } else { - send(res, 200, { - device_id: deviceId, - display_name: rows[0].display_name, - last_seen_ip: rows[0].ip, - last_seen_ts: rows[0].last_seen - }) + send( + res, + 200, + { + device_id: deviceId, + display_name: rows[0].display_name, + last_seen_ip: rows[0].ip, + last_seen_ts: rows[0].last_seen + }, + clientServer.logger + ) } }) .catch((e) => { /* istanbul ignore next */ - clientServer.logger.error('Error querying devices:', e) + clientServer.logger.error('Error querying devices:') /* istanbul ignore next */ - send(res, 500, errMsg('unknown', 'Error querying devices')) + send(res, 500, errMsg('unknown', e), clientServer.logger) }) }) } diff --git a/packages/matrix-client-server/src/login/getLogin.ts b/packages/matrix-client-server/src/login/getLogin.ts index 5049cfaa..0577e0bf 100644 --- a/packages/matrix-client-server/src/login/getLogin.ts +++ b/packages/matrix-client-server/src/login/getLogin.ts @@ -3,7 +3,7 @@ import type MatrixClientServer from '..' const getLogin = (clientServer: MatrixClientServer): expressAppHandler => { return (req, res) => { - send(res, 200, clientServer.conf.login_flows) + send(res, 200, clientServer.conf.login_flows, clientServer.logger) } } diff --git a/packages/matrix-client-server/src/login/postLogin.ts b/packages/matrix-client-server/src/login/postLogin.ts index ad2babb8..41361fb9 100644 --- a/packages/matrix-client-server/src/login/postLogin.ts +++ b/packages/matrix-client-server/src/login/postLogin.ts @@ -1,11 +1,11 @@ import { errMsg, - expressAppHandler, + type expressAppHandler, jsonContent, send, validateParameters } from '@twake/utils' -import MatrixClientServer from '..' +import type MatrixClientServer from '..' import { type UserIdentifier } from '../types' interface LoginRequestBody { @@ -37,8 +37,12 @@ const postLogin = (clientServer: MatrixClientServer): expressAppHandler => { case 'm.login.password': // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions if (!body.password) { - clientServer.logger.error('Missing password') - send(res, 400, errMsg('missingParam', 'password')) + send( + res, + 400, + errMsg('missingParam', 'Missing password'), + clientServer.logger + ) // return } } From b75bd13ee2cc24f9769bb4e432508191a86ced83 Mon Sep 17 00:00:00 2001 From: h1pp0X Date: Mon, 22 Jul 2024 09:40:18 +0400 Subject: [PATCH 10/10] fix : updated send calls for /account directory --- .../src/account/3pid/add.ts | 27 ++++++--- .../account/password/email/requestToken.ts | 48 ++++++++++----- .../account/password/msisdn/requestToken.ts | 60 ++++++++++++++----- .../src/account/whoami.ts | 8 +-- 4 files changed, 101 insertions(+), 42 deletions(-) diff --git a/packages/matrix-client-server/src/account/3pid/add.ts b/packages/matrix-client-server/src/account/3pid/add.ts index c0c57ae9..dae8f6df 100644 --- a/packages/matrix-client-server/src/account/3pid/add.ts +++ b/packages/matrix-client-server/src/account/3pid/add.ts @@ -29,11 +29,21 @@ const add = (clientServer: MatrixClientServer): expressAppHandler => { clientServer.uiauthenticate(req, res, allowedFlows, (obj, userId) => { validateParameters(res, schema, obj, clientServer.logger, (obj) => { if (!clientSecretRegex.test((obj as RequestBody).client_secret)) { - send(res, 400, errMsg('invalidParam', 'Invalid client_secret')) + send( + res, + 400, + errMsg('invalidParam', 'Invalid client_secret'), + clientServer.logger + ) return } if (!sidRegex.test((obj as RequestBody).sid)) { - send(res, 400, errMsg('invalidParam', 'Invalid session ID')) + send( + res, + 400, + errMsg('invalidParam', 'Invalid session ID'), + clientServer.logger + ) return } const body = obj as RequestBody @@ -49,12 +59,12 @@ const add = (clientServer: MatrixClientServer): expressAppHandler => { ) .then((sessionRows) => { if (sessionRows.length === 0) { - send(res, 400, errMsg('noValidSession')) + send(res, 400, errMsg('noValidSession'), clientServer.logger) return } // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions if (!sessionRows[0].validated_at) { - send(res, 400, errMsg('sessionNotValidated')) + send(res, 400, errMsg('sessionNotValidated'), clientServer.logger) return } clientServer.matrixDb @@ -63,7 +73,7 @@ const add = (clientServer: MatrixClientServer): expressAppHandler => { }) .then((rows) => { if (rows.length > 0) { - send(res, 400, errMsg('threepidInUse')) + send(res, 400, errMsg('threepidInUse'), clientServer.logger) } else { clientServer.matrixDb .insert('user_threepids', { @@ -74,16 +84,15 @@ const add = (clientServer: MatrixClientServer): expressAppHandler => { added_at: epoch() }) .then(() => { - send(res, 200, {}) + send(res, 200, {}, clientServer.logger) }) .catch((e) => { // istanbul ignore next clientServer.logger.error( - 'Error while inserting user_threepids', - e + 'Error while inserting user_threepids' ) // istanbul ignore next - send(res, 400, errMsg('unknown', e)) + send(res, 400, errMsg('unknown', e), clientServer.logger) }) } }) diff --git a/packages/matrix-client-server/src/account/password/email/requestToken.ts b/packages/matrix-client-server/src/account/password/email/requestToken.ts index 7b3f4da8..05974ba0 100644 --- a/packages/matrix-client-server/src/account/password/email/requestToken.ts +++ b/packages/matrix-client-server/src/account/password/email/requestToken.ts @@ -54,18 +54,28 @@ const RequestToken = (clientServer: MatrixClientServer): expressAppHandler => { const dst = (obj as RequestTokenArgs).email const nextLink = (obj as RequestTokenArgs).next_link if (!clientSecretRe.test(clientSecret)) { - send(res, 400, errMsg('invalidParam', 'invalid client_secret')) + send( + res, + 400, + errMsg('invalidParam', 'invalid client_secret'), + clientServer.logger + ) } else if (!validEmailRe.test(dst)) { - send(res, 400, errMsg('invalidEmail')) + send(res, 400, errMsg('invalidEmail'), clientServer.logger) // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions } else if (nextLink && !isValidUrl(nextLink)) { - send(res, 400, errMsg('invalidParam', 'invalid next_link')) + send( + res, + 400, + errMsg('invalidParam', 'invalid next_link'), + clientServer.logger + ) } else { clientServer.matrixDb .get('user_threepids', ['user_id'], { address: dst }) .then((rows) => { if (rows.length === 0) { - send(res, 400, errMsg('threepidNotFound')) + send(res, 400, errMsg('threepidNotFound'), clientServer.logger) } else { clientServer.matrixDb .get( @@ -79,10 +89,15 @@ const RequestToken = (clientServer: MatrixClientServer): expressAppHandler => { .then((rows) => { if (rows.length > 0) { if (sendAttempt === rows[0].last_send_attempt) { - send(res, 200, { - sid: rows[0].session_id, - submit_url: getSubmitUrl(clientServer.conf) - }) + send( + res, + 200, + { + sid: rows[0].session_id, + submit_url: getSubmitUrl(clientServer.conf) + }, + clientServer.logger + ) } else { clientServer.matrixDb .deleteWhere('threepid_validation_session', [ @@ -113,9 +128,14 @@ const RequestToken = (clientServer: MatrixClientServer): expressAppHandler => { }) .catch((err) => { // istanbul ignore next - clientServer.logger.error('Deletion error', err) + clientServer.logger.error('Deletion error') // istanbul ignore next - send(res, 500, errMsg('unknown', err)) + send( + res, + 500, + errMsg('unknown', err), + clientServer.logger + ) }) } } else { @@ -135,17 +155,17 @@ const RequestToken = (clientServer: MatrixClientServer): expressAppHandler => { }) .catch((err) => { /* istanbul ignore next */ - clientServer.logger.error('Send_attempt error', err) + clientServer.logger.error('Send_attempt error') /* istanbul ignore next */ - send(res, 500, errMsg('unknown', err)) + send(res, 500, errMsg('unknown', err), clientServer.logger) }) } }) .catch((err) => { /* istanbul ignore next */ - clientServer.logger.error('Error getting userID :', err) + clientServer.logger.error('Error getting userID') /* istanbul ignore next */ - send(res, 500, errMsg('unknown', err)) + send(res, 500, errMsg('unknown', err), clientServer.logger) }) } }) diff --git a/packages/matrix-client-server/src/account/password/msisdn/requestToken.ts b/packages/matrix-client-server/src/account/password/msisdn/requestToken.ts index 76f75c3a..f96357a3 100644 --- a/packages/matrix-client-server/src/account/password/msisdn/requestToken.ts +++ b/packages/matrix-client-server/src/account/password/msisdn/requestToken.ts @@ -60,20 +60,40 @@ const RequestToken = (clientServer: MatrixClientServer): expressAppHandler => { const dst = formatPhoneNumber(phoneNumber, country) const nextLink = (obj as RequestTokenArgs).next_link if (!clientSecretRegex.test(clientSecret)) { - send(res, 400, errMsg('invalidParam', 'Invalid client_secret')) + send( + res, + 400, + errMsg('invalidParam', 'Invalid client_secret'), + clientServer.logger + ) } else if (!validCountryRegex.test(country)) { - send(res, 400, errMsg('invalidParam', 'Invalid country')) + send( + res, + 400, + errMsg('invalidParam', 'Invalid country'), + clientServer.logger + ) // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions } else if (nextLink && !isValidUrl(nextLink)) { - send(res, 400, errMsg('invalidParam', 'Invalid next_link')) + send( + res, + 400, + errMsg('invalidParam', 'Invalid next_link'), + clientServer.logger + ) } else if (!validPhoneNumberRegex.test(dst)) { - send(res, 400, errMsg('invalidParam', 'Invalid phone number')) + send( + res, + 400, + errMsg('invalidParam', 'Invalid phone number'), + clientServer.logger + ) } else { clientServer.matrixDb .get('user_threepids', ['user_id'], { address: dst }) .then((rows) => { if (rows.length === 0) { - send(res, 400, errMsg('threepidNotFound')) + send(res, 400, errMsg('threepidNotFound'), clientServer.logger) } else { clientServer.matrixDb .get( @@ -87,10 +107,15 @@ const RequestToken = (clientServer: MatrixClientServer): expressAppHandler => { .then((rows) => { if (rows.length > 0) { if (sendAttempt === rows[0].last_send_attempt) { - send(res, 200, { - sid: rows[0].session_id, - submit_url: getSubmitUrl(clientServer.conf) - }) + send( + res, + 200, + { + sid: rows[0].session_id, + submit_url: getSubmitUrl(clientServer.conf) + }, + clientServer.logger + ) } else { clientServer.matrixDb .deleteWhere('threepid_validation_session', [ @@ -121,9 +146,14 @@ const RequestToken = (clientServer: MatrixClientServer): expressAppHandler => { }) .catch((err) => { // istanbul ignore next - console.error('Deletion error:', err) + clientServer.logger.error('Deletion error') // istanbul ignore next - send(res, 500, errMsg('unknown', err)) + send( + res, + 500, + errMsg('unknown', err), + clientServer.logger + ) }) } } else { @@ -143,17 +173,17 @@ const RequestToken = (clientServer: MatrixClientServer): expressAppHandler => { }) .catch((err) => { /* istanbul ignore next */ - console.error('Send_attempt error:', err) + clientServer.logger.error('Send_attempt error') /* istanbul ignore next */ - send(res, 500, errMsg('unknown', err)) + send(res, 500, errMsg('unknown', err), clientServer.logger) }) } }) .catch((err) => { /* istanbul ignore next */ - console.error('Error getting userID :', err) + clientServer.logger.error('Error getting userID') /* istanbul ignore next */ - send(res, 500, errMsg('unknown', err)) + send(res, 500, errMsg('unknown', err), clientServer.logger) }) } }) diff --git a/packages/matrix-client-server/src/account/whoami.ts b/packages/matrix-client-server/src/account/whoami.ts index 5761155c..62c08809 100644 --- a/packages/matrix-client-server/src/account/whoami.ts +++ b/packages/matrix-client-server/src/account/whoami.ts @@ -15,7 +15,7 @@ const whoami = (clientServer: MatrixClientServer): expressAppHandler => { .then((rows) => { // istanbul ignore if // might remove the istanbul ignore if an endpoint other than /register modifies the users table if (rows.length === 0) { - send(res, 403, errMsg('invalidUsername')) + send(res, 403, errMsg('invalidUsername'), clientServer.logger) return } const isGuest = rows[0].is_guest !== 0 @@ -24,13 +24,13 @@ const whoami = (clientServer: MatrixClientServer): expressAppHandler => { if (data.device_id) { body.device_id = data.device_id } - send(res, 200, body) + send(res, 200, body, clientServer.logger) }) .catch((e) => { // istanbul ignore next - clientServer.logger.error('Error while fetching user data', e) + clientServer.logger.error('Error while fetching user data') // istanbul ignore next - send(res, 500, errMsg('unknown')) + send(res, 500, errMsg('unknown', e), clientServer.logger) }) }) }