slack.ts 17 KB

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