slack.ts 17 KB

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