slack.ts 11 KB

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