slack.ts 15 KB

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