slack.ts 11 KB

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