-
Notifications
You must be signed in to change notification settings - Fork 399
/
ExpressReceiver.ts
592 lines (526 loc) · 20.5 KB
/
ExpressReceiver.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
import crypto from 'node:crypto';
import { type Server, type ServerOptions, createServer } from 'node:http';
import type { IncomingMessage, ServerResponse } from 'node:http';
import {
type Server as HTTPSServer,
type ServerOptions as HTTPSServerOptions,
createServer as createHttpsServer,
} from 'node:https';
import type { ListenOptions } from 'node:net';
import querystring from 'node:querystring';
import { ConsoleLogger, LogLevel, type Logger } from '@slack/logger';
import {
type CallbackOptions,
type InstallPathOptions,
InstallProvider,
type InstallProviderOptions,
type InstallURLOptions,
} from '@slack/oauth';
import express, {
type Request,
type Response,
type Application,
type RequestHandler,
Router,
type IRouter,
} from 'express';
import rawBody from 'raw-body';
import tsscmp from 'tsscmp';
import type App from '../App';
import { type CodedError, ReceiverAuthenticityError, ReceiverInconsistentStateError } from '../errors';
import type { AnyMiddlewareArgs, Receiver, ReceiverEvent } from '../types';
import type { StringIndexed } from '../types/utilities';
import * as httpFunc from './HTTPModuleFunctions';
import { HTTPResponseAck } from './HTTPResponseAck';
import { verifyRedirectOpts } from './verify-redirect-opts';
// Option keys for tls.createServer() and tls.createSecureContext(), exclusive of those for http.createServer()
const httpsOptionKeys = [
'ALPNProtocols',
'clientCertEngine',
'enableTrace',
'handshakeTimeout',
'rejectUnauthorized',
'requestCert',
'sessionTimeout',
'SNICallback',
'ticketKeys',
'pskCallback',
'pskIdentityHint',
'ca',
'cert',
'sigalgs',
'ciphers',
'clientCertEngine',
'crl',
'dhparam',
'ecdhCurve',
'honorCipherOrder',
'key',
'privateKeyEngine',
'privateKeyIdentifier',
'maxVersion',
'minVersion',
'passphrase',
'pfx',
'secureOptions',
'secureProtocol',
'sessionIdContext',
];
const missingServerErrorDescription =
'The receiver cannot be started because private state was mutated. Please report this to the maintainers.';
export const respondToSslCheck: RequestHandler = (req, res, next) => {
if (req.body?.ssl_check) {
res.send();
return;
}
next();
};
export const respondToUrlVerification: RequestHandler = (req, res, next) => {
if (req.body?.type && req.body.type === 'url_verification') {
res.json({ challenge: req.body.challenge });
return;
}
next();
};
// 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 ExpressReceiverOptions {
signingSecret: string | (() => PromiseLike<string>);
logger?: Logger;
logLevel?: LogLevel;
endpoints?:
| string
| {
[endpointType: string]: string;
};
signatureVerification?: boolean;
processBeforeResponse?: boolean;
clientId?: string;
clientSecret?: string;
stateSecret?: InstallProviderOptions['stateSecret']; // required when using default stateStore
redirectUri?: string;
installationStore?: InstallProviderOptions['installationStore']; // default MemoryInstallationStore
scopes?: InstallURLOptions['scopes'];
installerOptions?: InstallerOptions;
app?: Application;
router?: IRouter;
customPropertiesExtractor?: (request: Request) => StringIndexed;
dispatchErrorHandler?: (args: httpFunc.ReceiverDispatchErrorHandlerArgs) => Promise<void>;
processEventErrorHandler?: (args: httpFunc.ReceiverProcessEventErrorHandlerArgs) => Promise<boolean>;
// NOTE: for the compatibility with HTTPResponseAck, this handler is not async
// If we receive requests to provide async version of this handler,
// we can add a different name function for it.
unhandledRequestHandler?: (args: httpFunc.ReceiverUnhandledRequestHandlerArgs) => void;
unhandledRequestTimeoutMillis?: number;
}
// Additional Installer Options
interface InstallerOptions {
stateStore?: InstallProviderOptions['stateStore']; // default ClearStateStore
stateVerification?: InstallProviderOptions['stateVerification']; // defaults true
legacyStateVerification?: InstallProviderOptions['legacyStateVerification'];
stateCookieName?: InstallProviderOptions['stateCookieName'];
stateCookieExpirationSeconds?: InstallProviderOptions['stateCookieExpirationSeconds'];
authVersion?: InstallProviderOptions['authVersion']; // default 'v2'
metadata?: InstallURLOptions['metadata'];
installPath?: string;
directInstall?: InstallProviderOptions['directInstall']; // 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'];
}
/**
* Receives HTTP requests with Events, Slash Commands, and Actions
*/
export default class ExpressReceiver implements Receiver {
/* Express app */
public app: Application;
private server?: Server;
private bolt: App | undefined;
private logger: Logger;
private processBeforeResponse: boolean;
private signatureVerification: boolean;
public router: IRouter;
public installer: InstallProvider | undefined = undefined;
public installerOptions?: InstallerOptions;
private customPropertiesExtractor: (request: Request) => StringIndexed;
private dispatchErrorHandler: (args: httpFunc.ReceiverDispatchErrorHandlerArgs) => Promise<void>;
private processEventErrorHandler: (args: httpFunc.ReceiverProcessEventErrorHandlerArgs) => Promise<boolean>;
private unhandledRequestHandler: (args: httpFunc.ReceiverUnhandledRequestHandlerArgs) => void;
private unhandledRequestTimeoutMillis: number;
public constructor({
signingSecret = '',
logger = undefined,
logLevel = LogLevel.INFO,
endpoints = { events: '/slack/events' },
processBeforeResponse = false,
signatureVerification = true,
clientId = undefined,
clientSecret = undefined,
stateSecret = undefined,
redirectUri = undefined,
installationStore = undefined,
scopes = undefined,
installerOptions = {},
app = undefined,
router = undefined,
customPropertiesExtractor = (_req) => ({}),
dispatchErrorHandler = httpFunc.defaultAsyncDispatchErrorHandler,
processEventErrorHandler = httpFunc.defaultProcessEventErrorHandler,
unhandledRequestHandler = httpFunc.defaultUnhandledRequestHandler,
unhandledRequestTimeoutMillis = 3001,
}: ExpressReceiverOptions) {
this.app = app !== undefined ? app : express();
if (typeof logger !== 'undefined') {
this.logger = logger;
} else {
this.logger = new ConsoleLogger();
this.logger.setLevel(logLevel);
}
this.signatureVerification = signatureVerification;
const bodyParser = this.signatureVerification
? buildVerificationBodyParserMiddleware(this.logger, signingSecret)
: buildBodyParserMiddleware(this.logger);
const expressMiddleware: RequestHandler[] = [
bodyParser,
respondToSslCheck,
respondToUrlVerification,
this.requestHandler.bind(this),
];
this.processBeforeResponse = processBeforeResponse;
const endpointList = typeof endpoints === 'string' ? [endpoints] : Object.values(endpoints);
this.router = router !== undefined ? router : Router();
for (const endpoint of endpointList) {
this.router.post(endpoint, ...expressMiddleware);
}
this.customPropertiesExtractor = customPropertiesExtractor;
this.dispatchErrorHandler = dispatchErrorHandler;
this.processEventErrorHandler = processEventErrorHandler;
this.unhandledRequestHandler = unhandledRequestHandler;
this.unhandledRequestTimeoutMillis = unhandledRequestTimeoutMillis;
// 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 ?? 'v2',
clientOptions: installerOptions.clientOptions,
authorizationUrl: installerOptions.authorizationUrl,
});
}
// create install url options
const installUrlOptions = {
metadata: installerOptions.metadata,
scopes: scopes ?? [],
userScopes: installerOptions.userScopes,
redirectUri,
};
// Add OAuth routes to receiver
if (this.installer !== undefined) {
const { installer } = this;
const redirectUriPath =
installerOptions.redirectUriPath === undefined ? '/slack/oauth_redirect' : installerOptions.redirectUriPath;
const { callbackOptions, stateVerification } = installerOptions;
this.router.use(redirectUriPath, async (req, res) => {
try {
if (stateVerification === false) {
// when stateVerification is disabled pass install options directly to handler
// since they won't be encoded in the state param of the generated url
await installer.handleCallback(req, res, callbackOptions, installUrlOptions);
} else {
await installer.handleCallback(req, res, callbackOptions);
}
} catch (e) {
await this.dispatchErrorHandler({
error: e as Error | CodedError,
logger: this.logger,
request: req,
response: res,
});
}
});
const installPath = installerOptions.installPath === undefined ? '/slack/install' : installerOptions.installPath;
const { installPathOptions } = installerOptions;
this.router.get(installPath, async (req, res, next) => {
try {
try {
await installer.handleInstallPath(req, res, installPathOptions, installUrlOptions);
} catch (error) {
next(error);
}
} catch (e) {
await this.dispatchErrorHandler({
error: e as Error | CodedError,
logger: this.logger,
request: req,
response: res,
});
}
});
}
this.app.use(this.router);
}
public async requestHandler(req: Request, res: Response): Promise<void> {
const ack = new HTTPResponseAck({
logger: this.logger,
processBeforeResponse: this.processBeforeResponse,
unhandledRequestHandler: this.unhandledRequestHandler,
unhandledRequestTimeoutMillis: this.unhandledRequestTimeoutMillis,
httpRequest: req,
httpResponse: res,
});
const event: ReceiverEvent = {
body: req.body,
ack: ack.bind(),
retryNum: httpFunc.extractRetryNumFromHTTPRequest(req),
retryReason: httpFunc.extractRetryReasonFromHTTPRequest(req),
customProperties: this.customPropertiesExtractor(req),
};
try {
await this.bolt?.processEvent(event);
if (ack.storedResponse !== undefined) {
httpFunc.buildContentResponse(res, ack.storedResponse);
this.logger.debug('stored response sent');
}
} catch (err) {
const acknowledgedByHandler = await this.processEventErrorHandler({
error: err as Error | CodedError,
logger: this.logger,
request: req,
response: res,
storedResponse: ack.storedResponse,
});
if (acknowledgedByHandler) {
// If the value is false, we don't touch the value as a race condition
// with ack() call may occur especially when processBeforeResponse: false
ack.ack();
}
}
}
public init(bolt: App): void {
this.bolt = bolt;
}
// TODO: can this method be defined as generic instead of using overloads?
public start(port: number): Promise<Server>;
public start(portOrListenOptions: number | ListenOptions, serverOptions?: ServerOptions): Promise<Server>;
public start(
portOrListenOptions: number | ListenOptions,
httpsServerOptions?: HTTPSServerOptions,
): Promise<HTTPSServer>;
public start(
portOrListenOptions: number | ListenOptions,
serverOptions: ServerOptions | HTTPSServerOptions = {},
): Promise<Server | HTTPSServer> {
let createServerFn:
| typeof createServer<typeof IncomingMessage, typeof ServerResponse>
| typeof createHttpsServer<typeof IncomingMessage, typeof ServerResponse> = createServer;
// Look for HTTPS-specific serverOptions to determine which factory function to use
if (Object.keys(serverOptions).filter((k) => httpsOptionKeys.includes(k)).length > 0) {
createServerFn = createHttpsServer;
}
if (this.server !== undefined) {
return Promise.reject(
new ReceiverInconsistentStateError('The receiver cannot be started because it was already started.'),
);
}
this.server = createServerFn(serverOptions, this.app);
return new Promise((resolve, reject) => {
if (this.server === undefined) {
throw new ReceiverInconsistentStateError(missingServerErrorDescription);
}
this.server.on('error', (error) => {
if (this.server === undefined) {
throw new ReceiverInconsistentStateError(missingServerErrorDescription);
}
this.server.close();
// If the error event occurs before listening completes (like EADDRINUSE), this works well. However, if the
// error event happens some after the Promise is already resolved, the error would be silently swallowed up.
// The documentation doesn't describe any specific errors that can occur after listening has started, so this
// feels safe.
reject(error);
});
this.server.on('close', () => {
// Not removing all listeners because consumers could have added their own `close` event listener, and those
// should be called. If the consumer doesn't dispose of any references to the server properly, this would be
// a memory leak.
// this.server?.removeAllListeners();
this.server = undefined;
});
this.server.listen(portOrListenOptions, () => {
if (this.server === undefined) {
return reject(new ReceiverInconsistentStateError(missingServerErrorDescription));
}
return resolve(this.server);
});
});
}
// TODO: the arguments should be defined as the arguments to close() (which happen to be none), but for sake of
// generic types
public stop(): Promise<void> {
if (this.server === undefined) {
return Promise.reject(
new ReceiverInconsistentStateError('The receiver cannot be stopped because it was not started.'),
);
}
return new Promise((resolve, reject) => {
this.server?.close((error) => {
if (error !== undefined) {
return reject(error);
}
this.server = undefined;
return resolve();
});
});
}
}
export function verifySignatureAndParseRawBody(
logger: Logger,
signingSecret: string | (() => PromiseLike<string>),
): RequestHandler {
return buildVerificationBodyParserMiddleware(logger, signingSecret);
}
/**
* This request handler has two responsibilities:
* - Verify the request signature
* - Parse request.body and assign the successfully parsed object to it.
*/
function buildVerificationBodyParserMiddleware(
logger: Logger,
signingSecret: string | (() => PromiseLike<string>),
): RequestHandler {
return async (req, res, next): Promise<void> => {
// *** Parsing body ***
// As the verification passed, parse the body as an object and assign it to req.body
const stringBody = await parseExpressRequestRawBody(req);
// Following middlewares can expect `req.body` is already parsed.
try {
// This handler parses `req.body` or `req.rawBody`(on Google Could Platform)
// and overwrites `req.body` with the parsed JS object.
req.body = verifySignatureAndParseBody(
typeof signingSecret === 'string' ? signingSecret : await signingSecret(),
stringBody,
req.headers,
);
} catch (error) {
if (error) {
if (error instanceof ReceiverAuthenticityError) {
logError(logger, 'Request verification failed', error);
res.status(401).send();
return;
}
logError(logger, 'Parsing request body failed', error);
res.status(400).send();
return;
}
}
next();
};
}
// biome-ignore lint/suspicious/noExplicitAny: errors can be anything
function logError(logger: Logger, message: string, error: any): void {
const logMessage =
'code' in error ? `${message} (code: ${error.code}, message: ${error.message})` : `${message} (error: ${error})`;
logger.warn(logMessage);
}
function verifyRequestSignature(
signingSecret: string,
body: string,
signature: string | undefined,
requestTimestamp: string | undefined,
): void {
if (signature === undefined || requestTimestamp === undefined) {
throw new ReceiverAuthenticityError('Slack request signing verification failed. Some headers are missing.');
}
const ts = Number(requestTimestamp);
if (Number.isNaN(ts)) {
throw new ReceiverAuthenticityError('Slack request signing verification failed. Timestamp is invalid.');
}
// Divide current date to match Slack ts format
// Subtract 5 minutes from current time
const fiveMinutesAgo = Math.floor(Date.now() / 1000) - 60 * 5;
if (ts < fiveMinutesAgo) {
throw new ReceiverAuthenticityError('Slack request signing verification failed. Timestamp is too old.');
}
const hmac = crypto.createHmac('sha256', signingSecret);
const [version, hash] = signature.split('=');
hmac.update(`${version}:${ts}:${body}`);
if (!tsscmp(hash, hmac.digest('hex'))) {
throw new ReceiverAuthenticityError('Slack request signing verification failed. Signature mismatch.');
}
}
/**
* This request handler has two responsibilities:
* - Verify the request signature
* - Parse `request.body` and assign the successfully parsed object to it.
*/
export function verifySignatureAndParseBody(
signingSecret: string,
body: string,
// biome-ignore lint/suspicious/noExplicitAny: TODO: headers should only be of a certain type, but some other functions here expect a more complicated type. revisit to type properly later.
headers: Record<string, any>,
): AnyMiddlewareArgs['body'] {
// *** Request verification ***
const {
'x-slack-signature': signature,
'x-slack-request-timestamp': requestTimestamp,
'content-type': contentType,
} = headers;
verifyRequestSignature(signingSecret, body, signature, requestTimestamp);
return parseRequestBody(body, contentType);
}
export function buildBodyParserMiddleware(logger: Logger): RequestHandler {
return async (req, res, next) => {
const stringBody = await parseExpressRequestRawBody(req);
try {
const { 'content-type': contentType } = req.headers;
req.body = parseRequestBody(stringBody, contentType);
} catch (error) {
if (error) {
logError(logger, 'Parsing request body failed', error);
res.status(400).send();
return;
}
}
next();
};
}
// biome-ignore lint/suspicious/noExplicitAny: request bodies can be anything
function parseRequestBody(stringBody: string, contentType: string | undefined): any {
if (contentType === 'application/x-www-form-urlencoded') {
const parsedBody = querystring.parse(stringBody);
if (typeof parsedBody.payload === 'string') {
return JSON.parse(parsedBody.payload);
}
return parsedBody;
}
return JSON.parse(stringBody);
}
// On some environments like GCP (Google Cloud Platform),
// req.body can be pre-parsed and be passed as req.rawBody
async function parseExpressRequestRawBody(req: Parameters<RequestHandler>[0]): Promise<string> {
if ('rawBody' in req && req.rawBody) {
return Promise.resolve(req.rawBody.toString());
}
return (await rawBody(req)).toString();
}