slack.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  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. generateMarkdownSectionBlock, GrowiCommand, parseSlashCommand, postEphemeralErrors, verifySlackRequest,
  8. } from '@growi/slack';
  9. import { Relation } from '~/entities/relation';
  10. import { SlackOauthReq } from '~/interfaces/slack-to-growi/slack-oauth-req';
  11. import { InstallationRepository } from '~/repositories/installation';
  12. import { RelationRepository } from '~/repositories/relation';
  13. import { OrderRepository } from '~/repositories/order';
  14. import { AddSigningSecretToReq } from '~/middlewares/slack-to-growi/add-signing-secret-to-req';
  15. import { AuthorizeCommandMiddleware, AuthorizeInteractionMiddleware } from '~/middlewares/slack-to-growi/authorizer';
  16. import { ExtractGrowiUriFromReq } from '~/middlewares/slack-to-growi/extract-growi-uri-from-req';
  17. import { InstallerService } from '~/services/InstallerService';
  18. import { SelectGrowiService } from '~/services/SelectGrowiService';
  19. import { RegisterService } from '~/services/RegisterService';
  20. import { UnregisterService } from '~/services/UnregisterService';
  21. import { InvalidUrlError } from '../models/errors';
  22. import loggerFactory from '~/utils/logger';
  23. const logger = loggerFactory('slackbot-proxy:controllers:slack');
  24. @Controller('/slack')
  25. export class SlackCtrl {
  26. @Inject()
  27. installerService: InstallerService;
  28. @Inject()
  29. installationRepository: InstallationRepository;
  30. @Inject()
  31. relationRepository: RelationRepository;
  32. @Inject()
  33. orderRepository: OrderRepository;
  34. @Inject()
  35. selectGrowiService: SelectGrowiService;
  36. @Inject()
  37. registerService: RegisterService;
  38. @Inject()
  39. unregisterService: UnregisterService;
  40. @Get('/install')
  41. async install(): Promise<string> {
  42. const url = await this.installerService.installer.generateInstallUrl({
  43. // Add the scopes your app needs
  44. scopes: [
  45. 'channels:history',
  46. 'commands',
  47. 'groups:history',
  48. 'im:history',
  49. 'mpim:history',
  50. 'chat:write',
  51. 'team:read',
  52. ],
  53. });
  54. return `<a href="${url}">`
  55. // eslint-disable-next-line max-len
  56. + '<img alt="Add to Slack" height="40" width="139" src="https://platform.slack-edge.com/img/add_to_slack.png" srcSet="https://platform.slack-edge.com/img/add_to_slack.png 1x, https://platform.slack-edge.com/img/add_to_slack@2x.png 2x" />'
  57. + '</a>';
  58. }
  59. /**
  60. * Send command to specified GROWIs
  61. * @param growiCommand
  62. * @param relations
  63. * @param body
  64. * @returns
  65. */
  66. private async sendCommand(growiCommand: GrowiCommand, relations: Relation[], body: any) {
  67. if (relations.length === 0) {
  68. throw new Error('relations must be set');
  69. }
  70. const botToken = relations[0].installation?.data.bot?.token; // relations[0] should be exist
  71. const promises = relations.map((relation: Relation) => {
  72. // generate API URL
  73. const url = new URL('/_api/v3/slack-integration/proxied/commands', relation.growiUri);
  74. return axios.post(url.toString(), {
  75. ...body,
  76. growiCommand,
  77. }, {
  78. headers: {
  79. 'x-growi-ptog-tokens': relation.tokenPtoG,
  80. },
  81. });
  82. });
  83. // pickup PromiseRejectedResult only
  84. const results = await Promise.allSettled(promises);
  85. const rejectedResults: PromiseRejectedResult[] = results.filter((result): result is PromiseRejectedResult => result.status === 'rejected');
  86. try {
  87. // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
  88. return postEphemeralErrors(rejectedResults, body.channel_id, body.user_id, botToken!);
  89. }
  90. catch (err) {
  91. logger.error(err);
  92. }
  93. }
  94. @Post('/commands')
  95. @UseBefore(AddSigningSecretToReq, verifySlackRequest, AuthorizeCommandMiddleware)
  96. async handleCommand(@Req() req: SlackOauthReq, @Res() res: Res): Promise<void|string|Res|WebAPICallResult> {
  97. const { body, authorizeResult } = req;
  98. if (body.text == null) {
  99. return 'No text.';
  100. }
  101. const growiCommand = parseSlashCommand(body);
  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. generateMarkdownSectionBlock('*No relation found.*'),
  133. generateMarkdownSectionBlock('Run `/growi register` first.'),
  134. ],
  135. });
  136. }
  137. // status
  138. if (growiCommand.growiCommandType === 'status') {
  139. return res.json({
  140. blocks: [
  141. generateMarkdownSectionBlock('*Found Relations to GROWI.*'),
  142. ...relations.map(relation => generateMarkdownSectionBlock(`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. body.growiUris = [];
  150. relations.forEach((relation) => {
  151. if (relation.siglePostCommands.includes(growiCommand.growiCommandType)) {
  152. body.growiUris.push(relation.growiUri);
  153. }
  154. });
  155. if (body.growiUris != null && body.growiUris.length > 0) {
  156. return this.selectGrowiService.process(growiCommand, authorizeResult, body);
  157. }
  158. /*
  159. * forward to GROWI server
  160. */
  161. this.sendCommand(growiCommand, relations, body);
  162. }
  163. @Post('/interactions')
  164. @UseBefore(AuthorizeInteractionMiddleware, ExtractGrowiUriFromReq)
  165. async handleInteraction(@Req() req: SlackOauthReq, @Res() res: Res): Promise<void|string|Res|WebAPICallResult> {
  166. logger.info('receive interaction', req.body);
  167. logger.info('receive interaction', req.authorizeResult);
  168. const { body, authorizeResult } = req;
  169. // Send response immediately to avoid opelation_timeout error
  170. // See https://api.slack.com/apis/connections/events-api#the-events-api__responding-to-events
  171. res.send();
  172. // pass
  173. if (body.ssl_check != null) {
  174. return;
  175. }
  176. const installationId = authorizeResult.enterpriseId || authorizeResult.teamId;
  177. // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
  178. const installation = await this.installationRepository.findByTeamIdOrEnterpriseId(installationId!);
  179. const payload = JSON.parse(body.payload);
  180. const callBackId = payload?.view?.callback_id;
  181. // register
  182. if (callBackId === 'register') {
  183. try {
  184. await this.registerService.insertOrderRecord(installation, authorizeResult.botToken, payload);
  185. }
  186. catch (err) {
  187. if (err instanceof InvalidUrlError) {
  188. logger.info(err.message);
  189. return;
  190. }
  191. logger.error(err);
  192. }
  193. await this.registerService.notifyServerUriToSlack(authorizeResult.botToken, payload);
  194. return;
  195. }
  196. // unregister
  197. if (callBackId === 'unregister') {
  198. await this.unregisterService.unregister(installation, authorizeResult, payload);
  199. return;
  200. }
  201. // forward to GROWI server
  202. if (callBackId === 'select_growi') {
  203. const selectedGrowiInformation = await this.selectGrowiService.handleSelectInteraction(installation, payload);
  204. return this.sendCommand(selectedGrowiInformation.growiCommand, [selectedGrowiInformation.relation], selectedGrowiInformation.sendCommandBody);
  205. }
  206. /*
  207. * forward to GROWI server
  208. */
  209. const relation = await this.relationRepository.findOne({ installation, growiUri: req.growiUri });
  210. if (relation == null) {
  211. logger.error('*No relation found.*');
  212. return;
  213. }
  214. try {
  215. // generate API URL
  216. const url = new URL('/_api/v3/slack-integration/proxied/interactions', req.growiUri);
  217. await axios.post(url.toString(), {
  218. ...body,
  219. }, {
  220. headers: {
  221. 'x-growi-ptog-tokens': relation.tokenPtoG,
  222. },
  223. });
  224. }
  225. catch (err) {
  226. logger.error(err);
  227. }
  228. }
  229. @Post('/events')
  230. async handleEvent(@BodyParams() body:{[key:string]:string}, @Res() res: Res): Promise<void|string> {
  231. // eslint-disable-next-line max-len
  232. // see: https://api.slack.com/apis/connections/events-api#the-events-api__subscribing-to-event-types__events-api-request-urls__request-url-configuration--verification
  233. if (body.type === 'url_verification') {
  234. return body.challenge;
  235. }
  236. logger.info('receive event', body);
  237. return;
  238. }
  239. @Get('/oauth_redirect')
  240. async handleOauthRedirect(@Req() req: Req, @Res() res: Res): Promise<void> {
  241. if (req.query.state === '') {
  242. res.writeHead(500, { 'Content-Type': 'text/html; charset=utf-8' });
  243. res.end('<html>'
  244. + '<head><meta name="viewport" content="width=device-width,initial-scale=1"></head>'
  245. + '<body style="text-align:center; padding-top:20%;">'
  246. + '<h1>Illegal state, try it again.</h1>'
  247. + '<a href="/slack/install">'
  248. + 'Go to install page'
  249. + '</a>'
  250. + '</body></html>');
  251. }
  252. await this.installerService.installer.handleCallback(req, res, {
  253. success: (installation, metadata, req, res) => {
  254. logger.info('Success to install', { installation, metadata });
  255. const appPageUrl = `https://slack.com/apps/${installation.appId}`;
  256. res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
  257. res.end('<html>'
  258. + '<head><meta name="viewport" content="width=device-width,initial-scale=1"></head>'
  259. + '<body style="text-align:center; padding-top:20%;">'
  260. + '<h1>Congratulations!</h1>'
  261. + '<p>GROWI Bot installation has succeeded.</p>'
  262. + `<a href="${appPageUrl}">`
  263. + 'Access to Slack App detail page.'
  264. + '</a>'
  265. + '</body></html>');
  266. },
  267. failure: (error, installOptions, req, res) => {
  268. res.writeHead(500, { 'Content-Type': 'text/html; charset=utf-8' });
  269. res.end('<html>'
  270. + '<head><meta name="viewport" content="width=device-width,initial-scale=1"></head>'
  271. + '<body style="text-align:center; padding-top:20%;">'
  272. + '<h1>GROWI Bot installation failed</h1>'
  273. + '<p>Please contact administrators of your workspace</p>'
  274. + 'Reference: <a href="https://slack.com/help/articles/222386767-Manage-app-installation-settings-for-your-workspace">'
  275. + 'Manage app installation settings for your workspace'
  276. + '</a>'
  277. + '</body></html>');
  278. },
  279. });
  280. }
  281. }