-
Notifications
You must be signed in to change notification settings - Fork 385
/
SocketModeReceiver.ts
270 lines (245 loc) · 10.5 KB
/
SocketModeReceiver.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
/* eslint-disable @typescript-eslint/no-explicit-any */
import { URL } from 'url';
import { createServer, ServerResponse, Server } from 'http';
import { SocketModeClient } from '@slack/socket-mode';
import { Logger, ConsoleLogger, LogLevel } from '@slack/logger';
import { InstallProvider, CallbackOptions, InstallProviderOptions, InstallURLOptions, InstallPathOptions } from '@slack/oauth';
import { AppsConnectionsOpenResponse } from '@slack/web-api';
import { match } from 'path-to-regexp';
import { ParamsDictionary } from 'express-serve-static-core';
import { ParamsIncomingMessage } from './ParamsIncomingMessage';
import App from '../App';
import { CodedError } from '../errors';
import { Receiver, ReceiverEvent } from '../types';
import { StringIndexed } from '../types/helpers';
import { buildReceiverRoutes, ReceiverRoutes } from './custom-routes';
import { verifyRedirectOpts } from './verify-redirect-opts';
import {
SocketModeFunctions as socketModeFunc,
SocketModeReceiverProcessEventErrorHandlerArgs,
} from './SocketModeFunctions';
// TODO: we throw away the key names for endpoints, so maybe we should use this interface. is it better for migrations?
// if that's the reason, let's document that with a comment.
export interface SocketModeReceiverOptions {
logger?: Logger;
logLevel?: LogLevel;
clientId?: string;
clientSecret?: string;
stateSecret?: InstallProviderOptions['stateSecret']; // required when using default stateStore
redirectUri?: string;
installationStore?: InstallProviderOptions['installationStore']; // default MemoryInstallationStore
scopes?: InstallURLOptions['scopes'];
installerOptions?: InstallerOptions;
appToken: string; // App Level Token
customRoutes?: CustomRoute[];
customPropertiesExtractor?: (args: any) => StringIndexed;
processEventErrorHandler?: (args: SocketModeReceiverProcessEventErrorHandlerArgs) => Promise<boolean>;
}
export interface CustomRoute {
path: string;
method: string | string[];
handler: (req: ParamsIncomingMessage, res: ServerResponse) => void;
}
// Additional Installer Options
interface InstallerOptions {
stateStore?: InstallProviderOptions['stateStore']; // default ClearStateStore
stateVerification?: InstallProviderOptions['stateVerification']; // default true
legacyStateVerification?: InstallProviderOptions['legacyStateVerification'];
stateCookieName?: InstallProviderOptions['stateCookieName'];
stateCookieExpirationSeconds?: InstallProviderOptions['stateCookieExpirationSeconds'];
authVersion?: InstallProviderOptions['authVersion']; // default 'v2'
metadata?: InstallURLOptions['metadata'];
installPath?: string;
directInstall?: boolean; // see https://api.slack.com/start/distributing/directory#direct_install
renderHtmlForInstallPath?: InstallProviderOptions['renderHtmlForInstallPath'];
redirectUriPath?: string;
installPathOptions?: InstallPathOptions;
callbackOptions?: CallbackOptions;
userScopes?: InstallURLOptions['userScopes'];
clientOptions?: InstallProviderOptions['clientOptions'];
authorizationUrl?: InstallProviderOptions['authorizationUrl'];
port?: number; // used to create a server when doing OAuth or serving custom routes
}
/**
* Receives Events, Slash Commands, and Actions of a web socket connection
*/
export default class SocketModeReceiver implements Receiver {
/* Express app */
public client: SocketModeClient;
private app: App | undefined;
private logger: Logger;
public installer: InstallProvider | undefined = undefined;
private httpServer?: Server;
private httpServerPort?: number;
private routes: ReceiverRoutes;
private processEventErrorHandler: (args: SocketModeReceiverProcessEventErrorHandlerArgs) => Promise<boolean>;
public constructor({
appToken,
logger = undefined,
logLevel = LogLevel.INFO,
clientId = undefined,
clientSecret = undefined,
stateSecret = undefined,
redirectUri = undefined,
installationStore = undefined,
scopes = undefined,
installerOptions = {},
customRoutes = [],
customPropertiesExtractor = (_args) => ({}),
processEventErrorHandler = socketModeFunc.defaultProcessEventErrorHandler,
}: SocketModeReceiverOptions) {
this.client = new SocketModeClient({
appToken,
logLevel,
logger,
clientOptions: installerOptions.clientOptions,
});
this.logger = logger ?? (() => {
const defaultLogger = new ConsoleLogger();
defaultLogger.setLevel(logLevel);
return defaultLogger;
})();
this.routes = buildReceiverRoutes(customRoutes);
this.processEventErrorHandler = processEventErrorHandler;
// Verify redirect options if supplied, throws coded error if invalid
verifyRedirectOpts({ redirectUri, redirectUriPath: installerOptions.redirectUriPath });
if (
clientId !== undefined &&
clientSecret !== undefined &&
(installerOptions.stateVerification === false || // state store not needed
stateSecret !== undefined ||
installerOptions.stateStore !== undefined) // user provided state store
) {
this.installer = new InstallProvider({
clientId,
clientSecret,
stateSecret,
installationStore,
logLevel,
logger, // pass logger that was passed in constructor, not one created locally
directInstall: installerOptions.directInstall,
stateStore: installerOptions.stateStore,
stateVerification: installerOptions.stateVerification,
legacyStateVerification: installerOptions.legacyStateVerification,
stateCookieName: installerOptions.stateCookieName,
stateCookieExpirationSeconds: installerOptions.stateCookieExpirationSeconds,
renderHtmlForInstallPath: installerOptions.renderHtmlForInstallPath,
authVersion: installerOptions.authVersion,
clientOptions: installerOptions.clientOptions,
authorizationUrl: installerOptions.authorizationUrl,
});
}
// Add OAuth and/or custom routes to receiver
if (this.installer !== undefined || customRoutes.length) {
const installPath = installerOptions.installPath === undefined ? '/slack/install' : installerOptions.installPath;
this.httpServerPort = installerOptions.port === undefined ? 3000 : installerOptions.port;
this.httpServer = createServer(async (req, res) => {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const method = req.method!.toUpperCase();
// Handle OAuth-related requests
if (this.installer) {
// create install url options
const installUrlOptions = {
metadata: installerOptions.metadata,
scopes: scopes ?? [],
userScopes: installerOptions.userScopes,
redirectUri,
};
// Installation has been initiated
const redirectUriPath = installerOptions.redirectUriPath === undefined ? '/slack/oauth_redirect' : installerOptions.redirectUriPath;
if (req.url && req.url.startsWith(redirectUriPath)) {
const { stateVerification, callbackOptions } = installerOptions;
if (stateVerification === false) {
// if stateVerification is disabled make install options available to handler
// since they won't be encoded in the state param of the generated url
await this.installer.handleCallback(req, res, callbackOptions, installUrlOptions);
} else {
await this.installer.handleCallback(req, res, callbackOptions);
}
return;
}
// Visiting the installation endpoint
if (req.url && req.url.startsWith(installPath)) {
const { installPathOptions } = installerOptions;
await this.installer.handleInstallPath(req, res, installPathOptions, installUrlOptions);
return;
}
}
// Handle request for custom routes
if (customRoutes.length && req.url) {
// NOTE: the domain and scheme are irrelevant here.
// The URL object is only used to safely obtain the path to match
const { pathname: path } = new URL(req.url as string, 'http://localhost');
const routes = Object.keys(this.routes);
for (let i = 0; i < routes.length; i += 1) {
const route = routes[i];
const matchRegex = match(route, { decode: decodeURIComponent });
const pathMatch = matchRegex(path);
if (pathMatch && this.routes[route][method] !== undefined) {
const params = pathMatch.params as ParamsDictionary;
const message: ParamsIncomingMessage = Object.assign(req, { params });
this.routes[route][method](message, res);
return;
}
}
}
this.logger.info(`An unhandled HTTP request (${req.method}) made to ${req.url} was ignored`);
res.writeHead(404, {});
res.end();
});
this.logger.debug(`Listening for HTTP requests on port ${this.httpServerPort}`);
if (this.installer) {
this.logger.debug(`Go to http://localhost:${this.httpServerPort}${installPath} to initiate OAuth flow`);
}
}
this.client.on('slack_event', async (args) => {
const { ack, body, retry_num, retry_reason } = args;
const event: ReceiverEvent = {
body,
ack,
retryNum: retry_num,
retryReason: retry_reason,
customProperties: customPropertiesExtractor(args),
};
try {
await this.app?.processEvent(event);
} catch (error) {
const shouldBeAcked = await this.processEventErrorHandler({
error: error as Error | CodedError,
logger: this.logger,
event,
});
if (shouldBeAcked) {
await ack();
}
}
});
}
public init(app: App): void {
this.app = app;
}
public start(): Promise<AppsConnectionsOpenResponse> {
if (this.httpServer !== undefined) {
// This HTTP server is only for the OAuth flow support
this.httpServer.listen(this.httpServerPort);
}
// start socket mode client
return this.client.start();
}
public stop(): Promise<void> {
if (this.httpServer !== undefined) {
// This HTTP server is only for the OAuth flow support
this.httpServer.close((error) => {
if (error) this.logger.error(`Failed to shutdown the HTTP server for OAuth flow: ${error}`);
});
}
return new Promise((resolve, reject) => {
try {
this.client.disconnect();
resolve();
} catch (error) {
reject(error);
}
});
}
}