From 8be30acb1169cb600b06308ffdeb2caeda0cf3c0 Mon Sep 17 00:00:00 2001 From: Michael Telatynski <7t3chguy@gmail.com> Date: Tue, 3 May 2022 22:40:57 +0100 Subject: [PATCH] Apply suggestions from SonarQube (#2340) --- spec/browserify/sync-browserify.spec.js | 4 +- src/autodiscovery.ts | 6 +- src/client.ts | 57 ++++++++----------- src/crypto/OlmDevice.ts | 8 +-- src/crypto/OutgoingRoomKeyRequestManager.ts | 4 +- src/crypto/SecretStorage.ts | 19 +++---- src/crypto/aes.ts | 2 +- src/crypto/algorithms/olm.ts | 8 +-- src/crypto/backup.ts | 14 ++--- src/crypto/dehydration.ts | 12 ++-- src/crypto/index.ts | 6 +- src/crypto/key_passphrase.ts | 4 +- src/crypto/verification/SAS.ts | 4 +- .../verification/request/InRoomChannel.ts | 5 +- src/http-api.ts | 6 +- src/matrix.ts | 3 +- src/pushprocessor.ts | 2 +- src/utils.ts | 12 +++- src/webrtc/call.ts | 6 +- 19 files changed, 86 insertions(+), 96 deletions(-) diff --git a/spec/browserify/sync-browserify.spec.js b/spec/browserify/sync-browserify.spec.js index fd4a0dc9b..8a087c807 100644 --- a/spec/browserify/sync-browserify.spec.js +++ b/spec/browserify/sync-browserify.spec.js @@ -47,7 +47,7 @@ describe("Browserify Test", function() { httpBackend.stop(); }); - it("Sync", async function() { + it("Sync", function() { const event = utils.mkMembership({ room: ROOM_ID, mship: "join", @@ -71,7 +71,7 @@ describe("Browserify Test", function() { }; httpBackend.when("GET", "/sync").respond(200, syncData); - return await Promise.race([ + return Promise.race([ httpBackend.flushAllExpected(), new Promise((_, reject) => { client.once("sync.unexpectedError", reject); diff --git a/src/autodiscovery.ts b/src/autodiscovery.ts index c60bd0529..5f875cc68 100644 --- a/src/autodiscovery.ts +++ b/src/autodiscovery.ts @@ -410,14 +410,14 @@ export class AutoDiscovery { * the following properties: * raw: The JSON object returned by the server. * action: One of SUCCESS, IGNORE, or FAIL_PROMPT. - * reason: Relatively human readable description of what went wrong. + * reason: Relatively human-readable description of what went wrong. * error: The actual Error, if one exists. * @param {string} url The URL to fetch a JSON object from. * @return {Promise} Resolves to the returned state. * @private */ - private static async fetchWellKnownObject(url: string): Promise { - return new Promise(function(resolve, reject) { + private static fetchWellKnownObject(url: string): Promise { + return new Promise(function(resolve) { // eslint-disable-next-line const request = require("./matrix").getRequest(); if (!request) throw new Error("No request library available"); diff --git a/src/client.ts b/src/client.ts index d61ce4f7c..45ced3946 100644 --- a/src/client.ts +++ b/src/client.ts @@ -1296,9 +1296,9 @@ export class MatrixClient extends TypedEventEmitter { + public getDehydratedDevice(): Promise { try { - return await this.http.authedRequest( + return this.http.authedRequest( undefined, Method.Get, "/dehydrated_device", @@ -1324,7 +1324,7 @@ export class MatrixClient extends TypedEventEmitter { @@ -2605,9 +2602,9 @@ export class MatrixClient extends TypedEventEmitter} Information object from API or null */ public async getKeyBackupVersion(): Promise { - let res; + let res: IKeyBackupInfo; try { - res = await this.http.authedRequest( + res = await this.http.authedRequest( undefined, Method.Get, "/room_keys/version", undefined, undefined, { prefix: PREFIX_UNSTABLE }, ); @@ -2618,11 +2615,7 @@ export class MatrixClient extends TypedEventEmitter( undefined, Method.Get, path.path, path.queryData, undefined, { prefix: PREFIX_UNSTABLE }, - ) as IRoomsKeysResponse | IRoomKeysResponse | IKeyBackupSession; + ); if ((res as IRoomsKeysResponse).rooms) { const rooms = (res as IRoomsKeysResponse).rooms; @@ -3372,7 +3365,7 @@ export class MatrixClient extends TypedEventEmitter(eventType: string): Promise { + public getAccountDataFromServer(eventType: string): Promise { if (this.isInitialSyncComplete()) { const event = this.store.getAccountData(eventType); if (!event) { @@ -3387,7 +3380,7 @@ export class MatrixClient extends TypedEventEmitter { + this.syncLeftRoomsPromise.then(() => { logger.log("Marking success of sync left room request"); this.syncedLeftRooms = true; // flip the bit on success }).finally(() => { @@ -7203,7 +7196,7 @@ export class MatrixClient extends TypedEventEmitter { - return await this.cryptoStore.getEndToEndSessionProblem(deviceKey, timestamp); + public sessionMayHaveProblems(deviceKey: string, timestamp: number): Promise { + return this.cryptoStore.getEndToEndSessionProblem(deviceKey, timestamp); } - public async filterOutNotifiedErrorDevices(devices: IOlmDevice[]): Promise { - return await this.cryptoStore.filterOutNotifiedErrorDevices(devices); + public filterOutNotifiedErrorDevices(devices: IOlmDevice[]): Promise { + return this.cryptoStore.filterOutNotifiedErrorDevices(devices); } // Outbound group session diff --git a/src/crypto/OutgoingRoomKeyRequestManager.ts b/src/crypto/OutgoingRoomKeyRequestManager.ts index e053d8072..832294110 100644 --- a/src/crypto/OutgoingRoomKeyRequestManager.ts +++ b/src/crypto/OutgoingRoomKeyRequestManager.ts @@ -189,9 +189,7 @@ export class OutgoingRoomKeyRequestManager { // in state ROOM_KEY_REQUEST_STATES.SENT, so we must have // raced with another tab to mark the request cancelled. // Try again, to make sure the request is resent. - return await this.queueRoomKeyRequest( - requestBody, recipients, resend, - ); + return this.queueRoomKeyRequest(requestBody, recipients, resend); } // We don't want to wait for the timer, so we send it diff --git a/src/crypto/SecretStorage.ts b/src/crypto/SecretStorage.ts index b0c7891d0..f36b66c92 100644 --- a/src/crypto/SecretStorage.ts +++ b/src/crypto/SecretStorage.ts @@ -329,7 +329,7 @@ export class SecretStorage { // encoded, since this is how a key would normally be stored. if (encInfo.passthrough) return encodeBase64(decryption.get_private_key()); - return await decryption.decrypt(encInfo); + return decryption.decrypt(encInfo); } finally { if (decryption && decryption.free) decryption.free(); } @@ -345,15 +345,10 @@ export class SecretStorage { * with, or null if it is not present or not encrypted with a trusted * key */ - public async isStored(name: string, checkKey: boolean): Promise | null> { + public async isStored(name: string, checkKey = true): Promise | null> { // check if secret exists const secretInfo = await this.accountDataAdapter.getAccountDataFromServer(name); - if (!secretInfo) return null; - if (!secretInfo.encrypted) { - return null; - } - - if (checkKey === undefined) checkKey = true; + if (!secretInfo?.encrypted) return null; const ret = {}; @@ -598,11 +593,11 @@ export class SecretStorage { if (keys[keyId].algorithm === SECRET_STORAGE_ALGORITHM_V1_AES) { const decryption = { - encrypt: async function(secret: string): Promise { - return await encryptAES(secret, privateKey, name); + encrypt: function(secret: string): Promise { + return encryptAES(secret, privateKey, name); }, - decrypt: async function(encInfo: IEncryptedPayload): Promise { - return await decryptAES(encInfo, privateKey, name); + decrypt: function(encInfo: IEncryptedPayload): Promise { + return decryptAES(encInfo, privateKey, name); }, }; return [keyId, decryption]; diff --git a/src/crypto/aes.ts b/src/crypto/aes.ts index 077c0afd0..4aa38ac54 100644 --- a/src/crypto/aes.ts +++ b/src/crypto/aes.ts @@ -250,7 +250,7 @@ async function deriveKeysBrowser(key: Uint8Array, name: string): Promise<[Crypto ['sign', 'verify'], ); - return await Promise.all([aesProm, hmacProm]); + return Promise.all([aesProm, hmacProm]); } export function encryptAES(data: string, key: Uint8Array, name: string, ivStr?: string): Promise { diff --git a/src/crypto/algorithms/olm.ts b/src/crypto/algorithms/olm.ts index 369178737..c640d14ef 100644 --- a/src/crypto/algorithms/olm.ts +++ b/src/crypto/algorithms/olm.ts @@ -70,7 +70,7 @@ class OlmEncryption extends EncryptionAlgorithm { return Promise.resolve(); } - this.prepPromise = this.crypto.downloadKeys(roomMembers).then((res) => { + this.prepPromise = this.crypto.downloadKeys(roomMembers).then(() => { return this.crypto.ensureOlmSessionsForUsers(roomMembers); }).then(() => { this.sessionPrepared = true; @@ -144,7 +144,7 @@ class OlmEncryption extends EncryptionAlgorithm { } } - return await Promise.all(promises).then(() => encryptedContent); + return Promise.all(promises).then(() => encryptedContent); } } @@ -261,7 +261,7 @@ class OlmDecryption extends DecryptionAlgorithm { * * @return {string} payload, if decrypted successfully. */ - private async decryptMessage(theirDeviceIdentityKey: string, message: IMessage): Promise { + private decryptMessage(theirDeviceIdentityKey: string, message: IMessage): Promise { // This is a wrapper that serialises decryptions of prekey messages, because // otherwise we race between deciding we have no active sessions for the message // and creating a new one, which we can only do once because it removes the OTK. @@ -274,7 +274,7 @@ class OlmDecryption extends DecryptionAlgorithm { }); // we want the error, but don't propagate it to the next decryption this.olmDevice.olmPrekeyPromise = myPromise.catch(() => {}); - return await myPromise; + return myPromise; } } diff --git a/src/crypto/backup.ts b/src/crypto/backup.ts index eddbabe11..c68e5def5 100644 --- a/src/crypto/backup.ts +++ b/src/crypto/backup.ts @@ -132,18 +132,18 @@ export class BackupManager { if (!Algorithm) { throw new Error("Unknown backup algorithm: " + info.algorithm); } - if (!(typeof info.auth_data === "object")) { + if (typeof info.auth_data !== "object") { throw new Error("Invalid backup data returned"); } return Algorithm.checkBackupVersion(info); } - public static async makeAlgorithm(info: IKeyBackupInfo, getKey: GetKey): Promise { + public static makeAlgorithm(info: IKeyBackupInfo, getKey: GetKey): Promise { const Algorithm = algorithmsByName[info.algorithm]; if (!Algorithm) { throw new Error("Unknown backup algorithm"); } - return await Algorithm.init(info.auth_data, getKey); + return Algorithm.init(info.auth_data, getKey); } public async enableKeyBackup(info: IKeyBackupInfo): Promise { @@ -777,15 +777,15 @@ export class Aes256 implements BackupAlgorithm { public get untrusted() { return false; } - async encryptSession(data: Record): Promise { + public encryptSession(data: Record): Promise { const plainText: Record = Object.assign({}, data); delete plainText.session_id; delete plainText.room_id; delete plainText.first_known_index; - return await encryptAES(JSON.stringify(plainText), this.key, data.session_id); + return encryptAES(JSON.stringify(plainText), this.key, data.session_id); } - async decryptSessions(sessions: Record): Promise { + public async decryptSessions(sessions: Record): Promise { const keys: IMegolmSessionData[] = []; for (const [sessionId, sessionData] of Object.entries(sessions)) { @@ -800,7 +800,7 @@ export class Aes256 implements BackupAlgorithm { return keys; } - async keyMatches(key: Uint8Array): Promise { + public async keyMatches(key: Uint8Array): Promise { if (this.authData.mac) { const { mac } = await calculateKeyCheck(key, this.authData.iv); return this.authData.mac.replace(/=+$/g, '') === mac.replace(/=+/g, ''); diff --git a/src/crypto/dehydration.ts b/src/crypto/dehydration.ts index 492344818..b775d7606 100644 --- a/src/crypto/dehydration.ts +++ b/src/crypto/dehydration.ts @@ -61,11 +61,13 @@ export class DehydrationManager { private key: Uint8Array; private keyInfo: {[props: string]: any}; private deviceDisplayName: string; + constructor(private readonly crypto: Crypto) { this.getDehydrationKeyFromCache(); } - async getDehydrationKeyFromCache(): Promise { - return await this.crypto.cryptoStore.doTxn( + + public getDehydrationKeyFromCache(): Promise { + return this.crypto.cryptoStore.doTxn( 'readonly', [IndexedDBCryptoStore.STORE_ACCOUNT], (txn) => { @@ -93,7 +95,7 @@ export class DehydrationManager { } /** set the key, and queue periodic dehydration to the server in the background */ - async setKeyAndQueueDehydration( + public async setKeyAndQueueDehydration( key: Uint8Array, keyInfo: {[props: string]: any} = {}, deviceDisplayName: string = undefined, ): Promise { @@ -104,7 +106,7 @@ export class DehydrationManager { } } - async setKey( + public async setKey( key: Uint8Array, keyInfo: {[props: string]: any} = {}, deviceDisplayName: string = undefined, ): Promise { @@ -148,7 +150,7 @@ export class DehydrationManager { } /** returns the device id of the newly created dehydrated device */ - async dehydrateDevice(): Promise { + public async dehydrateDevice(): Promise { if (this.inProgress) { logger.log("Dehydration already in progress -- not starting new dehydration"); return; diff --git a/src/crypto/index.ts b/src/crypto/index.ts index 201545e80..0842dda53 100644 --- a/src/crypto/index.ts +++ b/src/crypto/index.ts @@ -402,7 +402,7 @@ export class Crypto extends TypedEventEmitter { +export function keyFromAuthData(authData: IAuthData, password: string): Promise { if (!global.Olm) { throw new Error("Olm is not available"); } @@ -50,7 +50,7 @@ export async function keyFromAuthData(authData: IAuthData, password: string): Pr ); } - return await deriveKey( + return deriveKey( password, authData.private_key_salt, authData.private_key_iterations, authData.private_key_bits || DEFAULT_BITSIZE, diff --git a/src/crypto/verification/SAS.ts b/src/crypto/verification/SAS.ts index a909ce742..93244464f 100644 --- a/src/crypto/verification/SAS.ts +++ b/src/crypto/verification/SAS.ts @@ -271,9 +271,9 @@ export class SAS extends Base { do { try { if (this.initiatedByMe) { - return await this.doSendVerification(); + return this.doSendVerification(); } else { - return await this.doRespondVerification(); + return this.doRespondVerification(); } } catch (err) { if (err instanceof SwitchStartEventError) { diff --git a/src/crypto/verification/request/InRoomChannel.ts b/src/crypto/verification/request/InRoomChannel.ts index 9e8690e1d..67082ff83 100644 --- a/src/crypto/verification/request/InRoomChannel.ts +++ b/src/crypto/verification/request/InRoomChannel.ts @@ -184,7 +184,7 @@ export class InRoomChannel implements IVerificationChannel { * @param {boolean} isLiveEvent whether this is an even received through sync or not * @returns {Promise} a promise that resolves when any requests as an answer to the passed-in event are sent. */ - public async handleEvent(event: MatrixEvent, request: VerificationRequest, isLiveEvent = false): Promise { + public handleEvent(event: MatrixEvent, request: VerificationRequest, isLiveEvent = false): Promise { // prevent processing the same event multiple times, as under // some circumstances Room.timeline can get emitted twice for the same event if (request.hasEventId(event.getId())) { @@ -221,8 +221,7 @@ export class InRoomChannel implements IVerificationChannel { const isRemoteEcho = !!event.getUnsigned().transaction_id; const isSentByUs = event.getSender() === this.client.getUserId(); - return await request.handleEvent( - type, event, isLiveEvent, isRemoteEcho, isSentByUs); + return request.handleEvent(type, event, isLiveEvent, isRemoteEcho, isSentByUs); } /** diff --git a/src/http-api.ts b/src/http-api.ts index 5ee24312a..c5c7517fd 100644 --- a/src/http-api.ts +++ b/src/http-api.ts @@ -30,7 +30,7 @@ import type { Request as _Request, CoreOptions } from "request"; import * as callbacks from "./realtime-callbacks"; import { IUploadOpts } from "./@types/requests"; import { IAbortablePromise, IUsageLimit } from "./@types/partials"; -import { IDeferred } from "./utils"; +import { IDeferred, sleep } from "./utils"; import { Callback } from "./client"; import * as utils from "./utils"; import { logger } from './logger'; @@ -1114,9 +1114,9 @@ export async function retryNetworkOperation(maxAttempts: number, callback: () const timeout = 1000 * Math.pow(2, attempts); logger.log(`network operation failed ${attempts} times,` + ` retrying in ${timeout}ms...`); - await new Promise(r => setTimeout(r, timeout)); + await sleep(timeout); } - return await callback(); + return callback(); } catch (err) { if (err instanceof ConnectionError) { attempts += 1; diff --git a/src/matrix.ts b/src/matrix.ts index 5379b461a..c85544e66 100644 --- a/src/matrix.ts +++ b/src/matrix.ts @@ -17,8 +17,7 @@ limitations under the License. import { MemoryCryptoStore } from "./crypto/store/memory-crypto-store"; import { MemoryStore } from "./store/memory"; import { MatrixScheduler } from "./scheduler"; -import { MatrixClient } from "./client"; -import { ICreateClientOpts } from "./client"; +import { MatrixClient, ICreateClientOpts } from "./client"; import { DeviceTrustLevel } from "./crypto/CrossSigning"; import { ISecretStorageKeyInfo } from "./crypto/api"; diff --git a/src/pushprocessor.ts b/src/pushprocessor.ts index ae170751f..2f4f58bd4 100644 --- a/src/pushprocessor.ts +++ b/src/pushprocessor.ts @@ -300,7 +300,7 @@ export class PushProcessor { const memberCount = room.currentState.getJoinedMemberCount(); - const m = cond.is.match(/^([=<>]*)([0-9]*)$/); + const m = cond.is.match(/^([=<>]*)(\d*)$/); if (!m) { return false; } diff --git a/src/utils.ts b/src/utils.ts index 95e415502..777531286 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -465,7 +465,7 @@ export function defer(): IDeferred { export async function promiseMapSeries( promises: Array>, - fn: (t: T) => void, + fn: (t: T) => Promise | void, // if async/promise we don't care about the type as we only await resolution ): Promise { for (const o of promises) { await fn(await o); @@ -473,7 +473,7 @@ export async function promiseMapSeries( } export function promiseTry(fn: () => T | Promise): Promise { - return new Promise((resolve) => resolve(fn())); + return Promise.resolve(fn()); } // Creates and awaits all promises, running no more than `chunkSize` at the same time @@ -676,7 +676,13 @@ export function prevString(s: string, alphabet = DEFAULT_ALPHABET): string { export function lexicographicCompare(a: string, b: string): number { // Dev note: this exists because I'm sad that you can use math operators on strings, so I've // hidden the operation in this function. - return (a < b) ? -1 : ((a === b) ? 0 : 1); + if (a < b) { + return -1; + } else if (a > b) { + return 1; + } else { + return 0; + } } const collator = new Intl.Collator(); diff --git a/src/webrtc/call.ts b/src/webrtc/call.ts index 16f443b4b..dcc1016a6 100644 --- a/src/webrtc/call.ts +++ b/src/webrtc/call.ts @@ -988,9 +988,7 @@ export class MatrixCall extends TypedEventEmitter { + public async setScreensharingEnabled(enabled: boolean, desktopCapturerSourceId?: string): Promise { // Skip if there is nothing to do if (enabled && this.isScreensharing()) { logger.warn(`There is already a screensharing stream - there is nothing to do!`); @@ -1002,7 +1000,7 @@ export class MatrixCall extends TypedEventEmitter