forked from slackapi/bolt-js
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApp.ts
More file actions
971 lines (867 loc) · 37.1 KB
/
App.ts
File metadata and controls
971 lines (867 loc) · 37.1 KB
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
/* eslint-disable @typescript-eslint/explicit-member-accessibility, @typescript-eslint/strict-boolean-expressions */
import { Agent } from 'http';
import { SecureContextOptions } from 'tls';
import util from 'util';
import { WebClient, ChatPostMessageArguments, addAppMetadata, WebClientOptions } from '@slack/web-api';
import { Logger, LogLevel, ConsoleLogger } from '@slack/logger';
import axios, { AxiosInstance } from 'axios';
import ExpressReceiver, { ExpressReceiverOptions } from './ExpressReceiver';
import {
ignoreSelf as ignoreSelfMiddleware,
onlyActions,
matchConstraints,
onlyCommands,
matchCommandName,
onlyOptions,
onlyShortcuts,
onlyEvents,
matchEventType,
matchMessage,
onlyViewActions,
} from './middleware/builtin';
import { processMiddleware } from './middleware/process';
import { ConversationStore, conversationContext, MemoryStore } from './conversation-store';
import { WorkflowStep } from './WorkflowStep';
import {
Middleware,
AnyMiddlewareArgs,
SlackActionMiddlewareArgs,
SlackCommandMiddlewareArgs,
SlackEventMiddlewareArgs,
SlackOptionsMiddlewareArgs,
SlackShortcutMiddlewareArgs,
SlackViewMiddlewareArgs,
SlackAction,
SlackShortcut,
Context,
SayFn,
AckFn,
RespondFn,
OptionsSource,
BlockAction,
InteractiveMessage,
SlackViewAction,
Receiver,
ReceiverEvent,
RespondArguments,
} from './types';
import { IncomingEventType, getTypeAndConversation, assertNever } from './helpers';
import { CodedError, asCodedError, AppInitializationError, MultipleListenerError } from './errors';
// eslint-disable-next-line import/order
import allSettled = require('promise.allsettled'); // eslint-disable-line @typescript-eslint/no-require-imports
// eslint-disable-next-line @typescript-eslint/no-require-imports
const packageJson = require('../package.json'); // eslint-disable-line @typescript-eslint/no-var-requires
/** App initialization options */
export interface AppOptions {
signingSecret?: ExpressReceiverOptions['signingSecret'];
endpoints?: ExpressReceiverOptions['endpoints'];
processBeforeResponse?: ExpressReceiverOptions['processBeforeResponse'];
clientId?: ExpressReceiverOptions['clientId'];
clientSecret?: ExpressReceiverOptions['clientSecret'];
stateSecret?: ExpressReceiverOptions['stateSecret']; // required when using default stateStore
installationStore?: ExpressReceiverOptions['installationStore']; // default MemoryInstallationStore
scopes?: ExpressReceiverOptions['scopes'];
installerOptions?: ExpressReceiverOptions['installerOptions'];
agent?: Agent;
clientTls?: Pick<SecureContextOptions, 'pfx' | 'key' | 'passphrase' | 'cert' | 'ca'>;
convoStore?: ConversationStore | false;
token?: AuthorizeResult['botToken']; // either token or authorize
botId?: AuthorizeResult['botId']; // only used when authorize is not defined, shortcut for fetching
botUserId?: AuthorizeResult['botUserId']; // only used when authorize is not defined, shortcut for fetching
authorize?: Authorize<false>; // either token or authorize
orgAuthorize?: Authorize<true>; // either token or orgAuthorize
receiver?: Receiver;
logger?: Logger;
logLevel?: LogLevel;
ignoreSelf?: boolean;
clientOptions?: Pick<WebClientOptions, 'slackApiUrl'>;
}
export { LogLevel, Logger } from '@slack/logger';
/** Authorization function - seeds the middleware processing and listeners with an authorization context */
export interface Authorize<IsEnterpriseInstall extends boolean = false> {
(source: AuthorizeSourceData<IsEnterpriseInstall>, body?: AnyMiddlewareArgs['body']): Promise<AuthorizeResult>;
}
/** Authorization function inputs - authenticated data about an event for the authorization function */
export interface AuthorizeSourceData<IsEnterpriseInstall extends boolean = false> {
teamId: IsEnterpriseInstall extends true ? string | undefined : string;
enterpriseId: IsEnterpriseInstall extends true ? string : string | undefined;
userId?: string;
conversationId?: string;
isEnterpriseInstall: IsEnterpriseInstall;
}
/** Authorization function outputs - data that will be available as part of event processing */
export interface AuthorizeResult {
// one of either botToken or userToken are required
botToken?: string; // used by `say` (preferred over userToken)
userToken?: string; // used by `say` (overridden by botToken)
botId?: string; // required for `ignoreSelf` global middleware
botUserId?: string; // optional but allows `ignoreSelf` global middleware be more filter more than just message events
teamId?: string;
enterpriseId?: string;
[key: string]: any;
}
export interface ActionConstraints<A extends SlackAction = SlackAction> {
type?: A['type'];
block_id?: A extends BlockAction ? string | RegExp : never;
action_id?: A extends BlockAction ? string | RegExp : never;
callback_id?: Extract<A, { callback_id?: string }> extends any ? string | RegExp : never;
}
export interface ShortcutConstraints<S extends SlackShortcut = SlackShortcut> {
type?: S['type'];
callback_id?: string | RegExp;
}
export interface ViewConstraints {
callback_id?: string | RegExp;
type?: 'view_closed' | 'view_submission';
}
export interface ErrorHandler {
(error: CodedError): Promise<void>;
}
class WebClientPool {
private pool: { [token: string]: WebClient } = {};
public getOrCreate(token: string, clientOptions: WebClientOptions): WebClient {
const cachedClient = this.pool[token];
if (typeof cachedClient !== 'undefined') {
return cachedClient;
}
const client = new WebClient(token, clientOptions);
this.pool[token] = client;
return client;
}
}
/**
* A Slack App
*/
export default class App {
/** Slack Web API client */
public client: WebClient;
private clientOptions: WebClientOptions;
// Some payloads don't have teamId anymore. So we use EnterpriseId in those scenarios
private clients: { [teamOrEnterpriseId: string]: WebClientPool } = {};
/** Receiver - ingests events from the Slack platform */
private receiver: Receiver;
/** Logger */
private logger: Logger;
/** Authorize */
private authorize!: Authorize<false>;
/** Org Authorize */
private orgAuthorize!: Authorize<true>;
/** Global middleware chain */
private middleware: Middleware<AnyMiddlewareArgs>[];
/** Listener middleware chains */
private listeners: Middleware<AnyMiddlewareArgs>[][];
private errorHandler: ErrorHandler;
private axios: AxiosInstance;
private installerOptions: ExpressReceiverOptions['installerOptions'];
constructor({
signingSecret = undefined,
endpoints = undefined,
agent = undefined,
clientTls = undefined,
receiver = undefined,
convoStore = undefined,
token = undefined,
botId = undefined,
botUserId = undefined,
authorize = undefined,
orgAuthorize = undefined,
logger = undefined,
logLevel = undefined,
ignoreSelf = true,
clientOptions = undefined,
processBeforeResponse = false,
clientId = undefined,
clientSecret = undefined,
stateSecret = undefined,
installationStore = undefined,
scopes = undefined,
installerOptions = undefined,
}: AppOptions = {}) {
if (typeof logger === 'undefined') {
// Initialize with the default logger
const consoleLogger = new ConsoleLogger();
consoleLogger.setName('bolt-app');
this.logger = consoleLogger;
} else {
this.logger = logger;
}
if (typeof logLevel !== 'undefined' && this.logger.getLevel() !== logLevel) {
this.logger.setLevel(logLevel);
}
this.errorHandler = defaultErrorHandler(this.logger);
this.clientOptions = {
agent,
// App propagates only the log level to WebClient as WebClient has its own logger
logLevel: this.logger.getLevel(),
tls: clientTls,
slackApiUrl: clientOptions !== undefined ? clientOptions.slackApiUrl : undefined,
};
// the public WebClient instance (app.client) - this one doesn't have a token
this.client = new WebClient(undefined, this.clientOptions);
this.axios = axios.create({
httpAgent: agent,
httpsAgent: agent,
...clientTls,
});
this.middleware = [];
this.listeners = [];
// Add clientOptions to InstallerOptions to pass them to @slack/oauth
this.installerOptions = {
clientOptions: this.clientOptions,
...installerOptions,
};
// Check for required arguments of ExpressReceiver
if (receiver !== undefined) {
this.receiver = receiver;
} else if (signingSecret === undefined) {
// No custom receiver
throw new AppInitializationError(
'Signing secret not found, so could not initialize the default receiver. Set a signing secret or use a ' +
'custom receiver.',
);
} else {
// Create default ExpressReceiver
this.receiver = new ExpressReceiver({
signingSecret,
endpoints,
processBeforeResponse,
clientId,
clientSecret,
stateSecret,
installationStore,
scopes,
installerOptions: this.installerOptions,
logger: this.logger,
});
}
let usingOauth = false;
if (
(this.receiver as ExpressReceiver).installer !== undefined &&
(this.receiver as ExpressReceiver).installer!.authorize !== undefined
) {
// This supports using the built in ExpressReceiver, declaring your own ExpressReceiver
// and theoretically, doing a fully custom (non express) receiver that implements OAuth
usingOauth = true;
}
if (token !== undefined) {
if (authorize !== undefined || orgAuthorize !== undefined || usingOauth) {
throw new AppInitializationError(
`token as well as authorize, orgAuthorize, or oauth installer options were provided. ${tokenUsage}`,
);
}
this.authorize = singleAuthorization(this.client, { botId, botUserId, botToken: token });
this.orgAuthorize = singleAuthorization(this.client, { botId, botUserId, botToken: token });
} else if (authorize === undefined && orgAuthorize === undefined && !usingOauth) {
throw new AppInitializationError(
`No token, no authorize, no orgAuthorize, and no oauth installer options provided. ${tokenUsage}`,
);
} else if ((authorize !== undefined || orgAuthorize !== undefined) && usingOauth) {
throw new AppInitializationError(`Both authorize options and oauth installer options provided. ${tokenUsage}`);
} else if (authorize === undefined && orgAuthorize === undefined && usingOauth) {
this.authorize = (this.receiver as ExpressReceiver).installer!.authorize;
this.orgAuthorize = (this.receiver as ExpressReceiver).installer!.authorize;
} else if (authorize === undefined && orgAuthorize !== undefined && !usingOauth) {
// only supporting org installs
this.orgAuthorize = orgAuthorize;
} else if (authorize !== undefined && orgAuthorize === undefined && !usingOauth) {
// only supporting non org installs
this.authorize = authorize;
} else if (authorize !== undefined && orgAuthorize !== undefined && !usingOauth) {
// supporting both org installs and non org installs
this.authorize = authorize;
this.orgAuthorize = orgAuthorize;
} else {
this.logger.error('Never should have reached this point, please report to the team');
assertNever();
}
// Conditionally use a global middleware that ignores events (including messages) that are sent from this app
if (ignoreSelf) {
this.use(ignoreSelfMiddleware());
}
// Use conversation state global middleware
if (convoStore !== false) {
// Use the memory store by default, or another store if provided
const store: ConversationStore = convoStore === undefined ? new MemoryStore() : convoStore;
this.use(conversationContext(store));
}
// Should be last to avoid exposing partially initialized app
this.receiver.init(this);
}
/**
* Register a new middleware, processed in the order registered.
*
* @param m global middleware function
*/
public use(m: Middleware<AnyMiddlewareArgs>): this {
this.middleware.push(m);
return this;
}
/**
* Register WorkflowStep middleware
*
* @param workflowStep global workflow step middleware function
*/
public step(workflowStep: WorkflowStep): this {
const m = workflowStep.getMiddleware();
this.middleware.push(m);
return this;
}
/**
* Convenience method to call start on the receiver
*
* TODO: args could be defined using a generic constraint from the receiver type
*
* @param args receiver-specific start arguments
*/
public start(...args: any[]): Promise<unknown> {
return this.receiver.start(...args);
}
public stop(...args: any[]): Promise<unknown> {
return this.receiver.stop(...args);
}
public event<EventType extends string = string>(
eventName: EventType,
...listeners: Middleware<SlackEventMiddlewareArgs<EventType>>[]
): void {
this.listeners.push([onlyEvents, matchEventType(eventName), ...listeners] as Middleware<AnyMiddlewareArgs>[]);
}
// TODO: just make a type alias for Middleware<SlackEventMiddlewareArgs<'message'>>
// TODO: maybe remove the first two overloads
public message(...listeners: Middleware<SlackEventMiddlewareArgs<'message'>>[]): void;
public message(pattern: string | RegExp, ...listeners: Middleware<SlackEventMiddlewareArgs<'message'>>[]): void;
public message(...patternsOrMiddleware: (string | RegExp | Middleware<SlackEventMiddlewareArgs<'message'>>)[]): void {
const messageMiddleware = patternsOrMiddleware.map((patternOrMiddleware) => {
if (typeof patternOrMiddleware === 'string' || util.types.isRegExp(patternOrMiddleware)) {
return matchMessage(patternOrMiddleware);
}
return patternOrMiddleware;
});
this.listeners.push([
onlyEvents,
matchEventType('message'),
...messageMiddleware,
] as Middleware<AnyMiddlewareArgs>[]);
}
public shortcut<Shortcut extends SlackShortcut = SlackShortcut>(
callbackId: string | RegExp,
...listeners: Middleware<SlackShortcutMiddlewareArgs<Shortcut>>[]
): void;
public shortcut<
Shortcut extends SlackShortcut = SlackShortcut,
Constraints extends ShortcutConstraints<Shortcut> = ShortcutConstraints<Shortcut>
>(
constraints: Constraints,
...listeners: Middleware<SlackShortcutMiddlewareArgs<Extract<Shortcut, { type: Constraints['type'] }>>>[]
): void;
public shortcut<
Shortcut extends SlackShortcut = SlackShortcut,
Constraints extends ShortcutConstraints<Shortcut> = ShortcutConstraints<Shortcut>
>(
callbackIdOrConstraints: string | RegExp | Constraints,
...listeners: Middleware<SlackShortcutMiddlewareArgs<Extract<Shortcut, { type: Constraints['type'] }>>>[]
): void {
const constraints: ShortcutConstraints =
typeof callbackIdOrConstraints === 'string' || util.types.isRegExp(callbackIdOrConstraints)
? { callback_id: callbackIdOrConstraints }
: callbackIdOrConstraints;
// Fail early if the constraints contain invalid keys
const unknownConstraintKeys = Object.keys(constraints).filter((k) => k !== 'callback_id' && k !== 'type');
if (unknownConstraintKeys.length > 0) {
this.logger.error(
`Slack listener cannot be attached using unknown constraint keys: ${unknownConstraintKeys.join(', ')}`,
);
return;
}
this.listeners.push([
onlyShortcuts,
matchConstraints(constraints),
...listeners,
] as Middleware<AnyMiddlewareArgs>[]);
}
// NOTE: this is what's called a convenience generic, so that types flow more easily without casting.
// https://basarat.gitbooks.io/typescript/docs/types/generics.html#design-pattern-convenience-generic
public action<Action extends SlackAction = SlackAction>(
actionId: string | RegExp,
...listeners: Middleware<SlackActionMiddlewareArgs<Action>>[]
): void;
public action<
Action extends SlackAction = SlackAction,
Constraints extends ActionConstraints<Action> = ActionConstraints<Action>
>(
constraints: Constraints,
// NOTE: Extract<> is able to return the whole union when type: undefined. Why?
...listeners: Middleware<SlackActionMiddlewareArgs<Extract<Action, { type: Constraints['type'] }>>>[]
): void;
public action<
Action extends SlackAction = SlackAction,
Constraints extends ActionConstraints<Action> = ActionConstraints<Action>
>(
actionIdOrConstraints: string | RegExp | Constraints,
...listeners: Middleware<SlackActionMiddlewareArgs<Extract<Action, { type: Constraints['type'] }>>>[]
): void {
// Normalize Constraints
const constraints: ActionConstraints =
typeof actionIdOrConstraints === 'string' || util.types.isRegExp(actionIdOrConstraints)
? { action_id: actionIdOrConstraints }
: actionIdOrConstraints;
// Fail early if the constraints contain invalid keys
const unknownConstraintKeys = Object.keys(constraints).filter(
(k) => k !== 'action_id' && k !== 'block_id' && k !== 'callback_id' && k !== 'type',
);
if (unknownConstraintKeys.length > 0) {
this.logger.error(
`Action listener cannot be attached using unknown constraint keys: ${unknownConstraintKeys.join(', ')}`,
);
return;
}
this.listeners.push([onlyActions, matchConstraints(constraints), ...listeners] as Middleware<AnyMiddlewareArgs>[]);
}
// TODO: should command names also be regex?
public command(commandName: string, ...listeners: Middleware<SlackCommandMiddlewareArgs>[]): void {
this.listeners.push([onlyCommands, matchCommandName(commandName), ...listeners] as Middleware<AnyMiddlewareArgs>[]);
}
public options<Source extends OptionsSource = OptionsSource>(
actionId: string | RegExp,
...listeners: Middleware<SlackOptionsMiddlewareArgs<Source>>[]
): void;
public options<Source extends OptionsSource = OptionsSource>(
constraints: ActionConstraints,
...listeners: Middleware<SlackOptionsMiddlewareArgs<Source>>[]
): void;
public options<Source extends OptionsSource = OptionsSource>(
actionIdOrConstraints: string | RegExp | ActionConstraints,
...listeners: Middleware<SlackOptionsMiddlewareArgs<Source>>[]
): void {
const constraints: ActionConstraints =
typeof actionIdOrConstraints === 'string' || util.types.isRegExp(actionIdOrConstraints)
? { action_id: actionIdOrConstraints }
: actionIdOrConstraints;
this.listeners.push([onlyOptions, matchConstraints(constraints), ...listeners] as Middleware<AnyMiddlewareArgs>[]);
}
public view<ViewActionType extends SlackViewAction = SlackViewAction>(
callbackId: string | RegExp,
...listeners: Middleware<SlackViewMiddlewareArgs<ViewActionType>>[]
): void;
public view<ViewActionType extends SlackViewAction = SlackViewAction>(
constraints: ViewConstraints,
...listeners: Middleware<SlackViewMiddlewareArgs<ViewActionType>>[]
): void;
public view<ViewActionType extends SlackViewAction = SlackViewAction>(
callbackIdOrConstraints: string | RegExp | ViewConstraints,
...listeners: Middleware<SlackViewMiddlewareArgs<ViewActionType>>[]
): void {
const constraints: ViewConstraints =
typeof callbackIdOrConstraints === 'string' || util.types.isRegExp(callbackIdOrConstraints)
? { callback_id: callbackIdOrConstraints, type: 'view_submission' }
: callbackIdOrConstraints;
// Fail early if the constraints contain invalid keys
const unknownConstraintKeys = Object.keys(constraints).filter((k) => k !== 'callback_id' && k !== 'type');
if (unknownConstraintKeys.length > 0) {
this.logger.error(
`View listener cannot be attached using unknown constraint keys: ${unknownConstraintKeys.join(', ')}`,
);
return;
}
if (constraints.type !== undefined && !validViewTypes.includes(constraints.type)) {
this.logger.error(`View listener cannot be attached using unknown view event type: ${constraints.type}`);
return;
}
this.listeners.push([
onlyViewActions,
matchConstraints(constraints),
...listeners,
] as Middleware<AnyMiddlewareArgs>[]);
}
public error(errorHandler: ErrorHandler): void {
this.errorHandler = errorHandler;
}
/**
* Handles events from the receiver
*/
public async processEvent(event: ReceiverEvent): Promise<void> {
const { body, ack } = event;
// TODO: when generating errors (such as in the say utility) it may become useful to capture the current context,
// or even all of the args, as properties of the error. This would give error handling code some ability to deal
// with "finally" type error situations.
// Introspect the body to determine what type of incoming event is being handled, and any channel context
const { type, conversationId } = getTypeAndConversation(body);
// If the type could not be determined, warn and exit
if (type === undefined) {
this.logger.warn('Could not determine the type of an incoming event. No listeners will be called.');
return;
}
// From this point on, we assume that body is not just a key-value map, but one of the types of bodies we expect
const bodyArg = body as AnyMiddlewareArgs['body'];
// Check if type event with the authorizations object or if it has a top level is_enterprise_install property
const isEnterpriseInstall = isBodyWithTypeEnterpriseInstall(bodyArg, type);
const source = buildSource(type, conversationId, bodyArg, isEnterpriseInstall);
let authorizeResult: AuthorizeResult;
try {
if (source.isEnterpriseInstall) {
authorizeResult = await this.orgAuthorize(source as AuthorizeSourceData<true>, bodyArg);
} else {
authorizeResult = await this.authorize(source as AuthorizeSourceData<false>, bodyArg);
}
} catch (error) {
this.logger.warn('Authorization of incoming event did not succeed. No listeners will be called.');
error.code = 'slack_bolt_authorization_error';
return this.handleError(error);
}
// Try to set teamId from AuthorizeResult before using one from source
if (authorizeResult.teamId === undefined && source.teamId !== undefined) {
authorizeResult.teamId = source.teamId;
}
// Try to set enterpriseId from AuthorizeResult before using one from source
if (authorizeResult.enterpriseId === undefined && source.enterpriseId !== undefined) {
authorizeResult.enterpriseId = source.enterpriseId;
}
const context: Context = { ...authorizeResult };
// Factory for say() utility
const createSay = (channelId: string): SayFn => {
const token = selectToken(context);
return (message: Parameters<SayFn>[0]) => {
const postMessageArguments: ChatPostMessageArguments =
typeof message === 'string'
? { token, text: message, channel: channelId }
: { ...message, token, channel: channelId };
return this.client.chat.postMessage(postMessageArguments);
};
};
// Set body and payload (this value will eventually conform to AnyMiddlewareArgs)
// NOTE: the following doesn't work because... distributive?
// const listenerArgs: Partial<AnyMiddlewareArgs> = {
const listenerArgs: Pick<AnyMiddlewareArgs, 'body' | 'payload'> & {
/** Say function might be set below */
say?: SayFn;
/** Respond function might be set below */
respond?: RespondFn;
/** Ack function might be set below */
ack?: AckFn<any>;
} = {
body: bodyArg,
payload:
type === IncomingEventType.Event
? (bodyArg as SlackEventMiddlewareArgs['body']).event
: type === IncomingEventType.ViewAction
? (bodyArg as SlackViewMiddlewareArgs['body']).view
: type === IncomingEventType.Shortcut
? (bodyArg as SlackShortcutMiddlewareArgs['body'])
: type === IncomingEventType.Action &&
isBlockActionOrInteractiveMessageBody(bodyArg as SlackActionMiddlewareArgs['body'])
? (bodyArg as SlackActionMiddlewareArgs<BlockAction | InteractiveMessage>['body']).actions[0]
: (bodyArg as (
| Exclude<
AnyMiddlewareArgs,
SlackEventMiddlewareArgs | SlackActionMiddlewareArgs | SlackViewMiddlewareArgs
>
| SlackActionMiddlewareArgs<Exclude<SlackAction, BlockAction | InteractiveMessage>>
)['body']),
};
// Set aliases
if (type === IncomingEventType.Event) {
const eventListenerArgs = listenerArgs as SlackEventMiddlewareArgs;
eventListenerArgs.event = eventListenerArgs.payload;
if (eventListenerArgs.event.type === 'message') {
const messageEventListenerArgs = eventListenerArgs as SlackEventMiddlewareArgs<'message'>;
messageEventListenerArgs.message = messageEventListenerArgs.payload;
}
} else if (type === IncomingEventType.Action) {
const actionListenerArgs = listenerArgs as SlackActionMiddlewareArgs;
actionListenerArgs.action = actionListenerArgs.payload;
} else if (type === IncomingEventType.Command) {
const commandListenerArgs = listenerArgs as SlackCommandMiddlewareArgs;
commandListenerArgs.command = commandListenerArgs.payload;
} else if (type === IncomingEventType.Options) {
const optionListenerArgs = listenerArgs as SlackOptionsMiddlewareArgs<OptionsSource>;
optionListenerArgs.options = optionListenerArgs.payload;
} else if (type === IncomingEventType.ViewAction) {
const viewListenerArgs = listenerArgs as SlackViewMiddlewareArgs;
viewListenerArgs.view = viewListenerArgs.payload;
} else if (type === IncomingEventType.Shortcut) {
const shortcutListenerArgs = listenerArgs as SlackShortcutMiddlewareArgs;
shortcutListenerArgs.shortcut = shortcutListenerArgs.payload;
}
// Set say() utility
if (conversationId !== undefined && type !== IncomingEventType.Options) {
listenerArgs.say = createSay(conversationId);
}
// Set respond() utility
if (body.response_url) {
listenerArgs.respond = (response: string | RespondArguments): Promise<any> => {
const validResponse: RespondArguments = typeof response === 'string' ? { text: response } : response;
return this.axios.post(body.response_url, validResponse);
};
}
// Set ack() utility
if (type !== IncomingEventType.Event) {
listenerArgs.ack = ack;
} else {
// Events API requests are acknowledged right away, since there's no data expected
await ack();
}
// Get the client arg
let { client } = this;
const token = selectToken(context);
if (token !== undefined) {
let pool;
const clientOptionsCopy = { ...this.clientOptions };
if (authorizeResult.teamId !== undefined) {
pool = this.clients[authorizeResult.teamId];
if (pool === undefined) {
// eslint-disable-next-line no-multi-assign
pool = this.clients[authorizeResult.teamId] = new WebClientPool();
}
// Add teamId to clientOptions so it can be automatically added to web-api calls
clientOptionsCopy.teamId = authorizeResult.teamId;
} else if (authorizeResult.enterpriseId !== undefined) {
pool = this.clients[authorizeResult.enterpriseId];
if (pool === undefined) {
// eslint-disable-next-line no-multi-assign
pool = this.clients[authorizeResult.enterpriseId] = new WebClientPool();
}
}
if (pool !== undefined) {
client = pool.getOrCreate(token, clientOptionsCopy);
}
}
// Dispatch event through the global middleware chain
try {
await processMiddleware(
this.middleware,
listenerArgs as AnyMiddlewareArgs,
context,
client,
this.logger,
async () => {
// Dispatch the event through the listener middleware chains and aggregate their results
// TODO: change the name of this.middleware and this.listeners to help this make more sense
const listenerResults = this.listeners.map(async (origListenerMiddleware) => {
// Copy the array so modifications don't affect the original
const listenerMiddleware = [...origListenerMiddleware];
// Don't process the last item in the listenerMiddleware array - it shouldn't get a next fn
const listener = listenerMiddleware.pop();
if (listener !== undefined) {
return processMiddleware(
listenerMiddleware,
listenerArgs as AnyMiddlewareArgs,
context,
client,
this.logger,
async () =>
// When the listener middleware chain is done processing, call the listener without a next fn
listener({ ...(listenerArgs as AnyMiddlewareArgs), context, client, logger: this.logger }),
);
}
});
const settledListenerResults = await allSettled(listenerResults);
const rejectedListenerResults = settledListenerResults.filter(
(lr) => lr.status === 'rejected',
) as allSettled.PromiseRejection<Error>[];
if (rejectedListenerResults.length === 1) {
throw rejectedListenerResults[0].reason;
} else if (rejectedListenerResults.length > 1) {
throw new MultipleListenerError(rejectedListenerResults.map((rlr) => rlr.reason));
}
},
);
} catch (error) {
return this.handleError(error);
}
}
/**
* Global error handler. The final destination for all errors (hopefully).
*/
private handleError(error: Error): Promise<void> {
return this.errorHandler(asCodedError(error));
}
}
const tokenUsage =
'Apps used in one workspace should be initialized with a token. Apps used in many workspaces ' +
'should be initialized with oauth installer or authorize.';
const validViewTypes = ['view_closed', 'view_submission'];
/**
* Helper which builds the data structure the authorize hook uses to provide tokens for the context.
*/
function buildSource<IsEnterpriseInstall extends boolean>(
type: IncomingEventType,
channelId: string | undefined,
body: AnyMiddlewareArgs['body'],
isEnterpriseInstall: IsEnterpriseInstall,
): AuthorizeSourceData<IsEnterpriseInstall> {
// NOTE: potentially something that can be optimized, so that each of these conditions isn't evaluated more than once.
// if this makes it prettier, great! but we should probably check perf before committing to any specific optimization.
const teamId: string | undefined = (() => {
if (type === IncomingEventType.Event) {
const bodyAsEvent = body as SlackEventMiddlewareArgs['body'];
if (
Array.isArray(bodyAsEvent.authorizations) &&
bodyAsEvent.authorizations[0] !== undefined &&
bodyAsEvent.authorizations[0].team_id !== null
) {
return bodyAsEvent.authorizations[0].team_id;
}
return bodyAsEvent.team_id;
}
if (type === IncomingEventType.Command) {
return (body as SlackCommandMiddlewareArgs['body']).team_id;
}
if (
type === IncomingEventType.Action ||
type === IncomingEventType.Options ||
type === IncomingEventType.ViewAction ||
type === IncomingEventType.Shortcut
) {
const bodyAsActionOrOptionsOrViewActionOrShortcut = body as (
| SlackActionMiddlewareArgs
| SlackOptionsMiddlewareArgs
| SlackViewMiddlewareArgs
| SlackShortcutMiddlewareArgs
)['body'];
// When the app is installed using org-wide deployment, team property will be null
if (bodyAsActionOrOptionsOrViewActionOrShortcut.team !== null) {
return bodyAsActionOrOptionsOrViewActionOrShortcut.team.id;
}
// This is the only place where this function might return undefined
return bodyAsActionOrOptionsOrViewActionOrShortcut.user.team_id;
}
return assertNever(type);
})();
const enterpriseId: string | undefined = (() => {
if (type === IncomingEventType.Event) {
const bodyAsEvent = body as SlackEventMiddlewareArgs['body'];
if (
Array.isArray(bodyAsEvent.authorizations) &&
bodyAsEvent.authorizations[0] !== undefined &&
bodyAsEvent.authorizations[0].enterprise_id !== null
) {
return bodyAsEvent.authorizations[0].enterprise_id;
}
return bodyAsEvent.enterprise_id;
}
if (type === IncomingEventType.Command) {
return (body as SlackCommandMiddlewareArgs['body']).enterprise_id;
}
if (
type === IncomingEventType.Action ||
type === IncomingEventType.Options ||
type === IncomingEventType.ViewAction ||
type === IncomingEventType.Shortcut
) {
// NOTE: no type system backed exhaustiveness check within this group of incoming event types
const bodyAsActionOrOptionsOrViewActionOrShortcut = body as (
| SlackActionMiddlewareArgs
| SlackOptionsMiddlewareArgs
| SlackViewMiddlewareArgs
| SlackShortcutMiddlewareArgs
)['body'];
// When the app is installed using org-wide deployment, team property will be null
if (bodyAsActionOrOptionsOrViewActionOrShortcut.team !== null) {
return bodyAsActionOrOptionsOrViewActionOrShortcut.team.enterprise_id;
}
if (bodyAsActionOrOptionsOrViewActionOrShortcut.enterprise !== undefined) {
return bodyAsActionOrOptionsOrViewActionOrShortcut.enterprise.id;
}
return undefined;
}
return assertNever(type);
})();
const userId: string | undefined = (() => {
if (type === IncomingEventType.Event) {
// NOTE: no type system backed exhaustiveness check within this incoming event type
const { event } = body as SlackEventMiddlewareArgs['body'];
if ('user' in event) {
if (typeof event.user === 'string') {
return event.user;
}
if (typeof event.user === 'object') {
return event.user.id;
}
}
if ('channel' in event && typeof event.channel !== 'string' && 'creator' in event.channel) {
return event.channel.creator;
}
if ('subteam' in event && event.subteam.created_by !== undefined) {
return event.subteam.created_by;
}
return undefined;
}
if (
type === IncomingEventType.Action ||
type === IncomingEventType.Options ||
type === IncomingEventType.ViewAction ||
type === IncomingEventType.Shortcut
) {
// NOTE: no type system backed exhaustiveness check within this incoming event type
const bodyAsActionOrOptionsOrViewActionOrShortcut = body as (
| SlackActionMiddlewareArgs
| SlackOptionsMiddlewareArgs
| SlackViewMiddlewareArgs
| SlackShortcutMiddlewareArgs
)['body'];
return bodyAsActionOrOptionsOrViewActionOrShortcut.user.id;
}
if (type === IncomingEventType.Command) {
return (body as SlackCommandMiddlewareArgs['body']).user_id;
}
return assertNever(type);
})();
return {
userId,
isEnterpriseInstall,
teamId: teamId as IsEnterpriseInstall extends true ? string | undefined : string,
enterpriseId: enterpriseId as IsEnterpriseInstall extends true ? string : string | undefined,
conversationId: channelId,
};
}
function isBodyWithTypeEnterpriseInstall(body: AnyMiddlewareArgs['body'], type: IncomingEventType): boolean {
if (type === IncomingEventType.Event) {
const bodyAsEvent = body as SlackEventMiddlewareArgs['body'];
if (Array.isArray(bodyAsEvent.authorizations) && bodyAsEvent.authorizations[0] !== undefined) {
return !!bodyAsEvent.authorizations[0].is_enterprise_install;
}
}
// command payloads have this property set as a string
if (body.is_enterprise_install === 'true') {
return true;
}
// all remaining types have a boolean property
if (body.is_enterprise_install !== undefined) {
return body.is_enterprise_install;
}
// as a fallback we assume it's a single team installation (but this should never happen)
return false;
}
function isBlockActionOrInteractiveMessageBody(
body: SlackActionMiddlewareArgs['body'],
): body is SlackActionMiddlewareArgs<BlockAction | InteractiveMessage>['body'] {
return (body as SlackActionMiddlewareArgs<BlockAction | InteractiveMessage>['body']).actions !== undefined;
}
function defaultErrorHandler(logger: Logger): ErrorHandler {
return (error) => {
logger.error(error);
return Promise.reject(error);
};
}
function singleAuthorization(
client: WebClient,
authorization: Partial<AuthorizeResult> & { botToken: Required<AuthorizeResult>['botToken'] },
): Authorize<boolean> {
// TODO: warn when something needed isn't found
const identifiers: Promise<{ botUserId: string; botId: string }> =
authorization.botUserId !== undefined && authorization.botId !== undefined
? Promise.resolve({ botUserId: authorization.botUserId, botId: authorization.botId })
: client.auth.test({ token: authorization.botToken }).then((result) => {
return {
botUserId: result.user_id as string,
botId: result.bot_id as string,
};
});
return async ({ isEnterpriseInstall }) => {
return { isEnterpriseInstall, botToken: authorization.botToken, ...(await identifiers) };
};
}
function selectToken(context: Context): string | undefined {
return context.botToken !== undefined ? context.botToken : context.userToken;
}
/* Instrumentation */
addAppMetadata({ name: packageJson.name, version: packageJson.version });