slack.ts 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. import {
  2. BodyParams, Controller, Get, Inject, Post, Req, Res, UseBefore,
  3. } from '@tsed/common';
  4. import axios from 'axios';
  5. import { WebAPICallResult } from '@slack/web-api';
  6. import {
  7. generateMarkdownSectionBlock, parseSlashCommand, postEphemeralErrors, verifySlackRequest,
  8. } from '@growi/slack';
  9. import { Relation } from '~/entities/relation';
  10. import { SlackOauthReq } from '~/interfaces/slack-to-growi/slack-oauth-req';
  11. import { InstallationRepository } from '~/repositories/installation';
  12. import { RelationRepository } from '~/repositories/relation';
  13. import { OrderRepository } from '~/repositories/order';
  14. import { AddSigningSecretToReq } from '~/middlewares/slack-to-growi/add-signing-secret-to-req';
  15. import { AuthorizeCommandMiddleware, AuthorizeInteractionMiddleware } from '~/middlewares/slack-to-growi/authorizer';
  16. import { InstallerService } from '~/services/InstallerService';
  17. import { RegisterService } from '~/services/RegisterService';
  18. import loggerFactory from '~/utils/logger';
  19. const logger = loggerFactory('slackbot-proxy:controllers:slack');
  20. @Controller('/slack')
  21. export class SlackCtrl {
  22. @Inject()
  23. installerService: InstallerService;
  24. @Inject()
  25. installationRepository: InstallationRepository;
  26. @Inject()
  27. relationRepository: RelationRepository;
  28. @Inject()
  29. orderRepository: OrderRepository;
  30. @Inject()
  31. registerService: RegisterService;
  32. @Get('/install')
  33. async install(): Promise<string> {
  34. const url = await this.installerService.installer.generateInstallUrl({
  35. // Add the scopes your app needs
  36. scopes: [
  37. 'channels:history',
  38. 'commands',
  39. 'groups:history',
  40. 'im:history',
  41. 'mpim:history',
  42. 'chat:write',
  43. ],
  44. });
  45. return `<a href="${url}">`
  46. // eslint-disable-next-line max-len
  47. + '<img alt="Add to Slack" height="40" width="139" src="https://platform.slack-edge.com/img/add_to_slack.png" srcSet="https://platform.slack-edge.com/img/add_to_slack.png 1x, https://platform.slack-edge.com/img/add_to_slack@2x.png 2x" />'
  48. + '</a>';
  49. }
  50. @Post('/commands')
  51. @UseBefore(AddSigningSecretToReq, verifySlackRequest, AuthorizeCommandMiddleware)
  52. async handleCommand(@Req() req: SlackOauthReq, @Res() res: Res): Promise<void|string|Res|WebAPICallResult> {
  53. const { body, authorizeResult } = req;
  54. if (body.text == null) {
  55. return 'No text.';
  56. }
  57. const growiCommand = parseSlashCommand(body);
  58. // register
  59. if (growiCommand.growiCommandType === 'register') {
  60. // Send response immediately to avoid opelation_timeout error
  61. // See https://api.slack.com/apis/connections/events-api#the-events-api__responding-to-events
  62. res.send();
  63. return this.registerService.process(growiCommand, authorizeResult, body as {[key:string]:string});
  64. }
  65. /*
  66. * forward to GROWI server
  67. */
  68. const installationId = authorizeResult.enterpriseId || authorizeResult.teamId;
  69. // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
  70. const installation = await this.installationRepository.findByTeamIdOrEnterpriseId(installationId!);
  71. const relations = await this.relationRepository.find({ installation });
  72. if (relations.length === 0) {
  73. return res.json({
  74. blocks: [
  75. generateMarkdownSectionBlock('*No relation found.*'),
  76. generateMarkdownSectionBlock('Run `/growi register` first.'),
  77. ],
  78. });
  79. }
  80. // Send response immediately to avoid opelation_timeout error
  81. // See https://api.slack.com/apis/connections/events-api#the-events-api__responding-to-events
  82. res.send();
  83. const promises = relations.map((relation: Relation) => {
  84. // generate API URL
  85. const url = new URL('/_api/v3/slack-integration/proxied/commands', relation.growiUri);
  86. return axios.post(url.toString(), {
  87. ...body,
  88. tokenPtoG: relation.tokenPtoG,
  89. growiCommand,
  90. });
  91. });
  92. // pickup PromiseRejectedResult only
  93. const results = await Promise.allSettled(promises);
  94. const rejectedResults: PromiseRejectedResult[] = results.filter((result): result is PromiseRejectedResult => result.status === 'rejected');
  95. const botToken = installation?.data.bot?.token;
  96. try {
  97. // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
  98. return postEphemeralErrors(rejectedResults, body.channel_id, body.user_id, botToken!);
  99. }
  100. catch (err) {
  101. logger.error(err);
  102. }
  103. }
  104. @Post('/interactions')
  105. @UseBefore(AuthorizeInteractionMiddleware)
  106. async handleInteraction(@Req() req: SlackOauthReq, @Res() res: Res): Promise<void|string|Res|WebAPICallResult> {
  107. logger.info('receive interaction', req.body);
  108. logger.info('receive interaction', req.authorizeResult);
  109. const { body, authorizeResult } = req;
  110. // Send response immediately to avoid opelation_timeout error
  111. // See https://api.slack.com/apis/connections/events-api#the-events-api__responding-to-events
  112. res.send();
  113. // pass
  114. if (body.ssl_check != null) {
  115. return;
  116. }
  117. const installationId = authorizeResult.enterpriseId || authorizeResult.teamId;
  118. // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
  119. const installation = await this.installationRepository.findByTeamIdOrEnterpriseId(installationId!);
  120. const payload = JSON.parse(body.payload);
  121. const { type } = payload;
  122. // register
  123. // response_urls is an array but the element included is only one.
  124. if (type === 'view_submission' && payload.response_urls[0].action_id === 'submit_growi_url_and_access_tokens') {
  125. await this.registerService.upsertOrderRecord(this.orderRepository, installation, payload);
  126. await this.registerService.notifyServerUriToSlack(authorizeResult, payload);
  127. return;
  128. }
  129. /*
  130. * forward to GROWI server
  131. */
  132. const relations = await this.relationRepository.find({ installation });
  133. const promises = relations.map((relation: Relation) => {
  134. // generate API URL
  135. const url = new URL('/_api/v3/slack-integration/proxied/interactions', relation.growiUri);
  136. return axios.post(url.toString(), {
  137. ...body,
  138. tokenPtoG: relation.tokenPtoG,
  139. });
  140. });
  141. // pickup PromiseRejectedResult only
  142. const results = await Promise.allSettled(promises);
  143. const rejectedResults: PromiseRejectedResult[] = results.filter((result): result is PromiseRejectedResult => result.status === 'rejected');
  144. const botToken = installation?.data.bot?.token;
  145. try {
  146. // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
  147. return postEphemeralErrors(rejectedResults, body.channel_id, body.user_id, botToken!);
  148. }
  149. catch (err) {
  150. logger.error(err);
  151. }
  152. }
  153. @Post('/events')
  154. async handleEvent(@BodyParams() body:{[key:string]:string}, @Res() res: Res): Promise<void|string> {
  155. // eslint-disable-next-line max-len
  156. // see: https://api.slack.com/apis/connections/events-api#the-events-api__subscribing-to-event-types__events-api-request-urls__request-url-configuration--verification
  157. if (body.type === 'url_verification') {
  158. return body.challenge;
  159. }
  160. logger.info('receive event', body);
  161. return;
  162. }
  163. @Get('/oauth_redirect')
  164. async handleOauthRedirect(@Req() req: Req, @Res() res: Res): Promise<void> {
  165. if (req.query.state === '') {
  166. res.writeHead(500, { 'Content-Type': 'text/html; charset=utf-8' });
  167. res.end('<html>'
  168. + '<head><meta name="viewport" content="width=device-width,initial-scale=1"></head>'
  169. + '<body style="text-align:center; padding-top:20%;">'
  170. + '<h1>Illegal state, try it again.</h1>'
  171. + '<a href="/slack/install">'
  172. + 'Go to install page'
  173. + '</a>'
  174. + '</body></html>');
  175. }
  176. await this.installerService.installer.handleCallback(req, res, {
  177. success: (installation, metadata, req, res) => {
  178. logger.info('Success to install', { installation, metadata });
  179. const appPageUrl = `https://slack.com/apps/${installation.appId}`;
  180. res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
  181. res.end('<html>'
  182. + '<head><meta name="viewport" content="width=device-width,initial-scale=1"></head>'
  183. + '<body style="text-align:center; padding-top:20%;">'
  184. + '<h1>Congratulations!</h1>'
  185. + '<p>GROWI Bot installation has succeeded.</p>'
  186. + `<a href="${appPageUrl}">`
  187. + 'Access to Slack App detail page.'
  188. + '</a>'
  189. + '</body></html>');
  190. },
  191. failure: (error, installOptions, req, res) => {
  192. res.writeHead(500, { 'Content-Type': 'text/html; charset=utf-8' });
  193. res.end('<html>'
  194. + '<head><meta name="viewport" content="width=device-width,initial-scale=1"></head>'
  195. + '<body style="text-align:center; padding-top:20%;">'
  196. + '<h1>GROWI Bot installation failed</h1>'
  197. + '<p>Please contact administrators of your workspace</p>'
  198. + 'Reference: <a href="https://slack.com/help/articles/222386767-Manage-app-installation-settings-for-your-workspace">'
  199. + 'Manage app installation settings for your workspace'
  200. + '</a>'
  201. + '</body></html>');
  202. },
  203. });
  204. }
  205. }