-
Notifications
You must be signed in to change notification settings - Fork 72
/
bridge.ts
1823 lines (1681 loc) · 69.4 KB
/
bridge.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 2020 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 Datastore from "nedb";
import {promises as fs} from "fs";
import * as util from "util";
import yaml from "js-yaml";
import { Application, Request as ExRequest, Response as ExResponse, NextFunction } from "express";
// eslint-disable-next-line @typescript-eslint/no-var-requires
const MatrixScheduler = require("matrix-js-sdk").MatrixScheduler;
import { AppServiceRegistration, AppService, AppServiceOutput } from "matrix-appservice";
import { BridgeContext } from "./components/bridge-context"
import { ClientFactory } from "./components/client-factory"
import { AppServiceBot } from "./components/app-service-bot"
import { RequestFactory } from "./components/request-factory";
import { Request } from "./components/request";
import { Intent, IntentOpts, IntentBackingStore, PowerLevelContent } from "./components/intent";
import { RoomBridgeStore } from "./components/room-bridge-store";
import { UserBridgeStore } from "./components/user-bridge-store";
import { UserActivityStore } from "./components/user-activity-store";
import { EventBridgeStore } from "./components/event-bridge-store";
import { MatrixUser } from "./models/users/matrix"
import { MatrixRoom } from "./models/rooms/matrix"
import { PrometheusMetrics, BridgeGaugesCounts } from "./components/prometheusmetrics"
import { MembershipCache, UserMembership, UserProfile } from "./components/membership-cache"
import { RoomLinkValidator, RoomLinkValidatorStatus, Rules } from "./components/room-link-validator"
import { RoomUpgradeHandler, RoomUpgradeHandlerOpts } from "./components/room-upgrade-handler";
import { EventQueue } from "./components/event-queue";
import * as logging from "./components/logging";
import { UserActivityTracker } from "./components/user-activity";
import { Defer, defer as deferPromise } from "./utils/promiseutil";
import { unstable } from "./errors";
import { BridgeStore } from "./components/bridge-store";
import { RemoteUser } from "./models/users/remote";
import BridgeInternalError = unstable.BridgeInternalError;
import wrapError = unstable.wrapError;
import EventNotHandledError = unstable.EventNotHandledError;
import { ThirdpartyProtocolResponse, ThirdpartyLocationResponse, ThirdpartyUserResponse } from "./thirdparty";
import { RemoteRoom } from "./models/rooms/remote";
import { Registry } from "prom-client";
import { ClientEncryptionStore, EncryptedEventBroker } from "./components/encryption";
import { EphemeralEvent, PresenceEvent, ReadReceiptEvent, TypingEvent, WeakEvent } from "./components/event-types";
import * as BotSDK from "matrix-bot-sdk";
import { ActivityTracker, ActivityTrackerOpts } from "./components/activity-tracker";
const log = logging.get("bridge");
// The frequency at which we will check the list of accumulated Intent objects.
const INTENT_CULL_CHECK_PERIOD_MS = 1000 * 60; // once per minute
// How long a given Intent object can hang around unused for.
const INTENT_CULL_EVICT_AFTER_MS = 1000 * 60 * 15; // 15 minutes
export const BRIDGE_PING_EVENT_TYPE = "org.matrix.bridge.ping";
export const BRIDGE_PING_TIMEOUT_MS = 60000;
// How old can a receipt be before we treat it as stale.
const RECEIPT_CUTOFF_TIME_MS = 60000;
export interface BridgeController {
/**
* The bridge will invoke when an event has been received from the HS.
*/
onEvent: (request: Request<WeakEvent>, context?: BridgeContext) => void;
/**
* The bridge will invoke this when a typing, read reciept or presence event
* is received from the HS. **This will only work with the `bridgeEncryption`
* configuration set.**
*/
onEphemeralEvent?: (request: Request<TypingEvent|ReadReceiptEvent|PresenceEvent>) => void;
/**
* The bridge will invoke this function when queried via onUserQuery. If
* not supplied, no users will be provisioned on user queries. Provisioned users
* will automatically be stored in the associated `userStore`.
*/
onUserQuery?: (matrixUser: MatrixUser) =>
PossiblePromise<{name?: string, url?: string, remote?: RemoteUser}|null|void>;
/**
* The bridge will invoke this function when queried via onAliasQuery. If
* not supplied, no rooms will be provisioned on alias queries. Provisioned rooms
* will automatically be stored in the associated `roomStore`. */
onAliasQuery?: (alias: string, aliasLocalpart: string) =>
PossiblePromise<{roomId?: string, creationOpts?: Record<string, unknown>, remote?: RemoteRoom}|null|void>;
/**
* The bridge will invoke this function when a room has been created
* via onAliasQuery.
*/
onAliasQueried?: (alias: string, roomId: string) => PossiblePromise<void>;
/**
* Invoked when logging. Defaults to a function which logs to the console.
* */
onLog?: (text: string, isError: boolean) => void;
/**
* If supplied, the bridge will respond to third-party entity lookups using the
* contained helper functions.
*/
thirdPartyLookup?: {
protocols: string[];
getProtocol?(protocol: string): PossiblePromise<ThirdpartyProtocolResponse>;
getLocation?(protocol: string, fields: Record<string, string[]|string>):
PossiblePromise<ThirdpartyLocationResponse[]>;
parseLocation?(alias: string): PossiblePromise<ThirdpartyLocationResponse[]>;
getUser?(protocol: string, fields: Record<string, string[]|string>):
PossiblePromise<ThirdpartyUserResponse[]>;
parseUser?(userid: string): PossiblePromise<ThirdpartyLocationResponse[]>;
};
userActivityTracker?: UserActivityTracker;
}
type PossiblePromise<T> = T|Promise<T>;
export interface BridgeOpts {
/**
* Application service registration object or path to the registration file.
*/
registration: AppServiceRegistration|string;
/**
* The base HS url
*/
homeserverUrl: string;
/**
* The domain part for user_ids and room aliases e.g. "bar" in "@foo:bar".
*/
domain: string;
/**
* A human readable string that will be used when the bridge signals errors
* to the client. Will not include in error events if ommited.
*/
networkName?: string;
/**
* The controller logic for the bridge.
*/
controller: BridgeController;
/**
* True to disable enabling of stores.
* This should be used by bridges that use their own database instances and
* do not need any of the included store objects. This implies setting
* disableContext to True. Default: false.
*/
disableStores?: boolean;
/**
* The room store instance to use, or the path to the room .db file to load.
* A database will be ClientFactoryEncryptionStorecreated if this is not specified. If `disableStores` is set,
* no database will be created or used.
*/
roomStore?: RoomBridgeStore|string;
/**
* The user store instance to use, or the path to the user .db file to load.
* A database will be created if this is not specified. If `disableStores` is set,
* no database will be created or used.
*/
userStore?: UserBridgeStore|string;
/**
* The user activity store instance to use, or the path to the user .db file to load.
* A database will be created if this is not specified. If `disableStores` is set,
* no database will be created or used.
*/
userActivityStore?: UserActivityStore|string;
/**
* The event store instance to use, or the path to the user .db file to load.
* A database will NOT be created if this is not specified. If `disableStores` is set,
* no database will be created or used.
*/
eventStore?: EventBridgeStore|string;
/**
* The membership cache instance
* to use, which can be manually created by a bridge for greater control over
* caching. By default a membership cache will be created internally.
*/
membershipCache?: MembershipCache;
/**
* True to stop receiving onEvent callbacks
* for events which were sent by a bridge user. Default: true.
*/
suppressEcho?: boolean;
/**
* The client factory instance to use. If not supplied, one will be created.
*/
clientFactory?: ClientFactory;
/**
* True to enable SUCCESS/FAILED log lines to be sent to onLog. Default: true.
*/
logRequestOutcome?: boolean;
/**
* Escape userIds for non-bot intents with
* {@link MatrixUser~escapeUserId}
* Default: true
*/
escapeUserIds?: boolean;
/**
* Options to supply to created Intent instances.
*/
intentOptions?: {
/**
* Options to supply to the bot intent.
*/
bot?: IntentOpts;
/**
* Options to supply to the client intents.
*/
clients?: IntentOpts;
};
/**
* The factory function used to create intents.
*/
onIntentCreate?: (userId: string) => Intent,
/**
* Options for the `onEvent` queue. When the bridge
* receives an incoming transaction, it needs to asyncly query the data store for
* contextual info before calling onEvent. A queue is used to keep the onEvent
* calls consistent with the arrival order from the incoming transactions.
*/
queue?: {
/**
* The type of queue to use when feeding through to {@link Bridge~onEvent}.
* - If `none`, events are fed through as soon as contextual info is obtained, which may result
* in out of order events but stops HOL blocking.
* - If `single`, onEvent calls will be in order but may be slower due to HOL blocking.
* - If `per_room`, a queue per room ID is made which reduces the impact of HOL blocking to be scoped to a room.
*
* Default: `single`.
*/
type?: "none"|"single"|"per_room";
/**
* `true` to only feed through the next event after the request object in the previous
* call succeeds or fails. It is **vital** that you consistently resolve/reject the
* request if this is 'true', else you will not get any further events from this queue.
* To aid debugging this, consider setting a delayed listener on the request factory.
*
* If `false`, the mere invocation of onEvent is enough to trigger the next event in the queue.
* You probably want to set this to `true` if your {@link Bridge~onEvent} is
* performing async operations where ordering matters (e.g. messages).
*
* Default: false.
* */
perRequest?: boolean;
};
/**
* `true` to disable {@link BridgeContext}
* parameters in {@link Bridge.onEvent}. Disabling the context makes the
* bridge do fewer database lookups, but prevents there from being a
* `context` parameter.
*
* Default: `false`.
*/
disableContext?: boolean;
roomLinkValidation?: {
rules: Rules;
};
authenticateThirdpartyEndpoints?: boolean;
roomUpgradeOpts?: RoomUpgradeHandlerOpts;
bridgeEncryption?: {
homeserverUrl: string;
store: ClientEncryptionStore;
};
eventValidation?: {
/**
* Should we validate that the sender of an edit matches the parent event.
*/
validateEditSender?: {
/**
* If the parent edit event could not be found,
* should the event be rejected.
*/
allowEventOnLookupFail: boolean;
};
};
trackUserActivity?: ActivityTrackerOpts;
}
interface VettedBridgeOpts {
/**
* Application service registration object or path to the registration file.
*/
registration: AppServiceRegistration | string;
/**
* The base HS url
*/
homeserverUrl: string;
/**
* The domain part for user_ids and room aliases e.g. "bar" in "@foo:bar".
*/
domain: string;
/**
* A human readable string that will be used when the bridge signals errors
* to the client. Will not include in error events if ommited.
*/
networkName?: string;
/**
* The controller logic for the bridge.
*/
controller: BridgeController;
/**
* True to disable enabling of stores.
* This should be used by bridges that use their own database instances and
* do not need any of the included store objects. This implies setting
* disableContext to True. Default: false.
*/
disableStores: boolean;
/**
* The room store instance to use, or the path to the room .db file to load.
* A database will be created if this is not specified. If `disableStores` is set,
* no database will be created or used.
*/
roomStore: RoomBridgeStore | string;
/**
* The user store instance to use, or the path to the user .db file to load.
* A database will be created if this is not specified. If `disableStores` is set,
* no database will be created or used.
*/
userStore: UserBridgeStore | string;
/**
* The user activity store instance to use, or the path to the user .db file to load.
* A database will be created if this is not specified. If `disableStores` is set,
* no database will be created or used.
*/
userActivityStore: UserActivityStore | string;
/**
* The event store instance to use, or the path to the user .db file to load.
* A database will NOT be created if this is not specified. If `disableStores` is set,
* no database will be created or used.
*/
eventStore?: EventBridgeStore | string;
/**
* True to stop receiving onEvent callbacks
* for events which were sent by a bridge user. Default: true.
*/
suppressEcho: boolean;
/**
* The client factory instance to use. If not supplied, one will be created.
*/
clientFactory?: ClientFactory;
/**
* True to enable SUCCESS/FAILED log lines to be sent to onLog. Default: true.
*/
logRequestOutcome: boolean;
/**
* Escape userIds for non-bot intents with
* {@link MatrixUser~escapeUserId}
* Default: true
*/
escapeUserIds?: boolean;
/**
* Options to supply to created Intent instances.
*/
intentOptions: {
/**
* Options to supply to the bot intent.
*/
bot?: IntentOpts;
/**
* Options to supply to the client intents.
*/
clients?: IntentOpts;
};
/**
* The factory function used to create intents.
*/
onIntentCreate: (userId: string, opts: IntentOpts) => Intent,
/**
* Options for the `onEvent` queue. When the bridge
* receives an incoming transaction, it needs to asyncly query the data store for
* contextual info before calling onEvent. A queue is used to keep the onEvent
* calls consistent with the arrival order from the incoming transactions.
*/
queue: {
/**
* The type of queue to use when feeding through to {@link Bridge~onEvent}.
* - If `none`, events are fed through as soon as contextual info is obtained, which may result
* in out of order events but stops HOL blocking.
* - If `single`, onEvent calls will be in order but may be slower due to HOL blocking.
* - If `per_room`, a queue per room ID is made which reduces the impact of HOL blocking to be scoped to a room.
*
* Default: `single`.
*/
type: "none" | "single" | "per_room";
/**
* `true` to only feed through the next event after the request object in the previous
* call succeeds or fails. It is **vital** that you consistently resolve/reject the
* request if this is 'true', else you will not get any further events from this queue.
* To aid debugging this, consider setting a delayed listener on the request factory.
*
* If `false`, the mere invocation of onEvent is enough to trigger the next event in the queue.
* You probably want to set this to `true` if your {@link Bridge~onEvent} is
* performing async operations where ordering matters (e.g. messages).
*
* Default: false.
* */
perRequest: boolean;
};
/**
* `true` to disable {@link BridgeContext}
* parameters in {@link Bridge.onEvent}. Disabling the context makes the
* bridge do fewer database lookups, but prevents there from being a
* `context` parameter.
*
* Default: `false`.
*/
disableContext: boolean;
roomLinkValidation?: {
rules: Rules;
};
authenticateThirdpartyEndpoints: boolean;
roomUpgradeOpts?: RoomUpgradeHandlerOpts;
bridgeEncryption?: {
homeserverUrl: string;
store: ClientEncryptionStore;
};
eventValidation?: {
validateEditSender?: {
allowEventOnLookupFail: boolean;
};
};
userActivityTracking?: ActivityTrackerOpts;
}
export class Bridge {
private requestFactory: RequestFactory;
private intents: Map<string, { intent: Intent, lastAccessed: number}>; // user_id + request_id => Intent
private powerlevelMap: Map<string, PowerLevelContent>; // room_id => powerlevels
private membershipCache: MembershipCache;
private queue: EventQueue;
private intentBackingStore: IntentBackingStore;
private prevRequestPromise: Promise<unknown>;
private readonly onLog: (message: string, isError: boolean) => void;
private intentLastAccessedTimeout: NodeJS.Timeout|null = null;
private botIntent?: Intent;
private appServiceBot?: AppServiceBot;
private clientFactory?: ClientFactory;
private metrics?: PrometheusMetrics;
private roomLinkValidator?: RoomLinkValidator;
private roomUpgradeHandler?: RoomUpgradeHandler;
private roomStore?: RoomBridgeStore;
private userStore?: UserBridgeStore;
private userActivityStore?: UserActivityStore;
private eventStore?: EventBridgeStore;
private registration?: AppServiceRegistration;
private appservice?: AppService;
private botSdkAS?: BotSDK.Appservice;
private eeEventBroker?: EncryptedEventBroker;
private selfPingDeferred?: {
defer: Defer<void>;
roomId: string;
timeout: NodeJS.Timeout;
}
public readonly opts: VettedBridgeOpts;
private internalActivityTracker?: ActivityTracker;
public get activityTracker(): ActivityTracker|undefined {
return this.internalActivityTracker;
}
public get appService(): AppService {
if (!this.appservice) {
throw Error('appservice not defined yet');
}
return this.appservice;
}
public get botUserId(): string {
if (!this.registration) {
throw Error('Registration not defined yet');
}
return `@${this.registration.getSenderLocalpart()}:${this.opts.domain}`;
}
/**
* @param opts Options to pass to the bridge
* @param opts.roomUpgradeOpts Options to supply to
* the room upgrade handler. If not defined then upgrades are NOT handled by the bridge.
*/
constructor (opts: BridgeOpts) {
if (typeof opts !== "object") {
throw new Error("opts must be supplied.");
}
const required = [
"homeserverUrl", "registration", "domain", "controller"
];
const missingKeys = required.filter(k => !Object.keys(opts).includes(k));
if (missingKeys.length) {
throw new Error(`Missing '${missingKeys.join("', '")}' in opts.`);
}
if (typeof opts.controller.onEvent !== "function") {
throw new Error("controller.onEvent is a required function");
}
this.opts = {
...opts,
disableContext: opts.disableStores ? true : (opts.disableContext ?? false),
disableStores: opts.disableStores ?? false,
authenticateThirdpartyEndpoints: opts.authenticateThirdpartyEndpoints ?? false,
userStore: opts.userStore || "user-store.db",
userActivityStore: opts.userActivityStore || "user-activity-store.db",
roomStore: opts.roomStore || "room-store.db",
intentOptions: opts.intentOptions || {},
onIntentCreate: opts.onIntentCreate ?? this.onIntentCreate.bind(this),
queue: {
type: opts.queue?.type || "single",
perRequest: opts.queue?.perRequest ?? false,
},
logRequestOutcome: opts.logRequestOutcome ?? true,
suppressEcho: opts.suppressEcho ?? true,
eventValidation: opts.hasOwnProperty("eventValidation") ? opts.eventValidation : {
validateEditSender: {
allowEventOnLookupFail: false
}
}
};
this.queue = EventQueue.create(this.opts.queue, this.onConsume.bind(this));
// Default: logger -> log to console
this.onLog = opts.controller.onLog || function(text, isError) {
if (isError) {
log.error(text);
return;
}
log.info(text);
};
// we'll init these at runtime
this.requestFactory = new RequestFactory();
this.intents = new Map();
this.powerlevelMap = new Map();
this.membershipCache = opts.membershipCache || new MembershipCache();
this.intentBackingStore = {
setMembership: this.membershipCache.setMemberEntry.bind(this.membershipCache),
setPowerLevelContent: this.setPowerLevelEntry.bind(this),
getMembership: this.membershipCache.getMemberEntry.bind(this.membershipCache),
getMemberProfile: this.membershipCache.getMemberProfile.bind(this.membershipCache),
getPowerLevelContent: this.getPowerLevelEntry.bind(this)
};
this.prevRequestPromise = Promise.resolve();
if (this.opts.roomUpgradeOpts) {
this.opts.roomUpgradeOpts.consumeEvent = this.opts.roomUpgradeOpts.consumeEvent !== false;
if (this.opts.disableStores) {
this.opts.roomUpgradeOpts.migrateStoreEntries = false;
}
this.roomUpgradeHandler = new RoomUpgradeHandler(this.opts.roomUpgradeOpts, this);
}
}
/**
* Load the user and room databases. Access them via getUserStore() and getRoomStore().
*/
public async loadDatabases(): Promise<void> {
if (this.opts.disableStores) {
return;
}
const storePromises: Promise<BridgeStore>[] = [];
// Load up the databases if they provided file paths to them (or defaults)
if (typeof this.opts.userStore === "string") {
storePromises.push(loadDatabase(this.opts.userStore, UserBridgeStore));
}
else {
storePromises.push(Promise.resolve(this.opts.userStore));
}
if (typeof this.opts.userActivityStore === "string") {
storePromises.push(loadDatabase(this.opts.userActivityStore, UserActivityStore));
}
else {
storePromises.push(Promise.resolve(this.opts.userActivityStore));
}
if (typeof this.opts.roomStore === "string") {
storePromises.push(loadDatabase(this.opts.roomStore, RoomBridgeStore));
}
else {
storePromises.push(Promise.resolve(this.opts.roomStore));
}
if (typeof this.opts.eventStore === "string") {
storePromises.push(loadDatabase(this.opts.eventStore, EventBridgeStore));
}
else if (this.opts.eventStore) {
storePromises.push(Promise.resolve(this.opts.eventStore));
}
// This works because if they provided a string we converted it to a Promise
// which will be resolved when we have the db instance. If they provided a
// db instance then this will resolve immediately.
const [userStore, userActivityStore, roomStore, eventStore] = await Promise.all(storePromises);
this.userStore = userStore as UserBridgeStore;
this.userActivityStore = userActivityStore as UserActivityStore;
this.roomStore = roomStore as RoomBridgeStore;
this.eventStore = eventStore as EventBridgeStore;
}
/**
* Load registration, databases and initalise bridge components.
*
* **This must be called before `listen()`**
*/
public async initalise(): Promise<void> {
if (typeof this.opts.registration === "string") {
const regObj = yaml.load(await fs.readFile(this.opts.registration, 'utf8'));
if (typeof regObj !== "object") {
throw Error("Failed to parse registration file: yaml file did not parse to object")
}
const registration = AppServiceRegistration.fromObject(regObj as AppServiceOutput);
if (registration === null) {
throw Error("Failed to parse registration file");
}
this.registration = registration;
}
else {
this.registration = this.opts.registration;
}
const asToken = this.registration.getAppServiceToken();
if (!asToken) {
throw Error('No AS token provided, cannot create ClientFactory');
}
const rawReg = this.registration.getOutput();
this.botSdkAS = new BotSDK.Appservice({
registration: {
...rawReg,
url: rawReg.url || undefined,
protocols: rawReg.protocols || undefined,
namespaces: {
users: rawReg.namespaces?.users || [],
rooms: rawReg.namespaces?.rooms || [],
aliases: rawReg.namespaces?.aliases || [],
}
},
homeserverUrl: this.opts.homeserverUrl,
homeserverName: this.opts.domain,
// Unused atm.
port: 0,
bindAddress: "127.0.0.1",
});
if (this.metrics) {
this.metrics.registerMatrixSdkMetrics(this.botSdkAS);
}
this.clientFactory = this.opts.clientFactory || new ClientFactory({
url: this.opts.homeserverUrl,
token: asToken,
appServiceUserId: this.botUserId,
clientSchedulerBuilder: function() {
return new MatrixScheduler(retryAlgorithm, queueAlgorithm);
},
});
this.clientFactory.setLogFunction((text, isErr) => {
this.onLog(text, isErr || false);
});
await this.checkHomeserverSupport();
this.appServiceBot = new AppServiceBot(
this.botSdkAS.botClient, this.botUserId, this.registration, this.membershipCache,
);
if (this.opts.bridgeEncryption) {
this.eeEventBroker = new EncryptedEventBroker(
this.membershipCache,
this.appServiceBot,
this.onEvent.bind(this),
// If the bridge supports pushEphemeral, don't use sync data.
!this.registration.pushEphemeral ? this.onEphemeralEvent.bind(this) : undefined,
this.getIntent.bind(this),
this.opts.bridgeEncryption.store,
);
}
if (this.opts.roomLinkValidation !== undefined) {
this.roomLinkValidator = new RoomLinkValidator(
this.opts.roomLinkValidation,
this.appServiceBot,
);
}
this.requestFactory = new RequestFactory();
if (this.opts.logRequestOutcome) {
this.requestFactory.addDefaultResolveCallback((req) =>
this.onLog(
"[" + req.getId() + "] SUCCESS (" + req.getDuration() + "ms)",
false,
)
);
this.requestFactory.addDefaultRejectCallback((req, err) =>
this.onLog(
"[" + req.getId() + "] FAILED (" + req.getDuration() + "ms) " +
(err ? util.inspect(err) : ""),
false,
)
);
}
const botIntentOpts: IntentOpts = {
registered: true,
backingStore: this.intentBackingStore,
getJsSdkClient: () => {
if (!this.clientFactory) {
throw Error('clientFactory not ready yet');
}
return this.clientFactory.getClientAs(
undefined,
undefined,
this.opts.bridgeEncryption?.homeserverUrl,
!!this.opts.bridgeEncryption,
)
},
...this.opts.intentOptions?.bot, // copy across opts, if defined
};
this.botIntent = this.opts.onIntentCreate(this.botUserId, botIntentOpts);
this.setupIntentCulling();
if (this.opts.userActivityTracking) {
if (!this.registration.pushEphemeral) {
log.info("Sending ephemeral events to the bridge is currently disabled in the registration file," +
" so user activity will not be captured");
}
this.internalActivityTracker = new ActivityTracker(
this.botIntent.matrixClient, this.opts.userActivityTracking
);
}
await this.loadDatabases();
}
/**
* Setup a HTTP listener to handle appservice traffic.
* ** This must be called after .initalise() **
* @param port The port to listen on.
* @param appServiceInstance The AppService instance to attach to.
* If not provided, one will be created.
* @param hostname Optional hostname to bind to.
*/
public async listen(
port: number, hostname = "0.0.0.0", backlog = 10, appServiceInstance?: AppService): Promise<void> {
if (!this.registration) {
throw Error('initalise() not called, cannot listen');
}
const homeserverToken = this.registration.getHomeserverToken();
if (!homeserverToken) {
throw Error('No HS token provided, cannot create AppService');
}
this.appservice = appServiceInstance || new AppService({
homeserverToken,
});
this.appservice.onUserQuery = (userId) => this.onUserQuery(userId);
this.appservice.onAliasQuery = this.onAliasQuery.bind(this);
this.appservice.on("event", async (event) => {
let passthrough = true;
const weakEvent = event as WeakEvent;
if (this.eeEventBroker) {
passthrough = await this.eeEventBroker.onASEvent(weakEvent);
}
if (passthrough) {
return this.onEvent(weakEvent);
}
return undefined;
});
this.appservice.on("ephemeral", async (event) =>
this.onEphemeralEvent(event as unknown as EphemeralEvent)
);
this.appservice.on("http-log", (line) => {
this.onLog(line, false);
});
this.customiseAppserviceThirdPartyLookup();
if (this.metrics) {
this.metrics.addAppServicePath(this);
}
await this.appservice.listen(port, hostname, backlog);
}
/**
* Run the bridge (start listening). This calls `initalise()` and `listen()`.
* @param port The port to listen on.
* @param appServiceInstance The AppService instance to attach to.
* If not provided, one will be created.
* @param hostname Optional hostname to bind to.
* @return A promise resolving when the bridge is ready.
*/
public async run(port: number, appServiceInstance?: AppService, hostname = "0.0.0.0", backlog = 10): Promise<void> {
await this.initalise();
await this.listen(port, hostname, backlog, appServiceInstance);
}
// Set a timer going which will periodically remove Intent objects to prevent
// them from accumulating too much. Removal is based on access time (calls to
// getIntent). Intents expire after `INTENT_CULL_EVICT_AFTER_MS` of not being called.
private setupIntentCulling() {
if (this.intentLastAccessedTimeout) {
clearTimeout(this.intentLastAccessedTimeout);
}
this.intentLastAccessedTimeout = setTimeout(() => {
const now = Date.now();
for (const [key, entry] of this.intents.entries()) {
// Do not delete intents that sync.
const lastAccess = now - entry.lastAccessed;
if (lastAccess < INTENT_CULL_EVICT_AFTER_MS) {
// Intent is still in use.
continue;
}
if (this.eeEventBroker?.shouldAvoidCull(entry.intent)) {
// Intent is syncing events for encrypted rooms
continue;
}
this.intents.delete(key);
}
this.intentLastAccessedTimeout = null;
// repeat forever. We have no cancellation mechanism but we don't expect
// Bridge objects to be continually recycled so this is fine.
this.setupIntentCulling();
}, INTENT_CULL_CHECK_PERIOD_MS);
}
private customiseAppserviceThirdPartyLookup() {
const lookupController = this.opts.controller.thirdPartyLookup;
if (!lookupController) {
// Nothing to do.
return;
}
const protocols = lookupController.protocols || [];
const respondErr = function(e: {code?: number, err?: string}, res: ExResponse) {
if (e.code && e.err) {
res.status(e.code).json({error: e.err});
}
else {
res.status(500).send("Failed: " + e);
}
}
if (lookupController.getProtocol) {
const getProtocolFunc = lookupController.getProtocol;
this.addAppServicePath({
method: "GET",
path: "/_matrix/app/:version(v1|unstable)/thirdparty/protocol/:protocol",
checkToken: this.opts.authenticateThirdpartyEndpoints,
handler: async (req, res) => {
const protocol = req.params.protocol;
if (protocols.length && protocols.indexOf(protocol) === -1) {
res.status(404).json({err: "Unknown 3PN protocol " + protocol});
return;
}
try {
const result = await getProtocolFunc(protocol);
res.status(200).json(result);
}
catch (ex) {
respondErr(ex, res)
}
},
});
}
if (lookupController.getLocation) {
const getLocationFunc = lookupController.getLocation;
this.addAppServicePath({
method: "GET",
path: "/_matrix/app/:version(v1|unstable)/thirdparty/location/:protocol",
checkToken: this.opts.authenticateThirdpartyEndpoints,
handler: async (req, res) => {
const protocol = req.params.protocol;
if (protocols.length && protocols.indexOf(protocol) === -1) {
res.status(404).json({err: "Unknown 3PN protocol " + protocol});
return;
}
// Do not leak access token to function
delete req.query.access_token;
try {
const result = await getLocationFunc(protocol, req.query as Record<string, string[]|string>);
res.status(200).json(result);
}
catch (ex) {
respondErr(ex, res)
}
},
});
}
if (lookupController.parseLocation) {
const parseLocationFunc = lookupController.parseLocation;
this.addAppServicePath({
method: "GET",
path: "/_matrix/app/:version(v1|unstable)/thirdparty/location",
checkToken: this.opts.authenticateThirdpartyEndpoints,
handler: async (req, res) => {
const alias = req.query.alias;
if (!alias) {
res.status(400).send({err: "Missing 'alias' parameter"});
return;
}
if (typeof alias !== "string") {
res.status(400).send({err: "'alias' must be a string"});
return;
}
try {
const result = await parseLocationFunc(alias);
res.status(200).json(result);
}
catch (ex) {
respondErr(ex, res)
}
},
});
}
if (lookupController.getUser) {
const getUserFunc = lookupController.getUser;
this.addAppServicePath({
method: "GET",
path: "/_matrix/app/:version(v1|unstable)/thirdparty/user/:protocol",
checkToken: this.opts.authenticateThirdpartyEndpoints,
handler: async (req, res) => {
const protocol = req.params.protocol;
if (protocols.length && protocols.indexOf(protocol) === -1) {
res.status(404).json({err: "Unknown 3PN protocol " + protocol});
return;
}
// Do not leak access token to function
delete req.query.access_token;
try {
const result = await getUserFunc(protocol, req.query as Record<string, string[]|string>);
res.status(200).json(result);
}
catch (ex) {
respondErr(ex, res)
}
}
});
}
if (lookupController.parseUser) {
const parseUserFunc = lookupController.parseUser;
this.addAppServicePath({
method: "GET",
path: "/_matrix/app/:version(v1|unstable)/thirdparty/user",
checkToken: this.opts.authenticateThirdpartyEndpoints,
handler: async (req, res) => {
const userid = req.query.userid;
if (!userid) {
res.status(400).send({err: "Missing 'userid' parameter"});
return;
}
if (typeof userid !== "string") {
res.status(400).send({err: "'userid' must be a string"});
return;
}
try {
const result = await parseUserFunc(userid);
res.status(200).json(result);
}
catch (ex) {
respondErr(ex, res)
}
},
});
}
}
/**
* Install a custom handler for an incoming HTTP API request. This allows
* callers to add extra functionality, implement new APIs, etc...
* @param opts Named options
* @param opts.method The HTTP method name.
* @param opts.path Path to the endpoint.
* @param opts.checkToken Should the token be automatically checked. Defaults to true.