2021-09-22 12:59:11 -04:00
|
|
|
import { HmacSHA1 } from "crypto-js";
|
2024-09-19 09:06:34 -04:00
|
|
|
import { getRequestFn, LogService, MatrixClient, MemoryStorageProvider, PantalaimonClient } from "@vector-im/matrix-bot-sdk";
|
2021-09-22 12:59:11 -04:00
|
|
|
|
2022-01-06 06:41:55 -05:00
|
|
|
const REGISTRATION_ATTEMPTS = 10;
|
|
|
|
const REGISTRATION_RETRY_BASE_DELAY_MS = 100;
|
|
|
|
|
2021-09-24 05:12:18 -04:00
|
|
|
/**
|
|
|
|
* Register a user using the synapse admin api that requires the use of a registration secret rather than an admin user.
|
|
|
|
* This should only be used by test code and should not be included from any file in the source directory
|
|
|
|
* either by explicit imports or copy pasting.
|
2021-11-09 07:15:49 -05:00
|
|
|
*
|
2021-09-24 05:12:18 -04:00
|
|
|
* @param username The username to give the user.
|
|
|
|
* @param displayname The displayname to give the user.
|
|
|
|
* @param password The password to use.
|
|
|
|
* @param admin True to make the user an admin, false otherwise.
|
|
|
|
* @returns The response from synapse.
|
|
|
|
*/
|
2022-08-16 10:51:18 -04:00
|
|
|
export async function registerUser(homeserver: string, username: string, displayname: string, password: string, admin: boolean): Promise<void> {
|
|
|
|
let registerUrl = `${homeserver}/_synapse/admin/v1/register`
|
2022-01-24 12:04:21 -05:00
|
|
|
const data: {nonce: string} = await new Promise((resolve, reject) => {
|
2022-02-24 09:46:15 -05:00
|
|
|
getRequestFn()({uri: registerUrl, method: "GET", timeout: 60000}, (error: any, response: any, resBody: any) => {
|
2022-01-24 12:04:21 -05:00
|
|
|
error ? reject(error) : resolve(JSON.parse(resBody))
|
|
|
|
});
|
|
|
|
});
|
|
|
|
const nonce = data.nonce!;
|
|
|
|
let mac = HmacSHA1(`${nonce}\0${username}\0${password}\0${admin ? 'admin' : 'notadmin'}`, 'REGISTRATION_SHARED_SECRET');
|
2022-01-06 06:41:55 -05:00
|
|
|
for (let i = 1; i <= REGISTRATION_ATTEMPTS; ++i) {
|
|
|
|
try {
|
2022-01-24 12:04:21 -05:00
|
|
|
const params = {
|
|
|
|
uri: registerUrl,
|
|
|
|
method: "POST",
|
|
|
|
headers: {"Content-Type": "application/json"},
|
|
|
|
body: JSON.stringify({
|
|
|
|
nonce,
|
|
|
|
username,
|
|
|
|
displayname,
|
|
|
|
password,
|
|
|
|
admin,
|
|
|
|
mac: mac.toString()
|
|
|
|
}),
|
|
|
|
timeout: 60000
|
|
|
|
}
|
|
|
|
return await new Promise((resolve, reject) => {
|
2022-02-24 09:46:15 -05:00
|
|
|
getRequestFn()(params, (error: any) => error ? reject(error) : resolve());
|
2022-01-06 06:41:55 -05:00
|
|
|
});
|
|
|
|
} catch (ex) {
|
|
|
|
// In case of timeout or throttling, backoff and retry.
|
|
|
|
if (ex?.code === 'ESOCKETTIMEDOUT' || ex?.code === 'ETIMEDOUT'
|
2022-01-24 12:04:21 -05:00
|
|
|
|| ex?.body?.errcode === 'M_LIMIT_EXCEEDED') {
|
2022-01-06 06:41:55 -05:00
|
|
|
await new Promise(resolve => setTimeout(resolve, REGISTRATION_RETRY_BASE_DELAY_MS * i * i));
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
throw ex;
|
|
|
|
}
|
|
|
|
}
|
2022-01-18 06:34:38 -05:00
|
|
|
throw new Error(`Retried registration ${REGISTRATION_ATTEMPTS} times, is Mjolnir or Synapse misconfigured?`);
|
2021-09-22 12:59:11 -04:00
|
|
|
}
|
|
|
|
|
2022-01-25 07:19:44 -05:00
|
|
|
export type RegistrationOptions = {
|
|
|
|
/**
|
|
|
|
* If specified and true, make the user an admin.
|
|
|
|
*/
|
|
|
|
isAdmin?: boolean,
|
|
|
|
/**
|
|
|
|
* If `exact`, use the account with this exact name, attempting to reuse
|
|
|
|
* an existing account if possible.
|
|
|
|
*
|
|
|
|
* If `contains` create a new account with a name that contains this
|
|
|
|
* specific string.
|
|
|
|
*/
|
|
|
|
name: { exact: string } | { contains: string },
|
|
|
|
/**
|
|
|
|
* If specified and true, throttle this user.
|
|
|
|
*/
|
|
|
|
isThrottled?: boolean
|
|
|
|
}
|
|
|
|
|
2021-09-22 12:59:11 -04:00
|
|
|
/**
|
2022-01-25 07:19:44 -05:00
|
|
|
* Register a new test user.
|
2021-10-07 08:42:08 -04:00
|
|
|
*
|
2022-02-24 09:46:15 -05:00
|
|
|
* @returns A string that is both the username and password of a new user.
|
2021-09-22 12:59:11 -04:00
|
|
|
*/
|
2022-08-16 10:51:18 -04:00
|
|
|
async function registerNewTestUser(homeserver: string, options: RegistrationOptions) {
|
2021-09-22 12:59:11 -04:00
|
|
|
do {
|
2022-01-25 07:19:44 -05:00
|
|
|
let username;
|
|
|
|
if ("exact" in options.name) {
|
|
|
|
username = options.name.exact;
|
|
|
|
} else {
|
|
|
|
username = `mjolnir-test-user-${options.name.contains}${Math.floor(Math.random() * 100000)}`
|
|
|
|
}
|
|
|
|
try {
|
2022-08-16 10:51:18 -04:00
|
|
|
await registerUser(homeserver, username, username, username, Boolean(options.isAdmin));
|
2022-01-25 07:19:44 -05:00
|
|
|
return username;
|
|
|
|
} catch (e) {
|
2022-01-24 12:04:21 -05:00
|
|
|
if (e?.body?.errcode === 'M_USER_IN_USE') {
|
2022-01-25 07:19:44 -05:00
|
|
|
if ("exact" in options.name) {
|
|
|
|
LogService.debug("test/clientHelper", `${username} already registered, reusing`);
|
|
|
|
return username;
|
|
|
|
} else {
|
|
|
|
LogService.debug("test/clientHelper", `${username} already registered, trying another`);
|
|
|
|
}
|
2021-09-22 12:59:11 -04:00
|
|
|
} else {
|
|
|
|
console.error(`failed to register user ${e}`);
|
|
|
|
throw e;
|
|
|
|
}
|
2022-01-25 07:19:44 -05:00
|
|
|
}
|
|
|
|
} while (true);
|
2021-11-09 07:15:49 -05:00
|
|
|
}
|
2021-09-22 12:59:11 -04:00
|
|
|
|
2021-09-24 05:12:18 -04:00
|
|
|
/**
|
2022-01-25 07:19:44 -05:00
|
|
|
* Registers a test user and returns a `MatrixClient` logged in and ready to use.
|
2021-10-07 08:42:08 -04:00
|
|
|
*
|
2021-09-24 05:12:18 -04:00
|
|
|
* @returns A new `MatrixClient` session for a unique test user.
|
|
|
|
*/
|
2022-08-16 10:51:18 -04:00
|
|
|
export async function newTestUser(homeserver: string, options: RegistrationOptions): Promise<MatrixClient> {
|
|
|
|
const username = await registerNewTestUser(homeserver, options);
|
|
|
|
const pantalaimon = new PantalaimonClient(homeserver, new MemoryStorageProvider());
|
2022-01-25 07:19:44 -05:00
|
|
|
const client = await pantalaimon.createClientWithCredentials(username, username);
|
|
|
|
if (!options.isThrottled) {
|
|
|
|
let userId = await client.getUserId();
|
2022-08-16 10:51:18 -04:00
|
|
|
await overrideRatelimitForUser(homeserver, userId);
|
2022-01-25 07:19:44 -05:00
|
|
|
}
|
|
|
|
return client;
|
|
|
|
}
|
|
|
|
|
|
|
|
let _globalAdminUser: MatrixClient;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Get a client that can perform synapse admin API actions.
|
|
|
|
* @returns A client logged in with an admin user.
|
|
|
|
*/
|
2022-08-16 10:51:18 -04:00
|
|
|
async function getGlobalAdminUser(homeserver: string): Promise<MatrixClient> {
|
2022-01-25 07:19:44 -05:00
|
|
|
// Initialize global admin user if needed.
|
|
|
|
if (!_globalAdminUser) {
|
|
|
|
const USERNAME = "mjolnir-test-internal-admin-user";
|
|
|
|
try {
|
2022-08-16 10:51:18 -04:00
|
|
|
await registerUser(homeserver, USERNAME, USERNAME, USERNAME, true);
|
2022-01-25 07:19:44 -05:00
|
|
|
} catch (e) {
|
|
|
|
if (e.isAxiosError && e?.response?.data?.errcode === 'M_USER_IN_USE') {
|
|
|
|
// Then we've already registered the user in a previous run and that is ok.
|
|
|
|
} else {
|
|
|
|
throw e;
|
|
|
|
}
|
|
|
|
}
|
2022-08-16 10:51:18 -04:00
|
|
|
_globalAdminUser = await new PantalaimonClient(homeserver, new MemoryStorageProvider()).createClientWithCredentials(USERNAME, USERNAME);
|
2022-01-25 07:19:44 -05:00
|
|
|
}
|
|
|
|
return _globalAdminUser;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Disable ratelimiting for this user in Synapse.
|
|
|
|
* @param userId The user to disable ratelimiting for, has to include both the server part and local part.
|
|
|
|
*/
|
2022-08-16 10:51:18 -04:00
|
|
|
export async function overrideRatelimitForUser(homeserver: string, userId: string) {
|
|
|
|
await (await getGlobalAdminUser(homeserver)).doRequest("POST", `/_synapse/admin/v1/users/${userId}/override_ratelimit`, null, {
|
2022-01-25 07:19:44 -05:00
|
|
|
"messages_per_second": 0,
|
|
|
|
"burst_count": 0
|
|
|
|
});
|
2021-09-22 12:59:11 -04:00
|
|
|
}
|
|
|
|
|
2022-01-25 07:19:44 -05:00
|
|
|
/**
|
|
|
|
* Put back the default ratelimiting for this user in Synapse.
|
|
|
|
* @param userId The user to use default ratelimiting for, has to include both the server part and local part.
|
|
|
|
*/
|
2022-08-16 10:51:18 -04:00
|
|
|
export async function resetRatelimitForUser(homeserver: string, userId: string) {
|
|
|
|
await (await getGlobalAdminUser(homeserver)).doRequest("DELETE", `/_synapse/admin/v1/users/${userId}/override_ratelimit`, null);
|
2022-01-25 07:19:44 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
|
2021-09-24 05:12:18 -04:00
|
|
|
/**
|
|
|
|
* Utility to create an event listener for m.notice msgtype m.room.messages.
|
|
|
|
* @param targetRoomdId The roomId to listen into.
|
|
|
|
* @param cb The callback when a m.notice event is found in targetRoomId.
|
|
|
|
* @returns The callback to pass to `MatrixClient.on('room.message', cb)`
|
|
|
|
*/
|
2022-02-24 09:46:15 -05:00
|
|
|
export function noticeListener(targetRoomdId: string, cb: (event: any) => void) {
|
|
|
|
return (roomId: string, event: any) => {
|
2021-09-22 12:59:11 -04:00
|
|
|
if (roomId !== targetRoomdId) return;
|
|
|
|
if (event?.content?.msgtype !== "m.notice") return;
|
|
|
|
cb(event);
|
2021-11-09 07:15:49 -05:00
|
|
|
}
|
2021-09-24 05:12:18 -04:00
|
|
|
}
|