slack.ts 17 KB

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