Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added initial Developer Mode #742

Merged
merged 1 commit into from
Jan 11, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion examples/socket-mode/README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Bolt-js Socket Mode Test App

This is a quick example app to test socket-mode with bolt-js.
This is a quick example app to test [Socket Mode](https://api.slack.com/socket-mode) with bolt-js.

If using OAuth, local development requires a public URL where Slack can send requests. In this guide, we'll be using [`ngrok`](https://ngrok.com/download). Checkout [this guide](https://api.slack.com/tutorials/tunneling-with-ngrok) for setting it up. OAuth installation is only needed for public distribution. For internal apps, we recommend installing via your app config.

Expand Down
60 changes: 54 additions & 6 deletions src/App.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ export interface AppOptions {
ignoreSelf?: boolean;
clientOptions?: Pick<WebClientOptions, 'slackApiUrl'>;
socketMode?: boolean;
developerMode?: boolean;
}

export { LogLevel, Logger } from '@slack/logger';
Expand Down Expand Up @@ -162,6 +163,9 @@ export default class App {
/** Logger */
private logger: Logger;

/** Log Level */
private logLevel: LogLevel;

/** Authorize */
private authorize!: Authorize<false>;

Expand All @@ -180,6 +184,10 @@ export default class App {

private installerOptions: ExpressReceiverOptions['installerOptions'];

private socketMode: boolean;

private developerMode: boolean;

constructor({
signingSecret = undefined,
endpoints = undefined,
Expand All @@ -204,8 +212,23 @@ export default class App {
installationStore = undefined,
scopes = undefined,
installerOptions = undefined,
socketMode = false,
socketMode = undefined,
developerMode = false,
}: AppOptions = {}) {
// this.logLevel = logLevel;
this.developerMode = developerMode;
if (developerMode) {
// Set logLevel to Debug in Developer Mode if one wasn't passed in
this.logLevel = logLevel ?? LogLevel.DEBUG;
// Set SocketMode to true if one wasn't passed in
this.socketMode = socketMode ?? true;
} else {
// If devs aren't using Developer Mode or Socket Mode, set it to false
this.socketMode = socketMode ?? false;
// Set logLevel to Info if one wasn't passed in
this.logLevel = logLevel ?? LogLevel.INFO;
}

if (typeof logger === 'undefined') {
// Initialize with the default logger
const consoleLogger = new ConsoleLogger();
Expand All @@ -214,8 +237,8 @@ export default class App {
} else {
this.logger = logger;
}
if (typeof logLevel !== 'undefined' && this.logger.getLevel() !== logLevel) {
this.logger.setLevel(logLevel);
if (typeof this.logLevel !== 'undefined' && this.logger.getLevel() !== this.logLevel) {
this.logger.setLevel(this.logLevel);
}
this.errorHandler = defaultErrorHandler(this.logger);
this.clientOptions = {
Expand Down Expand Up @@ -243,10 +266,28 @@ export default class App {
...installerOptions,
};

if (
this.developerMode &&
this.installerOptions &&
(typeof this.installerOptions.callbackOptions === 'undefined' ||
(typeof this.installerOptions.callbackOptions !== 'undefined' &&
typeof this.installerOptions.callbackOptions.failure === 'undefined'))
) {
// add a custom failure callback for Developer Mode in case they are using OAuth
this.logger.debug('adding Developer Mode custom OAuth failure handler');
this.installerOptions.callbackOptions = {
failure: (error, _installOptions, _req, res) => {
this.logger.debug(error);
res.writeHead(500, { 'Content-Type': 'text/html' });
stevengill marked this conversation as resolved.
Show resolved Hide resolved
res.end(`<html><body><h1>OAuth failed!</h1><div>${error}</div></body></html>`);
},
};
}

// Check for required arguments of ExpressReceiver
if (receiver !== undefined) {
this.receiver = receiver;
} else if (socketMode) {
} else if (this.socketMode) {
if (appToken === undefined) {
throw new AppInitializationError('You must provide an appToken when using Socket Mode');
}
Expand All @@ -260,7 +301,7 @@ export default class App {
installationStore,
scopes,
logger,
logLevel,
logLevel: this.logLevel,
installerOptions: this.installerOptions,
});
} else if (signingSecret === undefined) {
Expand All @@ -282,7 +323,7 @@ export default class App {
installationStore,
scopes,
logger,
logLevel,
logLevel: this.logLevel,
installerOptions: this.installerOptions,
});
}
Expand Down Expand Up @@ -558,6 +599,13 @@ export default class App {
*/
public async processEvent(event: ReceiverEvent): Promise<void> {
const { body, ack } = event;

if (this.developerMode) {
// log the body of the event
// this may contain sensitive info like tokens
this.logger.debug(JSON.stringify(body));
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I stringify so we can see all of the nested objects

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just a suggestion. This can be a global middleware as I do in my personal template project: https://github.com/seratch/bolt-starter/blob/55bf3bac47d7f94d9b868ddd0314782aef6d7245/index.js#L28-L47

You can "use" a middleware for request logging in the constructor. We may want to expose the middleware for developers who just want to use it without developer mode.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That is a good suggestion. The nice thing about its current placement is that it is one of the first things that happens. In case middleware was broken or some other error happens, the event could potentially not get logged if it was in middleware.

Lets keep discussing as this is something we can change in a minor release.

}

// 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.
Expand Down
24 changes: 10 additions & 14 deletions src/SocketModeReceiver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,13 +65,6 @@ export default class SocketModeReceiver implements Receiver {
clientOptions: installerOptions.clientOptions,
});

// const expressMiddleware: RequestHandler[] = [
// verifySignatureAndParseRawBody(logger, signingSecret),
// respondToSslCheck,
// respondToUrlVerification,
// this.requestHandler.bind(this),
// ];

if (typeof logger !== 'undefined') {
this.logger = logger;
} else {
Expand Down Expand Up @@ -108,12 +101,10 @@ export default class SocketModeReceiver implements Receiver {
const installPath = installerOptions.installPath === undefined ? '/slack/install' : installerOptions.installPath;

const server = createServer(async (req, res) => {
if (req.url === redirectUriPath) {
if (req.url !== undefined && req.url.startsWith(redirectUriPath)) {
// call installer.handleCallback to wrap up the install flow
await this.installer!.handleCallback(req, res);
}

if (req.url === installPath) {
await this.installer!.handleCallback(req, res, installerOptions.callbackOptions);
} else if (req.url !== undefined && req.url.startsWith(installPath)) {
try {
const url = await this.installer!.generateInstallUrl({
metadata: installerOptions.metadata,
Expand All @@ -128,12 +119,17 @@ export default class SocketModeReceiver implements Receiver {
} catch (err) {
throw new Error(err);
}
} else {
this.logger.error(`Tried to reach ${req.url} which isn't a`);
// Return 404 because we don't support route
res.writeHead(404, {});
res.end(`route ${req.url} doesn't exist!`);
}
});

const port = installerOptions.port === undefined ? 3000 : installerOptions.port;
this.logger.info(`listening on port ${port} for OAuth`);
this.logger.info(`Go to http://localhost:${port}/slack/install to initiate OAuth flow`);
this.logger.debug(`listening on port ${port} for OAuth`);
this.logger.debug(`Go to http://localhost:${port}${installPath} to initiate OAuth flow`);
// use port 3000 by default
server.listen(port);
}
Expand Down