slack.ts 14 KB

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