slack.ts 10 KB

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