slack.ts 12 KB

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