-
Notifications
You must be signed in to change notification settings - Fork 73
/
Copy pathMain.ts
1751 lines (1553 loc) · 69.7 KB
/
Main.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright 2019 The Matrix.org Foundation C.I.C.
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 {
Bridge, BridgeBlocker, PrometheusMetrics, StateLookup,
Logger, Intent, UserMembership, WeakEvent, PresenceEvent,
AppService, AppServiceRegistration, UserActivityState, UserActivityTracker,
UserActivityTrackerConfig, MembershipQueue, PowerLevelContent, StateLookupEvent } from "matrix-appservice-bridge";
import { Gauge, Counter } from "prom-client";
import * as path from "path";
import * as randomstring from "randomstring";
import { WebClient } from "@slack/web-api";
import { IConfig, CACHING_DEFAULTS } from "./IConfig";
import { OAuth2 } from "./OAuth2";
import { BridgedRoom } from "./BridgedRoom";
import { SlackGhost } from "./SlackGhost";
import { MatrixUser } from "./MatrixUser";
import { SlackHookHandler } from "./SlackHookHandler";
import { AdminCommands } from "./AdminCommands";
import { Provisioner } from "./provisioning/Provisioner";
import { INTERNAL_ID_LEN } from "./BaseSlackHandler";
import { SlackRTMHandler } from "./SlackRTMHandler";
import { ConversationsInfoResponse, ConversationsOpenResponse, AuthTestResponse, UsersInfoResponse } from "./SlackResponses";
import { Datastore, RoomEntry, SlackAccount, TeamEntry } from "./datastore/Models";
import { NedbDatastore } from "./datastore/NedbDatastore";
import { PgDatastore } from "./datastore/postgres/PgDatastore";
import { SlackClientFactory } from "./SlackClientFactory";
import { Response } from "express";
import { SlackRoomStore } from "./SlackRoomStore";
import QuickLRU from "@alloc/quick-lru";
import PQueue from "p-queue";
import { UserAdminRoom } from "./rooms/UserAdminRoom";
import { TeamSyncer } from "./TeamSyncer";
import { SlackGhostStore } from "./SlackGhostStore";
import { AllowDenyList, DenyReason } from "./AllowDenyList";
const log = new Logger("Main");
const STARTUP_TEAM_INIT_CONCURRENCY = 10;
const STARTUP_RETRY_TIME_MS = 5000;
export const METRIC_ACTIVE_USERS = "active_users";
export const METRIC_ACTIVE_ROOMS = "active_rooms";
export const METRIC_PUPPETS = "remote_puppets";
export const METRIC_RECEIVED_MESSAGE = "received_messages";
export const METRIC_SENT_MESSAGES = "sent_messages";
export const METRIC_OAUTH_SESSIONS = "oauth_session_result";
export interface ISlackTeam {
id: string;
domain: string;
name: string;
}
interface MetricsLabels { [labelName: string]: string; }
type TimerFunc = (labels?: Partial<Record<string, string | number>> | undefined) => void;
class SlackBridgeBlocker extends BridgeBlocker {
constructor(userLimit: number, private slackBridge: Main) {
super(userLimit);
}
async blockBridge() {
log.info("Blocking the bridge");
await this.slackBridge.disableHookHandler();
await this.slackBridge.disableRtm();
await super.blockBridge();
}
async unblockBridge() {
log.info("Unblocking the bridge");
if (this.slackBridge.config.rtm?.enable) {
this.slackBridge.enableRtm();
}
if (this.slackBridge.config.slack_hook_port) {
this.slackBridge.enableHookHandler();
}
await super.unblockBridge();
}
}
export class Main {
public get botIntent(): Intent {
return this.bridge.getIntent();
}
public get userIdPrefix(): string {
return this.config.username_prefix;
}
public get botUserId(): string {
return this.bridge.getBot().getUserId();
}
public get clientFactory(): SlackClientFactory {
return this.clientfactory;
}
public get ghostStore(): SlackGhostStore {
return this.ghosts;
}
public readonly oauth2: OAuth2|null = null;
public datastore!: Datastore;
public readonly rooms: SlackRoomStore = new SlackRoomStore();
private ghosts!: SlackGhostStore; // Defined in .run
private matrixUsersById: QuickLRU<string, MatrixUser>;
private bridge: Bridge;
private appservice: AppService;
private ready = false;
// TODO(paul): ugh. this.getBotIntent() doesn't work before .run time
// So we can't create the StateLookup instance yet
private stateStorage: StateLookup|null = null;
private metrics?: {
prometheus: PrometheusMetrics;
metricActiveRooms: Gauge<string>;
metricActiveUsers: Gauge<string>;
metricPuppets: Gauge<string>;
bridgeBlocked: Gauge<string>;
oauthSessions: Counter<string>;
};
private metricsCollectorInterval?: NodeJS.Timeout;
private adminCommands: AdminCommands;
private clientfactory!: SlackClientFactory;
public readonly teamSyncer?: TeamSyncer;
public readonly allowDenyList: AllowDenyList;
public slackRtm?: SlackRTMHandler;
private slackHookHandler?: SlackHookHandler;
private provisioner: Provisioner;
private bridgeBlocker?: BridgeBlocker;
public readonly membershipQueue: MembershipQueue;
constructor(public readonly config: IConfig, registration: AppServiceRegistration) {
this.adminCommands = new AdminCommands(this);
if (config.oauth2) {
const redirectPrefix = config.oauth2.redirect_prefix || config.inbound_uri_prefix;
if (!redirectPrefix) {
throw Error("Either inbound_uri_prefix or oauth2.redirect_prefix must be defined for oauth2 support");
}
this.oauth2 = new OAuth2({
client_id: config.oauth2.client_id,
client_secret: config.oauth2.client_secret,
main: this,
redirect_prefix: redirectPrefix,
template_file: config.oauth2.html_template || path.join(__dirname, ".." , "templates/oauth_result.html.njk"),
});
}
config.caching = { ...CACHING_DEFAULTS, ...config.caching };
this.matrixUsersById = new QuickLRU({ maxSize: config.caching.matrixUserCache });
if ((!config.rtm || !config.rtm.enable) && (!config.slack_hook_port || !config.inbound_uri_prefix)) {
throw Error("Neither rtm.enable nor slack_hook_port|inbound_uri_prefix is defined in the config." +
"The bridge must define a listener in order to run");
}
if ((!config.rtm?.enable || !config.oauth2) && config.puppeting?.enabled) {
throw Error("Either rtm and/or oauth2 is not enabled, but puppeting is enabled. Both need to be enabled for puppeting to work.");
}
let bridgeStores = {};
const usingNeDB = config.db === undefined || config.db?.engine === "nedb";
if (usingNeDB) {
const dbdir = config.dbdir || "";
const URL = "https://github.com/matrix-org/matrix-appservice-slack/blob/master/docs/datastores.md";
log.warn("** NEDB IS END-OF-LIFE **");
log.warn("Starting with version 1.0, the nedb datastore is being discontinued in favour of " +
`postgresql. Please see ${URL} for more information.`);
if (config.rmau_limit) {
throw new Error("RMAU limits are unsupported in NeDB, cannot continue");
}
bridgeStores = {
eventStore: path.join(dbdir, "event-store.db"),
roomStore: path.join(dbdir, "room-store.db"),
userStore: path.join(dbdir, "user-store.db"),
};
} else {
bridgeStores = {
// Don't create store
disableStores: true,
};
}
if (config.db?.engine === "postgres") {
// Need to create this early for encryption support
const postgresDb = new PgDatastore(config.db.connectionString);
this.datastore = postgresDb;
}
if (config.encryption?.enabled && config.db?.engine !== "postgres") {
throw Error('Encrypted bridge support only works with PostgreSQL.');
}
this.bridge = new Bridge({
controller: {
onEvent: (request) => {
const ev = request.getData();
const isAdminRoomRelated = UserAdminRoom.IsAdminRoomInvite(ev, this.botUserId)
|| ev.room_id === this.config.matrix_admin_room;
if (this.bridgeBlocker?.isBlocked && !isAdminRoomRelated) {
log.info(`Bridge is blocked, dropping Matrix event ${ev.event_id} (${ev.room_id})`);
return;
}
if (ev.state_key) {
this.stateStorage?.onEvent({
...ev,
state_key: ev.state_key as string,
}).catch((ex) => {
log.error(`Failed to store event in stateStorage ${ev.event_id} (${ev.room_id})`, ex);
});
}
this.onMatrixEvent(ev).then(() => {
log.info(`Handled ${ev.event_id} (${ev.room_id})`);
}).catch((ex) => {
log.error(`Failed to handle ${ev.event_id} (${ev.room_id})`, ex);
});
},
onEphemeralEvent: request => {
if (this.bridgeBlocker?.isBlocked) {
log.info('Bridge is blocked, dropping Matrix ephemeral event');
return;
}
const ev = request.getData();
if (ev.type === "m.typing") {
const room = this.rooms.getByMatrixRoomId(ev.room_id);
if (room) {
room.onMatrixTyping(ev.content.user_ids).then(() => {
log.debug(`Handled typing event for ${ev.room_id}`);
}).catch((ex) => {
log.error(`Failed handle typing event for room ${room.MatrixRoomId}`, ex);
});
}
} else if (ev.type === "m.presence") {
this.onMatrixPresence(ev).then(() => {
log.debug(`Handled presence for ${ev.sender} (${ev.content.presence})`);
}).catch((ex) => {
log.error(`Failed handle presence for ${ev.sender}`, ex);
});
}
// Slack has no concept of receipts, we can't bridge those.
},
onUserQuery: () => ({}), // auto-provision users with no additional data
},
roomUpgradeOpts: {
consumeEvent: true,
migrateGhosts: true,
onRoomMigrated: this.onRoomUpgrade.bind(this),
migrateStoreEntries: false,
},
domain: config.homeserver.server_name,
homeserverUrl: config.homeserver.url,
registration,
...bridgeStores,
disableContext: true,
suppressEcho: true,
bridgeEncryption: config.encryption?.enabled ? {
homeserverUrl: config.encryption.pantalaimon_url,
store: this.datastore as PgDatastore,
} : undefined,
});
this.membershipQueue = new MembershipQueue(this.bridge, { });
if (config.rtm?.enable) {
this.enableRtm();
}
if (config.slack_hook_port) {
this.enableHookHandler();
}
if (config.rmau_limit) {
this.bridgeBlocker = new SlackBridgeBlocker(config.rmau_limit, this);
}
if (config.enable_metrics) {
this.initialiseMetrics();
}
if (config.team_sync) {
this.teamSyncer = new TeamSyncer(this);
}
this.allowDenyList = new AllowDenyList(
config.puppeting?.direct_messages,
config.provisioning?.channel_adl,
);
const homeserverToken = registration.getHomeserverToken();
if (homeserverToken === null) {
throw Error("Homeserver token is null");
}
this.appservice = new AppService({
homeserverToken,
httpMaxSizeBytes: 0,
});
this.provisioner = new Provisioner(
this,
this.appservice,
{
// Default to HS token if no secret is configured
secret: homeserverToken,
...(config.provisioning ?? { enabled: true }),
},
);
}
public teamIsUsingRtm(teamId: string): boolean {
return (this.slackRtm !== undefined) && this.slackRtm.teamIsUsingRtm(teamId);
}
public getIntent(userId: string): Intent {
return this.bridge.getIntent(userId);
}
public initialiseMetrics(): void {
// Do not set up the handler here, we set it up after listening.
const prometheus = this.bridge.getPrometheusMetrics();
this.bridge.registerBridgeGauges(() => {
const now = Date.now() / 1000;
const remoteRoomsByAge = new PrometheusMetrics.AgeCounters();
const matrixRoomsByAge = new PrometheusMetrics.AgeCounters();
this.rooms.all.forEach((room) => {
if (room.RemoteATime) {
remoteRoomsByAge.bump(now - room.RemoteATime);
}
if (room.MatrixATime) {
matrixRoomsByAge.bump(now - room.MatrixATime);
}
});
const countAges = (users: QuickLRU<string, MatrixUser|SlackGhost>) => {
const counts = new PrometheusMetrics.AgeCounters();
const snapshot = [...users.values()].filter((u) => u !== undefined && u.aTime && u.aTime > 0);
for (const user of snapshot) {
if (user.aTime) {
counts.bump(now - user.aTime);
}
}
return counts;
};
return {
matrixRoomConfigs: this.rooms.matrixRoomCount,
remoteRoomConfigs: this.rooms.remoteRoomCount,
// As a relaybot we don't create remote-side ghosts
remoteGhosts: 0,
matrixRoomsByAge,
remoteRoomsByAge,
matrixUsersByAge: countAges(this.matrixUsersById),
remoteUsersByAge: countAges(this.ghosts.cached),
};
});
prometheus.addCounter({
help: "count of received messages",
labels: ["side"],
name: METRIC_RECEIVED_MESSAGE,
});
prometheus.addCounter({
help: "count of sent messages",
labels: ["side"],
name: METRIC_SENT_MESSAGES,
});
prometheus.addCounter({
help: "Count of the number of remote API calls made",
labels: ["method"],
name: "remote_api_calls",
});
prometheus.addTimer({
help: "Histogram of processing durations of received Matrix messages",
labels: ["outcome"],
name: "matrix_request_seconds",
});
prometheus.addTimer({
help: "Histogram of processing durations of received remote messages",
labels: ["outcome"],
name: "remote_request_seconds",
});
const metricActiveUsers = prometheus.addGauge({
help: "Count of active users",
labels: ["remote", "team_id"],
name: METRIC_ACTIVE_USERS,
});
const metricActiveRooms = prometheus.addGauge({
help: "Count of active bridged rooms (types are 'channel' and 'user')",
labels: ["team_id", "type"],
name: METRIC_ACTIVE_ROOMS,
});
const metricPuppets = prometheus.addGauge({
help: "Amount of puppeted users on the remote side of the bridge",
labels: ["team_id"],
name: METRIC_PUPPETS,
});
const bridgeBlocked = prometheus.addGauge({
name: "blocked",
help: "Is the bridge currently blocking messages",
});
const oauthSessions = prometheus.addCounter({
name: METRIC_OAUTH_SESSIONS,
help: "Metric tracking the result of oauth sessions",
labels: ["result", "reason"],
});
this.metrics = {
prometheus,
metricActiveUsers,
metricActiveRooms,
metricPuppets,
bridgeBlocked,
oauthSessions,
};
log.info(`Enabled prometheus metrics`);
}
public incCounter(name: string, labels: MetricsLabels = {}): void {
this.metrics?.prometheus.incCounter(name, labels);
}
public incRemoteCallCounter(type: string): void {
this.metrics?.prometheus.incCounter("remote_api_calls", {method: type});
}
/**
* Gathers the active rooms and users from the database and updates the metrics.
* This function should be called on a regular interval or after an important
* change to the metrics has happened.
*/
public async updateActivityMetrics(): Promise<void> {
if (!this.metrics) {
return;
}
const roomsByTeamAndType = await this.datastore.getActiveRoomsPerTeam();
const usersByTeamAndRemote = await this.datastore.getActiveUsersPerTeam();
this.metrics.metricActiveRooms.reset();
for (const [teamId, teamData] of roomsByTeamAndType.entries()) {
for (const [roomType, numberOfActiveRooms] of teamData.entries()) {
this.metrics.metricActiveRooms.set({ team_id: teamId, type: roomType }, numberOfActiveRooms);
}
}
this.metrics.metricActiveUsers.reset();
for (const [teamId, teamData] of usersByTeamAndRemote.entries()) {
this.metrics.metricActiveUsers.set({ team_id: teamId, remote: "true" }, teamData.get(true) || 0);
this.metrics.metricActiveUsers.set({ team_id: teamId, remote: "false" }, teamData.get(false) || 0);
}
this.metrics.bridgeBlocked.set(this.bridgeBlocker?.isBlocked ? 1 : 0);
}
public startTimer(name: string, labels: MetricsLabels = {}): TimerFunc {
return this.metrics ? this.metrics.prometheus.startTimer(name, labels) : () => {};
}
public getUrlForMxc(mxcUrl: string, local = false): string {
// Media may be encrypted, use this.
let baseUrl = this.config.homeserver.url;
if (this.config.encryption?.enabled && local) {
baseUrl = this.config.encryption?.pantalaimon_url;
} else if (this.config.homeserver.media_url) {
baseUrl = this.config.homeserver.media_url;
}
return `${baseUrl}/_matrix/media/r0/download/${mxcUrl.slice("mxc://".length)}`;
}
public async getTeamDomainForMessage(message: {team_domain?: string, team_id?: string}, teamId?: string): Promise<string|undefined> {
if (typeof message.team_domain === 'string') {
return message.team_domain;
}
if (!teamId) {
if (!message.team_id) {
throw Error("Cannot determine team, no id given.");
} else if (typeof message.team_id !== 'string') {
throw Error("Cannot determine team, id is invalid.");
}
teamId = message.team_id;
}
const team = await this.datastore.getTeam(teamId);
if (team) {
return team.domain;
}
}
public getOrCreateMatrixUser(id: string): MatrixUser {
let u = this.matrixUsersById.get(id);
if (u) {
return u;
}
u = new MatrixUser(this, {user_id: id});
this.matrixUsersById.set(id, u);
return u;
}
public genInboundId(): string {
let attempts = 10;
while (attempts > 0) {
const id = randomstring.generate(INTERNAL_ID_LEN);
if (this.rooms.getByInboundId(id) === undefined) {
return id;
}
attempts--;
}
// Prevent tightlooping if randomness goes odd
throw Error("Failed to generate a unique inbound ID after 10 attempts");
}
public async addBridgedRoom(room: BridgedRoom): Promise<void> {
this.rooms.upsertRoom(room);
if (this.slackRtm && room.SlackTeamId) {
// This will start a new RTM client for the team, if the team
// doesn't currently have a client running.
await this.slackRtm.startTeamClientIfNotStarted(room.SlackTeamId);
}
}
public async fixDMMetadata(room: BridgedRoom, targetSlackRecipient: SlackGhost) {
if (room.SlackType !== "im" || !room.SlackTeamId) {
return;
}
const puppetedSlackGhosts: SlackGhost[] = [];
const otherSlackGhosts: SlackGhost[] = [];
for (const userId of await this.listGhostUsers(room.MatrixRoomId)) {
const slackGhost = await this.ghosts.getExisting(userId);
if (!slackGhost) {
log.warn(`Could not find Slack ghost for ${userId} in DM ${room.MatrixRoomId}`);
continue;
}
const puppetMatrixUser = await this.datastore.getPuppetMatrixUserBySlackId(room.SlackTeamId, slackGhost.slackId);
if (puppetMatrixUser) {
puppetedSlackGhosts.push(slackGhost);
} else {
otherSlackGhosts.push(slackGhost);
}
}
const allSlackGhosts = otherSlackGhosts.concat(puppetedSlackGhosts);
if (otherSlackGhosts.length !== 1 && puppetedSlackGhosts.length !== 1) {
log.warn(
`Cannot update metadata of DM ${room.MatrixRoomId} ` +
`with ${!allSlackGhosts.length ? "no" : "multiple"} potential Slack recipients`,
allSlackGhosts.map(r => r.matrixUserId).join(","));
return;
}
const slackRecipient = otherSlackGhosts.length ? otherSlackGhosts[0] : puppetedSlackGhosts[0];
if (slackRecipient.slackId !== targetSlackRecipient.slackId) {
log.debug(
`Not updating metadata of DM ${room.MatrixRoomId} ` +
`not owned by Slack user ${targetSlackRecipient.slackId}`);
return;
}
const profileInfo = await targetSlackRecipient.intent.getProfileInfo(targetSlackRecipient.matrixUserId);
for (const slackGhost of allSlackGhosts) {
try {
const intent = this.getIntent(slackGhost.matrixUserId);
if (profileInfo.displayname) {
await intent.setRoomName(room.MatrixRoomId, profileInfo.displayname);
}
if (profileInfo.avatar_url) {
await intent.setRoomAvatar(room.MatrixRoomId, profileInfo.avatar_url);
}
break;
} catch (ex) {
// TODO Use MatrixError and break if error is due to something other than power levels
log.warn(ex);
}
}
}
public getInboundUrlForRoom(room: BridgedRoom): string {
return this.config.inbound_uri_prefix + room.InboundId;
}
public getStoredEvent(roomId: string, eventType: string, stateKey?: string): StateLookupEvent|StateLookupEvent[]|null|undefined {
return this.stateStorage?.getState(roomId, eventType, stateKey);
}
public async getState(roomId: string, eventType: string): Promise<unknown> {
const cachedEvent = this.getStoredEvent(roomId, eventType, "");
if (cachedEvent && Array.isArray(cachedEvent) && cachedEvent.length) {
// StateLookup returns entire state events. client.getStateEvent returns
// *just the content*
return cachedEvent[0].content;
}
return this.botIntent.getStateEvent(roomId, eventType, undefined, true);
}
public async listAllUsers(roomId: string): Promise<string[]> {
const members = await this.bridge.getBot().getJoinedMembers(roomId);
return Object.keys(members);
}
public async listGhostUsers(roomId: string): Promise<string[]> {
const userIds = await this.listAllUsers(roomId);
const regexp = new RegExp("^@" + this.config.username_prefix);
return userIds.filter((i) => i.match(regexp));
}
public async drainAndLeaveMatrixRoom(roomId: string): Promise<void> {
const userIds = await this.listGhostUsers(roomId);
log.info(`Draining ${userIds.length} ghosts from ${roomId}`);
const intents = userIds.map(userId => this.getIntent(userId));
intents.push(this.botIntent);
await Promise.allSettled(intents.map(async (intent) => intent.leave(roomId)));
}
public async listRoomsFor(): Promise<string[]> {
return this.bridge.getBot().getJoinedRooms();
}
private async handleMatrixMembership(ev: {
event_id: string,
state_key: string,
type: string,
room_id: string,
sender: string,
content: {
is_direct?: boolean;
membership: UserMembership;
}
}, room: BridgedRoom | undefined, endTimer: TimerFunc) {
const bot = this.bridge.getBot();
const senderIsRemote = bot.isRemoteUser(ev.sender);
const recipientIsRemote = bot.isRemoteUser(ev.state_key);
// Bot membership
if (ev.state_key === this.botUserId) {
const membership = ev.content.membership;
const forRoom = this.rooms.getByMatrixRoomId(ev.room_id);
if (membership === "invite") {
// Automatically accept all invitations
// NOTE: This can race and fail if the invite goes down the AS stream
// before the homeserver believes we can actually join the room.
await this.botIntent.join(ev.room_id);
// Mark the room as active if we managed to join.
if (forRoom) {
forRoom.MatrixRoomActive = true;
await this.stateStorage?.trackRoom(ev.room_id);
}
} else if (membership === "leave" || membership === "ban") {
// We've been kicked out :(
if (forRoom) {
forRoom.MatrixRoomActive = false;
this.stateStorage?.untrackRoom(ev.room_id);
}
}
endTimer({ outcome: "success" });
return;
}
// Matrix User -> Remote user
if (!senderIsRemote && recipientIsRemote) {
if (ev.content.is_direct) {
// DM
try {
await this.handleDmInvite(ev.state_key, ev.sender, ev.room_id);
endTimer({ outcome: "success" });
} catch (e) {
log.error("Failed to handle DM invite: ", e);
endTimer({ outcome: "fail" });
}
} else if (room) {
// Normal invite
await room.onMatrixInvite(ev.sender, ev.state_key);
endTimer({ outcome: "success" });
}
return;
}
if (!room) {
// We can't do anything else without a room
return;
}
// Regular membership from matrix user
if (!senderIsRemote) {
const membership = ev.content.membership;
if (membership === "join") {
await room.onMatrixJoin(ev.state_key);
// Do we need to onboard this user?
if (this.config.puppeting?.enabled && this.config.puppeting.onboard_users) {
const adminRoomUser = await this.datastore.getUserAdminRoom(ev.state_key);
const puppets = await this.datastore.getPuppetsByMatrixId(ev.state_key);
if (!adminRoomUser && puppets.length === 0) {
// No admin room, and no puppets but just joined a Slack room.
await UserAdminRoom.inviteAndCreateAdminRoom(ev.state_key, this);
}
}
} else if (membership === "leave" || membership === "ban") {
await room.onMatrixLeave(ev.state_key);
}
// Invites are not handled
}
}
public async onMatrixEvent(ev: WeakEvent): Promise<void> {
if (ev.sender === this.botUserId) {
// We don't want to handle echo.
return;
}
this.incCounter(METRIC_RECEIVED_MESSAGE, {side: "matrix"});
const endTimer = this.startTimer("matrix_request_seconds");
// Admin room message
if (ev.room_id === this.config.matrix_admin_room &&
ev.type === "m.room.message") {
try {
await this.onMatrixAdminMessage(ev);
} catch (e) {
log.error("Failed processing admin message: ", e);
endTimer({outcome: "fail"});
return;
}
endTimer({outcome: "success"});
return;
}
if (UserAdminRoom.IsAdminRoomInvite(ev, this.botUserId)) {
await this.datastore.setUserAdminRoom(ev.sender, ev.room_id);
await this.botIntent.join(ev.room_id);
await this.botIntent.sendMessage(ev.room_id, {
msgtype: "m.notice",
body: "Welcome to your Slack bridge admin room. Please say `help` for commands.",
formatted_body: "Welcome to your Slack bridge admin room. Please say <code>help</code> for commands.",
format: "org.matrix.custom.html",
});
endTimer({outcome: "success"});
return;
}
const room = this.rooms.getByMatrixRoomId(ev.room_id);
if (ev.type === "m.room.member") {
const stateKey = ev.state_key;
if (stateKey !== undefined) {
await this.handleMatrixMembership({
...ev,
content: {
membership: ev.content.membership as UserMembership,
is_direct: ev.content.is_direct as boolean|undefined,
},
state_key: stateKey,
}, room, endTimer);
}
return;
}
if (!room) {
const adminRoomUser = await this.datastore.getUserForAdminRoom(ev.room_id);
if (adminRoomUser) {
if (adminRoomUser !== ev.sender) {
// Not the correct user, ignore.
endTimer({outcome: "dropped"});
return;
}
try {
const adminRoom = this.rooms.getOrCreateAdminRoom(ev.room_id, adminRoomUser, this);
await adminRoom.handleEvent({
type: ev.type,
content: {
msgtype: ev.content.msgtype as string,
body: ev.content.body as string,
}
});
endTimer({outcome: "success"});
} catch (ex) {
log.error("Failed to handle admin mesage:", ex);
endTimer({outcome: "dropped"});
}
return;
}
log.warn(`Ignoring ev for matrix room with unknown slack channel: ${ev.room_id}`);
endTimer({outcome: "dropped"});
return; // Can't do anything without a room.
}
// Handle a m.room.redaction event
if (ev.type === "m.room.redaction") {
try {
await room.onMatrixRedaction(ev);
} catch (e) {
log.error("Failed processing matrix redaction message: ", e);
endTimer({outcome: "fail"});
return;
}
endTimer({outcome: "success"});
return;
}
// Handle a m.reaction event
if (ev.type === "m.reaction") {
try {
await room.onMatrixReaction(ev);
} catch (e) {
log.error("Failed processing reaction message: ", e);
endTimer({outcome: "fail"});
return;
}
endTimer({outcome: "success"});
}
let success = false;
// Handle a m.room.message event
if (ev.type !== "m.room.message" || !ev.content) {
log.debug(`${ev.event_id} ${ev.room_id} cannot be handled`);
return;
}
if (ev.content["m.relates_to"] !== undefined) {
const relatesTo = ev.content["m.relates_to"] as {rel_type: string, event_id: string};
if (relatesTo.rel_type === "m.replace" && relatesTo.event_id) {
// We have an edit.
try {
success = await room.onMatrixEdit(ev);
} catch (e) {
log.error("Failed processing matrix edit: ", e);
endTimer({outcome: "fail"});
}
return;
}
} // Allow this to fall through, so we can handle replies.
try {
log.info(`Handling matrix room message ${ev.event_id} ${ev.room_id}`);
success = await room.onMatrixMessage(ev);
} catch (e) {
log.error("Failed processing matrix message: ", e);
endTimer({outcome: "fail"});
return;
}
endTimer({outcome: success ? "success" : "dropped"});
}
public async handleDmInvite(recipient: string, sender: string, roomId: string): Promise<void> {
const intent = this.getIntent(recipient);
await intent.join(roomId);
if (!this.slackRtm) {
await intent.sendEvent(roomId, "m.room.message", {
body: "This slack bridge instance doesn't support private messaging.",
msgtype: "m.notice",
});
await intent.leave(roomId);
return;
}
const slackGhost = await this.ghosts.getExisting(recipient);
if (!slackGhost || !slackGhost.teamId) {
// TODO: Create users dynamically who have never spoken.
// https://github.com/matrix-org/matrix-appservice-slack/issues/211
await intent.sendEvent(roomId, "m.room.message", {
body: "The user does not exist or has not used the bridge yet.",
msgtype: "m.notice",
});
await intent.leave(roomId);
return;
}
const teamId = slackGhost.teamId;
const rtmClient = this.slackRtm && await this.slackRtm.getUserClient(teamId, sender);
const slackClient = await this.clientFactory.getClientForUser(teamId, sender);
if (!rtmClient || !slackClient) {
await intent.sendEvent(roomId, "m.room.message", {
body: "You have not enabled puppeting for this Slack workspace. You must do that to speak to members.",
msgtype: "m.notice",
});
await intent.leave(roomId);
return;
}
const userData = (await slackClient.users.info({
user: slackGhost.slackId,
})) as UsersInfoResponse;
// Check if the user is denied Slack Direct Messages (DMs)
const denyReason = this.allowDenyList.allowDM(sender, slackGhost.slackId, userData.user?.name);
if (denyReason !== DenyReason.ALLOWED) {
await intent.sendEvent(roomId, "m.room.message", {
body: denyReason === DenyReason.MATRIX ? "The admin of this Slack bridge has denied you to directly message Slack users." :
"The admin of this Slack bridge has denied users to directly message this Slack user.",
msgtype: "m.notice",
});
await intent.leave(roomId);
return;
}
const openResponse = (await slackClient.conversations.open({users: slackGhost.slackId, return_im: true})) as ConversationsOpenResponse;
if (openResponse.already_open) {
// Check to see if we have a room for this channel already.
const existing = this.rooms.getBySlackChannelId(openResponse.channel.id);
if (existing) {
await intent.sendEvent(roomId, "m.room.message", {
body: "You already have a conversation open with this person, leaving that room and reattaching here.",
msgtype: "m.notice",
});
try {
await intent.setRoomName(existing.MatrixRoomId, "");
await intent.setRoomAvatar(existing.MatrixRoomId, "");
} catch (ex) {
log.error("Failed to clear name of now-empty DM", ex);
}
await this.actionUnlink({ matrix_room_id: existing.MatrixRoomId });
}
}
const puppetIdent = (await slackClient.auth.test()) as AuthTestResponse;
const team = await this.datastore.getTeam(teamId);
if (!team) {
throw Error(`Expected team ${teamId} for DM to be in datastore`);
}
// The convo may be open, but we do not have a channel for it. Create the channel.
const room = new BridgedRoom(this, {
inbound_id: openResponse.channel.id,
matrix_room_id: roomId,
slack_team_id: puppetIdent.team_id,
slack_channel_id: openResponse.channel.id,
slack_channel_name: undefined,
puppet_owner: sender,
is_private: true,
slack_type: "im",
}, team , slackClient);
room.updateUsingChannelInfo(openResponse);
await this.addBridgedRoom(room);
await this.datastore.upsertRoom(room);
await intent.join(roomId);
const profileInfo = await intent.getProfileInfo(slackGhost.matrixUserId);
try {
if (profileInfo.displayname) {
await intent.setRoomName(room.MatrixRoomId, profileInfo.displayname);
}
if (profileInfo.avatar_url) {
await intent.setRoomAvatar(room.MatrixRoomId, profileInfo.avatar_url);
}
} catch (ex) {
log.warn("Unable to set metadata of newly-joined DM", ex);
}
}
public async onMatrixAdminMessage(ev: {
event_id: string,
state_key?: string,
type: string,
room_id: string,
sender: string,
content?: {
body?: unknown,
},
}): Promise<void> {
if (typeof ev.content !== "object" || !ev.content || typeof ev.content.body !== "string") {
throw Error("Received an invalid Matrix admin message. event.content.body was not a string.");
}
const cmd = ev.content.body;
// Ignore "# comment" lines as chatter between humans sharing the console
if (cmd.match(/^\s*#/)) {
return;
}
let response: string[] | null = [];