1
0
mirror of https://github.com/matrix-org/matrix-js-sdk.git synced 2025-11-25 05:23:13 +03:00

Enforce logger module via lint rules

This adds lint rules (and fixes various errors) to ensure we use the `logger`
intermediary module, rather than accessing the console directly.
This commit is contained in:
J. Ryan Stinnett
2020-10-01 14:28:22 +01:00
parent fa9921e091
commit 09bd91a588
16 changed files with 33 additions and 22 deletions

View File

@@ -28,6 +28,8 @@ module.exports = {
"indent": "off", "indent": "off",
"no-constant-condition": "off", "no-constant-condition": "off",
"no-async-promise-executor": "off", "no-async-promise-executor": "off",
// We use a `logger` intermediary module
"no-console": "error",
}, },
overrides: [{ overrides: [{
"files": ["src/**/*.ts"], "files": ["src/**/*.ts"],

View File

@@ -31,5 +31,5 @@ try {
const crypto = require('crypto'); const crypto = require('crypto');
utils.setCrypto(crypto); utils.setCrypto(crypto);
} catch (err) { } catch (err) {
console.log('nodejs was compiled without crypto support: some tests will fail'); logger.log('nodejs was compiled without crypto support: some tests will fail');
} }

View File

@@ -26,6 +26,7 @@ import {MemoryCryptoStore} from '../../../src/crypto/store/memory-crypto-store';
import 'fake-indexeddb/auto'; import 'fake-indexeddb/auto';
import 'jest-localstorage-mock'; import 'jest-localstorage-mock';
import {OlmDevice} from "../../../src/crypto/OlmDevice"; import {OlmDevice} from "../../../src/crypto/OlmDevice";
import {logger} from '../../../src/logger';
const userId = "@alice:example.com"; const userId = "@alice:example.com";
@@ -51,7 +52,7 @@ const masterKeyPub = "nqOvzeuGWT/sRx3h7+MHoInYj3Uk2LD/unI9kDYcHwk";
describe("CrossSigningInfo.getCrossSigningKey", function() { describe("CrossSigningInfo.getCrossSigningKey", function() {
if (!global.Olm) { if (!global.Olm) {
console.warn('Not running megolm backup unit tests: libolm not present'); logger.warn('Not running megolm backup unit tests: libolm not present');
return; return;
} }

View File

@@ -22,6 +22,7 @@ import {TestClient} from '../../TestClient';
import {HttpResponse, setHttpResponses} from '../../test-utils'; import {HttpResponse, setHttpResponses} from '../../test-utils';
import { resetCrossSigningKeys } from "./crypto-utils"; import { resetCrossSigningKeys } from "./crypto-utils";
import { MatrixError } from '../../../src/http-api'; import { MatrixError } from '../../../src/http-api';
import {logger} from '../../../src/logger';
async function makeTestClient(userInfo, options, keys) { async function makeTestClient(userInfo, options, keys) {
if (!keys) keys = {}; if (!keys) keys = {};
@@ -49,7 +50,7 @@ async function makeTestClient(userInfo, options, keys) {
describe("Cross Signing", function() { describe("Cross Signing", function() {
if (!global.Olm) { if (!global.Olm) {
console.warn('Not running megolm backup unit tests: libolm not present'); logger.warn('Not running megolm backup unit tests: libolm not present');
return; return;
} }

View File

@@ -22,6 +22,7 @@ import {TestClient} from '../../TestClient';
import {makeTestClients} from './verification/util'; import {makeTestClients} from './verification/util';
import {encryptAES} from "../../../src/crypto/aes"; import {encryptAES} from "../../../src/crypto/aes";
import {resetCrossSigningKeys, createSecretStorageKey} from "./crypto-utils"; import {resetCrossSigningKeys, createSecretStorageKey} from "./crypto-utils";
import {logger} from '../../../src/logger';
import * as utils from "../../../src/utils"; import * as utils from "../../../src/utils";
@@ -29,7 +30,7 @@ try {
const crypto = require('crypto'); const crypto = require('crypto');
utils.setCrypto(crypto); utils.setCrypto(crypto);
} catch (err) { } catch (err) {
console.log('nodejs was compiled without crypto support'); logger.log('nodejs was compiled without crypto support');
} }
async function makeTestClient(userInfo, options) { async function makeTestClient(userInfo, options) {
@@ -60,7 +61,7 @@ function sign(obj, key, userId) {
describe("Secrets", function() { describe("Secrets", function() {
if (!global.Olm) { if (!global.Olm) {
console.warn('Not running megolm backup unit tests: libolm not present'); logger.warn('Not running megolm backup unit tests: libolm not present');
return; return;
} }

View File

@@ -18,12 +18,13 @@ limitations under the License.
import {TestClient} from '../../../TestClient'; import {TestClient} from '../../../TestClient';
import {MatrixEvent} from "../../../../src/models/event"; import {MatrixEvent} from "../../../../src/models/event";
import nodeCrypto from "crypto"; import nodeCrypto from "crypto";
import {logger} from '../../../../src/logger';
export async function makeTestClients(userInfos, options) { export async function makeTestClients(userInfos, options) {
const clients = []; const clients = [];
const clientMap = {}; const clientMap = {};
const sendToDevice = function(type, map) { const sendToDevice = function(type, map) {
// console.log(this.getUserId(), "sends", type, map); // logger.log(this.getUserId(), "sends", type, map);
for (const [userId, devMap] of Object.entries(map)) { for (const [userId, devMap] of Object.entries(map)) {
if (userId in clientMap) { if (userId in clientMap) {
for (const [deviceId, msg] of Object.entries(devMap)) { for (const [deviceId, msg] of Object.entries(devMap)) {
@@ -67,7 +68,7 @@ export async function makeTestClients(userInfos, options) {
setImmediate(() => { setImmediate(() => {
for (const tc of clients) { for (const tc of clients) {
if (tc.client === this) { // eslint-disable-line babel/no-invalid-this if (tc.client === this) { // eslint-disable-line babel/no-invalid-this
console.log("sending remote echo!!"); logger.log("sending remote echo!!");
tc.client.emit("Room.timeline", remoteEcho); tc.client.emit("Room.timeline", remoteEcho);
} else { } else {
tc.client.emit("Room.timeline", event); tc.client.emit("Room.timeline", event);

View File

@@ -2054,7 +2054,7 @@ MatrixClient.prototype._restoreKeyBackup = function(
// This is async. // This is async.
this._crypto.storeSessionBackupPrivateKey(privKey) this._crypto.storeSessionBackupPrivateKey(privKey)
.catch((e) => { .catch((e) => {
console.warn("Error caching session backup key:", e); logger.warn("Error caching session backup key:", e);
}).then(cacheCompleteCallback); }).then(cacheCompleteCallback);
if (progressCallback) { if (progressCallback) {

View File

@@ -734,7 +734,7 @@ export async function requestKeysDuringVerification(baseApis, userId, deviceId)
if (baseApis.getUserId() !== userId) { if (baseApis.getUserId() !== userId) {
return; return;
} }
console.log("Cross-signing: Self-verification done; requesting keys"); logger.log("Cross-signing: Self-verification done; requesting keys");
// This happens asynchronously, and we're not concerned about waiting for // This happens asynchronously, and we're not concerned about waiting for
// it. We return here in order to test. // it. We return here in order to test.
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
@@ -748,7 +748,7 @@ export async function requestKeysDuringVerification(baseApis, userId, deviceId)
const crossSigning = new CrossSigningInfo( const crossSigning = new CrossSigningInfo(
original.userId, original.userId,
{ getCrossSigningKey: async (type) => { { getCrossSigningKey: async (type) => {
console.debug("Cross-signing: requesting secret", logger.debug("Cross-signing: requesting secret",
type, deviceId); type, deviceId);
const { promise } = client.requestSecret( const { promise } = client.requestSecret(
`m.cross_signing.${type}`, [deviceId], `m.cross_signing.${type}`, [deviceId],
@@ -811,6 +811,6 @@ export async function requestKeysDuringVerification(baseApis, userId, deviceId)
timeout, timeout,
]).then(resolve, reject); ]).then(resolve, reject);
}).catch((e) => { }).catch((e) => {
console.warn("Cross-signing: failure while requesting keys:", e); logger.warn("Cross-signing: failure while requesting keys:", e);
}); });
} }

View File

@@ -144,7 +144,7 @@ OlmDevice.prototype.init = async function(opts = {}) {
try { try {
if (fromExportedDevice) { if (fromExportedDevice) {
if (pickleKey) { if (pickleKey) {
console.warn( logger.warn(
'ignoring opts.pickleKey' 'ignoring opts.pickleKey'
+ ' because opts.fromExportedDevice is present.', + ' because opts.fromExportedDevice is present.',
); );

View File

@@ -247,7 +247,7 @@ export class SecretStorage extends EventEmitter {
) { ) {
const hasKey = await this.hasKey(keys[0]); const hasKey = await this.hasKey(keys[0]);
if (hasKey) { if (hasKey) {
console.log("Fixing up passthrough secret: " + name); logger.log("Fixing up passthrough secret: " + name);
await this.storePassthrough(name, keys[0]); await this.storePassthrough(name, keys[0]);
const newData = await this._baseApis.getAccountDataFromServer(name); const newData = await this._baseApis.getAccountDataFromServer(name);
return newData; return newData;

View File

@@ -146,7 +146,7 @@ export function Crypto(baseApis, sessionStore, userId, deviceId,
method, method,
); );
} else { } else {
console.warn(`Excluding unknown verification method ${method}`); logger.warn(`Excluding unknown verification method ${method}`);
} }
} }
} else { } else {

View File

@@ -26,6 +26,7 @@ import {
newUserCancelledError, newUserCancelledError,
} from './Error'; } from './Error';
import {encodeUnpaddedBase64, decodeBase64} from "../olmlib"; import {encodeUnpaddedBase64, decodeBase64} from "../olmlib";
import {logger} from '../../logger';
export const SHOW_QR_CODE_METHOD = "m.qr_code.show.v1"; export const SHOW_QR_CODE_METHOD = "m.qr_code.show.v1";
export const SCAN_QR_CODE_METHOD = "m.qr_code.scan.v1"; export const SCAN_QR_CODE_METHOD = "m.qr_code.scan.v1";
@@ -94,7 +95,7 @@ export class ReciprocateQRCode extends Base {
if (!targetKey) throw newKeyMismatchError(); if (!targetKey) throw newKeyMismatchError();
if (keyInfo !== targetKey) { if (keyInfo !== targetKey) {
console.error("key ID from key info does not match"); logger.error("key ID from key info does not match");
throw newKeyMismatchError(); throw newKeyMismatchError();
} }
for (const deviceKeyId in device.keys) { for (const deviceKeyId in device.keys) {
@@ -102,7 +103,7 @@ export class ReciprocateQRCode extends Base {
const deviceTargetKey = keys[deviceKeyId]; const deviceTargetKey = keys[deviceKeyId];
if (!deviceTargetKey) throw newKeyMismatchError(); if (!deviceTargetKey) throw newKeyMismatchError();
if (device.keys[deviceKeyId] !== deviceTargetKey) { if (device.keys[deviceKeyId] !== deviceTargetKey) {
console.error("master key does not match"); logger.error("master key does not match");
throw newKeyMismatchError(); throw newKeyMismatchError();
} }
} }

View File

@@ -961,7 +961,7 @@ export async function retryNetworkOperation(maxAttempts, callback) {
try { try {
if (attempts > 0) { if (attempts > 0) {
const timeout = 1000 * Math.pow(2, attempts); const timeout = 1000 * Math.pow(2, attempts);
console.log(`network operation failed ${attempts} times,` + logger.log(`network operation failed ${attempts} times,` +
` retrying in ${timeout}ms...`); ` retrying in ${timeout}ms...`);
await new Promise(r => setTimeout(r, timeout)); await new Promise(r => setTimeout(r, timeout));
} }

View File

@@ -40,11 +40,13 @@ log.methodFactory = function(methodName, logLevel, loggerName) {
methodName === "warn" || methodName === "warn" ||
methodName === "trace" || methodName === "trace" ||
methodName === "info"; methodName === "info";
/* eslint-disable no-console */
if (supportedByConsole) { if (supportedByConsole) {
return console[methodName](...args); return console[methodName](...args);
} else { } else {
return console.log(...args); return console.log(...args);
} }
/* eslint-enable no-console */
}; };
}; };

View File

@@ -16,6 +16,7 @@ limitations under the License.
import {EventEmitter} from 'events'; import {EventEmitter} from 'events';
import {EventStatus} from '../models/event'; import {EventStatus} from '../models/event';
import {logger} from '../logger';
/** /**
* A container for relation events that supports easy access to common ways of * A container for relation events that supports easy access to common ways of
@@ -60,7 +61,7 @@ export class Relations extends EventEmitter {
const relation = event.getRelation(); const relation = event.getRelation();
if (!relation) { if (!relation) {
console.error("Event must have relation info"); logger.error("Event must have relation info");
return; return;
} }
@@ -68,7 +69,7 @@ export class Relations extends EventEmitter {
const eventType = event.getType(); const eventType = event.getType();
if (this.relationType !== relationType || this.eventType !== eventType) { if (this.relationType !== relationType || this.eventType !== eventType) {
console.error("Event relation info doesn't match this container"); logger.error("Event relation info doesn't match this container");
return; return;
} }
@@ -104,7 +105,7 @@ export class Relations extends EventEmitter {
const relation = event.getRelation(); const relation = event.getRelation();
if (!relation) { if (!relation) {
console.error("Event must have relation info"); logger.error("Event must have relation info");
return; return;
} }
@@ -112,7 +113,7 @@ export class Relations extends EventEmitter {
const eventType = event.getType(); const eventType = event.getType();
if (this.relationType !== relationType || this.eventType !== eventType) { if (this.relationType !== relationType || this.eventType !== eventType) {
console.error("Event relation info doesn't match this container"); logger.error("Event relation info doesn't match this container");
return; return;
} }

View File

@@ -16,6 +16,7 @@ limitations under the License.
*/ */
import {escapeRegExp, globToRegexp, isNullOrUndefined} from "./utils"; import {escapeRegExp, globToRegexp, isNullOrUndefined} from "./utils";
import {logger} from './logger';
/** /**
* @module pushprocessor * @module pushprocessor
@@ -444,7 +445,7 @@ PushProcessor.rewriteDefaultRules = function(incomingRules) {
} else { } else {
// Add the rule // Add the rule
const ruleId = override.rule_id; const ruleId = override.rule_id;
console.warn(`Adding default global override for ${ruleId}`); logger.warn(`Adding default global override for ${ruleId}`);
globalOverrides.push(override); globalOverrides.push(override);
} }
} }