slack.ts 10 KB

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