slack.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  1. import {
  2. BodyParams, Controller, Get, Inject, Post, Req, Res, UseBefore,
  3. } from '@tsed/common';
  4. import axios from 'axios';
  5. import { WebAPICallResult } from '@slack/web-api';
  6. import {
  7. markdownSectionBlock, GrowiCommand, parseSlashCommand, postEphemeralErrors, verifySlackRequest, generateWebClient,
  8. InvalidGrowiCommandError,
  9. } from '@growi/slack';
  10. import { Relation } from '~/entities/relation';
  11. import { SlackOauthReq } from '~/interfaces/slack-to-growi/slack-oauth-req';
  12. import { InstallationRepository } from '~/repositories/installation';
  13. import { RelationRepository } from '~/repositories/relation';
  14. import { OrderRepository } from '~/repositories/order';
  15. import { AddSigningSecretToReq } from '~/middlewares/slack-to-growi/add-signing-secret-to-req';
  16. import { AuthorizeCommandMiddleware, AuthorizeInteractionMiddleware } from '~/middlewares/slack-to-growi/authorizer';
  17. import { ExtractGrowiUriFromReq } from '~/middlewares/slack-to-growi/extract-growi-uri-from-req';
  18. import { InstallerService } from '~/services/InstallerService';
  19. import { SelectGrowiService } from '~/services/SelectGrowiService';
  20. import { RegisterService } from '~/services/RegisterService';
  21. import { RelationsService } from '~/services/RelationsService';
  22. import { UnregisterService } from '~/services/UnregisterService';
  23. import { InvalidUrlError } from '../models/errors';
  24. import loggerFactory from '~/utils/logger';
  25. import { JoinToConversationMiddleware } from '~/middlewares/slack-to-growi/join-to-conversation';
  26. const logger = loggerFactory('slackbot-proxy:controllers:slack');
  27. @Controller('/slack')
  28. export class SlackCtrl {
  29. @Inject()
  30. installerService: InstallerService;
  31. @Inject()
  32. installationRepository: InstallationRepository;
  33. @Inject()
  34. relationRepository: RelationRepository;
  35. @Inject()
  36. orderRepository: OrderRepository;
  37. @Inject()
  38. selectGrowiService: SelectGrowiService;
  39. @Inject()
  40. registerService: RegisterService;
  41. @Inject()
  42. relationsService: RelationsService;
  43. @Inject()
  44. unregisterService: UnregisterService;
  45. /**
  46. * Send command to specified GROWIs
  47. * @param growiCommand
  48. * @param relations
  49. * @param body
  50. * @returns
  51. */
  52. private async sendCommand(growiCommand: GrowiCommand, relations: Relation[], body: any) {
  53. if (relations.length === 0) {
  54. throw new Error('relations must be set');
  55. }
  56. const botToken = relations[0].installation?.data.bot?.token; // relations[0] should be exist
  57. const promises = relations.map((relation: Relation) => {
  58. // generate API URL
  59. const url = new URL('/_api/v3/slack-integration/proxied/commands', relation.growiUri);
  60. return axios.post(url.toString(), {
  61. ...body,
  62. growiCommand,
  63. }, {
  64. headers: {
  65. 'x-growi-ptog-tokens': relation.tokenPtoG,
  66. },
  67. });
  68. });
  69. // pickup PromiseRejectedResult only
  70. const results = await Promise.allSettled(promises);
  71. const rejectedResults: PromiseRejectedResult[] = results.filter((result): result is PromiseRejectedResult => result.status === 'rejected');
  72. try {
  73. // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
  74. return postEphemeralErrors(rejectedResults, body.channel_id, body.user_id, botToken!);
  75. }
  76. catch (err) {
  77. logger.error(err);
  78. }
  79. }
  80. @Post('/commands')
  81. @UseBefore(AddSigningSecretToReq, verifySlackRequest, AuthorizeCommandMiddleware, JoinToConversationMiddleware)
  82. async handleCommand(@Req() req: SlackOauthReq, @Res() res: Res): Promise<void|string|Res|WebAPICallResult> {
  83. const { body, authorizeResult } = req;
  84. let growiCommand;
  85. try {
  86. growiCommand = parseSlashCommand(body);
  87. }
  88. catch (err) {
  89. if (err instanceof InvalidGrowiCommandError) {
  90. res.json({
  91. blocks: [
  92. markdownSectionBlock('*Command type is not specified.*'),
  93. markdownSectionBlock('Run `/growi help` to check the commands you can use.'),
  94. ],
  95. });
  96. }
  97. logger.error(err.message);
  98. return;
  99. }
  100. // register
  101. if (growiCommand.growiCommandType === 'register') {
  102. // Send response immediately to avoid opelation_timeout error
  103. // See https://api.slack.com/apis/connections/events-api#the-events-api__responding-to-events
  104. res.send();
  105. return this.registerService.process(growiCommand, authorizeResult, body as {[key:string]:string});
  106. }
  107. // unregister
  108. if (growiCommand.growiCommandType === 'unregister') {
  109. if (growiCommand.growiCommandArgs.length === 0) {
  110. return 'GROWI Urls is required.';
  111. }
  112. if (!growiCommand.growiCommandArgs.every(v => v.match(/^(https?:\/\/)/))) {
  113. return 'GROWI Urls must be urls.';
  114. }
  115. // Send response immediately to avoid opelation_timeout error
  116. // See https://api.slack.com/apis/connections/events-api#the-events-api__responding-to-events
  117. res.send();
  118. return this.unregisterService.process(growiCommand, authorizeResult, body as {[key:string]:string});
  119. }
  120. const installationId = authorizeResult.enterpriseId || authorizeResult.teamId;
  121. // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
  122. const installation = await this.installationRepository.findByTeamIdOrEnterpriseId(installationId!);
  123. const relations = await this.relationRepository.createQueryBuilder('relation')
  124. .where('relation.installationId = :id', { id: installation?.id })
  125. .leftJoinAndSelect('relation.installation', 'installation')
  126. .getMany();
  127. if (relations.length === 0) {
  128. return res.json({
  129. blocks: [
  130. markdownSectionBlock('*No relation found.*'),
  131. markdownSectionBlock('Run `/growi register` first.'),
  132. ],
  133. });
  134. }
  135. // status
  136. if (growiCommand.growiCommandType === 'status') {
  137. return res.json({
  138. blocks: [
  139. markdownSectionBlock('*Found Relations to GROWI.*'),
  140. ...relations.map(relation => markdownSectionBlock(`GROWI url: ${relation.growiUri}`)),
  141. ],
  142. });
  143. }
  144. // Send response immediately to avoid opelation_timeout error
  145. // See https://api.slack.com/apis/connections/events-api#the-events-api__responding-to-events
  146. res.send();
  147. const baseDate = new Date();
  148. const allowedRelationsForSingleUse:Relation[] = [];
  149. const disallowedGrowiUrls: Set<string> = new Set();
  150. // check permission for single use
  151. await Promise.all(relations.map(async(relation) => {
  152. const isSupported = await this.relationsService.isSupportedGrowiCommandForSingleUse(relation, growiCommand.growiCommandType, baseDate);
  153. if (isSupported) {
  154. allowedRelationsForSingleUse.push(relation);
  155. }
  156. else {
  157. disallowedGrowiUrls.add(relation.growiUri);
  158. }
  159. }));
  160. // select GROWI
  161. if (allowedRelationsForSingleUse.length > 0) {
  162. body.growiUrisForSingleUse = allowedRelationsForSingleUse.map(v => v.growiUri);
  163. return this.selectGrowiService.process(growiCommand, authorizeResult, body);
  164. }
  165. // check permission for broadcast use
  166. const relationsForBroadcastUse:Relation[] = [];
  167. await Promise.all(relations.map(async(relation) => {
  168. const isSupported = await this.relationsService.isSupportedGrowiCommandForBroadcastUse(relation, growiCommand.growiCommandType, baseDate);
  169. if (isSupported) {
  170. relationsForBroadcastUse.push(relation);
  171. }
  172. else {
  173. disallowedGrowiUrls.add(relation.growiUri);
  174. }
  175. }));
  176. // forward to GROWI server
  177. if (relationsForBroadcastUse.length > 0) {
  178. this.sendCommand(growiCommand, relationsForBroadcastUse, body);
  179. }
  180. // when all of GROWI disallowed
  181. if (relations.length === disallowedGrowiUrls.size) {
  182. // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
  183. const client = generateWebClient(authorizeResult.botToken!);
  184. const linkUrlList = Array.from(disallowedGrowiUrls).map((growiUrl) => {
  185. return '\n'
  186. + `• ${new URL('/admin/slack-integration', growiUrl).toString()}`;
  187. });
  188. return client.chat.postEphemeral({
  189. text: 'Error occured.',
  190. channel: body.channel_id,
  191. user: body.user_id,
  192. blocks: [
  193. markdownSectionBlock('*None of GROWI permitted the command.*'),
  194. markdownSectionBlock(`*'${growiCommand.growiCommandType}'* command was not allowed.`),
  195. markdownSectionBlock(
  196. `To use this command, modify settings from following pages: ${linkUrlList}`,
  197. ),
  198. ],
  199. });
  200. }
  201. }
  202. @Post('/interactions')
  203. @UseBefore(AuthorizeInteractionMiddleware, ExtractGrowiUriFromReq)
  204. async handleInteraction(@Req() req: SlackOauthReq, @Res() res: Res): Promise<void|string|Res|WebAPICallResult> {
  205. logger.info('receive interaction', req.authorizeResult);
  206. logger.debug('receive interaction', req.body);
  207. const { body, authorizeResult } = req;
  208. // Send response immediately to avoid opelation_timeout error
  209. // See https://api.slack.com/apis/connections/events-api#the-events-api__responding-to-events
  210. res.send();
  211. // pass
  212. if (body.ssl_check != null) {
  213. return;
  214. }
  215. const installationId = authorizeResult.enterpriseId || authorizeResult.teamId;
  216. // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
  217. const installation = await this.installationRepository.findByTeamIdOrEnterpriseId(installationId!);
  218. const payload = JSON.parse(body.payload);
  219. const callBackId = payload?.view?.callback_id;
  220. // register
  221. if (callBackId === 'register') {
  222. try {
  223. await this.registerService.insertOrderRecord(installation, authorizeResult.botToken, payload);
  224. }
  225. catch (err) {
  226. if (err instanceof InvalidUrlError) {
  227. logger.info(err.message);
  228. return;
  229. }
  230. logger.error(err);
  231. }
  232. await this.registerService.notifyServerUriToSlack(authorizeResult.botToken, payload);
  233. return;
  234. }
  235. // unregister
  236. if (callBackId === 'unregister') {
  237. await this.unregisterService.unregister(installation, authorizeResult, payload);
  238. return;
  239. }
  240. // forward to GROWI server
  241. if (callBackId === 'select_growi') {
  242. const selectedGrowiInformation = await this.selectGrowiService.handleSelectInteraction(installation, payload);
  243. return this.sendCommand(selectedGrowiInformation.growiCommand, [selectedGrowiInformation.relation], selectedGrowiInformation.sendCommandBody);
  244. }
  245. /*
  246. * forward to GROWI server
  247. */
  248. const relation = await this.relationRepository.findOne({ installation, growiUri: req.growiUri });
  249. if (relation == null) {
  250. logger.error('*No relation found.*');
  251. return;
  252. }
  253. try {
  254. // generate API URL
  255. const url = new URL('/_api/v3/slack-integration/proxied/interactions', req.growiUri);
  256. await axios.post(url.toString(), {
  257. ...body,
  258. }, {
  259. headers: {
  260. 'x-growi-ptog-tokens': relation.tokenPtoG,
  261. },
  262. });
  263. }
  264. catch (err) {
  265. logger.error(err);
  266. }
  267. }
  268. @Post('/events')
  269. async handleEvent(@BodyParams() body:{[key:string]:string} /* , @Res() res: Res */): Promise<void|string> {
  270. // eslint-disable-next-line max-len
  271. // see: https://api.slack.com/apis/connections/events-api#the-events-api__subscribing-to-event-types__events-api-request-urls__request-url-configuration--verification
  272. if (body.type === 'url_verification') {
  273. return body.challenge;
  274. }
  275. logger.info('receive event', body);
  276. return;
  277. }
  278. @Get('/oauth_redirect')
  279. async handleOauthRedirect(@Req() req: Req, @Res() res: Res): Promise<void> {
  280. if (req.query.state === '') {
  281. res.writeHead(500, { 'Content-Type': 'text/html; charset=utf-8' });
  282. res.end('<html>'
  283. + '<head><meta name="viewport" content="width=device-width,initial-scale=1"></head>'
  284. + '<body style="text-align:center; padding-top:20%;">'
  285. + '<h1>Illegal state, try it again.</h1>'
  286. + '<a href="/">'
  287. + 'Go to install page'
  288. + '</a>'
  289. + '</body></html>');
  290. }
  291. await this.installerService.installer.handleCallback(req, res, {
  292. success: async(installation, metadata, req, res) => {
  293. logger.info('Success to install', { installation, metadata });
  294. const appPageUrl = `https://slack.com/apps/${installation.appId}`;
  295. res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
  296. res.end('<html>'
  297. + '<head><meta name="viewport" content="width=device-width,initial-scale=1">'
  298. + '<link href="/bootstrap/css/bootstrap.min.css" rel="stylesheet">'
  299. + '</head>'
  300. + '<body style="text-align:center; padding-top:20%;">'
  301. + '<h1>Congratulations!</h1>'
  302. + '<p>GROWI Bot installation has succeeded.</p>'
  303. + '<div class="d-inline-flex flex-column">'
  304. + `<a class="mb-3" href="${appPageUrl}">`
  305. + 'Access to Slack App detail page.'
  306. + '</a>'
  307. + '<a class="btn btn-outline-success" href="https://docs.growi.org/en/admin-guide/management-cookbook/slack-integration/official-bot-settings.html">'
  308. + 'Getting started'
  309. + '</a>'
  310. + '</div>'
  311. + '</body></html>');
  312. if (installation.bot == null) {
  313. res.writeHead(500, { 'Content-Type': 'text/html; charset=utf-8' });
  314. return res.end('html'
  315. + '<head><meta name="viewport" content="width=device-width,initial-scale=1">'
  316. + '<link href="/bootstrap/css/bootstrap.min.css" rel="stylesheet">'
  317. + '</head>'
  318. + '<body style="text-align:center; padding-top:20%;">'
  319. + '<p>Installation setting is not correct.</p>'
  320. + '</body></html>');
  321. }
  322. const client = generateWebClient(installation.bot.token);
  323. await client.chat.postMessage({
  324. channel: installation.user.id,
  325. user: installation.user.id,
  326. blocks: [
  327. {
  328. type: 'section',
  329. text: {
  330. type: 'mrkdwn',
  331. // eslint-disable-next-line max-len
  332. text: 'You have successfully installed GROWI Official Bot on this Slack workspace. At first you do `/growi register` in the channel that you want to use. Looking for additional help? See <https://docs.growi.org/en/admin-guide/management-cookbook/slack-integration/official-bot-settings.html#official-bot-settings | Docs>.',
  333. },
  334. },
  335. ],
  336. });
  337. // TODO fix Home later
  338. await client.views.publish({
  339. user_id: installation.user.id,
  340. view: {
  341. type: 'home',
  342. blocks: [
  343. {
  344. type: 'section',
  345. text: {
  346. type: 'mrkdwn',
  347. text: 'Welcome GROWI Official Bot Home',
  348. },
  349. },
  350. {
  351. type: 'section',
  352. text: {
  353. type: 'mrkdwn',
  354. // eslint-disable-next-line max-len
  355. text: 'Learn how to use GROWI Official bot. See <https://docs.growi.org/en/admin-guide/management-cookbook/slack-integration/official-bot-settings.html#official-bot-settings | Docs>.',
  356. },
  357. },
  358. ],
  359. },
  360. });
  361. },
  362. failure: (error, installOptions, req, res) => {
  363. res.writeHead(500, { 'Content-Type': 'text/html; charset=utf-8' });
  364. res.end('<html>'
  365. + '<head><meta name="viewport" content="width=device-width,initial-scale=1"></head>'
  366. + '<body style="text-align:center; padding-top:20%;">'
  367. + '<h1>GROWI Bot installation failed</h1>'
  368. + '<p>Please contact administrators of your workspace</p>'
  369. + 'Reference: <a href="https://slack.com/help/articles/222386767-Manage-app-installation-settings-for-your-workspace">'
  370. + 'Manage app installation settings for your workspace'
  371. + '</a>'
  372. + '</body></html>');
  373. },
  374. });
  375. }
  376. }