slack.ts 15 KB

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