slack.ts 16 KB

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