Skip to content
This repository was archived by the owner on Sep 11, 2024. It is now read-only.

Fix soft crash around inviting invalid MXIDs in start DM on first message flow #9281

Merged
merged 11 commits into from
Sep 16, 2022
42 changes: 26 additions & 16 deletions src/utils/permalinks/Permalinks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -189,9 +189,16 @@ export class RoomPermalinkCreator {
return false;
}
const serverName = getServerName(userId);
return !isHostnameIpAddress(serverName) &&
!isHostInRegex(serverName, this.bannedHostsRegexps) &&
isHostInRegex(serverName, this.allowedHostsRegexps);

let domain = serverName;
try {
domain = getHostnameFromMatrixServerName(serverName);
} catch (e) {
console.error("Error encountered while updating highest power level user", e);
}
return !isHostnameIpAddress(domain) &&
!isHostInRegex(domain, this.bannedHostsRegexps) &&
isHostInRegex(domain, this.allowedHostsRegexps);
});
const maxEntry = allowedEntries.reduce((max, entry) => {
return (entry[1] > max[1]) ? entry : max;
Expand Down Expand Up @@ -250,14 +257,19 @@ export class RoomPermalinkCreator {
.sort((a, b) => this.populationMap[b] - this.populationMap[a]);

for (let i = 0; i < serversByPopulation.length && candidates.size < MAX_SERVER_CANDIDATES; i++) {
const server = serversByPopulation[i];
if (
!candidates.has(server) &&
!isHostnameIpAddress(server) &&
!isHostInRegex(server, this.bannedHostsRegexps) &&
isHostInRegex(server, this.allowedHostsRegexps)
) {
candidates.add(server);
const serverName = serversByPopulation[i];
try {
const domain = getHostnameFromMatrixServerName(serverName);
if (
!candidates.has(serverName) &&
!isHostnameIpAddress(domain) &&
!isHostInRegex(domain, this.bannedHostsRegexps) &&
isHostInRegex(domain, this.allowedHostsRegexps)
) {
candidates.add(serverName);
}
} catch (e) {
console.error("Encountered error while updating server candidates", e);
}
}

Expand Down Expand Up @@ -445,21 +457,19 @@ function getServerName(userId: string): string {
return userId.split(":").splice(1).join(":");
}

function getHostnameFromMatrixDomain(domain: string): string {
if (!domain) return null;
return new URL(`https://${domain}`).hostname;
function getHostnameFromMatrixServerName(serverName: string): string {
if (!serverName) return null;
return new URL(`https://${serverName}`).hostname;
}

function isHostInRegex(hostname: string, regexps: RegExp[]): boolean {
hostname = getHostnameFromMatrixDomain(hostname);
if (!hostname) return true; // assumed
if (regexps.length > 0 && !regexps[0].test) throw new Error(regexps[0].toString());

return regexps.some(h => h.test(hostname));
}

function isHostnameIpAddress(hostname: string): boolean {
hostname = getHostnameFromMatrixDomain(hostname);
if (!hostname) return false;

// is-ip doesn't want IPv6 addresses surrounded by brackets, so
Expand Down