Merge pull request #116 from matrix-org/yoric/lint

Increasing linting level
This commit is contained in:
David Teller 2021-08-17 10:28:07 +02:00 committed by GitHub
commit bc222e2345
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
19 changed files with 72 additions and 59 deletions

View File

@ -26,7 +26,7 @@ const levelToFn = {
[LogLevel.ERROR.toString()]: LogService.error,
};
export async function logMessage(level: LogLevel, module: string, message: string | any, additionalRoomIds: string[] | string = null, isRecursive = false) {
export async function logMessage(level: LogLevel, module: string, message: string | any, additionalRoomIds: string[] | string | null = null, isRecursive = false) {
if (!additionalRoomIds) additionalRoomIds = [];
if (!Array.isArray(additionalRoomIds)) additionalRoomIds = [additionalRoomIds];

View File

@ -153,7 +153,7 @@ export class Mjolnir {
await logMessage(LogLevel.DEBUG, "Mjolnir@startup", "Loading protected rooms...");
await this.resyncJoinedRooms(false);
try {
const data = await this.client.getAccountData(PROTECTED_ROOMS_EVENT_TYPE);
const data: Object|null = await this.client.getAccountData(PROTECTED_ROOMS_EVENT_TYPE);
if (data && data['rooms']) {
for (const roomId of data['rooms']) {
this.protectedRooms[roomId] = Permalinks.forRoom(roomId);
@ -252,7 +252,7 @@ export class Mjolnir {
private async getEnabledProtections() {
let enabled: string[] = [];
try {
const protections = await this.client.getAccountData(ENABLED_PROTECTIONS_EVENT_TYPE);
const protections: Object|null = await this.client.getAccountData(ENABLED_PROTECTIONS_EVENT_TYPE);
if (protections && protections['enabled']) {
for (const protection of protections['enabled']) {
enabled.push(protection);
@ -296,7 +296,7 @@ export class Mjolnir {
await this.client.setAccountData(ENABLED_PROTECTIONS_EVENT_TYPE, {enabled: existing});
}
public async watchList(roomRef: string): Promise<BanList> {
public async watchList(roomRef: string): Promise<BanList|null> {
const joinedRooms = await this.client.getJoinedRooms();
const permalink = Permalinks.parseUrl(roomRef);
if (!permalink.roomIdOrAlias) return null;
@ -321,12 +321,12 @@ export class Mjolnir {
return list;
}
public async unwatchList(roomRef: string): Promise<BanList> {
public async unwatchList(roomRef: string): Promise<BanList|null> {
const permalink = Permalinks.parseUrl(roomRef);
if (!permalink.roomIdOrAlias) return null;
const roomId = await this.client.resolveRoom(permalink.roomIdOrAlias);
const list = this.banLists.find(b => b.roomId === roomId);
const list = this.banLists.find(b => b.roomId === roomId) || null;
if (list) this.banLists.splice(this.banLists.indexOf(list), 1);
await this.client.setAccountData(WATCHED_LISTS_EVENT_TYPE, {
@ -347,7 +347,7 @@ export class Mjolnir {
this.applyUnprotectedRooms();
try {
const accountData = await this.client.getAccountData(WARN_UNPROTECTED_ROOM_EVENT_PREFIX + roomId);
const accountData: Object|null = await this.client.getAccountData(WARN_UNPROTECTED_ROOM_EVENT_PREFIX + roomId);
if (accountData && accountData['warned']) return; // already warned
} catch (e) {
// Ignore - probably haven't warned about it yet
@ -595,7 +595,7 @@ export class Mjolnir {
}
}
private async printActionResult(errors: RoomUpdateError[], title: string = null, logAnyways = false) {
private async printActionResult(errors: RoomUpdateError[], title: string|null = null, logAnyways = false) {
if (errors.length <= 0) return false;
if (!logAnyways) {

View File

@ -33,7 +33,6 @@ import { redactUserMessagesIn } from "../utils";
export async function applyUserBans(lists: BanList[], roomIds: string[], mjolnir: Mjolnir): Promise<RoomUpdateError[]> {
// We can only ban people who are not already banned, and who match the rules.
const errors: RoomUpdateError[] = [];
let bansApplied = 0;
for (const roomId of roomIds) {
try {
// We specifically use sendNotice to avoid having to escape HTML
@ -76,7 +75,6 @@ export async function applyUserBans(lists: BanList[], roomIds: string[], mjolnir
await logMessage(LogLevel.WARN, "ApplyBan", `Tried to ban ${member.userId} in ${roomId} but Mjolnir is running in no-op mode`, roomId);
}
bansApplied++;
banned = true;
break;
}

View File

@ -23,7 +23,8 @@ async function addRemoveFromDirectory(inRoomId: string, event: any, mjolnir: Mjo
const message = "I am not a Synapse administrator, or the endpoint is blocked";
const reply = RichReply.createFor(inRoomId, event, message, message);
reply['msgtype'] = "m.notice";
return mjolnir.client.sendMessage(inRoomId, reply);
mjolnir.client.sendMessage(inRoomId, reply);
return;
}
const targetRoomId = await mjolnir.client.resolveRoom(roomRef);

View File

@ -28,7 +28,8 @@ export async function execMoveAliasCommand(roomId: string, event: any, mjolnir:
const message = "I am not a Synapse administrator, or the endpoint is blocked";
const reply = RichReply.createFor(roomId, event, message, message);
reply['msgtype'] = "m.notice";
return mjolnir.client.sendMessage(roomId, reply);
mjolnir.client.sendMessage(roomId, reply);
return;
}
await mjolnir.client.deleteRoomAlias(movingAlias);
@ -48,7 +49,8 @@ export async function execAddAliasCommand(roomId: string, event: any, mjolnir: M
const message = "I am not a Synapse administrator, or the endpoint is blocked";
const reply = RichReply.createFor(roomId, event, message, message);
reply['msgtype'] = "m.notice";
return mjolnir.client.sendMessage(roomId, reply);
mjolnir.client.sendMessage(roomId, reply);
return;
}
const newRoomId = await mjolnir.client.resolveRoom(targetRoom);
@ -66,7 +68,8 @@ export async function execRemoveAliasCommand(roomId: string, event: any, mjolnir
const message = "I am not a Synapse administrator, or the endpoint is blocked";
const reply = RichReply.createFor(roomId, event, message, message);
reply['msgtype'] = "m.notice";
return mjolnir.client.sendMessage(roomId, reply);
mjolnir.client.sendMessage(roomId, reply);
return;
}
await mjolnir.client.deleteRoomAlias(aliasToRemove);

View File

@ -26,7 +26,8 @@ export async function execDeactivateCommand(roomId: string, event: any, mjolnir:
const message = "I am not a Synapse administrator, or the endpoint is blocked";
const reply = RichReply.createFor(roomId, event, message, message);
reply['msgtype'] = "m.notice";
return mjolnir.client.sendMessage(roomId, reply);
mjolnir.client.sendMessage(roomId, reply);
return;
}
await mjolnir.deactivateSynapseUser(victim);

View File

@ -28,7 +28,8 @@ export async function execImportCommand(roomId: string, event: any, mjolnir: Mjo
const errMessage = "Unable to find list - check your shortcode.";
const errReply = RichReply.createFor(roomId, event, errMessage, errMessage);
errReply["msgtype"] = "m.notice";
return mjolnir.client.sendMessage(roomId, errReply);
mjolnir.client.sendMessage(roomId, errReply);
return;
}
let importedRules = 0;
@ -52,7 +53,10 @@ export async function execImportCommand(roomId: string, event: any, mjolnir: Mjo
reason: reason,
};
const stateKey = `rule:${ruleContent.entity}`;
await mjolnir.client.sendStateEvent(list.roomId, ruleTypeToStable(RULE_USER), stateKey, ruleContent);
let stableRule = ruleTypeToStable(RULE_USER);
if (stableRule) {
await mjolnir.client.sendStateEvent(list.roomId, stableRule, stateKey, ruleContent);
}
importedRules++;
}
} else if (stateEvent['type'] === 'm.room.server_acl' && stateEvent['state_key'] === '') {
@ -70,7 +74,10 @@ export async function execImportCommand(roomId: string, event: any, mjolnir: Mjo
reason: reason,
};
const stateKey = `rule:${ruleContent.entity}`;
await mjolnir.client.sendStateEvent(list.roomId, ruleTypeToStable(RULE_SERVER), stateKey, ruleContent);
let stableRule = ruleTypeToStable(RULE_SERVER);
if (stableRule) {
await mjolnir.client.sendStateEvent(list.roomId, stableRule, stateKey, ruleContent);
}
importedRules++;
}
}

View File

@ -15,19 +15,9 @@ limitations under the License.
*/
import { Mjolnir } from "../Mjolnir";
import BanList, { RULE_ROOM, RULE_SERVER, RULE_USER, USER_RULE_TYPES } from "../models/BanList";
import { LogLevel, LogService, MatrixGlob, RichReply } from "matrix-bot-sdk";
import { RECOMMENDATION_BAN, recommendationToStable } from "../models/ListRule";
import { LogLevel } from "matrix-bot-sdk";
import config from "../config";
import { logMessage } from "../LogProxy";
import { DEFAULT_LIST_EVENT_TYPE } from "./SetDefaultBanListCommand";
interface Arguments {
list: BanList;
entity: string;
ruleType: string;
reason: string;
}
// !mjolnir kick <user> [room] [reason]
export async function execKickCommand(roomId: string, event: any, mjolnir: Mjolnir, parts: string[]) {

View File

@ -21,8 +21,8 @@ import { Permalinks } from "matrix-bot-sdk";
// !mjolnir redact <user ID> [room alias] [limit]
export async function execRedactCommand(roomId: string, event: any, mjolnir: Mjolnir, parts: string[]) {
const userId = parts[2];
let roomAlias = null;
let limit = Number.parseInt(parts.length > 3 ? parts[3] : null, 10); // default to NaN for later
let roomAlias: string|null = null;
let limit = Number.parseInt(parts.length > 3 ? parts[3] : "", 10); // default to NaN for later
if (parts.length > 3 && isNaN(limit)) {
roomAlias = await mjolnir.client.resolveRoom(parts[3]);
if (parts.length > 4) {

View File

@ -27,7 +27,8 @@ export async function execSetDefaultListCommand(roomId: string, event: any, mjol
const replyText = "No ban list with that shortcode was found.";
const reply = RichReply.createFor(roomId, event, replyText, replyText);
reply["msgtype"] = "m.notice";
return mjolnir.client.sendMessage(roomId, reply);
mjolnir.client.sendMessage(roomId, reply);
return;
}
await mjolnir.client.setAccountData(DEFAULT_LIST_EVENT_TYPE, {shortcode});

View File

@ -26,7 +26,8 @@ export async function execShutdownRoomCommand(roomId: string, event: any, mjolni
const message = "I am not a Synapse administrator, or the endpoint is blocked";
const reply = RichReply.createFor(roomId, event, message, message);
reply['msgtype'] = "m.notice";
return mjolnir.client.sendMessage(roomId, reply);
mjolnir.client.sendMessage(roomId, reply);
return;
}
await mjolnir.shutdownSynapseRoom(await mjolnir.client.resolveRoom(victim));

View File

@ -23,17 +23,17 @@ import { logMessage } from "../LogProxy";
import { DEFAULT_LIST_EVENT_TYPE } from "./SetDefaultBanListCommand";
interface Arguments {
list: BanList;
list: BanList | null;
entity: string;
ruleType: string;
ruleType: string | null;
reason: string;
}
// Exported for tests
export async function parseArguments(roomId: string, event: any, mjolnir: Mjolnir, parts: string[]): Promise<Arguments> {
export async function parseArguments(roomId: string, event: any, mjolnir: Mjolnir, parts: string[]): Promise<Arguments|null> {
let defaultShortcode = null;
try {
const data = await mjolnir.client.getAccountData(DEFAULT_LIST_EVENT_TYPE);
const data: Object = await mjolnir.client.getAccountData(DEFAULT_LIST_EVENT_TYPE);
defaultShortcode = data['shortcode'];
} catch (e) {
LogService.warn("UnbanBanCommand", "Non-fatal error getting default ban list");
@ -43,9 +43,9 @@ export async function parseArguments(roomId: string, event: any, mjolnir: Mjolni
}
let argumentIndex = 2;
let ruleType = null;
let entity = null;
let list = null;
let ruleType: string | null = null;
let entity: string | null = null;
let list: BanList | null = null;
let force = false;
while (argumentIndex < 7 && argumentIndex < parts.length) {
const arg = parts[argumentIndex++];
@ -62,7 +62,7 @@ export async function parseArguments(roomId: string, event: any, mjolnir: Mjolni
else if (!ruleType) ruleType = RULE_SERVER;
} else if (!list) {
const foundList = mjolnir.lists.find(b => b.listShortcode.toLowerCase() === arg.toLowerCase());
if (foundList) {
if (foundList !== undefined) {
list = foundList;
}
}
@ -88,10 +88,10 @@ export async function parseArguments(roomId: string, event: any, mjolnir: Mjolni
}
if (!list) {
list = mjolnir.lists.find(b => b.listShortcode.toLowerCase() === defaultShortcode);
list = mjolnir.lists.find(b => b.listShortcode.toLowerCase() === defaultShortcode) || null;
}
let replyMessage = null;
let replyMessage: string | null = null;
if (!list) replyMessage = "No ban list matching that shortcode was found";
else if (!ruleType) replyMessage = "Please specify the type as either 'user', 'room', or 'server'";
else if (!entity) replyMessage = "No entity found";
@ -128,7 +128,7 @@ export async function execBanCommand(roomId: string, event: any, mjolnir: Mjolni
};
const stateKey = `rule:${bits.entity}`;
await mjolnir.client.sendStateEvent(bits.list.roomId, bits.ruleType, stateKey, ruleContent);
await mjolnir.client.sendStateEvent(bits.list!.roomId, bits.ruleType!, stateKey, ruleContent);
await mjolnir.client.unstableApis.addReactionToEvent(roomId, event['event_id'], '✅');
}
@ -140,14 +140,14 @@ export async function execUnbanCommand(roomId: string, event: any, mjolnir: Mjol
const ruleContent = {}; // empty == clear/unban
const stateKey = `rule:${bits.entity}`;
await mjolnir.client.sendStateEvent(bits.list.roomId, bits.ruleType, stateKey, ruleContent);
await mjolnir.client.sendStateEvent(bits.list!.roomId, bits.ruleType!, stateKey, ruleContent);
if (USER_RULE_TYPES.includes(bits.ruleType) && bits.reason === 'true') {
if (USER_RULE_TYPES.includes(bits.ruleType!) && bits.reason === 'true') {
const rule = new MatrixGlob(bits.entity);
await logMessage(LogLevel.INFO, "UnbanBanCommand", "Unbanning users that match glob: " + bits.entity);
let unbannedSomeone = false;
for (const protectedRoomId of Object.keys(mjolnir.protectedRooms)) {
const members = await mjolnir.client.getRoomMembers(protectedRoomId, null, ['ban'], null);
const members = await mjolnir.client.getRoomMembers(protectedRoomId, undefined, ['ban'], undefined);
await logMessage(LogLevel.DEBUG, "UnbanBanCommand", `Found ${members.length} banned user(s)`);
for (const member of members) {
const victim = member.membershipFor;

View File

@ -24,7 +24,8 @@ export async function execWatchCommand(roomId: string, event: any, mjolnir: Mjol
const replyText = "Cannot watch list due to error - is that a valid room alias?";
const reply = RichReply.createFor(roomId, event, replyText, replyText);
reply["msgtype"] = "m.notice";
return mjolnir.client.sendMessage(roomId, reply);
mjolnir.client.sendMessage(roomId, reply);
return;
}
await mjolnir.client.unstableApis.addReactionToEvent(roomId, event['event_id'], '✅');
}
@ -36,7 +37,8 @@ export async function execUnwatchCommand(roomId: string, event: any, mjolnir: Mj
const replyText = "Cannot unwatch list due to error - is that a valid room alias?";
const reply = RichReply.createFor(roomId, event, replyText, replyText);
reply["msgtype"] = "m.notice";
return mjolnir.client.sendMessage(roomId, reply);
mjolnir.client.sendMessage(roomId, reply);
return;
}
await mjolnir.client.unstableApis.addReactionToEvent(roomId, event['event_id'], '✅');
}

View File

@ -66,7 +66,7 @@ interface IConfig {
* here as much as possible.
*/
RUNTIME: {
client: MatrixClient;
client?: MatrixClient;
};
}
@ -116,7 +116,6 @@ const defaultConfig: IConfig = {
// Needed to make the interface happy.
RUNTIME: {
client: null,
},
};

View File

@ -32,7 +32,7 @@ import { MembershipEvent } from "matrix-bot-sdk/lib/models/events/MembershipEven
import * as htmlEscape from "escape-html";
import { Healthz } from "./health/healthz";
config.RUNTIME = {client: null};
config.RUNTIME = {};
LogService.setLogger(new RichConsoleLogger());
LogService.setLevel(LogLevel.fromString(config.logLevel, LogLevel.DEBUG));

View File

@ -28,7 +28,7 @@ export const ALL_RULE_TYPES = [...USER_RULE_TYPES, ...ROOM_RULE_TYPES, ...SERVER
export const SHORTCODE_EVENT_TYPE = "org.matrix.mjolnir.shortcode";
export function ruleTypeToStable(rule: string, unstable = true): string {
export function ruleTypeToStable(rule: string, unstable = true): string|null {
if (USER_RULE_TYPES.includes(rule)) return unstable ? USER_RULE_TYPES[USER_RULE_TYPES.length - 1] : RULE_USER;
if (ROOM_RULE_TYPES.includes(rule)) return unstable ? ROOM_RULE_TYPES[ROOM_RULE_TYPES.length - 1] : RULE_ROOM;
if (SERVER_RULE_TYPES.includes(rule)) return unstable ? SERVER_RULE_TYPES[SERVER_RULE_TYPES.length - 1] : RULE_SERVER;
@ -37,7 +37,7 @@ export function ruleTypeToStable(rule: string, unstable = true): string {
export default class BanList {
private rules: ListRule[] = [];
private shortcode: string = null;
private shortcode: string|null = null;
constructor(public readonly roomId: string, public readonly roomRef, private client: MatrixClient) {
}
@ -85,7 +85,7 @@ export default class BanList {
continue;
}
let kind: string = null;
let kind: string|null = null;
if (USER_RULE_TYPES.includes(event['type'])) {
kind = RULE_USER;
} else if (ROOM_RULE_TYPES.includes(event['type'])) {

View File

@ -19,7 +19,7 @@ import { MatrixGlob } from "matrix-bot-sdk";
export const RECOMMENDATION_BAN = "m.ban";
export const RECOMMENDATION_BAN_TYPES = [RECOMMENDATION_BAN, "org.matrix.mjolnir.ban"];
export function recommendationToStable(recommendation: string, unstable = true): string {
export function recommendationToStable(recommendation: string, unstable = true): string|null {
if (RECOMMENDATION_BAN_TYPES.includes(recommendation)) return unstable ? RECOMMENDATION_BAN_TYPES[RECOMMENDATION_BAN_TYPES.length - 1] : RECOMMENDATION_BAN;
return null;
}
@ -32,8 +32,12 @@ export class ListRule {
this.glob = new MatrixGlob(entity);
}
public get recommendation(): string {
/**
* The recommendation for this rule, or `null` if there is no recommendation or the recommendation is invalid.
*/
public get recommendation(): string|null {
if (RECOMMENDATION_BAN_TYPES.includes(this.action)) return RECOMMENDATION_BAN;
return null;
}
public isMatch(entity: string): boolean {

View File

@ -150,7 +150,7 @@ export async function getMessagesByUserIn(client: MatrixClient, sender: string,
let token = timeline['prev_batch'] || response['next_batch'];
let bfMessages = {chunk: syncedMessages, end: token};
do {
const messages = [];
const messages: any[] = [];
for (const event of (bfMessages['chunk'] || [])) {
if (processed >= limit) return; // we're done even if we don't want to be
processed++;
@ -199,7 +199,9 @@ export async function replaceRoomIdsWithPills(client: MatrixClient, text: string
}
const regexRoomId = new RegExp(escapeRegex(roomId), "g");
content.body = content.body.replace(regexRoomId, alias);
content.formatted_body = content.formatted_body.replace(regexRoomId, `<a href="${Permalinks.forRoom(alias, viaServers)}">${alias}</a>`);
if (content.formatted_body) {
content.formatted_body = content.formatted_body.replace(regexRoomId, `<a href="${Permalinks.forRoom(alias, viaServers)}">${alias}</a>`);
}
}
return content;

View File

@ -1,12 +1,16 @@
{
"compilerOptions": {
"alwaysStrict": true,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"module": "commonjs",
"moduleResolution": "node",
"noImplicitReturns": true,
"noUnusedLocals": true,
"target": "es2015",
"noImplicitAny": false,
"sourceMap": true,
"strictNullChecks": true,
"outDir": "./lib",
"types": [
"node",