slack.ts 10 KB

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