slack.ts 16 KB

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