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

Improve plaintext formatting of Matrix messages sent via webhooks #778

Open
wants to merge 5 commits into
base: develop
Choose a base branch
from
Open
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
1 change: 1 addition & 0 deletions changelog.d/778.feature
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Improve plaintext formatting of Matrix messages sent via webhooks.
22 changes: 11 additions & 11 deletions docs/link_channels.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,13 @@ first the individual Matrix room and Slack channel need to be created, and then
a command needs to be issued in the administration console room to add the link
to the bridge's database.

## Determining your channel ID

You'll need a "channel ID" to link rooms.
To obtain it, right-click your channel name in Slack and select "Copy Link".
The channel id is the last argument in the url
(`https://XXX.Slack.com/messages/<channel id>/`)

## RTM API

The Real Time Messaging (RTM) API is the newer and recommended way to use the bridge.
Expand Down Expand Up @@ -47,12 +54,9 @@ The Real Time Messaging (RTM) API is the newer and recommended way to use the br
/invite @bot-user-name
```

You will also need to determine the "channel ID" that Slack uses to identify
the channel. Right-click your channel name in Slack and select "Copy Link".
The channel id is the last argument in the url
(`https://XXX.Slack.com/messages/<channel id>/`)
4. Obtain the channel ID (see "Determining your channel ID")

4. Issue a ``link`` command in the administration control room with these
5. Issue a ``link`` command in the administration control room with these
collected values as arguments:

```
Expand Down Expand Up @@ -104,17 +108,13 @@ although it can be useful for single channels or if you are using Mattermost.
of its `token` field. Add a URL to this web hook pointing back at the
application service port you configured during setup.

You will also need to determine the "channel ID" that Slack uses to identify
the channel. Unfortunately, it is not easily obtained from the Slack UI. The
easiest way to do this is to send a message from Slack to the bridge; the
bridge will log the channel ID as part of the unrecognised message output.
You can then take note of the `channel_id` field.
1. Obtain the channel ID (see "Determining your channel ID")

1. Issue a ``link`` command in the administration control room with these
collected values as arguments:

```
link --channel_id CHANNELID --room !the-matrix:room.id --webhook_url https://hooks.Slack.com/services/ABC/DEF/123
link --channel_id CHANNELID --room !the-matrix:room.id --webhook_url https://hooks.Slack.com/services/ABC/DEF/123 --webhook_token TOKEN
```

## Unlink Channels
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@
"eslint-plugin-react-hooks": "^4.6.0",
"js-yaml": "^4.1.0",
"mocha": "^10.0.0",
"node-mocks-http": "^1.14.1",
"nyc": "^15.1.0",
"postcss": "^8.4.21",
"prom-client": "^14.0.1",
Expand Down
8 changes: 7 additions & 1 deletion src/AdminCommands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -181,11 +181,12 @@ export class AdminCommands {
return new AdminCommand(
"link",
"connect a Matrix and a Slack room together",
async ({respond, room, channel_id, webhook_url, slack_bot_token, team_id}: {
async ({respond, room, channel_id, webhook_url, webhook_token, slack_bot_token, team_id}: {
respond: ResponseCallback,
room?: string,
channel_id?: string,
webhook_url?: string,
webhook_token?: string,
slack_bot_token?: string,
team_id?: string,
}) => {
Expand All @@ -200,6 +201,7 @@ export class AdminCommands {
team_id,
slack_channel_id: channel_id,
slack_webhook_uri: webhook_url,
slack_webhook_token: webhook_token,
});
respond("Room is now " + r.getStatus());
if (r.SlackWebhookUri) {
Expand Down Expand Up @@ -234,6 +236,10 @@ export class AdminCommands {
alias: "u",
description: "Slack webhook URL. Used with Slack outgoing hooks integration",
},
webhook_token: {
alias: "k",
description: "Slack webhook token. Used with Slack outgoing hooks integration",
},
},
);
}
Expand Down
43 changes: 38 additions & 5 deletions src/BridgedRoom.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
limitations under the License.
*/

import axios from "axios";
import axios, { AxiosInstance } from "axios";
import { Logger, Intent } from "matrix-appservice-bridge";
import { SlackGhost } from "./SlackGhost";
import { Main, METRIC_SENT_MESSAGES } from "./Main";
Expand All @@ -36,6 +36,7 @@
slack_channel_name?: string;
slack_channel_id?: string;
slack_webhook_uri?: string;
slack_webhook_token?: string;
slack_team_id?: string;
slack_type: SlackChannelTypes;
is_private?: boolean;
Expand Down Expand Up @@ -95,6 +96,14 @@
this.setValue("slackWebhookUri", value);
}

public get SlackWebhookToken(): string|undefined {
return this.slackWebhookToken;
}

public set SlackWebhookToken(value: string|undefined) {
this.setValue("slackWebhookToken", value);
}

public get MatrixRoomId(): string {
return this.matrixRoomId;
}
Expand Down Expand Up @@ -135,6 +144,7 @@
slack_channel_name: entry.remote.name,
slack_team_id: entry.remote.slack_team_id,
slack_webhook_uri: entry.remote.webhook_uri,
slack_webhook_token: entry.remote.webhook_token,
puppet_owner: entry.remote.puppet_owner,
is_private: entry.remote.slack_private,
slack_type: entry.remote.slack_type as SlackChannelTypes,
Expand All @@ -146,6 +156,7 @@
private slackChannelName?: string;
private slackChannelId?: string;
private slackWebhookUri?: string;
private slackWebhookToken?: string;
private slackTeamId?: string;
private slackType: SlackChannelTypes;
private isPrivate?: boolean;
Expand All @@ -169,7 +180,13 @@
*/
private dirty: boolean;

constructor(private main: Main, opts: IBridgedRoomOpts, private team?: TeamEntry, private botClient?: WebClient) {
constructor(
private main: Main,
opts: IBridgedRoomOpts,
private team?: TeamEntry,
private botClient?: WebClient,
private httpClient: AxiosInstance = axios
) {

this.MatrixRoomActive = true;
if (!opts.inbound_id) {
Expand All @@ -184,6 +201,7 @@
this.slackChannelName = opts.slack_channel_name;
this.slackChannelId = opts.slack_channel_id;
this.slackWebhookUri = opts.slack_webhook_uri;
this.slackWebhookToken = opts.slack_webhook_token;
this.slackTeamId = opts.slack_team_id;
this.slackType = opts.slack_type || "channel";
if (opts.is_private === undefined) {
Expand Down Expand Up @@ -241,13 +259,14 @@
id: `INTEG-${this.inboundId}`,
matrix_id: this.matrixRoomId,
remote: {
id: this.slackChannelId!,

Check warning on line 262 in src/BridgedRoom.ts

View workflow job for this annotation

GitHub Actions / lint

Forbidden non-null assertion
name: this.slackChannelName!,

Check warning on line 263 in src/BridgedRoom.ts

View workflow job for this annotation

GitHub Actions / lint

Forbidden non-null assertion
slack_team_id: this.slackTeamId!,

Check warning on line 264 in src/BridgedRoom.ts

View workflow job for this annotation

GitHub Actions / lint

Forbidden non-null assertion
slack_type: this.slackType!,

Check warning on line 265 in src/BridgedRoom.ts

View workflow job for this annotation

GitHub Actions / lint

Forbidden non-null assertion
slack_private: this.isPrivate!,

Check warning on line 266 in src/BridgedRoom.ts

View workflow job for this annotation

GitHub Actions / lint

Forbidden non-null assertion
webhook_uri: this.slackWebhookUri!,

Check warning on line 267 in src/BridgedRoom.ts

View workflow job for this annotation

GitHub Actions / lint

Forbidden non-null assertion
webhook_token: this.slackWebhookToken!,

Check warning on line 268 in src/BridgedRoom.ts

View workflow job for this annotation

GitHub Actions / lint

Forbidden non-null assertion
puppet_owner: this.puppetOwner!,

Check warning on line 269 in src/BridgedRoom.ts

View workflow job for this annotation

GitHub Actions / lint

Forbidden non-null assertion
},
remote_id: this.inboundId,
};
Expand All @@ -256,7 +275,7 @@
}

public async getClientForRequest(userId: string): Promise<{id: string, client: WebClient}|null> {
const puppet = await this.main.clientFactory.getClientForUserWithId(this.SlackTeamId!, userId);

Check warning on line 278 in src/BridgedRoom.ts

View workflow job for this annotation

GitHub Actions / lint

Forbidden non-null assertion
if (puppet) {
return puppet;
}
Expand Down Expand Up @@ -457,7 +476,7 @@
}
log.debug("Room might be encrypted, uploading file to Slack");
// Media might be encrypted, upload it to Slack to be safe.
const response = await axios.get<ArrayBuffer>(matrixToSlackResult.encrypted_file, {
const response = await this.httpClient.get<ArrayBuffer>(matrixToSlackResult.encrypted_file, {
headers: {
Authorization: `Bearer ${slackClient.token}`,
},
Expand Down Expand Up @@ -513,13 +532,27 @@

user.bumpATime();
this.matrixATime = Date.now() / 1000;

if (!slackClient) {
if (!this.slackWebhookUri) {
throw Error('No slackClient and slackWebhookUri');
}
const webhookRes = await axios.post(this.slackWebhookUri, body);
let plainText = body.text;
if (!plainText && body.attachments) {
const parts: string[] = [];
for (const attachment of body.attachments) {
parts.push(`Uploaded "${attachment.fallback}": ${attachment.image_url}`);
}
plainText = parts.join("\n");
}
if (!plainText) {
log.warn("Nothing to send via webhook from message", body);
return false;
}
const webhookRes = await this.httpClient.post(this.slackWebhookUri, { text: `<${body.username}> ${plainText}` });
if (webhookRes.status !== 200) {
log.error("Failed to send webhook message");
return false;
}
// Webhooks don't give us any ID, so we can't store this.
return true;
Expand Down Expand Up @@ -885,7 +918,7 @@
if (file.mode === "snippet") {
let htmlString: string;
try {
const fileReq = await axios.get<string>(filePrivateUrl, {
const fileReq = await this.httpClient.get<string>(filePrivateUrl, {
headers: {
// Token is checked above.
Authorization: `Bearer ${authToken}`,
Expand Down
6 changes: 6 additions & 0 deletions src/Main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1351,6 +1351,7 @@ export class Main {
public async actionLink(opts: {
matrix_room_id: string,
slack_webhook_uri?: string,
slack_webhook_token?: string,
slack_channel_id?: string,
slack_bot_token?: string,
team_id?: string,
Expand Down Expand Up @@ -1450,6 +1451,11 @@ export class Main {

if (opts.slack_webhook_uri) {
room.SlackWebhookUri = opts.slack_webhook_uri;
if (opts.slack_webhook_token) {
room.SlackWebhookToken = opts.slack_webhook_token;
} else {
throw new Error("Cannot link via a webhook without a webhook token");
}
}

if (opts.slack_channel_id) {
Expand Down
14 changes: 12 additions & 2 deletions src/SlackHookHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ export class SlackHookHandler extends BaseSlackHandler {
createServer = (cb) => httpsCreate(tlsOptions, cb);
}
return new Promise<void>((resolve, reject) => {
const srv = createServer(this.onRequest.bind(this));
const srv = createServer(this._onRequest.bind(this));
srv.once("error", reject);
srv.listen(port, () => {
const protocol = tlsConfig ? "https" : "http";
Expand All @@ -85,7 +85,7 @@ export class SlackHookHandler extends BaseSlackHandler {
}
}

private onRequest(req: IncomingMessage, res: ServerResponse) {
public _onRequest(req: IncomingMessage, res: ServerResponse) {
const HTTP_SERVER_ERROR = 500;
const {method, url } = req;
if (!method || !url) {
Expand Down Expand Up @@ -234,6 +234,16 @@ export class SlackHookHandler extends BaseSlackHandler {
return;
}

if (params.token !== room.SlackWebhookToken) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we permit it if no room.SlackWebhookToken exists?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there any situation when this could be true for webhook-bridged rooms? I don't think the bridge will allow you to set them up that way.

log.warn(`Ignoring message for ${room.MatrixRoomId} due to webhook token mismatch`);

response.writeHead(HTTP_CODES.FORBIDDEN);
response.end();

endTimer({outcome: "dropped"});
return;
}

if (method === "POST" && path === "post") {
try {
if (!room) {
Expand Down
1 change: 1 addition & 0 deletions src/datastore/Models.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ export interface RoomEntry {
id: string;
name: string;
webhook_uri?: string;
webhook_token?: string;
slack_private?: boolean;
puppet_owner?: string;
};
Expand Down
Loading
Loading