slack.ts 16 KB

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