slack.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  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, generateWebClient,
  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. let didAnyCommandRun = false;
  142. if (relationsForSingleUse.length > 0) {
  143. didAnyCommandRun = true;
  144. body.growiUrisForSingleUse = relationsForSingleUse.map(v => v.growiUri);
  145. return this.selectGrowiService.process(growiCommand, authorizeResult, body);
  146. }
  147. const relationsForBroadcastUse:Relation[] = [];
  148. await Promise.all(relations.map(async(relation) => {
  149. const isSupported = await this.relationsService.isSupportedGrowiCommandForBroadcastUse(relation, growiCommand.growiCommandType, baseDate);
  150. if (isSupported) {
  151. relationsForBroadcastUse.push(relation);
  152. }
  153. }));
  154. /*
  155. * forward to GROWI server
  156. */
  157. if (relationsForBroadcastUse.length > 0) {
  158. didAnyCommandRun = true;
  159. this.sendCommand(growiCommand, relationsForBroadcastUse, body);
  160. }
  161. if (!didAnyCommandRun) {
  162. const botToken = relations[0].installation?.data.bot?.token;
  163. // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
  164. const client = generateWebClient(botToken!);
  165. return client.chat.postEphemeral({
  166. text: 'Error occured.',
  167. channel: body.channel_id,
  168. user: body.user_id,
  169. blocks: [
  170. generateMarkdownSectionBlock(`It is not allowed to run *'${growiCommand.growiCommandType}'* command from this channel.`),
  171. ],
  172. });
  173. }
  174. }
  175. @Post('/interactions')
  176. @UseBefore(AuthorizeInteractionMiddleware, ExtractGrowiUriFromReq)
  177. async handleInteraction(@Req() req: SlackOauthReq, @Res() res: Res): Promise<void|string|Res|WebAPICallResult> {
  178. logger.info('receive interaction', req.authorizeResult);
  179. logger.debug('receive interaction', req.body);
  180. const { body, authorizeResult } = req;
  181. // Send response immediately to avoid opelation_timeout error
  182. // See https://api.slack.com/apis/connections/events-api#the-events-api__responding-to-events
  183. res.send();
  184. // pass
  185. if (body.ssl_check != null) {
  186. return;
  187. }
  188. const installationId = authorizeResult.enterpriseId || authorizeResult.teamId;
  189. // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
  190. const installation = await this.installationRepository.findByTeamIdOrEnterpriseId(installationId!);
  191. const payload = JSON.parse(body.payload);
  192. const callBackId = payload?.view?.callback_id;
  193. // register
  194. if (callBackId === 'register') {
  195. try {
  196. await this.registerService.insertOrderRecord(installation, authorizeResult.botToken, payload);
  197. }
  198. catch (err) {
  199. if (err instanceof InvalidUrlError) {
  200. logger.info(err.message);
  201. return;
  202. }
  203. logger.error(err);
  204. }
  205. await this.registerService.notifyServerUriToSlack(authorizeResult.botToken, payload);
  206. return;
  207. }
  208. // unregister
  209. if (callBackId === 'unregister') {
  210. await this.unregisterService.unregister(installation, authorizeResult, payload);
  211. return;
  212. }
  213. // forward to GROWI server
  214. if (callBackId === 'select_growi') {
  215. const selectedGrowiInformation = await this.selectGrowiService.handleSelectInteraction(installation, payload);
  216. return this.sendCommand(selectedGrowiInformation.growiCommand, [selectedGrowiInformation.relation], selectedGrowiInformation.sendCommandBody);
  217. }
  218. /*
  219. * forward to GROWI server
  220. */
  221. const relation = await this.relationRepository.findOne({ installation, growiUri: req.growiUri });
  222. if (relation == null) {
  223. logger.error('*No relation found.*');
  224. return;
  225. }
  226. try {
  227. // generate API URL
  228. const url = new URL('/_api/v3/slack-integration/proxied/interactions', req.growiUri);
  229. await axios.post(url.toString(), {
  230. ...body,
  231. }, {
  232. headers: {
  233. 'x-growi-ptog-tokens': relation.tokenPtoG,
  234. },
  235. });
  236. }
  237. catch (err) {
  238. logger.error(err);
  239. }
  240. }
  241. @Post('/events')
  242. async handleEvent(@BodyParams() body:{[key:string]:string} /* , @Res() res: Res */): Promise<void|string> {
  243. // eslint-disable-next-line max-len
  244. // see: https://api.slack.com/apis/connections/events-api#the-events-api__subscribing-to-event-types__events-api-request-urls__request-url-configuration--verification
  245. if (body.type === 'url_verification') {
  246. return body.challenge;
  247. }
  248. logger.info('receive event', body);
  249. return;
  250. }
  251. @Get('/oauth_redirect')
  252. async handleOauthRedirect(@Req() req: Req, @Res() res: Res): Promise<void> {
  253. if (req.query.state === '') {
  254. res.writeHead(500, { 'Content-Type': 'text/html; charset=utf-8' });
  255. res.end('<html>'
  256. + '<head><meta name="viewport" content="width=device-width,initial-scale=1"></head>'
  257. + '<body style="text-align:center; padding-top:20%;">'
  258. + '<h1>Illegal state, try it again.</h1>'
  259. + '<a href="/">'
  260. + 'Go to install page'
  261. + '</a>'
  262. + '</body></html>');
  263. }
  264. await this.installerService.installer.handleCallback(req, res, {
  265. success: (installation, metadata, req, res) => {
  266. logger.info('Success to install', { installation, metadata });
  267. const appPageUrl = `https://slack.com/apps/${installation.appId}`;
  268. res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
  269. res.end('<html>'
  270. + '<head><meta name="viewport" content="width=device-width,initial-scale=1"></head>'
  271. + '<body style="text-align:center; padding-top:20%;">'
  272. + '<h1>Congratulations!</h1>'
  273. + '<p>GROWI Bot installation has succeeded.</p>'
  274. + `<a href="${appPageUrl}">`
  275. + 'Access to Slack App detail page.'
  276. + '</a>'
  277. + '</body></html>');
  278. },
  279. failure: (error, installOptions, req, res) => {
  280. res.writeHead(500, { 'Content-Type': 'text/html; charset=utf-8' });
  281. res.end('<html>'
  282. + '<head><meta name="viewport" content="width=device-width,initial-scale=1"></head>'
  283. + '<body style="text-align:center; padding-top:20%;">'
  284. + '<h1>GROWI Bot installation failed</h1>'
  285. + '<p>Please contact administrators of your workspace</p>'
  286. + 'Reference: <a href="https://slack.com/help/articles/222386767-Manage-app-installation-settings-for-your-workspace">'
  287. + 'Manage app installation settings for your workspace'
  288. + '</a>'
  289. + '</body></html>');
  290. },
  291. });
  292. }
  293. }