slack.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  1. import {
  2. BodyParams, Controller, Get, Inject, PlatformResponse, Post, Req, Res, UseBefore,
  3. } from '@tsed/common';
  4. import axios from 'axios';
  5. import { WebAPICallResult } from '@slack/web-api';
  6. import { Installation } from '@slack/oauth';
  7. import {
  8. markdownSectionBlock, GrowiCommand, parseSlashCommand, postEphemeralErrors, verifySlackRequest, generateWebClient,
  9. InvalidGrowiCommandError, requiredScopes, postWelcomeMessage, REQUEST_TIMEOUT_FOR_PTOG,
  10. } from '@growi/slack';
  11. import { Relation } from '~/entities/relation';
  12. import { SlackOauthReq } from '~/interfaces/slack-to-growi/slack-oauth-req';
  13. import { InstallationRepository } from '~/repositories/installation';
  14. import { RelationRepository } from '~/repositories/relation';
  15. import { OrderRepository } from '~/repositories/order';
  16. import { AddSigningSecretToReq } from '~/middlewares/slack-to-growi/add-signing-secret-to-req';
  17. import { AuthorizeCommandMiddleware, AuthorizeInteractionMiddleware } from '~/middlewares/slack-to-growi/authorizer';
  18. import { ExtractGrowiUriFromReq } from '~/middlewares/slack-to-growi/extract-growi-uri-from-req';
  19. import { InstallerService } from '~/services/InstallerService';
  20. import { SelectGrowiService } from '~/services/SelectGrowiService';
  21. import { RegisterService } from '~/services/RegisterService';
  22. import { RelationsService } from '~/services/RelationsService';
  23. import { UnregisterService } from '~/services/UnregisterService';
  24. import { InvalidUrlError } from '../models/errors';
  25. import loggerFactory from '~/utils/logger';
  26. import { JoinToConversationMiddleware } from '~/middlewares/slack-to-growi/join-to-conversation';
  27. const logger = loggerFactory('slackbot-proxy:controllers:slack');
  28. @Controller('/slack')
  29. export class SlackCtrl {
  30. @Inject()
  31. installerService: InstallerService;
  32. @Inject()
  33. installationRepository: InstallationRepository;
  34. @Inject()
  35. relationRepository: RelationRepository;
  36. @Inject()
  37. orderRepository: OrderRepository;
  38. @Inject()
  39. selectGrowiService: SelectGrowiService;
  40. @Inject()
  41. registerService: RegisterService;
  42. @Inject()
  43. relationsService: RelationsService;
  44. @Inject()
  45. unregisterService: UnregisterService;
  46. /**
  47. * Send command to specified GROWIs
  48. * @param growiCommand
  49. * @param relations
  50. * @param body
  51. * @returns
  52. */
  53. private async sendCommand(growiCommand: GrowiCommand, relations: Relation[], body: any) {
  54. if (relations.length === 0) {
  55. throw new Error('relations must be set');
  56. }
  57. const botToken = relations[0].installation?.data.bot?.token; // relations[0] should be exist
  58. const promises = relations.map((relation: Relation) => {
  59. // generate API URL
  60. const url = new URL('/_api/v3/slack-integration/proxied/commands', relation.growiUri);
  61. return axios.post(url.toString(), {
  62. ...body,
  63. growiCommand,
  64. }, {
  65. headers: {
  66. 'x-growi-ptog-tokens': relation.tokenPtoG,
  67. },
  68. timeout: REQUEST_TIMEOUT_FOR_PTOG,
  69. });
  70. });
  71. // pickup PromiseRejectedResult only
  72. const results = await Promise.allSettled(promises);
  73. const rejectedResults: PromiseRejectedResult[] = results.filter((result): result is PromiseRejectedResult => result.status === 'rejected');
  74. try {
  75. // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
  76. return postEphemeralErrors(rejectedResults, body.channel_id, body.user_id, botToken!);
  77. }
  78. catch (err) {
  79. logger.error(err);
  80. }
  81. }
  82. @Post('/commands')
  83. @UseBefore(AddSigningSecretToReq, verifySlackRequest, AuthorizeCommandMiddleware, JoinToConversationMiddleware)
  84. async handleCommand(@Req() req: SlackOauthReq, @Res() res: Res): Promise<void|string|Res|WebAPICallResult> {
  85. const { body, authorizeResult } = req;
  86. let growiCommand;
  87. try {
  88. growiCommand = parseSlashCommand(body);
  89. }
  90. catch (err) {
  91. if (err instanceof InvalidGrowiCommandError) {
  92. res.json({
  93. blocks: [
  94. markdownSectionBlock('*Command type is not specified.*'),
  95. markdownSectionBlock('Run `/growi help` to check the commands you can use.'),
  96. ],
  97. });
  98. }
  99. logger.error(err.message);
  100. return;
  101. }
  102. // register
  103. if (growiCommand.growiCommandType === 'register') {
  104. return this.registerService.process(growiCommand, authorizeResult, body as {[key:string]:string});
  105. }
  106. // unregister
  107. if (growiCommand.growiCommandType === 'unregister') {
  108. if (growiCommand.growiCommandArgs.length === 0) {
  109. return 'GROWI Urls is required.';
  110. }
  111. if (!growiCommand.growiCommandArgs.every(v => v.match(/^(https?:\/\/)/))) {
  112. return 'GROWI Urls must be urls.';
  113. }
  114. return this.unregisterService.process(growiCommand, authorizeResult, body as {[key:string]:string});
  115. }
  116. const installationId = authorizeResult.enterpriseId || authorizeResult.teamId;
  117. // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
  118. const installation = await this.installationRepository.findByTeamIdOrEnterpriseId(installationId!);
  119. const relations = await this.relationRepository.createQueryBuilder('relation')
  120. .where('relation.installationId = :id', { id: installation?.id })
  121. .leftJoinAndSelect('relation.installation', 'installation')
  122. .getMany();
  123. if (relations.length === 0) {
  124. return res.json({
  125. blocks: [
  126. markdownSectionBlock('*No relation found.*'),
  127. markdownSectionBlock('Run `/growi register` first.'),
  128. ],
  129. });
  130. }
  131. // status
  132. if (growiCommand.growiCommandType === 'status') {
  133. return res.json({
  134. blocks: [
  135. markdownSectionBlock('*Found Relations to GROWI.*'),
  136. ...relations.map(relation => markdownSectionBlock(`GROWI url: ${relation.growiUri}`)),
  137. ],
  138. });
  139. }
  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.json({
  143. response_type: 'ephemeral',
  144. text: 'Processing your request ...',
  145. });
  146. const baseDate = new Date();
  147. const allowedRelationsForSingleUse:Relation[] = [];
  148. const allowedRelationsForBroadcastUse:Relation[] = [];
  149. const disallowedGrowiUrls: Set<string> = new Set();
  150. // check permission
  151. await Promise.all(relations.map(async(relation) => {
  152. const isSupportedForSingleUse = await this.relationsService.isSupportedGrowiCommandForSingleUse(
  153. relation, growiCommand.growiCommandType, baseDate,
  154. );
  155. let isSupportedForBroadcastUse = false;
  156. if (!isSupportedForSingleUse) {
  157. isSupportedForBroadcastUse = await this.relationsService.isSupportedGrowiCommandForBroadcastUse(
  158. relation, growiCommand.growiCommandType, baseDate,
  159. );
  160. }
  161. if (isSupportedForSingleUse) {
  162. allowedRelationsForSingleUse.push(relation);
  163. }
  164. else if (isSupportedForBroadcastUse) {
  165. allowedRelationsForBroadcastUse.push(relation);
  166. }
  167. else {
  168. disallowedGrowiUrls.add(relation.growiUri);
  169. }
  170. }));
  171. // when all of GROWI disallowed
  172. if (relations.length === disallowedGrowiUrls.size) {
  173. // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
  174. const client = generateWebClient(authorizeResult.botToken!);
  175. const linkUrlList = Array.from(disallowedGrowiUrls).map((growiUrl) => {
  176. return '\n'
  177. + `• ${new URL('/admin/slack-integration', growiUrl).toString()}`;
  178. });
  179. const growiDocsLink = 'https://docs.growi.org/en/admin-guide/upgrading/43x.html';
  180. return client.chat.postEphemeral({
  181. text: 'Error occured.',
  182. channel: body.channel_id,
  183. user: body.user_id,
  184. blocks: [
  185. markdownSectionBlock('*None of GROWI permitted the command.*'),
  186. markdownSectionBlock(`*'${growiCommand.growiCommandType}'* command was not allowed.`),
  187. markdownSectionBlock(
  188. `To use this command, modify settings from following pages: ${linkUrlList}`,
  189. ),
  190. markdownSectionBlock(
  191. `Or, if your GROWI version is 4.3.0 or below, upgrade GROWI to use commands and permission settings: ${growiDocsLink}`,
  192. ),
  193. ],
  194. });
  195. }
  196. // select GROWI
  197. if (allowedRelationsForSingleUse.length > 0) {
  198. body.growiUrisForSingleUse = allowedRelationsForSingleUse.map(v => v.growiUri);
  199. return this.selectGrowiService.process(growiCommand, authorizeResult, body);
  200. }
  201. // forward to GROWI server
  202. if (allowedRelationsForBroadcastUse.length > 0) {
  203. return this.sendCommand(growiCommand, allowedRelationsForBroadcastUse, body);
  204. }
  205. }
  206. @Post('/interactions')
  207. @UseBefore(AuthorizeInteractionMiddleware, ExtractGrowiUriFromReq)
  208. async handleInteraction(@Req() req: SlackOauthReq, @Res() res: Res): Promise<void|string|Res|WebAPICallResult> {
  209. logger.info('receive interaction', req.authorizeResult);
  210. logger.debug('receive interaction', req.body);
  211. const { body, authorizeResult } = req;
  212. // pass
  213. if (body.ssl_check != null) {
  214. return;
  215. }
  216. const installationId = authorizeResult.enterpriseId || authorizeResult.teamId;
  217. // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
  218. const installation = await this.installationRepository.findByTeamIdOrEnterpriseId(installationId!);
  219. const payload = JSON.parse(body.payload);
  220. const callBackId = payload?.view?.callback_id;
  221. // register
  222. if (callBackId === 'register') {
  223. try {
  224. await this.registerService.insertOrderRecord(installation, authorizeResult.botToken, payload);
  225. }
  226. catch (err) {
  227. if (err instanceof InvalidUrlError) {
  228. logger.info(err.message);
  229. return;
  230. }
  231. logger.error(err);
  232. }
  233. await this.registerService.notifyServerUriToSlack(authorizeResult.botToken, payload);
  234. return;
  235. }
  236. // unregister
  237. if (callBackId === 'unregister') {
  238. await this.unregisterService.unregister(installation, authorizeResult, payload);
  239. return;
  240. }
  241. // forward to GROWI server
  242. if (callBackId === 'select_growi') {
  243. // Send response immediately to avoid opelation_timeout error
  244. // See https://api.slack.com/apis/connections/events-api#the-events-api__responding-to-events
  245. res.send();
  246. const selectedGrowiInformation = await this.selectGrowiService.handleSelectInteraction(installation, payload);
  247. return this.sendCommand(selectedGrowiInformation.growiCommand, [selectedGrowiInformation.relation], selectedGrowiInformation.sendCommandBody);
  248. }
  249. // Send response immediately to avoid opelation_timeout error
  250. // See https://api.slack.com/apis/connections/events-api#the-events-api__responding-to-events
  251. res.send();
  252. /*
  253. * forward to GROWI server
  254. */
  255. const relation = await this.relationRepository.findOne({ installation, growiUri: req.growiUri });
  256. if (relation == null) {
  257. logger.error('*No relation found.*');
  258. return;
  259. }
  260. try {
  261. // generate API URL
  262. const url = new URL('/_api/v3/slack-integration/proxied/interactions', req.growiUri);
  263. await axios.post(url.toString(), {
  264. ...body,
  265. }, {
  266. headers: {
  267. 'x-growi-ptog-tokens': relation.tokenPtoG,
  268. },
  269. timeout: REQUEST_TIMEOUT_FOR_PTOG,
  270. });
  271. }
  272. catch (err) {
  273. logger.error(err);
  274. }
  275. }
  276. @Post('/events')
  277. async handleEvent(@BodyParams() body:{[key:string]:string} /* , @Res() res: Res */): Promise<void|string> {
  278. // eslint-disable-next-line max-len
  279. // see: https://api.slack.com/apis/connections/events-api#the-events-api__subscribing-to-event-types__events-api-request-urls__request-url-configuration--verification
  280. if (body.type === 'url_verification') {
  281. return body.challenge;
  282. }
  283. logger.info('receive event', body);
  284. return;
  285. }
  286. @Get('/oauth_redirect')
  287. async handleOauthRedirect(@Req() req: Req, @Res() serverRes: Res, @Res() platformRes: PlatformResponse): Promise<void|string> {
  288. // create 'Add to Slack' url
  289. const addToSlackUrl = await this.installerService.installer.generateInstallUrl({
  290. scopes: requiredScopes,
  291. });
  292. const state = req.query.state;
  293. if (state == null || state === '') {
  294. return platformRes.status(400).render('install-failed.ejs', { url: addToSlackUrl });
  295. }
  296. // promisify
  297. const installPromise = new Promise<Installation>((resolve, reject) => {
  298. this.installerService.installer.handleCallback(req, serverRes, {
  299. success: async(installation, metadata) => {
  300. logger.info('Success to install', { installation, metadata });
  301. resolve(installation);
  302. },
  303. failure: async(error) => {
  304. reject(error); // go to catch block
  305. },
  306. });
  307. });
  308. let httpStatus = 200;
  309. let httpBody;
  310. try {
  311. const installation = await installPromise;
  312. // check whether bot is not null
  313. if (installation.bot == null) {
  314. logger.warn('Success to install but something wrong. `installation.bot` is null.');
  315. httpStatus = 500;
  316. httpBody = await platformRes.render('install-succeeded-but-has-problem.ejs', { reason: '`installation.bot` is null' });
  317. }
  318. // MAIN PATH: everything is fine
  319. else {
  320. const appPageUrl = `https://slack.com/apps/${installation.appId}`;
  321. httpBody = await platformRes.render('install-succeeded.ejs', { appPageUrl });
  322. // generate client
  323. const client = generateWebClient(installation.bot.token);
  324. const userId = installation.user.id;
  325. await Promise.all([
  326. // post message
  327. postWelcomeMessage(client, userId),
  328. // publish home
  329. // TODO When Home tab show off, use bellow.
  330. // publishInitialHomeView(client, userId),
  331. ]);
  332. }
  333. }
  334. catch (error) {
  335. logger.error(error);
  336. httpStatus = 500;
  337. httpBody = await platformRes.status(400).render('install-failed.ejs', { url: addToSlackUrl });
  338. }
  339. platformRes.status(httpStatus);
  340. return httpBody;
  341. }
  342. }