slack.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642
  1. import { ServerResponse } from 'node: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 `\n• ${new URL('/admin/slack-integration', growiUrl).toString()}`;
  64. });
  65. const growiDocsLink =
  66. 'https://docs.growi.org/en/admin-guide/upgrading/43x.html';
  67. await respond(responseUrl, {
  68. text: 'Error occured.',
  69. blocks: [
  70. markdownSectionBlock('*None of GROWI permitted the command.*'),
  71. markdownSectionBlock(`*'${commandName}'* command was not allowed.`),
  72. markdownSectionBlock(
  73. `To use this command, modify settings from following pages: ${linkUrlList}`,
  74. ),
  75. markdownSectionBlock(
  76. `Or, if your GROWI version is 4.3.0 or below, upgrade GROWI to use commands and permission settings: ${growiDocsLink}`,
  77. ),
  78. ],
  79. });
  80. return;
  81. };
  82. @Controller('/slack')
  83. export class SlackCtrl {
  84. @Inject()
  85. installerService: InstallerService;
  86. @Inject()
  87. installationRepository: InstallationRepository;
  88. @Inject()
  89. relationRepository: RelationRepository;
  90. @Inject()
  91. orderRepository: OrderRepository;
  92. @Inject()
  93. selectGrowiService: SelectGrowiService;
  94. @Inject()
  95. registerService: RegisterService;
  96. @Inject()
  97. relationsService: RelationsService;
  98. @Inject()
  99. unregisterService: UnregisterService;
  100. @Inject()
  101. linkSharedService: LinkSharedService;
  102. /**
  103. * Send command to specified GROWIs
  104. * @param growiCommand
  105. * @param relations
  106. * @param body
  107. * @returns
  108. */
  109. private async sendCommand(
  110. growiCommand: GrowiCommand,
  111. relations: Relation[],
  112. // biome-ignore lint/suspicious/noExplicitAny: ignore
  113. body: any,
  114. ) {
  115. if (relations.length === 0) {
  116. throw new Error('relations must be set');
  117. }
  118. const promises = relations.map((relation: Relation) => {
  119. // generate API URL
  120. const url = new URL(
  121. '/_api/v3/slack-integration/proxied/commands',
  122. relation.growiUri,
  123. );
  124. return axios.post(
  125. url.toString(),
  126. {
  127. ...body,
  128. growiCommand,
  129. },
  130. {
  131. headers: {
  132. 'x-growi-ptog-tokens': relation.tokenPtoG,
  133. },
  134. timeout: REQUEST_TIMEOUT_FOR_PTOG,
  135. },
  136. );
  137. });
  138. // pickup PromiseRejectedResult only
  139. const results = await Promise.allSettled(promises);
  140. const rejectedResults: PromiseRejectedResult[] = results.filter(
  141. (result): result is PromiseRejectedResult => result.status === 'rejected',
  142. );
  143. try {
  144. return respondRejectedErrors(rejectedResults, growiCommand.responseUrl);
  145. } catch (err) {
  146. logger.error(err);
  147. }
  148. }
  149. @Post('/commands')
  150. @UseBefore(
  151. AddSigningSecretToReq,
  152. verifySlackRequest,
  153. AuthorizeCommandMiddleware,
  154. )
  155. async handleCommand(
  156. @Req() req: SlackOauthReq,
  157. @Res() res: Res,
  158. // biome-ignore lint/suspicious/noConfusingVoidType: TODO: fix in https://redmine.weseek.co.jp/issues/168174
  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. const installation =
  214. await this.installationRepository.findByTeamIdOrEnterpriseId(
  215. // biome-ignore lint/style/noNonNullAssertion: ignore
  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. markdownSectionBlock(
  249. `\`/growi ${growiCommand.growiCommandType}\` command is not supported in this version of GROWI bot. Run \`/growi help\` to see all supported commands.`,
  250. ),
  251. ],
  252. });
  253. }
  254. // help
  255. if (growiCommand.growiCommandType === 'help') {
  256. return this.sendCommand(growiCommand, relations, body);
  257. }
  258. const allowedRelationsForSingleUse: Relation[] = [];
  259. const allowedRelationsForBroadcastUse: Relation[] = [];
  260. const disallowedGrowiUrls: Set<string> = new Set();
  261. const channel: IChannelOptionalId = {
  262. id: body.channel_id,
  263. name: body.channel_name,
  264. };
  265. // check permission
  266. await Promise.all(
  267. relations.map(async (relation) => {
  268. const isSupportedForSingleUse =
  269. await this.relationsService.isPermissionsForSingleUseCommands(
  270. relation,
  271. growiCommand.growiCommandType,
  272. channel,
  273. );
  274. let isSupportedForBroadcastUse = false;
  275. if (!isSupportedForSingleUse) {
  276. isSupportedForBroadcastUse =
  277. await this.relationsService.isPermissionsUseBroadcastCommands(
  278. relation,
  279. growiCommand.growiCommandType,
  280. channel,
  281. );
  282. }
  283. if (isSupportedForSingleUse) {
  284. allowedRelationsForSingleUse.push(relation);
  285. } else if (isSupportedForBroadcastUse) {
  286. allowedRelationsForBroadcastUse.push(relation);
  287. } else {
  288. disallowedGrowiUrls.add(relation.growiUri);
  289. }
  290. }),
  291. );
  292. // when all of GROWI disallowed
  293. if (relations.length === disallowedGrowiUrls.size) {
  294. const linkUrlList = Array.from(disallowedGrowiUrls).map((growiUrl) => {
  295. return `\n• ${new URL('/admin/slack-integration', growiUrl).toString()}`;
  296. });
  297. const growiDocsLink =
  298. 'https://docs.growi.org/en/admin-guide/upgrading/43x.html';
  299. return respond(growiCommand.responseUrl, {
  300. text: 'Command not permitted.',
  301. blocks: [
  302. markdownSectionBlock('*None of GROWI permitted the command.*'),
  303. markdownSectionBlock(
  304. `*'${growiCommand.growiCommandType}'* command was not allowed.`,
  305. ),
  306. markdownSectionBlock(
  307. `To use this command, modify settings from following pages: ${linkUrlList}`,
  308. ),
  309. markdownSectionBlock(
  310. `Or, if your GROWI version is 4.3.0 or below, upgrade GROWI to use commands and permission settings: ${growiDocsLink}`,
  311. ),
  312. ],
  313. });
  314. }
  315. // select GROWI
  316. if (allowedRelationsForSingleUse.length > 0) {
  317. body.growiUrisForSingleUse = allowedRelationsForSingleUse.map(
  318. (v) => v.growiUri,
  319. );
  320. return this.selectGrowiService.processCommand(
  321. growiCommand,
  322. authorizeResult,
  323. body,
  324. );
  325. }
  326. // forward to GROWI server
  327. if (allowedRelationsForBroadcastUse.length > 0) {
  328. return this.sendCommand(
  329. growiCommand,
  330. allowedRelationsForBroadcastUse,
  331. body,
  332. );
  333. }
  334. }
  335. @Post('/interactions')
  336. @UseBefore(
  337. AddSigningSecretToReq,
  338. verifySlackRequest,
  339. parseSlackInteractionRequest,
  340. AuthorizeInteractionMiddleware,
  341. ExtractGrowiUriFromReq,
  342. )
  343. async handleInteraction(
  344. @Req() req: SlackOauthReq,
  345. @Res() res: Res,
  346. // biome-ignore lint/suspicious/noConfusingVoidType: TODO: fix in https://redmine.weseek.co.jp/issues/168174
  347. ): Promise<void | string | Res | WebAPICallResult> {
  348. logger.info('receive interaction', req.authorizeResult);
  349. logger.debug('receive interaction', req.body);
  350. const {
  351. body,
  352. authorizeResult,
  353. interactionPayload,
  354. interactionPayloadAccessor,
  355. growiUri,
  356. } = req;
  357. // pass
  358. if (body.ssl_check != null) {
  359. return;
  360. }
  361. if (interactionPayload == null) {
  362. return;
  363. }
  364. // register
  365. const registerResult = await this.registerService.processInteraction(
  366. authorizeResult,
  367. interactionPayload,
  368. interactionPayloadAccessor,
  369. );
  370. if (registerResult.isTerminated) return;
  371. // unregister
  372. const unregisterResult = await this.unregisterService.processInteraction(
  373. authorizeResult,
  374. interactionPayload,
  375. interactionPayloadAccessor,
  376. );
  377. if (unregisterResult.isTerminated) return;
  378. // immediate response to slack
  379. res.send();
  380. // select growi
  381. const selectGrowiResult = await this.selectGrowiService.processInteraction(
  382. authorizeResult,
  383. interactionPayload,
  384. interactionPayloadAccessor,
  385. );
  386. const selectedGrowiInformation = selectGrowiResult.result;
  387. if (!selectGrowiResult.isTerminated && selectedGrowiInformation != null) {
  388. return this.sendCommand(
  389. selectedGrowiInformation.growiCommand,
  390. [selectedGrowiInformation.relation],
  391. selectedGrowiInformation.sendCommandBody,
  392. );
  393. }
  394. // check permission
  395. const installationId =
  396. authorizeResult.enterpriseId || authorizeResult.teamId;
  397. const installation =
  398. await this.installationRepository.findByTeamIdOrEnterpriseId(
  399. // biome-ignore lint/style/noNonNullAssertion: ignore
  400. installationId!,
  401. );
  402. const relations = await this.relationRepository
  403. .createQueryBuilder('relation')
  404. .where('relation.installationId = :id', { id: installation?.id })
  405. .andWhere('relation.growiUri = :uri', { uri: growiUri })
  406. .leftJoinAndSelect('relation.installation', 'installation')
  407. .getMany();
  408. if (relations.length === 0) {
  409. return respond(interactionPayloadAccessor.getResponseUrl(), {
  410. blocks: [
  411. markdownSectionBlock('*No relation found.*'),
  412. markdownSectionBlock('Run `/growi register` first.'),
  413. ],
  414. });
  415. }
  416. const { actionId, callbackId } =
  417. interactionPayloadAccessor.getActionIdAndCallbackIdFromPayLoad();
  418. const privateMeta = interactionPayloadAccessor.getViewPrivateMetaData();
  419. const channelFromMeta = {
  420. name: privateMeta?.body?.channel_name || privateMeta?.channelName,
  421. };
  422. const channel: IChannelOptionalId =
  423. interactionPayload.channel || channelFromMeta;
  424. const permission =
  425. await this.relationsService.checkPermissionForInteractions(
  426. relations,
  427. actionId,
  428. callbackId,
  429. channel,
  430. );
  431. const {
  432. allowedRelations,
  433. disallowedGrowiUrls,
  434. commandName,
  435. rejectedResults,
  436. } = permission;
  437. try {
  438. await respondRejectedErrors(
  439. rejectedResults,
  440. interactionPayloadAccessor.getResponseUrl(),
  441. );
  442. } catch (err) {
  443. logger.error(err);
  444. }
  445. if (relations.length === disallowedGrowiUrls.size) {
  446. return postNotAllowedMessage(
  447. interactionPayloadAccessor.getResponseUrl(),
  448. disallowedGrowiUrls,
  449. commandName,
  450. );
  451. }
  452. /*
  453. * forward to GROWI server
  454. */
  455. allowedRelations.map(async (relation) => {
  456. try {
  457. // generate API URL
  458. const url = new URL(
  459. '/_api/v3/slack-integration/proxied/interactions',
  460. relation.growiUri,
  461. );
  462. await axios.post(
  463. url.toString(),
  464. {
  465. ...body,
  466. },
  467. {
  468. headers: {
  469. 'x-growi-ptog-tokens': relation.tokenPtoG,
  470. },
  471. },
  472. );
  473. } catch (err) {
  474. logger.error(err);
  475. }
  476. });
  477. }
  478. @Post('/events')
  479. @UseBefore(
  480. UrlVerificationMiddleware,
  481. AddSigningSecretToReq,
  482. verifySlackRequest,
  483. AuthorizeEventsMiddleware,
  484. )
  485. async handleEvent(@Req() req: SlackOauthReq): Promise<void> {
  486. const { authorizeResult } = req;
  487. const client = generateWebClient(authorizeResult.botToken);
  488. const { event } = req.body;
  489. // send welcome message
  490. if (event.type === 'app_home_opened') {
  491. try {
  492. await postWelcomeMessageOnce(client, event.channel);
  493. } catch (err) {
  494. logger.error('Failed to post welcome message', err);
  495. }
  496. }
  497. // unfurl
  498. if (this.linkSharedService.shouldHandleEvent(event.type)) {
  499. await this.linkSharedService.processEvent(client, event);
  500. }
  501. return;
  502. }
  503. @Get('/oauth_redirect')
  504. async handleOauthRedirect(
  505. @Req() req: Req,
  506. @Res() serverRes: ServerResponse,
  507. @Res() platformRes: PlatformResponse,
  508. ): Promise<string> {
  509. // create 'Add to Slack' url
  510. const addToSlackUrl =
  511. await this.installerService.installer.generateInstallUrl({
  512. scopes: requiredScopes,
  513. });
  514. const state = req.query.state;
  515. if (state == null || state === '') {
  516. return platformRes
  517. .status(400)
  518. .render('install-failed.ejs', { url: addToSlackUrl });
  519. }
  520. // promisify
  521. const installPromise = new Promise<Installation>((resolve, reject) => {
  522. this.installerService.installer.handleCallback(req, serverRes, {
  523. success: async (installation, metadata) => {
  524. logger.info('Success to install', { installation, metadata });
  525. resolve(installation);
  526. },
  527. failure: async (error) => {
  528. reject(error); // go to catch block
  529. },
  530. });
  531. });
  532. let httpStatus = 200;
  533. let httpBody: string | undefined;
  534. try {
  535. const installation = await installPromise;
  536. // check whether bot is not null
  537. if (installation.bot == null) {
  538. logger.warn(
  539. 'Success to install but something wrong. `installation.bot` is null.',
  540. );
  541. httpStatus = 500;
  542. httpBody = await platformRes.render(
  543. 'install-succeeded-but-has-problem.ejs',
  544. { reason: '`installation.bot` is null' },
  545. );
  546. }
  547. // MAIN PATH: everything is fine
  548. else {
  549. const appPageUrl = `https://slack.com/apps/${installation.appId}`;
  550. httpBody = await platformRes.render('install-succeeded.ejs', {
  551. appPageUrl,
  552. });
  553. // generate client
  554. const client = generateWebClient(installation.bot.token);
  555. const userId = installation.user.id;
  556. await Promise.all([
  557. // post message
  558. postInstallSuccessMessage(client, userId),
  559. // publish home
  560. // TODO: When Home tab show off, use bellow.
  561. // publishInitialHomeView(client, userId),
  562. ]);
  563. }
  564. } catch (error) {
  565. logger.error(error);
  566. httpStatus = 500;
  567. httpBody = await platformRes
  568. .status(400)
  569. .render('install-failed.ejs', { url: addToSlackUrl });
  570. }
  571. platformRes.status(httpStatus);
  572. return httpBody;
  573. }
  574. }