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

Permalink fixes. #38

Merged
merged 2 commits into from
Mar 9, 2023
Merged
Show file tree
Hide file tree
Changes from all 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
25 changes: 25 additions & 0 deletions NOTICE
Original file line number Diff line number Diff line change
Expand Up @@ -228,3 +228,28 @@ is included below:
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.

Draupnir also incorperates work from matrix-bot-sdk
https://github.com/turt2live/matrix-bot-sdk
which included the following license notice:
MIT License

Copyright (c) 2018 - 2022 Travis Ralston

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
3 changes: 2 additions & 1 deletion src/ManagementRoomOutput.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,8 @@ limitations under the License.
*/

import * as Sentry from "@sentry/node";
import { LogLevel, LogService, MessageType, Permalinks, TextualMessageEventContent, UserID } from "matrix-bot-sdk";
import { LogLevel, LogService, MessageType, TextualMessageEventContent, UserID } from "matrix-bot-sdk";
import { Permalinks } from "./commands/interface-manager/Permalinks";
import { IConfig } from "./config";
import { MatrixSendClient } from "./MatrixEmitter";
import { htmlEscape } from "./utils";
Expand Down
3 changes: 2 additions & 1 deletion src/ProtectedRoomsConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,8 @@ limitations under the License.
*/

import AwaitLock from 'await-lock';
import { LogService, Permalinks } from "matrix-bot-sdk";
import { LogService } from "matrix-bot-sdk";
import { Permalinks } from './commands/interface-manager/Permalinks';
import { IConfig } from "./config";
import { MatrixSendClient } from './MatrixEmitter';
const PROTECTED_ROOMS_EVENT_TYPE = "org.matrix.mjolnir.protected_rooms";
Expand Down
3 changes: 2 additions & 1 deletion src/ProtectedRoomsSet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,8 @@ limitations under the License.
* are NOT distributed, contributed, committed, or licensed under the Apache License.
*/

import { LogLevel, LogService, MatrixGlob, Permalinks, UserID } from "matrix-bot-sdk";
import { LogLevel, LogService, MatrixGlob, UserID } from "matrix-bot-sdk";
import { Permalinks } from "./commands/interface-manager/Permalinks";
import { IConfig } from "./config";
import ErrorCache, { ERROR_KIND_FATAL, ERROR_KIND_PERMISSION } from "./ErrorCache";
import ManagementRoomOutput from "./ManagementRoomOutput";
Expand Down
2 changes: 1 addition & 1 deletion src/appservice/AccessControl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,9 @@ limitations under the License.
*/

import { Bridge } from "matrix-appservice-bridge";
import { Permalinks } from "../commands/interface-manager/Permalinks";
import AccessControlUnit, { EntityAccess } from "../models/AccessControlUnit";
import PolicyList from "../models/PolicyList";
import { Permalinks } from "matrix-bot-sdk";

/**
* Utility to manage which users have access to the application service,
Expand Down
3 changes: 2 additions & 1 deletion src/appservice/MjolnirManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,14 @@ import { Mjolnir } from "../Mjolnir";
import { Request, WeakEvent, BridgeContext, Bridge, Intent, Logger } from "matrix-appservice-bridge";
import { getProvisionedMjolnirConfig } from "../config";
import PolicyList from "../models/PolicyList";
import { Permalinks, MatrixClient, UserID } from "matrix-bot-sdk";
import { MatrixClient, UserID } from "matrix-bot-sdk";
import { DataStore, MjolnirRecord } from "./datastore";
import { AccessControl } from "./AccessControl";
import { Access } from "../models/AccessControlUnit";
import { randomUUID } from "crypto";
import EventEmitter from "events";
import { MatrixEmitter } from "../MatrixEmitter";
import { Permalinks } from "../commands/interface-manager/Permalinks";

const log = new Logger('MjolnirManager');

Expand Down
3 changes: 2 additions & 1 deletion src/commands/CreateBanListCommand.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@ limitations under the License.

import { Mjolnir } from "../Mjolnir";
import PolicyList from "../models/PolicyList";
import { Permalinks, RichReply } from "matrix-bot-sdk";
import { RichReply } from "matrix-bot-sdk";
import { Permalinks } from "./interface-manager/Permalinks";

// !mjolnir list create <shortcode> <alias localpart>
export async function execCreateListCommand(roomId: string, event: any, mjolnir: Mjolnir, parts: string[]) {
Expand Down
3 changes: 2 additions & 1 deletion src/commands/ListProtectedRoomsCommand.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,8 @@ limitations under the License.
*/

import { Mjolnir } from "../Mjolnir";
import { Permalinks, RichReply } from "matrix-bot-sdk";
import { RichReply } from "matrix-bot-sdk";
import { Permalinks } from "./interface-manager/Permalinks";

// !mjolnir rooms
export async function execListProtectedRooms(roomId: string, event: any, mjolnir: Mjolnir) {
Expand Down
5 changes: 4 additions & 1 deletion src/commands/RedactCommand.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ limitations under the License.

import { Mjolnir } from "../Mjolnir";
import { redactUserMessagesIn } from "../utils";
import { Permalinks } from "matrix-bot-sdk";
import { Permalinks } from "./interface-manager/Permalinks";

// !mjolnir redact <user ID> [room alias] [limit]
export async function execRedactCommand(roomId: string, event: any, mjolnir: Mjolnir, parts: string[]) {
Expand All @@ -49,6 +49,9 @@ export async function execRedactCommand(roomId: string, event: any, mjolnir: Mjo
if (userId[0] !== '@') {
// Assume it's a permalink
const parsed = Permalinks.parseUrl(parts[2]);
if (parsed.roomIdOrAlias === undefined || parsed.eventId === undefined) {
throw new TypeError(`Got a malformed permalink ${parsed}`)
}
const targetRoomId = await mjolnir.client.resolveRoom(parsed.roomIdOrAlias);
await mjolnir.client.redactEvent(targetRoomId, parsed.eventId);
await mjolnir.client.unstableApis.addReactionToEvent(roomId, event['event_id'], '✅');
Expand Down
3 changes: 2 additions & 1 deletion src/commands/WatchUnwatchCommand.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,8 @@ limitations under the License.
*/

import { Mjolnir } from "../Mjolnir";
import { Permalinks, RichReply } from "matrix-bot-sdk";
import { RichReply } from "matrix-bot-sdk";
import { Permalinks } from "./interface-manager/Permalinks";

// !mjolnir watch <room alias or ID>
export async function execWatchCommand(roomId: string, event: any, mjolnir: Mjolnir, parts: string[]) {
Expand Down
6 changes: 5 additions & 1 deletion src/commands/interface-manager/MatrixRoomReference.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@
* All rights reserved.
*/

import { Permalinks, RoomAlias } from "matrix-bot-sdk";
import { RoomAlias } from "matrix-bot-sdk";
import { Permalinks } from "./Permalinks";

type JoinRoom = (roomIdOrAlias: string, viaServers?: string[]) => Promise</*room id*/string>;
type ResolveRoom = (roomIdOrAlias: string) => Promise</* room id */string>
Expand Down Expand Up @@ -48,6 +49,9 @@ type ResolveRoom = (roomIdOrAlias: string) => Promise</* room id */string>
*/
public static fromPermalink(permalink: string): MatrixRoomReference {
const parts = Permalinks.parseUrl(permalink);
if (parts.roomIdOrAlias === undefined) {
throw new TypeError(`There is no room id or alias in the permalink ${permalink}`);
}
return MatrixRoomReference.fromRoomIdOrAlias(parts.roomIdOrAlias, parts.viaServers);
}

Expand Down
133 changes: 133 additions & 0 deletions src/commands/interface-manager/Permalinks.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
/**
* Copyright (C) 2023 Gnuxie <Gnuxie@protonmail.com>
* All rights reserved.
*
* This file is only really here while we wait for
* https://github.com/turt2live/matrix-bot-sdk/pull/300
* to be merged and be used by matrix-appservice-bridge too.
*
* This file incorperates work from matrix-bot-sdk
* https://github.com/turt2live/matrix-bot-sdk
* which included the following license notice:
MIT License

Copyright (c) 2018 - 2022 Travis Ralston

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

/**
* The parts of a permalink.
* @see Permalinks
* @category Utilities
*/
export interface PermalinkParts {
/**
* The room ID or alias the permalink references. May be undefined.
*/
roomIdOrAlias?: string;

/**
* The user ID the permalink references. May be undefined.
*/
userId?: string;

/**
* The event ID the permalink references. May be undefined.
*/
eventId?: string;

/**
* The servers the permalink is routed through.
*/
viaServers: string[];
}

/**
* Functions for handling permalinks
* @category Utilities
*/
export class Permalinks {
private constructor() {
}

private static encodeViaArgs(servers: string[]): string {
if (!servers || !servers.length) return "";

return `?via=${servers.join("&via=")}`;
}

/**
* Creates a room permalink.
* @param {string} roomIdOrAlias The room ID or alias to create a permalink for.
* @param {string[]} viaServers The servers to route the permalink through.
* @returns {string} A room permalink.
*/
public static forRoom(roomIdOrAlias: string, viaServers: string[] = []): string {
return `https://matrix.to/#/${encodeURIComponent(roomIdOrAlias)}${Permalinks.encodeViaArgs(viaServers)}`;
}

/**
* Creates a user permalink.
* @param {string} userId The user ID to create a permalink for.
* @returns {string} A user permalink.
*/
public static forUser(userId: string): string {
return `https://matrix.to/#/${encodeURIComponent(userId)}`;
}

/**
* Creates an event permalink.
* @param {string} roomIdOrAlias The room ID or alias to create a permalink in.
* @param {string} eventId The event ID to reference in the permalink.
* @param {string[]} viaServers The servers to route the permalink through.
* @returns {string} An event permalink.
*/
public static forEvent(roomIdOrAlias: string, eventId: string, viaServers: string[] = []): string {
return `https://matrix.to/#/${encodeURIComponent(roomIdOrAlias)}/${encodeURIComponent(eventId)}${Permalinks.encodeViaArgs(viaServers)}`;
}

/**
* Parses a permalink URL into usable parts.
* @param {string} matrixTo The matrix.to URL to parse.
* @returns {PermalinkParts} The parts of the permalink.
*/
public static parseUrl(matrixTo: string): PermalinkParts {
const matrixToRegexp = /^https:\/\/matrix\.to\/#\/(?<entity>[^/?]+)\/?(?<eventId>[^?]+)?(?<query>\?[^]*)?$/;

const url = matrixToRegexp.exec(matrixTo)?.groups;
if (!url) {
throw new Error("Not a valid matrix.to URL");
}

const entity = decodeURIComponent(url.entity);
if (entity[0] === '@') {
return { userId: entity, roomIdOrAlias: undefined, eventId: undefined, viaServers: [] };
} else if (entity[0] === '#' || entity[0] === '!') {
return {
userId: undefined,
roomIdOrAlias: entity,
eventId: url.eventId && decodeURIComponent(url.eventId),
viaServers: new URLSearchParams(url.query).getAll('via'),
};
} else {
throw new Error("Unexpected entity");
}
}
}
3 changes: 2 additions & 1 deletion src/models/PolicyListManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,12 @@ limitations under the License.
* are NOT distributed, contributed, committed, or licensed under the Apache License.
*/

import { LogLevel, LogService, Permalinks } from "matrix-bot-sdk";
import { LogLevel, LogService } from "matrix-bot-sdk";
import { Mjolnir } from "../Mjolnir";
import { MatrixDataManager, RawSchemedData, SCHEMA_VERSION_KEY } from "./MatrixDataManager";
import { MatrixRoomReference } from "../commands/interface-manager/MatrixRoomReference";
import { PolicyList, WATCHED_LISTS_EVENT_TYPE, WARN_UNPROTECTED_ROOM_EVENT_PREFIX } from "./PolicyList";
import { Permalinks } from "../commands/interface-manager/Permalinks";

type WatchedListsEvent = RawSchemedData & { references?: string[]; };
/**
Expand Down
3 changes: 2 additions & 1 deletion src/protections/MessageIsMedia.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@ limitations under the License.

import { Protection } from "./IProtection";
import { Mjolnir } from "../Mjolnir";
import { LogLevel, Permalinks, UserID } from "matrix-bot-sdk";
import { LogLevel, UserID } from "matrix-bot-sdk";
import { Permalinks } from "../commands/interface-manager/Permalinks";

export class MessageIsMedia extends Protection {

Expand Down
3 changes: 2 additions & 1 deletion src/protections/MessageIsVoice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@ limitations under the License.

import { Protection } from "./IProtection";
import { Mjolnir } from "../Mjolnir";
import { LogLevel, Permalinks, UserID } from "matrix-bot-sdk";
import { LogLevel, UserID } from "matrix-bot-sdk";
import { Permalinks } from "../commands/interface-manager/Permalinks";

export class MessageIsVoice extends Protection {

Expand Down
3 changes: 2 additions & 1 deletion src/protections/ProtectionManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,14 +35,15 @@ import { MessageIsMedia } from "./MessageIsMedia";
import { TrustedReporters } from "./TrustedReporters";
import { JoinWaveShortCircuit } from "./JoinWaveShortCircuit";
import { Mjolnir } from "../Mjolnir";
import { LogLevel, LogService, Permalinks } from "matrix-bot-sdk";
import { LogLevel, LogService } from "matrix-bot-sdk";
import { ProtectionSettingValidationError } from "./ProtectionSettings";
import { Consequence } from "./consequence";
import { htmlEscape } from "../utils";
import { ERROR_KIND_FATAL, ERROR_KIND_PERMISSION } from "../ErrorCache";
import { RoomUpdateError } from "../models/RoomUpdateError";
import { BanPropagation } from "./BanPropagation";
import { MatrixDataManager, RawSchemedData, SchemaMigration, SCHEMA_VERSION_KEY } from "../models/MatrixDataManager";
import { Permalinks } from "../commands/interface-manager/Permalinks";

const PROTECTIONS: Protection[] = [
new FirstMessageIsImage(),
Expand Down
3 changes: 2 additions & 1 deletion src/queues/UnlistedUserRedactionQueue.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,8 @@ limitations under the License.
* However, this file is modified and the modifications in this file
* are NOT distributed, contributed, committed, or licensed under the Apache License.
*/
import { LogLevel, LogService, Permalinks } from "matrix-bot-sdk";
import { LogLevel, LogService } from "matrix-bot-sdk";
import { Permalinks } from "../commands/interface-manager/Permalinks";
import { Mjolnir } from "../Mjolnir";

/**
Expand Down
2 changes: 1 addition & 1 deletion test/integration/utilsTest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ describe("Test: utils", function() {
});
assert.equal(
message.content.formatted_body,
`it's fun here in <a href="https://matrix.to/#/${managementRoomAlias}">${managementRoomAlias}</a>`
`it's fun here in <a href="https://matrix.to/#/${encodeURIComponent(managementRoomAlias)}">${managementRoomAlias}</a>`
);
});
});
Expand Down