slack.ts 16 KB

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