slack.ts 10 KB

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