Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add command to elevate a user (or the bot) as room administrator #219

Merged
merged 17 commits into from
Mar 7, 2022
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -72,3 +72,6 @@ typings/

# Python packing directories.
mjolnir.egg-info/

# VS
.vs
13 changes: 13 additions & 0 deletions src/Mjolnir.ts
Original file line number Diff line number Diff line change
Expand Up @@ -964,6 +964,19 @@ export class Mjolnir {
});
}

/**
* Make a user administrator via the Synapse Admin API
* @param roomId the room where the user (or the bot) shall be made administrator.
* @param userId optionally specify the user mxID to be made administrator, if not specified the bot mxID will be used.
* @returns The list of errors encountered, for reporting to the management room.
*/
public async makeUserRoomAdmin(roomId: string, userId?: string): Promise<any> {
const endpoint = `/_synapse/admin/v1/rooms/${roomId}/make_room_admin`;
return await this.client.doRequest("POST", endpoint, null, {
user_id: userId || await this.client.getUserId(), /* if not specified make the bot administrator */
});
}

public queueRedactUserMessagesIn(userId: string, roomId: string) {
this.eventRedactionQueue.add(new RedactUserInRoom(userId, roomId));
}
Expand Down
4 changes: 4 additions & 0 deletions src/commands/CommandHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ import { execSetPowerLevelCommand } from "./SetPowerLevelCommand";
import { execShutdownRoomCommand } from "./ShutdownRoomCommand";
import { execAddAliasCommand, execMoveAliasCommand, execRemoveAliasCommand, execResolveCommand } from "./AliasCommands";
import { execKickCommand } from "./KickCommand";
import { execMakeRoomAdminCommand } from "./MakeRoomAdminCommand";

export const COMMAND_PREFIX = "!mjolnir";

Expand Down Expand Up @@ -109,6 +110,8 @@ export async function handleCommand(roomId: string, event: { content: { body: st
return await execShutdownRoomCommand(roomId, event, mjolnir, parts);
} else if (parts[1] === 'kick' && parts.length > 2) {
return await execKickCommand(roomId, event, mjolnir, parts);
} else if (parts[1] === 'make' && parts[2] === 'admin' && parts.length > 3) {
return await execMakeRoomAdminCommand(roomId, event, mjolnir, parts);
} else {
// Help menu
const menu = "" +
Expand Down Expand Up @@ -146,6 +149,7 @@ export async function handleCommand(roomId: string, event: { content: { body: st
"!mjolnir resolve <room alias> - Resolves a room alias to a room ID\n" +
"!mjolnir shutdown room <room alias/ID> [message] - Uses the bot's account to shut down a room, preventing access to the room on this server\n" +
"!mjolnir powerlevel <user ID> <power level> [room alias/ID] - Sets the power level of the user in the specified room (or all protected rooms)\n" +
"!mjolnir make admin <room alias> [room alias/ID] - Make the specified user or the bot itself admin of the room\n" +
maranda marked this conversation as resolved.
Show resolved Hide resolved
"!mjolnir help - This menu\n";
const html = `<b>Mjolnir help:</b><br><pre><code>${htmlEscape(menu)}</code></pre>`;
const text = `Mjolnir help:\n${menu}`;
Expand Down
33 changes: 33 additions & 0 deletions src/commands/MakeRoomAdminCommand.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/*
Copyright 2021 Marco Cirillo
maranda marked this conversation as resolved.
Show resolved Hide resolved

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

import { Mjolnir } from "../Mjolnir";
import { RichReply } from "matrix-bot-sdk";

// !mjolnir make admin <room> [<user ID>]
export async function execMakeRoomAdminCommand(roomId: string, event: any, mjolnir: Mjolnir, parts: string[]) {
const isAdmin = await mjolnir.isSynapseAdmin();
if (!isAdmin) {
maranda marked this conversation as resolved.
Show resolved Hide resolved
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";
mjolnir.client.sendMessage(roomId, reply);
return;
}

await mjolnir.makeUserRoomAdmin(await mjolnir.client.resolveRoom(parts[3]), parts[4]);
maranda marked this conversation as resolved.
Show resolved Hide resolved
await mjolnir.client.unstableApis.addReactionToEvent(roomId, event['event_id'], '✅');
}
78 changes: 78 additions & 0 deletions test/integration/commands/makedminCommandTest.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import { strict as assert } from "assert";

import config from "../../../src/config";
import { newTestUser } from "../clientHelper";
import { PowerLevelAction } from "matrix-bot-sdk/lib/models/PowerLevelAction";
import { LogService } from "matrix-bot-sdk";
import { getFirstReaction } from "./commandUtils";

describe("Test: The make admin command", function () {
afterEach(function () {
this.moderator?.stop();
this.userA?.stop();
this.userB?.stop();
});

it('Mjölnir make the bot self room administrator', async function () {
this.timeout(60000);
const mjolnir = config.RUNTIME.client!;
const mjolnirUserId = await mjolnir.getUserId();
const moderator = await newTestUser({ name: { contains: "moderator" } });
this.moderator = moderator;

await moderator.joinRoom(config.managementRoom);
LogService.debug("makeadminTest", `Joining managementRoom: ${config.managementRoom}`);
let targetRoom = await moderator.createRoom({ invite: [mjolnirUserId] });
maranda marked this conversation as resolved.
Show resolved Hide resolved
LogService.debug("makeadminTest", `moderator creating targetRoom: ${targetRoom}; and inviting ${mjolnirUserId}`);
await moderator.sendMessage(this.mjolnir.managementRoomId, { msgtype: 'm.text.', body: `!mjolnir rooms add ${targetRoom}` });
LogService.debug("makeadminTest", `Adding targetRoom: ${targetRoom}`);
try {
await moderator.start();
await getFirstReaction(mjolnir, this.mjolnir.managementRoomId, '✅', async () => {
LogService.debug("makeadminTest", `Sending: !mjolnir make admin ${targetRoom}`);
return await moderator.sendMessage(this.mjolnir.managementRoomId, { msgtype: 'm.text', body: `!mjolnir make admin ${targetRoom}` });
});
} finally {
await moderator.stop();
}
LogService.debug("makeadminTest", `Making self admin`);

assert.ok(await mjolnir.userHasPowerLevelForAction(mjolnirUserId, targetRoom, PowerLevelAction.Ban), "Bot user is now room admin.");
maranda marked this conversation as resolved.
Show resolved Hide resolved
});

it('Mjölnir make the tester room administrator', async function () {
this.timeout(60000);
const mjolnir = config.RUNTIME.client!;
const moderator = await newTestUser({ name: { contains: "moderator" } });
const userA = await newTestUser({ name: { contains: "a" } });
const userB = await newTestUser({ name: { contains: "b" } });
const userBId = await userB.getUserId();
this.moderator = moderator;
this.userA = userA;
this.userB = userB;
maranda marked this conversation as resolved.
Show resolved Hide resolved

await moderator.joinRoom(this.mjolnir.managementRoomId);
LogService.debug("makeadminTest", `Joining managementRoom: ${this.mjolnir.managementRoomId}`);
let targetRoom = await userA.createRoom({ invite: [userBId] });
LogService.debug("makeadminTest", `User A creating targetRoom: ${targetRoom}; and inviting ${userBId}`);
try {
await userB.start();
userB.joinRoom(targetRoom);
} finally {
LogService.debug("makeadminTest", `${userBId} joining targetRoom: ${targetRoom}`);
await userB.stop();
maranda marked this conversation as resolved.
Show resolved Hide resolved
}
try {
await moderator.start();
await getFirstReaction(mjolnir, this.mjolnir.managementRoomId, '✅', async () => {
LogService.debug("makeadminTest", `Sending: !mjolnir make admin ${targetRoom} ${userBId}`);
return await moderator.sendMessage(this.mjolnir.managementRoomId, { msgtype: 'm.text', body: `!mjolnir make admin ${targetRoom} ${userBId}` });
});
} finally {
await moderator.stop();
}
LogService.debug("makeadminTest", `Making User B admin`);

await assert.ok(await userA.userHasPowerLevelForAction(userBId, targetRoom, PowerLevelAction.Ban), "User B is now room admin.");
maranda marked this conversation as resolved.
Show resolved Hide resolved
maranda marked this conversation as resolved.
Show resolved Hide resolved
});
});