slack.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645
  1. import { ServerResponse } from 'http';
  2. import {
  3. type GrowiCommand,
  4. type IChannelOptionalId,
  5. REQUEST_TIMEOUT_FOR_PTOG,
  6. requiredScopes,
  7. supportedGrowiCommands,
  8. } from '@growi/slack';
  9. import {
  10. parseSlackInteractionRequest,
  11. verifySlackRequest,
  12. } from '@growi/slack/dist/middlewares';
  13. import { InvalidGrowiCommandError } from '@growi/slack/dist/models';
  14. import { markdownSectionBlock } from '@growi/slack/dist/utils/block-kit-builder';
  15. import { respondRejectedErrors } from '@growi/slack/dist/utils/post-ephemeral-errors';
  16. import { respond } from '@growi/slack/dist/utils/response-url';
  17. import { parseSlashCommand } from '@growi/slack/dist/utils/slash-command-parser';
  18. import { generateWebClient } from '@growi/slack/dist/utils/webclient-factory';
  19. import { Installation } from '@slack/oauth';
  20. import { WebAPICallResult } from '@slack/web-api';
  21. import {
  22. Controller,
  23. Get,
  24. Inject,
  25. PlatformResponse,
  26. Post,
  27. Req,
  28. Res,
  29. UseBefore,
  30. } from '@tsed/common';
  31. import axios from 'axios';
  32. import { Relation } from '~/entities/relation';
  33. import { SlackOauthReq } from '~/interfaces/slack-to-growi/slack-oauth-req';
  34. import { AddSigningSecretToReq } from '~/middlewares/slack-to-growi/add-signing-secret-to-req';
  35. import {
  36. AuthorizeCommandMiddleware,
  37. AuthorizeEventsMiddleware,
  38. AuthorizeInteractionMiddleware,
  39. } from '~/middlewares/slack-to-growi/authorizer';
  40. import { ExtractGrowiUriFromReq } from '~/middlewares/slack-to-growi/extract-growi-uri-from-req';
  41. import { UrlVerificationMiddleware } from '~/middlewares/slack-to-growi/url-verification';
  42. import { InstallationRepository } from '~/repositories/installation';
  43. import { OrderRepository } from '~/repositories/order';
  44. import { RelationRepository } from '~/repositories/relation';
  45. import { InstallerService } from '~/services/InstallerService';
  46. import { LinkSharedService } from '~/services/LinkSharedService';
  47. import { RegisterService } from '~/services/RegisterService';
  48. import { RelationsService } from '~/services/RelationsService';
  49. import { SelectGrowiService } from '~/services/SelectGrowiService';
  50. import { UnregisterService } from '~/services/UnregisterService';
  51. import loggerFactory from '~/utils/logger';
  52. import {
  53. postInstallSuccessMessage,
  54. postWelcomeMessageOnce,
  55. } from '~/utils/welcome-message';
  56. const logger = loggerFactory('slackbot-proxy:controllers:slack');
  57. const postNotAllowedMessage = async (
  58. responseUrl,
  59. disallowedGrowiUrls: Set<string>,
  60. commandName: string,
  61. ): Promise<void> => {
  62. const linkUrlList = Array.from(disallowedGrowiUrls).map((growiUrl) => {
  63. return (
  64. '\n' + `• ${new URL('/admin/slack-integration', growiUrl).toString()}`
  65. );
  66. });
  67. const growiDocsLink =
  68. 'https://docs.growi.org/en/admin-guide/upgrading/43x.html';
  69. await respond(responseUrl, {
  70. text: 'Error occured.',
  71. blocks: [
  72. markdownSectionBlock('*None of GROWI permitted the command.*'),
  73. markdownSectionBlock(`*'${commandName}'* command was not allowed.`),
  74. markdownSectionBlock(
  75. `To use this command, modify settings from following pages: ${linkUrlList}`,
  76. ),
  77. markdownSectionBlock(
  78. `Or, if your GROWI version is 4.3.0 or below, upgrade GROWI to use commands and permission settings: ${growiDocsLink}`,
  79. ),
  80. ],
  81. });
  82. return;
  83. };
  84. @Controller('/slack')
  85. export class SlackCtrl {
  86. @Inject()
  87. installerService: InstallerService;
  88. @Inject()
  89. installationRepository: InstallationRepository;
  90. @Inject()
  91. relationRepository: RelationRepository;
  92. @Inject()
  93. orderRepository: OrderRepository;
  94. @Inject()
  95. selectGrowiService: SelectGrowiService;
  96. @Inject()
  97. registerService: RegisterService;
  98. @Inject()
  99. relationsService: RelationsService;
  100. @Inject()
  101. unregisterService: UnregisterService;
  102. @Inject()
  103. linkSharedService: LinkSharedService;
  104. /**
  105. * Send command to specified GROWIs
  106. * @param growiCommand
  107. * @param relations
  108. * @param body
  109. * @returns
  110. */
  111. private async sendCommand(
  112. growiCommand: GrowiCommand,
  113. relations: Relation[],
  114. body: any,
  115. ) {
  116. if (relations.length === 0) {
  117. throw new Error('relations must be set');
  118. }
  119. const promises = relations.map((relation: Relation) => {
  120. // generate API URL
  121. const url = new URL(
  122. '/_api/v3/slack-integration/proxied/commands',
  123. relation.growiUri,
  124. );
  125. return axios.post(
  126. url.toString(),
  127. {
  128. ...body,
  129. growiCommand,
  130. },
  131. {
  132. headers: {
  133. 'x-growi-ptog-tokens': relation.tokenPtoG,
  134. },
  135. timeout: REQUEST_TIMEOUT_FOR_PTOG,
  136. },
  137. );
  138. });
  139. // pickup PromiseRejectedResult only
  140. const results = await Promise.allSettled(promises);
  141. const rejectedResults: PromiseRejectedResult[] = results.filter(
  142. (result): result is PromiseRejectedResult => result.status === 'rejected',
  143. );
  144. try {
  145. return respondRejectedErrors(rejectedResults, growiCommand.responseUrl);
  146. } catch (err) {
  147. logger.error(err);
  148. }
  149. }
  150. @Post('/commands')
  151. @UseBefore(
  152. AddSigningSecretToReq,
  153. verifySlackRequest,
  154. AuthorizeCommandMiddleware,
  155. )
  156. async handleCommand(
  157. @Req() req: SlackOauthReq,
  158. @Res() res: Res,
  159. ): Promise<void | string | Res | WebAPICallResult> {
  160. const { body, authorizeResult } = req;
  161. // retrieve bot token
  162. const { botToken } = authorizeResult;
  163. if (botToken == null) {
  164. const serverUri = process.env.SERVER_URI;
  165. res.json({
  166. blocks: [
  167. markdownSectionBlock('*Installation might be failed.*'),
  168. markdownSectionBlock(
  169. `Access to ${serverUri} and re-install GROWI App`,
  170. ),
  171. ],
  172. });
  173. }
  174. // parse /growi command
  175. let growiCommand: GrowiCommand;
  176. try {
  177. growiCommand = parseSlashCommand(body);
  178. } catch (err) {
  179. if (err instanceof InvalidGrowiCommandError) {
  180. res.json({
  181. blocks: [
  182. markdownSectionBlock('*Command type is not specified.*'),
  183. markdownSectionBlock(
  184. 'Run `/growi help` to check the commands you can use.',
  185. ),
  186. ],
  187. });
  188. }
  189. logger.error(err.message);
  190. return;
  191. }
  192. // Send response immediately to avoid opelation_timeout error
  193. // See https://api.slack.com/apis/connections/events-api#the-events-api__responding-to-events
  194. res.json();
  195. // register
  196. if (this.registerService.shouldHandleCommand(growiCommand)) {
  197. return this.registerService.processCommand(
  198. growiCommand,
  199. authorizeResult,
  200. body,
  201. );
  202. }
  203. // unregister
  204. if (this.unregisterService.shouldHandleCommand(growiCommand)) {
  205. return this.unregisterService.processCommand(
  206. growiCommand,
  207. authorizeResult,
  208. );
  209. }
  210. // get relations
  211. const installationId =
  212. authorizeResult.enterpriseId || authorizeResult.teamId;
  213. // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
  214. const installation =
  215. await this.installationRepository.findByTeamIdOrEnterpriseId(
  216. installationId!,
  217. );
  218. const relations = await this.relationRepository
  219. .createQueryBuilder('relation')
  220. .where('relation.installationId = :id', { id: installation?.id })
  221. .leftJoinAndSelect('relation.installation', 'installation')
  222. .getMany();
  223. if (relations.length === 0) {
  224. return respond(growiCommand.responseUrl, {
  225. blocks: [
  226. markdownSectionBlock('*No relation found.*'),
  227. markdownSectionBlock('Run `/growi register` first.'),
  228. ],
  229. });
  230. }
  231. // status
  232. if (growiCommand.growiCommandType === 'status') {
  233. return respond(growiCommand.responseUrl, {
  234. blocks: [
  235. markdownSectionBlock('*Found Relations to GROWI.*'),
  236. ...relations.map((relation) =>
  237. markdownSectionBlock(`GROWI url: ${relation.growiUri}`),
  238. ),
  239. ],
  240. });
  241. }
  242. // not supported commands
  243. if (!supportedGrowiCommands.includes(growiCommand.growiCommandType)) {
  244. return respond(growiCommand.responseUrl, {
  245. text: 'Command is not supported',
  246. blocks: [
  247. markdownSectionBlock('*Command is not supported*'),
  248. // eslint-disable-next-line max-len
  249. markdownSectionBlock(
  250. `\`/growi ${growiCommand.growiCommandType}\` command is not supported in this version of GROWI bot. Run \`/growi help\` to see all supported commands.`,
  251. ),
  252. ],
  253. });
  254. }
  255. // help
  256. if (growiCommand.growiCommandType === 'help') {
  257. return this.sendCommand(growiCommand, relations, body);
  258. }
  259. const allowedRelationsForSingleUse: Relation[] = [];
  260. const allowedRelationsForBroadcastUse: Relation[] = [];
  261. const disallowedGrowiUrls: Set<string> = new Set();
  262. const channel: IChannelOptionalId = {
  263. id: body.channel_id,
  264. name: body.channel_name,
  265. };
  266. // check permission
  267. await Promise.all(
  268. relations.map(async (relation) => {
  269. const isSupportedForSingleUse =
  270. await this.relationsService.isPermissionsForSingleUseCommands(
  271. relation,
  272. growiCommand.growiCommandType,
  273. channel,
  274. );
  275. let isSupportedForBroadcastUse = false;
  276. if (!isSupportedForSingleUse) {
  277. isSupportedForBroadcastUse =
  278. await this.relationsService.isPermissionsUseBroadcastCommands(
  279. relation,
  280. growiCommand.growiCommandType,
  281. channel,
  282. );
  283. }
  284. if (isSupportedForSingleUse) {
  285. allowedRelationsForSingleUse.push(relation);
  286. } else if (isSupportedForBroadcastUse) {
  287. allowedRelationsForBroadcastUse.push(relation);
  288. } else {
  289. disallowedGrowiUrls.add(relation.growiUri);
  290. }
  291. }),
  292. );
  293. // when all of GROWI disallowed
  294. if (relations.length === disallowedGrowiUrls.size) {
  295. const linkUrlList = Array.from(disallowedGrowiUrls).map((growiUrl) => {
  296. return (
  297. '\n' + `• ${new URL('/admin/slack-integration', growiUrl).toString()}`
  298. );
  299. });
  300. const growiDocsLink =
  301. 'https://docs.growi.org/en/admin-guide/upgrading/43x.html';
  302. return respond(growiCommand.responseUrl, {
  303. text: 'Command not permitted.',
  304. blocks: [
  305. markdownSectionBlock('*None of GROWI permitted the command.*'),
  306. markdownSectionBlock(
  307. `*'${growiCommand.growiCommandType}'* command was not allowed.`,
  308. ),
  309. markdownSectionBlock(
  310. `To use this command, modify settings from following pages: ${linkUrlList}`,
  311. ),
  312. markdownSectionBlock(
  313. `Or, if your GROWI version is 4.3.0 or below, upgrade GROWI to use commands and permission settings: ${growiDocsLink}`,
  314. ),
  315. ],
  316. });
  317. }
  318. // select GROWI
  319. if (allowedRelationsForSingleUse.length > 0) {
  320. body.growiUrisForSingleUse = allowedRelationsForSingleUse.map(
  321. (v) => v.growiUri,
  322. );
  323. return this.selectGrowiService.processCommand(
  324. growiCommand,
  325. authorizeResult,
  326. body,
  327. );
  328. }
  329. // forward to GROWI server
  330. if (allowedRelationsForBroadcastUse.length > 0) {
  331. return this.sendCommand(
  332. growiCommand,
  333. allowedRelationsForBroadcastUse,
  334. body,
  335. );
  336. }
  337. }
  338. @Post('/interactions')
  339. @UseBefore(
  340. AddSigningSecretToReq,
  341. verifySlackRequest,
  342. parseSlackInteractionRequest,
  343. AuthorizeInteractionMiddleware,
  344. ExtractGrowiUriFromReq,
  345. )
  346. async handleInteraction(
  347. @Req() req: SlackOauthReq,
  348. @Res() res: Res,
  349. ): Promise<void | string | Res | WebAPICallResult> {
  350. logger.info('receive interaction', req.authorizeResult);
  351. logger.debug('receive interaction', req.body);
  352. const {
  353. body,
  354. authorizeResult,
  355. interactionPayload,
  356. interactionPayloadAccessor,
  357. growiUri,
  358. } = req;
  359. // pass
  360. if (body.ssl_check != null) {
  361. return;
  362. }
  363. if (interactionPayload == null) {
  364. return;
  365. }
  366. // register
  367. const registerResult = await this.registerService.processInteraction(
  368. authorizeResult,
  369. interactionPayload,
  370. interactionPayloadAccessor,
  371. );
  372. if (registerResult.isTerminated) return;
  373. // unregister
  374. const unregisterResult = await this.unregisterService.processInteraction(
  375. authorizeResult,
  376. interactionPayload,
  377. interactionPayloadAccessor,
  378. );
  379. if (unregisterResult.isTerminated) return;
  380. // immediate response to slack
  381. res.send();
  382. // select growi
  383. const selectGrowiResult = await this.selectGrowiService.processInteraction(
  384. authorizeResult,
  385. interactionPayload,
  386. interactionPayloadAccessor,
  387. );
  388. const selectedGrowiInformation = selectGrowiResult.result;
  389. if (!selectGrowiResult.isTerminated && selectedGrowiInformation != null) {
  390. return this.sendCommand(
  391. selectedGrowiInformation.growiCommand,
  392. [selectedGrowiInformation.relation],
  393. selectedGrowiInformation.sendCommandBody,
  394. );
  395. }
  396. // check permission
  397. const installationId =
  398. authorizeResult.enterpriseId || authorizeResult.teamId;
  399. // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
  400. const installation =
  401. await this.installationRepository.findByTeamIdOrEnterpriseId(
  402. installationId!,
  403. );
  404. const relations = await this.relationRepository
  405. .createQueryBuilder('relation')
  406. .where('relation.installationId = :id', { id: installation?.id })
  407. .andWhere('relation.growiUri = :uri', { uri: growiUri })
  408. .leftJoinAndSelect('relation.installation', 'installation')
  409. .getMany();
  410. if (relations.length === 0) {
  411. return respond(interactionPayloadAccessor.getResponseUrl(), {
  412. blocks: [
  413. markdownSectionBlock('*No relation found.*'),
  414. markdownSectionBlock('Run `/growi register` first.'),
  415. ],
  416. });
  417. }
  418. const { actionId, callbackId } =
  419. interactionPayloadAccessor.getActionIdAndCallbackIdFromPayLoad();
  420. const privateMeta = interactionPayloadAccessor.getViewPrivateMetaData();
  421. const channelFromMeta = {
  422. name: privateMeta?.body?.channel_name || privateMeta?.channelName,
  423. };
  424. const channel: IChannelOptionalId =
  425. interactionPayload.channel || channelFromMeta;
  426. const permission =
  427. await this.relationsService.checkPermissionForInteractions(
  428. relations,
  429. actionId,
  430. callbackId,
  431. channel,
  432. );
  433. const {
  434. allowedRelations,
  435. disallowedGrowiUrls,
  436. commandName,
  437. rejectedResults,
  438. } = permission;
  439. try {
  440. await respondRejectedErrors(
  441. rejectedResults,
  442. interactionPayloadAccessor.getResponseUrl(),
  443. );
  444. } catch (err) {
  445. logger.error(err);
  446. }
  447. if (relations.length === disallowedGrowiUrls.size) {
  448. return postNotAllowedMessage(
  449. interactionPayloadAccessor.getResponseUrl(),
  450. disallowedGrowiUrls,
  451. commandName,
  452. );
  453. }
  454. /*
  455. * forward to GROWI server
  456. */
  457. allowedRelations.map(async (relation) => {
  458. try {
  459. // generate API URL
  460. const url = new URL(
  461. '/_api/v3/slack-integration/proxied/interactions',
  462. relation.growiUri,
  463. );
  464. await axios.post(
  465. url.toString(),
  466. {
  467. ...body,
  468. },
  469. {
  470. headers: {
  471. 'x-growi-ptog-tokens': relation.tokenPtoG,
  472. },
  473. },
  474. );
  475. } catch (err) {
  476. logger.error(err);
  477. }
  478. });
  479. }
  480. @Post('/events')
  481. @UseBefore(
  482. UrlVerificationMiddleware,
  483. AddSigningSecretToReq,
  484. verifySlackRequest,
  485. AuthorizeEventsMiddleware,
  486. )
  487. async handleEvent(@Req() req: SlackOauthReq): Promise<void> {
  488. const { authorizeResult } = req;
  489. const client = generateWebClient(authorizeResult.botToken);
  490. const { event } = req.body;
  491. // send welcome message
  492. if (event.type === 'app_home_opened') {
  493. try {
  494. await postWelcomeMessageOnce(client, event.channel);
  495. } catch (err) {
  496. logger.error('Failed to post welcome message', err);
  497. }
  498. }
  499. // unfurl
  500. if (this.linkSharedService.shouldHandleEvent(event.type)) {
  501. await this.linkSharedService.processEvent(client, event);
  502. }
  503. return;
  504. }
  505. @Get('/oauth_redirect')
  506. async handleOauthRedirect(
  507. @Req() req: Req,
  508. @Res() serverRes: ServerResponse,
  509. @Res() platformRes: PlatformResponse,
  510. ): Promise<void | string> {
  511. // create 'Add to Slack' url
  512. const addToSlackUrl =
  513. await this.installerService.installer.generateInstallUrl({
  514. scopes: requiredScopes,
  515. });
  516. const state = req.query.state;
  517. if (state == null || state === '') {
  518. return platformRes
  519. .status(400)
  520. .render('install-failed.ejs', { url: addToSlackUrl });
  521. }
  522. // promisify
  523. const installPromise = new Promise<Installation>((resolve, reject) => {
  524. this.installerService.installer.handleCallback(req, serverRes, {
  525. success: async (installation, metadata) => {
  526. logger.info('Success to install', { installation, metadata });
  527. resolve(installation);
  528. },
  529. failure: async (error) => {
  530. reject(error); // go to catch block
  531. },
  532. });
  533. });
  534. let httpStatus = 200;
  535. let httpBody;
  536. try {
  537. const installation = await installPromise;
  538. // check whether bot is not null
  539. if (installation.bot == null) {
  540. logger.warn(
  541. 'Success to install but something wrong. `installation.bot` is null.',
  542. );
  543. httpStatus = 500;
  544. httpBody = await platformRes.render(
  545. 'install-succeeded-but-has-problem.ejs',
  546. { reason: '`installation.bot` is null' },
  547. );
  548. }
  549. // MAIN PATH: everything is fine
  550. else {
  551. const appPageUrl = `https://slack.com/apps/${installation.appId}`;
  552. httpBody = await platformRes.render('install-succeeded.ejs', {
  553. appPageUrl,
  554. });
  555. // generate client
  556. const client = generateWebClient(installation.bot.token);
  557. const userId = installation.user.id;
  558. await Promise.all([
  559. // post message
  560. postInstallSuccessMessage(client, userId),
  561. // publish home
  562. // TODO: When Home tab show off, use bellow.
  563. // publishInitialHomeView(client, userId),
  564. ]);
  565. }
  566. } catch (error) {
  567. logger.error(error);
  568. httpStatus = 500;
  569. httpBody = await platformRes
  570. .status(400)
  571. .render('install-failed.ejs', { url: addToSlackUrl });
  572. }
  573. platformRes.status(httpStatus);
  574. return httpBody;
  575. }
  576. }