slack.ts 17 KB

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