growi-to-slack.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. import {
  2. Controller, Get, Post, Inject, Req, Res, UseBefore, PathParams, Put,
  3. } from '@tsed/common';
  4. import axios from 'axios';
  5. import createError from 'http-errors';
  6. import { addHours } from 'date-fns';
  7. import { ErrorCode, WebAPICallResult } from '@slack/web-api';
  8. import {
  9. verifyGrowiToSlackRequest, getConnectionStatuses, getConnectionStatus, REQUEST_TIMEOUT_FOR_PTOG, generateWebClient,
  10. } from '@growi/slack';
  11. import { WebclientRes, AddWebclientResponseToRes } from '~/middlewares/growi-to-slack/add-webclient-response-to-res';
  12. import { GrowiReq } from '~/interfaces/growi-to-slack/growi-req';
  13. import { InstallationRepository } from '~/repositories/installation';
  14. import { RelationRepository } from '~/repositories/relation';
  15. import { OrderRepository } from '~/repositories/order';
  16. import { InstallerService } from '~/services/InstallerService';
  17. import loggerFactory from '~/utils/logger';
  18. import { ViewInteractionPayloadDelegator } from '~/services/growi-uri-injector/ViewInteractionPayloadDelegator';
  19. import { ActionsBlockPayloadDelegator } from '~/services/growi-uri-injector/ActionsBlockPayloadDelegator';
  20. import { SectionBlockPayloadDelegator } from '~/services/growi-uri-injector/SectionBlockPayloadDelegator';
  21. const logger = loggerFactory('slackbot-proxy:controllers:growi-to-slack');
  22. @Controller('/g2s')
  23. export class GrowiToSlackCtrl {
  24. @Inject()
  25. installerService: InstallerService;
  26. @Inject()
  27. installationRepository: InstallationRepository;
  28. @Inject()
  29. relationRepository: RelationRepository;
  30. @Inject()
  31. orderRepository: OrderRepository;
  32. @Inject()
  33. viewInteractionPayloadDelegator: ViewInteractionPayloadDelegator;
  34. @Inject()
  35. actionsBlockPayloadDelegator: ActionsBlockPayloadDelegator;
  36. @Inject()
  37. sectionBlockPayloadDelegator: SectionBlockPayloadDelegator;
  38. async requestToGrowi(growiUrl:string, tokenPtoG:string):Promise<void> {
  39. const url = new URL('/_api/v3/slack-integration/proxied/commands', growiUrl);
  40. await axios.post(url.toString(), {
  41. type: 'url_verification',
  42. challenge: 'this_is_my_challenge_token',
  43. },
  44. {
  45. headers: {
  46. 'x-growi-ptog-tokens': tokenPtoG,
  47. },
  48. timeout: REQUEST_TIMEOUT_FOR_PTOG,
  49. });
  50. }
  51. @Get('/connection-status')
  52. @UseBefore(verifyGrowiToSlackRequest)
  53. async getConnectionStatuses(@Req() req: GrowiReq, @Res() res: Res): Promise<void|string|Res|WebAPICallResult> {
  54. // asserted (tokenGtoPs.length > 0) by verifyGrowiToSlackRequest
  55. const { tokenGtoPs } = req;
  56. // retrieve Relation with Installation
  57. const relations = await this.relationRepository.createQueryBuilder('relation')
  58. .where('relation.tokenGtoP IN (:...tokens)', { tokens: tokenGtoPs })
  59. .leftJoinAndSelect('relation.installation', 'installation')
  60. .getMany();
  61. logger.debug(`${relations.length} relations found`, relations);
  62. // key: tokenGtoP, value: botToken
  63. const botTokenResolverMapping: {[tokenGtoP:string]:string} = {};
  64. relations.forEach((relation) => {
  65. const botToken = relation.installation?.data?.bot?.token;
  66. if (botToken != null) {
  67. botTokenResolverMapping[relation.tokenGtoP] = botToken;
  68. }
  69. });
  70. const connectionStatuses = await getConnectionStatuses(Object.keys(botTokenResolverMapping), (tokenGtoP:string) => botTokenResolverMapping[tokenGtoP]);
  71. return res.send({ connectionStatuses });
  72. }
  73. @Put('/supported-commands')
  74. @UseBefore(verifyGrowiToSlackRequest)
  75. async putSupportedCommands(@Req() req: GrowiReq, @Res() res: Res): Promise<void|string|Res|WebAPICallResult> {
  76. // asserted (tokenGtoPs.length > 0) by verifyGrowiToSlackRequest
  77. const { tokenGtoPs } = req;
  78. const { supportedCommandsForBroadcastUse, supportedCommandsForSingleUse } = req.body;
  79. if (tokenGtoPs.length !== 1) {
  80. throw createError(400, 'installation is invalid');
  81. }
  82. const tokenGtoP = tokenGtoPs[0];
  83. const relation = await this.relationRepository.update({ tokenGtoP }, { supportedCommandsForBroadcastUse, supportedCommandsForSingleUse });
  84. return res.send({ relation });
  85. }
  86. @Post('/relation-test')
  87. @UseBefore(verifyGrowiToSlackRequest)
  88. async postRelation(@Req() req: GrowiReq, @Res() res: Res): Promise<void|string|Res|WebAPICallResult> {
  89. const { tokenGtoPs } = req;
  90. if (tokenGtoPs.length !== 1) {
  91. throw createError(400, 'installation is invalid');
  92. }
  93. const tokenGtoP = tokenGtoPs[0];
  94. // retrieve relation with Installation
  95. const relation = await this.relationRepository.createQueryBuilder('relation')
  96. .where('tokenGtoP = :token', { token: tokenGtoP })
  97. .leftJoinAndSelect('relation.installation', 'installation')
  98. .getOne();
  99. // Returns the result of the test if it already exists
  100. if (relation != null) {
  101. logger.debug('relation found', relation);
  102. const token = relation.installation.data.bot?.token;
  103. if (token == null) {
  104. throw createError(400, 'installation is invalid');
  105. }
  106. try {
  107. await this.requestToGrowi(relation.growiUri, relation.tokenPtoG);
  108. }
  109. catch (err) {
  110. logger.error(err);
  111. throw createError(400, `failed to request to GROWI. err: ${err.message}`);
  112. }
  113. const status = await getConnectionStatus(token);
  114. if (status.error != null) {
  115. throw createError(400, `failed to get connection. err: ${status.error}`);
  116. }
  117. return res.send({ relation, slackBotToken: token });
  118. }
  119. // retrieve latest Order with Installation
  120. const order = await this.orderRepository.createQueryBuilder('order')
  121. .orderBy('order.createdAt', 'DESC')
  122. .where('tokenGtoP = :token', { token: tokenGtoP })
  123. .leftJoinAndSelect('order.installation', 'installation')
  124. .getOne();
  125. if (order == null || order.isExpired()) {
  126. throw createError(400, 'order has expired or does not exist.');
  127. }
  128. // Access the GROWI URL saved in the Order record and check if the GtoP token is valid.
  129. try {
  130. await this.requestToGrowi(order.growiUrl, order.tokenPtoG);
  131. }
  132. catch (err) {
  133. logger.error(err);
  134. throw createError(400, `failed to request to GROWI. err: ${err.message}`);
  135. }
  136. logger.debug('order found', order);
  137. const token = order.installation.data.bot?.token;
  138. if (token == null) {
  139. throw createError(400, 'installation is invalid');
  140. }
  141. const status = await getConnectionStatus(token);
  142. if (status.error != null) {
  143. throw createError(400, `failed to get connection. err: ${status.error}`);
  144. }
  145. logger.debug('relation test is success', order);
  146. // temporary cache for 48 hours
  147. const expiredAtCommands = addHours(new Date(), 48);
  148. // Transaction is not considered because it is used infrequently,
  149. const response = await this.relationRepository.createQueryBuilder('relation')
  150. .insert()
  151. .values({
  152. installation: order.installation,
  153. tokenGtoP: order.tokenGtoP,
  154. tokenPtoG: order.tokenPtoG,
  155. growiUri: order.growiUrl,
  156. supportedCommandsForBroadcastUse: req.body.supportedCommandsForBroadcastUse,
  157. supportedCommandsForSingleUse: req.body.supportedCommandsForSingleUse,
  158. expiredAtCommands,
  159. })
  160. // https://github.com/typeorm/typeorm/issues/1090#issuecomment-634391487
  161. .orUpdate({
  162. conflict_target: ['installation', 'growiUri'],
  163. overwrite: ['tokenGtoP', 'tokenPtoG', 'supportedCommandsForBroadcastUse', 'supportedCommandsForSingleUse'],
  164. })
  165. .execute();
  166. // Find the generated relation
  167. const generatedRelation = await this.relationRepository.findOne({ id: response.identifiers[0].id });
  168. return res.send({ relation: generatedRelation, slackBotToken: token });
  169. }
  170. injectGrowiUri(req: GrowiReq, growiUri: string): void {
  171. if (req.body.view == null && req.body.blocks == null) {
  172. return;
  173. }
  174. if (req.body.view != null) {
  175. const parsedElement = JSON.parse(req.body.view);
  176. // delegate to ViewInteractionPayloadDelegator
  177. if (this.viewInteractionPayloadDelegator.shouldHandleToInject(parsedElement)) {
  178. this.viewInteractionPayloadDelegator.inject(parsedElement, growiUri);
  179. req.body.view = JSON.stringify(parsedElement);
  180. }
  181. }
  182. else if (req.body.blocks != null) {
  183. const parsedElement = JSON.parse(req.body.blocks);
  184. // delegate to ActionsBlockPayloadDelegator
  185. if (this.actionsBlockPayloadDelegator.shouldHandleToInject(parsedElement)) {
  186. this.actionsBlockPayloadDelegator.inject(parsedElement, growiUri);
  187. req.body.blocks = JSON.stringify(parsedElement);
  188. }
  189. // delegate to SectionBlockPayloadDelegator
  190. if (this.sectionBlockPayloadDelegator.shouldHandleToInject(parsedElement)) {
  191. this.sectionBlockPayloadDelegator.inject(parsedElement, growiUri);
  192. req.body.blocks = JSON.stringify(parsedElement);
  193. }
  194. }
  195. }
  196. @Post('/:method')
  197. @UseBefore(AddWebclientResponseToRes, verifyGrowiToSlackRequest)
  198. async callSlackApi(
  199. @PathParams('method') method: string, @Req() req: GrowiReq, @Res() res: WebclientRes,
  200. ): Promise<WebclientRes> {
  201. const { tokenGtoPs } = req;
  202. logger.debug('Slack API called: ', { method });
  203. if (tokenGtoPs.length !== 1) {
  204. return res.simulateWebAPIPlatformError('tokenGtoPs is invalid', 'invalid_tokenGtoP');
  205. }
  206. const tokenGtoP = tokenGtoPs[0];
  207. // retrieve relation with Installation
  208. const relation = await this.relationRepository.createQueryBuilder('relation')
  209. .where('tokenGtoP = :token', { token: tokenGtoP })
  210. .leftJoinAndSelect('relation.installation', 'installation')
  211. .getOne();
  212. if (relation == null) {
  213. return res.simulateWebAPIPlatformError('relation is invalid', 'invalid_relation');
  214. }
  215. const token = relation.installation.data.bot?.token;
  216. if (token == null) {
  217. return res.simulateWebAPIPlatformError('installation is invalid', 'invalid_installation');
  218. }
  219. // generate WebClient with no retry because GROWI main side will do
  220. const client = generateWebClient(token, {
  221. retryConfig: { retries: 0 },
  222. });
  223. try {
  224. this.injectGrowiUri(req, relation.growiUri);
  225. const opt = req.body;
  226. opt.headers = req.headers;
  227. logger.debug({ method, opt });
  228. // !! DO NOT REMOVE `await ` or it does not enter catch block even when axios error occured !! -- 2021.08.22 Yuki Takei
  229. const result = await client.apiCall(method, opt);
  230. return res.send(result);
  231. }
  232. catch (err) {
  233. logger.error(err);
  234. if (err.code === ErrorCode.PlatformError) {
  235. return res.simulateWebAPIPlatformError(err.message, err.code);
  236. }
  237. return res.simulateWebAPIRequestError(err.message, err.response?.status);
  238. }
  239. }
  240. }