2
0

slack.ts 14 KB

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