slack.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  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, channelId:string, userId:string, 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: channelId,
  40. user: userId,
  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.channel_id, body.user_id, 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. const permission = await this.relationsService.checkPermissionForInteractions(relations, actionId, callbackId, channelName);
  276. const {
  277. allowedRelations, disallowedGrowiUrls, commandName, rejectedResults,
  278. } = permission;
  279. try {
  280. // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
  281. await postEphemeralErrors(rejectedResults, payload.channel.id, payload.user.id, authorizeResult.botToken!);
  282. }
  283. catch (err) {
  284. logger.error(err);
  285. }
  286. if (relations.length === disallowedGrowiUrls.size) {
  287. // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
  288. const client = generateWebClient(authorizeResult.botToken!);
  289. return postNotAllowedMessage(client, payload.channel.id, payload.user.id, disallowedGrowiUrls, commandName);
  290. }
  291. /*
  292. * forward to GROWI server
  293. */
  294. allowedRelations.map(async(relation) => {
  295. try {
  296. // generate API URL
  297. const url = new URL('/_api/v3/slack-integration/proxied/interactions', relation.growiUri);
  298. await axios.post(url.toString(), {
  299. ...body,
  300. }, {
  301. headers: {
  302. 'x-growi-ptog-tokens': relation.tokenPtoG,
  303. },
  304. });
  305. }
  306. catch (err) {
  307. logger.error(err);
  308. }
  309. });
  310. }
  311. @Post('/events')
  312. @UseBefore(UrlVerificationMiddleware, AuthorizeEventsMiddleware)
  313. async handleEvent(@Req() req: SlackOauthReq): Promise<void> {
  314. const { authorizeResult } = req;
  315. const client = generateWebClient(authorizeResult.botToken);
  316. if (req.body.event.type === 'app_home_opened') {
  317. await postWelcomeMessage(client, req.body.event.channel);
  318. }
  319. return;
  320. }
  321. @Get('/oauth_redirect')
  322. async handleOauthRedirect(@Req() req: Req, @Res() serverRes: Res, @Res() platformRes: PlatformResponse): Promise<void|string> {
  323. // create 'Add to Slack' url
  324. const addToSlackUrl = await this.installerService.installer.generateInstallUrl({
  325. scopes: requiredScopes,
  326. });
  327. const state = req.query.state;
  328. if (state == null || state === '') {
  329. return platformRes.status(400).render('install-failed.ejs', { url: addToSlackUrl });
  330. }
  331. // promisify
  332. const installPromise = new Promise<Installation>((resolve, reject) => {
  333. this.installerService.installer.handleCallback(req, serverRes, {
  334. success: async(installation, metadata) => {
  335. logger.info('Success to install', { installation, metadata });
  336. resolve(installation);
  337. },
  338. failure: async(error) => {
  339. reject(error); // go to catch block
  340. },
  341. });
  342. });
  343. let httpStatus = 200;
  344. let httpBody;
  345. try {
  346. const installation = await installPromise;
  347. // check whether bot is not null
  348. if (installation.bot == null) {
  349. logger.warn('Success to install but something wrong. `installation.bot` is null.');
  350. httpStatus = 500;
  351. httpBody = await platformRes.render('install-succeeded-but-has-problem.ejs', { reason: '`installation.bot` is null' });
  352. }
  353. // MAIN PATH: everything is fine
  354. else {
  355. const appPageUrl = `https://slack.com/apps/${installation.appId}`;
  356. httpBody = await platformRes.render('install-succeeded.ejs', { appPageUrl });
  357. // generate client
  358. const client = generateWebClient(installation.bot.token);
  359. const userId = installation.user.id;
  360. await Promise.all([
  361. // post message
  362. postWelcomeMessage(client, userId),
  363. // publish home
  364. // TODO When Home tab show off, use bellow.
  365. // publishInitialHomeView(client, userId),
  366. ]);
  367. }
  368. }
  369. catch (error) {
  370. logger.error(error);
  371. httpStatus = 500;
  372. httpBody = await platformRes.status(400).render('install-failed.ejs', { url: addToSlackUrl });
  373. }
  374. platformRes.status(httpStatus);
  375. return httpBody;
  376. }
  377. }