-
Notifications
You must be signed in to change notification settings - Fork 4.3k
Expand file tree
/
Copy pathintegrations.controller.ts
More file actions
967 lines (899 loc) · 39.2 KB
/
Copy pathintegrations.controller.ts
File metadata and controls
967 lines (899 loc) · 39.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
import {
BadRequestException,
Body,
ClassSerializerInterceptor,
Controller,
Delete,
ForbiddenException,
Get,
HttpCode,
HttpStatus,
Param,
Post,
Put,
Query,
Res,
UseInterceptors,
} from '@nestjs/common';
import { ApiExcludeEndpoint, ApiOperation, ApiTags } from '@nestjs/swagger';
import {
CalculateLimitNovuIntegration,
CalculateLimitNovuIntegrationCommand,
FeatureFlagsService,
GetActiveIntegrations,
GetActiveIntegrationsCommand,
GetDecryptedIntegrations,
IntegrationResponseDto,
OtelSpan,
PinoLogger,
RequirePermissions,
} from '@novu/application-generic';
import { CommunityOrganizationRepository } from '@novu/dal';
import {
ApiAuthSchemeEnum,
ApiServiceLevelEnum,
ChannelTypeEnum,
FeatureFlagsKeysEnum,
FeatureNameEnum,
getFeatureForTierAsBoolean,
PermissionsEnum,
UserSessionData,
} from '@novu/shared';
import { Response } from 'express';
import { RequireAuthentication } from '../auth/framework/auth.decorator';
import { ExternalApiAccessible } from '../auth/framework/external-api.decorator';
import {
ApiCommonResponses,
ApiNotFoundResponse,
ApiOkResponse,
ApiResponse,
} from '../shared/framework/response.decorator';
import { isEnvironmentScopedAuthScheme } from '../shared/utils/auth.utils';
import { KeylessAccessible } from '../shared/framework/swagger/keyless.security';
import { SdkGroupName, SdkMethodName } from '../shared/framework/swagger/sdk.decorators';
import { UserSession } from '../shared/framework/user.decorator';
import { CONNECTION_RESULT_CSP } from '../shared/html/connection-result-page';
import { AutoConfigureIntegrationResponseDto } from './dtos/auto-configure-integration-response.dto';
import { CreateIntegrationRequestDto } from './dtos/create-integration-request.dto';
import { GenerateChatOauthUrlRequestDto } from './dtos/generate-chat-oauth-url.dto';
import { GenerateChatOAuthUrlResponseDto } from './dtos/generate-chat-oauth-url-response.dto';
import { GenerateConnectOauthUrlRequestDto } from './dtos/generate-connect-oauth-url-request.dto';
import { GenerateLinkUserOauthUrlRequestDto } from './dtos/generate-link-user-oauth-url-request.dto';
import { ChannelTypeLimitDto } from './dtos/get-channel-type-limit.sto';
import { IssueIntegrationStoreTelegramMobileLinkResponseDto } from './dtos/issue-integration-store-telegram-mobile-link-response.dto';
import { SlackQuickSetupRequestDto, SlackQuickSetupResponseDto } from './dtos/slack-quick-setup.dto';
import { UpdateIntegrationRequestDto } from './dtos/update-integration.dto';
import { WhatsAppValidateTokenRequestDto, WhatsAppValidateTokenResponseDto } from './dtos/whatsapp-validate-token.dto';
import {
WhatsAppEmbeddedSignupRequestDto,
WhatsAppEmbeddedSignupResponseDto,
} from './dtos/whatsapp-embedded-signup.dto';
import { AutoConfigureIntegrationCommand } from './usecases/auto-configure-integration/auto-configure-integration.command';
import { AutoConfigureIntegration } from './usecases/auto-configure-integration/auto-configure-integration.usecase';
import { AzureSetupOauthCallbackCommand } from './usecases/azure-setup-oauth-callback/azure-setup-oauth-callback.command';
import { AzureSetupOauthCallback } from './usecases/azure-setup-oauth-callback/azure-setup-oauth-callback.usecase';
import { ChatOauthCallbackCommand } from './usecases/chat-oauth-callback/chat-oauth-callback.command';
import { ResponseTypeEnum } from './usecases/chat-oauth-callback/chat-oauth-callback.response';
import { ChatOauthCallback } from './usecases/chat-oauth-callback/chat-oauth-callback.usecase';
import { CreateIntegrationCommand } from './usecases/create-integration/create-integration.command';
import { CreateIntegration } from './usecases/create-integration/create-integration.usecase';
import { GenerateAzureSetupOauthUrlCommand } from './usecases/generate-azure-setup-oauth-url/generate-azure-setup-oauth-url.command';
import { GenerateAzureSetupOauthUrl } from './usecases/generate-azure-setup-oauth-url/generate-azure-setup-oauth-url.usecase';
import { GenerateChatOauthUrlCommand } from './usecases/generate-chat-oath-url/generate-chat-oauth-url.command';
import { GenerateChatOauthUrl } from './usecases/generate-chat-oath-url/generate-chat-oauth-url.usecase';
import { GenerateConnectOauthUrlCommand } from './usecases/generate-chat-oath-url/generate-connect-oauth-url.command';
import { GenerateConnectOauthUrl } from './usecases/generate-chat-oath-url/generate-connect-oauth-url.usecase';
import { GenerateLinkUserOauthUrlCommand } from './usecases/generate-chat-oath-url/generate-link-user-oauth-url.command';
import { GenerateLinkUserOauthUrl } from './usecases/generate-chat-oath-url/generate-link-user-oauth-url.usecase';
import { GenerateMsTeamsArmTemplateCommand } from './usecases/generate-msteams-arm-template/generate-msteams-arm-template.command';
import { GenerateMsTeamsArmTemplate } from './usecases/generate-msteams-arm-template/generate-msteams-arm-template.usecase';
import { GetMsTeamsArmTemplate } from './usecases/generate-msteams-arm-template/get-msteams-arm-template.usecase';
import { GetInAppActivatedCommand } from './usecases/get-in-app-activated/get-in-app-activated.command';
import { GetInAppActivated } from './usecases/get-in-app-activated/get-in-app-activated.usecase';
import { GetIntegrationsCommand } from './usecases/get-integrations/get-integrations.command';
import { GetIntegrations } from './usecases/get-integrations/get-integrations.usecase';
import { GetWebhookSupportStatusCommand } from './usecases/get-webhook-support-status/get-webhook-support-status.command';
import { GetWebhookSupportStatus } from './usecases/get-webhook-support-status/get-webhook-support-status.usecase';
import { IssueIntegrationStoreTelegramMobileLinkCommand } from './usecases/issue-integration-store-telegram-mobile-link/issue-integration-store-telegram-mobile-link.command';
import { IssueIntegrationStoreTelegramMobileLink } from './usecases/issue-integration-store-telegram-mobile-link/issue-integration-store-telegram-mobile-link.usecase';
import { MsTeamsHealthCheckCommand } from './usecases/msteams-health-check/msteams-health-check.command';
import {
MsTeamsHealthCheck,
MsTeamsHealthCheckResult,
} from './usecases/msteams-health-check/msteams-health-check.usecase';
import { RemoveIntegrationCommand } from './usecases/remove-integration/remove-integration.command';
import { RemoveIntegration } from './usecases/remove-integration/remove-integration.usecase';
import { SetIntegrationAsPrimaryCommand } from './usecases/set-integration-as-primary/set-integration-as-primary.command';
import { SetIntegrationAsPrimary } from './usecases/set-integration-as-primary/set-integration-as-primary.usecase';
import { SlackQuickSetupCommand } from './usecases/slack-quick-setup/slack-quick-setup.command';
import { SlackQuickSetup } from './usecases/slack-quick-setup/slack-quick-setup.usecase';
import { UpdateIntegrationCommand } from './usecases/update-integration/update-integration.command';
import { UpdateIntegration } from './usecases/update-integration/update-integration.usecase';
import { WhatsAppValidateTokenCommand } from './usecases/whatsapp/whatsapp-validate-token.command';
import { WhatsAppValidateToken } from './usecases/whatsapp/whatsapp-validate-token.usecase';
import { WhatsAppEmbeddedSignupCommand } from './usecases/whatsapp/whatsapp-embedded-signup.command';
import { WhatsAppEmbeddedSignup } from './usecases/whatsapp/whatsapp-embedded-signup.usecase';
@ApiCommonResponses()
@Controller('/integrations')
@UseInterceptors(ClassSerializerInterceptor)
@ApiTags('Integrations')
export class IntegrationsController {
constructor(
private getInAppActivatedUsecase: GetInAppActivated,
private getIntegrationsUsecase: GetIntegrations,
private getActiveIntegrationsUsecase: GetActiveIntegrations,
private getWebhookSupportStatusUsecase: GetWebhookSupportStatus,
private createIntegrationUsecase: CreateIntegration,
private updateIntegrationUsecase: UpdateIntegration,
private autoConfigureIntegrationUsecase: AutoConfigureIntegration,
private setIntegrationAsPrimaryUsecase: SetIntegrationAsPrimary,
private removeIntegrationUsecase: RemoveIntegration,
private calculateLimitNovuIntegration: CalculateLimitNovuIntegration,
private organizationRepository: CommunityOrganizationRepository,
private generateChatOauthUrlUsecase: GenerateChatOauthUrl,
private generateConnectOauthUrlUsecase: GenerateConnectOauthUrl,
private generateLinkUserOauthUrlUsecase: GenerateLinkUserOauthUrl,
private chatOauthCallbackUsecase: ChatOauthCallback,
private slackQuickSetupUsecase: SlackQuickSetup,
private featureFlagsService: FeatureFlagsService,
private generateMsTeamsArmTemplateUsecase: GenerateMsTeamsArmTemplate,
private getMsTeamsArmTemplateUsecase: GetMsTeamsArmTemplate,
private generateAzureSetupOauthUrlUsecase: GenerateAzureSetupOauthUrl,
private azureSetupOauthCallbackUsecase: AzureSetupOauthCallback,
private msTeamsHealthCheckUsecase: MsTeamsHealthCheck,
private whatsAppValidateTokenUsecase: WhatsAppValidateToken,
private whatsAppEmbeddedSignupUsecase: WhatsAppEmbeddedSignup,
private issueIntegrationStoreTelegramMobileLinkUsecase: IssueIntegrationStoreTelegramMobileLink,
private logger: PinoLogger
) {
this.logger.setContext(IntegrationsController.name);
}
@Get('/')
@ApiOkResponse({
type: [IntegrationResponseDto],
description: 'The list of integrations belonging to the organization that are successfully returned.',
})
@ApiOperation({
summary: 'List all integrations',
description:
'List all the channels integrations created in the organization. Only integration metadata is returned, credentials field is returned as an empty object.',
})
@ExternalApiAccessible()
@KeylessAccessible()
@RequireAuthentication()
@RequirePermissions(PermissionsEnum.INTEGRATION_READ)
async listIntegrations(@UserSession() user: UserSessionData): Promise<IntegrationResponseDto[]> {
const canAccessCredentials = await this.canUserAccessCredentials(user);
return await this.getIntegrationsUsecase.execute(
GetIntegrationsCommand.create({
environmentId: user.environmentId,
organizationId: user.organizationId,
userId: user._id,
returnCredentials: canAccessCredentials,
scopeToEnvironment: isEnvironmentScopedAuthScheme(user.scheme),
})
);
}
@Get('/active')
@ApiOkResponse({
type: [IntegrationResponseDto],
description: 'The list of active integrations belonging to the organization that are successfully returned.',
})
@ApiOperation({
summary: 'List active integrations',
description:
'List all the active integrations created in the organization. Only integration metadata is returned, credentials field is returned as an empty object.',
})
@ExternalApiAccessible()
@SdkMethodName('listActive')
@RequireAuthentication()
@RequirePermissions(PermissionsEnum.INTEGRATION_READ)
async getActiveIntegrations(@UserSession() user: UserSessionData): Promise<IntegrationResponseDto[]> {
const canAccessCredentials = await this.canUserAccessCredentials(user);
return await this.getActiveIntegrationsUsecase.execute(
GetActiveIntegrationsCommand.create({
environmentId: user.environmentId,
organizationId: user.organizationId,
userId: user._id,
returnCredentials: canAccessCredentials,
scopeToEnvironment: isEnvironmentScopedAuthScheme(user.scheme),
})
);
}
@Get('/webhook/provider/:providerOrIntegrationId/status')
@ApiOkResponse({
type: Boolean,
description: 'The status of the webhook for the provider requested',
})
@ApiExcludeEndpoint()
@ApiOperation({
summary: 'Retrieve webhook status',
description: `Retrieve the status of the webhook for integration specified in query param **providerOrIntegrationId**.
This API returns a boolean value.`,
})
@SdkGroupName('Integrations.Webhooks')
@ExternalApiAccessible()
@RequireAuthentication()
@RequirePermissions(PermissionsEnum.INTEGRATION_READ)
async getWebhookSupportStatus(
@UserSession() user: UserSessionData,
@Param('providerOrIntegrationId') providerOrIntegrationId: string
): Promise<boolean> {
return await this.getWebhookSupportStatusUsecase.execute(
GetWebhookSupportStatusCommand.create({
environmentId: user.environmentId,
organizationId: user.organizationId,
providerOrIntegrationId,
userId: user._id,
})
);
}
@Post('/')
@ApiResponse(IntegrationResponseDto, 201)
@ApiOperation({
summary: 'Create an integration',
description: `Create an integration for the current environment the user is based on the API key provided.
Each provider supports different credentials, check the provider documentation for more details. Only integration metadata is returned, credentials field is returned as an empty object.`,
})
@ExternalApiAccessible()
@KeylessAccessible()
@RequireAuthentication()
@RequirePermissions(PermissionsEnum.INTEGRATION_WRITE)
async createIntegration(
@UserSession() user: UserSessionData,
@Body() body: CreateIntegrationRequestDto
): Promise<IntegrationResponseDto> {
try {
this.assertEnvironmentScopedForApiKey(user, body._environmentId);
const canAccessCredentials = await this.canUserAccessCredentials(user);
const integration = await this.createIntegrationUsecase.execute(
CreateIntegrationCommand.create({
userId: user._id,
name: body.name,
identifier: body.identifier,
environmentId: body._environmentId ?? user.environmentId,
organizationId: user.organizationId,
providerId: body.providerId,
channel: body.channel,
kind: body.kind,
credentials: body.credentials,
active: body.active ?? false,
check: body.check ?? false,
conditions: body.conditions,
configurations: body.configurations,
})
);
if (canAccessCredentials) {
return GetDecryptedIntegrations.getDecryptedCredentials(integration);
}
const { credentials: _credentials, ...integrationWithoutCredentials } = integration;
return integrationWithoutCredentials as unknown as IntegrationResponseDto;
} catch (e) {
if (e.message.includes('Integration validation failed') || e.message.includes('Cast to embedded')) {
throw new BadRequestException(e.message);
}
throw e;
}
}
@Put('/:integrationId')
@ApiResponse(IntegrationResponseDto)
@ApiNotFoundResponse({
description: 'The integration with the integrationId provided does not exist in the database.',
})
@ApiOperation({
summary: 'Update an integration',
description: `Update an integration by its unique key identifier **integrationId**.
Each provider supports different credentials, check the provider documentation for more details. Only integration metadata is returned, credentials field is returned as an empty object.`,
})
@ExternalApiAccessible()
@RequireAuthentication()
@RequirePermissions(PermissionsEnum.INTEGRATION_WRITE)
async updateIntegrationById(
@UserSession() user: UserSessionData,
@Param('integrationId') integrationId: string,
@Body() body: UpdateIntegrationRequestDto
): Promise<IntegrationResponseDto> {
try {
this.assertEnvironmentScopedForApiKey(user, body._environmentId);
const canAccessCredentials = await this.canUserAccessCredentials(user);
const integration = await this.updateIntegrationUsecase.execute(
UpdateIntegrationCommand.create({
userId: user._id,
name: body.name,
identifier: body.identifier,
environmentId: body._environmentId,
userEnvironmentId: user.environmentId,
organizationId: user.organizationId,
integrationId,
credentials: body.credentials,
active: body.active,
check: body.check ?? false,
conditions: body.conditions,
configurations: body.configurations,
restrictToUserEnvironment: isEnvironmentScopedAuthScheme(user.scheme),
})
);
if (canAccessCredentials) {
return GetDecryptedIntegrations.getDecryptedCredentials(integration);
}
const { credentials: _credentials, ...integrationWithoutCredentials } = integration;
return integrationWithoutCredentials as unknown as IntegrationResponseDto;
} catch (e) {
if (e.message.includes('Integration validation failed') || e.message.includes('Cast to embedded')) {
throw new BadRequestException(e.message);
}
throw e;
}
}
@Post('/:integrationId/auto-configure')
@ApiResponse(AutoConfigureIntegrationResponseDto, 200)
@ApiNotFoundResponse({
description: 'The integration with the integrationId provided does not exist in the database.',
})
@ApiOperation({
summary: 'Auto-configure an integration for inbound webhooks',
description: `Auto-configure an integration by its unique key identifier **integrationId** for inbound webhook support.
This will automatically generate required webhook signing keys and configure webhook endpoints. Only integration metadata is returned, credentials field is returned as an empty object.`,
})
@ExternalApiAccessible()
@RequireAuthentication()
@RequirePermissions(PermissionsEnum.INTEGRATION_WRITE)
async autoConfigureIntegration(
@UserSession() user: UserSessionData,
@Param('integrationId') integrationId: string
): Promise<AutoConfigureIntegrationResponseDto> {
const result = await this.autoConfigureIntegrationUsecase.execute(
AutoConfigureIntegrationCommand.create({
userId: user._id,
environmentId: user.environmentId,
organizationId: user.organizationId,
integrationId,
restrictToUserEnvironment: isEnvironmentScopedAuthScheme(user.scheme),
})
);
return result;
}
@Post('/:integrationId/set-primary')
@ApiResponse(IntegrationResponseDto)
@ApiNotFoundResponse({
description: 'The integration with the integrationId provided does not exist in the database.',
})
@ApiOperation({
summary: 'Update integration as primary',
description: `Update an integration as **primary** by its unique key identifier **integrationId**.
This API will set the integration as primary for that channel in the current environment.
Primary integration is used to deliver notification for sms and email channels in the workflow.
Only integration metadata is returned, credentials field is returned as an empty object.`,
})
@ExternalApiAccessible()
@RequireAuthentication()
@RequirePermissions(PermissionsEnum.INTEGRATION_WRITE)
@SdkMethodName('setAsPrimary')
async setIntegrationAsPrimary(
@UserSession() user: UserSessionData,
@Param('integrationId') integrationId: string
): Promise<IntegrationResponseDto> {
const canAccessCredentials = await this.canUserAccessCredentials(user);
const integration = await this.setIntegrationAsPrimaryUsecase.execute(
SetIntegrationAsPrimaryCommand.create({
userId: user._id,
environmentId: user.environmentId,
organizationId: user.organizationId,
integrationId,
restrictToUserEnvironment: isEnvironmentScopedAuthScheme(user.scheme),
})
);
if (canAccessCredentials) {
return GetDecryptedIntegrations.getDecryptedCredentials(integration);
}
const { credentials: _credentials, ...integrationWithoutCredentials } = integration;
return integrationWithoutCredentials as unknown as IntegrationResponseDto;
}
@Delete('/:integrationId')
@ApiResponse(IntegrationResponseDto, 200, true)
@ApiOperation({
summary: 'Delete an integration',
description: `Delete an integration by its unique key identifier **integrationId**.
This action is irreversible. Only integration metadata is returned, credentials field is returned as empty object.`,
})
@ExternalApiAccessible()
@KeylessAccessible()
@RequireAuthentication()
@RequirePermissions(PermissionsEnum.INTEGRATION_WRITE)
async removeIntegration(
@UserSession() user: UserSessionData,
@Param('integrationId') integrationId: string
): Promise<IntegrationResponseDto[]> {
return await this.removeIntegrationUsecase.execute(
RemoveIntegrationCommand.create({
userId: user._id,
environmentId: user.environmentId,
organizationId: user.organizationId,
integrationId,
restrictToUserEnvironment: isEnvironmentScopedAuthScheme(user.scheme),
})
);
}
@Get('/:channelType/limit')
@ApiExcludeEndpoint()
@OtelSpan()
@RequireAuthentication()
@RequirePermissions(PermissionsEnum.INTEGRATION_READ)
async getProviderLimit(
@UserSession() user: UserSessionData,
@Param('channelType') channelType: ChannelTypeEnum
): Promise<ChannelTypeLimitDto> {
const result = await this.calculateLimitNovuIntegration.execute(
CalculateLimitNovuIntegrationCommand.create({
channelType,
organizationId: user.organizationId,
environmentId: user.environmentId,
})
);
if (!result) {
return { limit: 0, count: 0 };
}
return result;
}
@Get('/in-app/status')
@ApiExcludeEndpoint()
@RequireAuthentication()
@RequirePermissions(PermissionsEnum.INTEGRATION_READ)
async getInAppActivated(@UserSession() user: UserSessionData) {
return await this.getInAppActivatedUsecase.execute(
GetInAppActivatedCommand.create({
organizationId: user.organizationId,
environmentId: user.environmentId,
})
);
}
@Get('/:integrationId/msteams-arm-template/deploy-url')
@ApiOkResponse({
description: 'Signed Azure Portal "Deploy to Azure" URL for the MS Teams ARM template.',
})
@ApiOperation({
summary: 'Get MS Teams ARM template deploy URL',
description:
'Returns a short-lived signed URL that opens the Azure Portal with a pre-filled ARM template to create the Azure Bot resource and enable the MS Teams channel.',
})
@ApiExcludeEndpoint()
@RequireAuthentication()
@RequirePermissions(PermissionsEnum.INTEGRATION_WRITE)
async getMsTeamsArmTemplateDeployUrl(
@UserSession() user: UserSessionData,
@Param('integrationId') integrationId: string
): Promise<{ deployUrl: string }> {
return this.generateMsTeamsArmTemplateUsecase.execute(
GenerateMsTeamsArmTemplateCommand.create({
userId: user._id,
organizationId: user.organizationId,
integrationId,
})
);
}
/**
* Public endpoint fetched by Azure Portal when the user clicks "Deploy to Azure".
* Protected by an HMAC-signed, time-expiring `sig` + `exp` query parameter pair —
* no session cookie is available because Azure's servers make this request, not the browser.
*/
@Get('/:integrationId/msteams-arm-template')
@ApiExcludeEndpoint()
@ApiOperation({ summary: 'Serve MS Teams ARM template JSON (signed)' })
async getMsTeamsArmTemplateJson(
@Res() res: Response,
@Param('integrationId') integrationId: string,
@Query('sig') sig: string,
@Query('exp') exp: string
): Promise<void> {
if (!sig || !exp) {
throw new BadRequestException('Missing required parameters: sig, exp');
}
const { template } = await this.getMsTeamsArmTemplateUsecase.execute(integrationId, sig, exp);
res.setHeader('Content-Type', 'application/json');
res.setHeader('Cache-Control', 'no-store');
res.send(JSON.stringify(template, null, 2));
}
/**
* Quick Setup: generate an Azure AD OAuth URL so Novu can create the App Registration
* on the user's behalf via Microsoft Graph.
*/
@Get('/:integrationId/msteams-azure-setup/oauth-url')
@ApiOkResponse({
description: 'Azure AD OAuth URL for the Quick Setup flow (Novu creates the app registration).',
})
@ApiOperation({
summary: 'Get Azure Quick Setup OAuth URL',
description:
'Returns an Azure AD OAuth URL that authorizes Novu to create an App Registration and client secret on your behalf via Microsoft Graph.',
})
@ApiExcludeEndpoint()
@RequireAuthentication()
@RequirePermissions(PermissionsEnum.INTEGRATION_WRITE)
async getAzureSetupOauthUrl(
@UserSession() user: UserSessionData,
@Param('integrationId') integrationId: string
): Promise<{ url: string }> {
const url = await this.generateAzureSetupOauthUrlUsecase.execute(
GenerateAzureSetupOauthUrlCommand.create({
userId: user._id,
organizationId: user.organizationId,
environmentId: user.environmentId,
integrationId,
})
);
return { url };
}
/**
* Health-check endpoint polled by the dashboard to determine if the saved MS Teams
* credentials, app catalog entry, and Graph permissions are ready after the Quick
* Setup OAuth flow.
*/
@Get('/:integrationId/msteams-health')
@ApiOkResponse({
description: 'Per-checkpoint health status for an MS Teams integration after Quick Setup.',
})
@ApiOperation({
summary: 'Get MS Teams integration health status',
description:
'Returns the readiness status of the stored MS Teams credentials, app catalog entry, and Graph permissions. Poll this endpoint after the OAuth setup completes to determine when it is safe to proceed to admin consent.',
})
@ApiExcludeEndpoint()
@RequireAuthentication()
@RequirePermissions(PermissionsEnum.INTEGRATION_READ)
async getMsTeamsHealth(
@UserSession() user: UserSessionData,
@Param('integrationId') integrationId: string,
@Query('checks') checksParam?: string
): Promise<MsTeamsHealthCheckResult> {
const checks = checksParam
? checksParam
.split(',')
.map((s) => s.trim())
.filter(Boolean)
: undefined;
return this.msTeamsHealthCheckUsecase.execute(
MsTeamsHealthCheckCommand.create({
environmentId: user.environmentId,
organizationId: user.organizationId,
integrationId,
checks,
})
);
}
/**
* Quick Setup callback: Azure AD redirects here after the user authorizes Novu.
* Creates the App Registration, secret, and service principal via Graph, saves
* credentials to the integration, then attempts to upload the Teams app to the catalog.
* Returns a self-closing script that posts a message to the opener tab and closes itself.
*/
@Get('/chat/oauth/azure-setup/callback')
@ApiExcludeEndpoint()
@ApiOperation({ summary: 'Azure Quick Setup OAuth callback' })
async handleAzureSetupOauthCallback(
@Res() res: Response,
@Query('code') code?: string,
@Query('state') state?: string,
@Query('error') error?: string,
@Query('error_description') errorDescription?: string
): Promise<void> {
res.setHeader('Content-Security-Policy', "default-src 'self'; script-src 'self' 'unsafe-inline'");
if (!state) {
res
.status(400)
.type('html')
.send(
AzureSetupOauthCallback.buildPopupHtml({
success: false,
errorMessage: 'Missing required OAuth parameter: state',
})
);
return;
}
try {
const result = await this.azureSetupOauthCallbackUsecase.execute(
AzureSetupOauthCallbackCommand.create({
state,
code,
error,
errorDescription,
})
);
res.type('html').send(result.html);
} catch (err: unknown) {
this.logger.error({ err }, 'Azure OAuth callback failed');
res
.status(200)
.type('html')
.send(
AzureSetupOauthCallback.buildPopupHtml({
success: false,
errorMessage: 'An unexpected error occurred while completing Azure setup.',
})
);
}
}
/**
* @deprecated Use POST /integrations/channel-connections/oauth or POST /integrations/channel-endpoints/oauth instead.
*/
@Post('/chat/oauth')
@ApiResponse(GenerateChatOAuthUrlResponseDto, 201)
@ApiOperation({
summary: 'Generate chat OAuth URL',
description: `**Deprecated** — use \`POST /integrations/channel-connections/oauth\` (connect) or \`POST /integrations/channel-endpoints/oauth\` (link_user) instead.
Generate an OAuth URL for chat integrations like Slack and MS Teams.
This URL allows subscribers to authorize the integration, enabling the system to send messages
through their chat workspace. The generated URL expires after 5 minutes.`,
deprecated: true,
})
@SdkMethodName('generateChatOAuthUrl')
@RequirePermissions(PermissionsEnum.INTEGRATION_WRITE)
@ExternalApiAccessible()
@RequireAuthentication()
async getChatOAuthUrl(
@UserSession() user: UserSessionData,
@Body() body: GenerateChatOauthUrlRequestDto
): Promise<GenerateChatOAuthUrlResponseDto> {
const url = await this.generateChatOauthUrlUsecase.execute(
GenerateChatOauthUrlCommand.create({
environmentId: user.environmentId,
organizationId: user.organizationId,
subscriberId: body.subscriberId,
integrationIdentifier: body.integrationIdentifier,
connectionIdentifier: body.connectionIdentifier,
context: body.context,
scope: body.scope,
userScope: body.userScope,
mode: body.mode,
connectionMode: body.connectionMode,
autoLinkUser: body.autoLinkUser,
})
);
return { url };
}
@Post('/channel-connections/oauth')
@ApiResponse(GenerateChatOAuthUrlResponseDto, 201)
@ApiOperation({
summary: 'Generate OAuth URL for a workspace/tenant connection',
description: `Generate an OAuth URL that creates a workspace or tenant-level channel connection (Slack workspace install or MS Teams admin consent).
The generated URL expires after 5 minutes.`,
})
@SdkMethodName('generateConnectOAuthUrl')
@RequirePermissions(PermissionsEnum.INTEGRATION_WRITE)
@ExternalApiAccessible()
@KeylessAccessible()
@RequireAuthentication()
async generateConnectOAuthUrl(
@UserSession() user: UserSessionData,
@Body() body: GenerateConnectOauthUrlRequestDto
): Promise<GenerateChatOAuthUrlResponseDto> {
const url = await this.generateConnectOauthUrlUsecase.execute(
GenerateConnectOauthUrlCommand.create({
environmentId: user.environmentId,
organizationId: user.organizationId,
subscriberId: body.subscriberId,
integrationIdentifier: body.integrationIdentifier,
connectionIdentifier: body.connectionIdentifier,
context: body.context,
scope: body.scope,
connectionMode: body.connectionMode,
autoLinkUser: body.autoLinkUser,
})
);
return { url };
}
@Post('/channel-endpoints/oauth')
@ApiResponse(GenerateChatOAuthUrlResponseDto, 201)
@ApiOperation({
summary: 'Generate OAuth URL to link a subscriber user identity',
description: `Generate an OAuth URL that links a specific subscriber to their chat identity (Slack user ID or MS Teams user OID).
The generated URL expires after 5 minutes.`,
})
@SdkMethodName('generateLinkUserOAuthUrl')
@RequirePermissions(PermissionsEnum.INTEGRATION_WRITE)
@ExternalApiAccessible()
@RequireAuthentication()
async generateLinkUserOAuthUrl(
@UserSession() user: UserSessionData,
@Body() body: GenerateLinkUserOauthUrlRequestDto
): Promise<GenerateChatOAuthUrlResponseDto> {
const url = await this.generateLinkUserOauthUrlUsecase.execute(
GenerateLinkUserOauthUrlCommand.create({
environmentId: user.environmentId,
organizationId: user.organizationId,
subscriberId: body.subscriberId,
integrationIdentifier: body.integrationIdentifier,
connectionIdentifier: body.connectionIdentifier,
context: body.context,
userScope: body.userScope,
})
);
return { url };
}
@Get('/chat/oauth/callback')
@ApiOperation({
summary: 'Handle chat OAuth callback',
description: `Generic OAuth callback handler for all chat integrations (Slack, Teams, Discord, etc.).
This endpoint processes the authorization code and stores the connection for any supported chat provider.`,
})
@ApiExcludeEndpoint()
async handleChatOAuthCallback(
@Res() res: Response,
@Query('code') providerCode?: string,
@Query('tenant') tenant?: string,
@Query('admin_consent') adminConsent?: string,
@Query('state') state?: string,
@Query('error') error?: string,
@Query('error_description') errorDescription?: string
): Promise<void> {
if (error) {
throw new BadRequestException(`OAuth error: ${error}${errorDescription ? ` - ${errorDescription}` : ''}`);
}
if (!state) {
throw new BadRequestException('Missing required OAuth parameter: state');
}
if (!providerCode && !tenant) {
throw new BadRequestException('Missing required OAuth parameters: code or tenant');
}
const result = await this.chatOauthCallbackUsecase.execute(
ChatOauthCallbackCommand.create({
providerCode,
tenant,
adminConsent,
state,
})
);
if (result.type === ResponseTypeEnum.HTML) {
res.setHeader('Content-Type', 'text/html');
res.setHeader('Content-Security-Policy', CONNECTION_RESULT_CSP);
res.send(result.result);
return;
}
res.redirect(result.result);
}
@Post('/whatsapp/validate-token')
@ApiResponse(WhatsAppValidateTokenResponseDto, 200)
@ApiOperation({
summary: 'Validate WhatsApp Business credentials inline',
description:
'Calls the Meta Graph API to validate a WhatsApp Cloud API access token (and optional phone number ID) before the user saves the integration. Returns the available scopes and resolves the WhatsApp Business Account ID, used by the dashboard onboarding flow to surface friendly inline errors.',
})
@ApiExcludeEndpoint()
@RequireAuthentication()
@RequirePermissions(PermissionsEnum.INTEGRATION_WRITE)
async validateWhatsAppToken(
@UserSession() user: UserSessionData,
@Body() body: WhatsAppValidateTokenRequestDto
): Promise<WhatsAppValidateTokenResponseDto> {
return this.whatsAppValidateTokenUsecase.execute(
WhatsAppValidateTokenCommand.create({
userId: user._id,
organizationId: user.organizationId,
accessToken: body.accessToken,
phoneNumberIdentification: body.phoneNumberIdentification,
businessAccountId: body.businessAccountId,
})
);
}
@Post('/whatsapp/embedded-signup')
@ApiResponse(WhatsAppEmbeddedSignupResponseDto, 200)
@ApiOperation({
summary: 'Complete WhatsApp Embedded Signup',
description:
'Exchanges a Meta Embedded Signup authorization code for a business integration token, saves WhatsApp credentials on the integration, registers the phone number when possible, and configures the agent webhook with Meta.',
})
@ApiExcludeEndpoint()
@RequireAuthentication()
@RequirePermissions(PermissionsEnum.INTEGRATION_WRITE)
@HttpCode(HttpStatus.OK)
async completeWhatsAppEmbeddedSignup(
@UserSession() user: UserSessionData,
@Body() body: WhatsAppEmbeddedSignupRequestDto
): Promise<WhatsAppEmbeddedSignupResponseDto> {
return this.whatsAppEmbeddedSignupUsecase.execute(
WhatsAppEmbeddedSignupCommand.create({
userId: user._id,
environmentId: user.environmentId,
organizationId: user.organizationId,
code: body.code,
wabaId: body.wabaId,
phoneNumberId: body.phoneNumberId,
integrationIdentifier: body.integrationIdentifier,
agentIdentifier: body.agentIdentifier,
})
);
}
@Post('/telegram/mobile-link')
@ApiResponse(IssueIntegrationStoreTelegramMobileLinkResponseDto, 200)
@ApiOperation({
summary: 'Issue a short-lived Telegram mobile setup link for the integration store',
description:
'Returns an opaque, single-use, short-lived setup token plus a mobile URL. The visitor pastes the BotFather token on the linked landing page and the consume endpoint creates a brand-new Telegram integration in the current environment.',
})
@ApiExcludeEndpoint()
@RequireAuthentication()
@RequirePermissions(PermissionsEnum.INTEGRATION_WRITE)
@HttpCode(HttpStatus.OK)
async createTelegramMobileLink(
@UserSession() user: UserSessionData
): Promise<IssueIntegrationStoreTelegramMobileLinkResponseDto> {
return this.issueIntegrationStoreTelegramMobileLinkUsecase.execute(
IssueIntegrationStoreTelegramMobileLinkCommand.create({
userId: user._id,
environmentId: user.environmentId,
organizationId: user.organizationId,
})
);
}
@Post('/:integrationId/slack-quick-setup')
@ExternalApiAccessible()
@ApiResponse(SlackQuickSetupResponseDto, 201)
@ApiOperation({
summary: 'Quick-setup a Slack integration',
description: `Creates a Slack app from a manifest using the provided App Configuration Token and saves the resulting credentials (client ID, client secret, signing secret) directly on the integration. The configuration token is used ephemerally and is never stored.`,
})
@ApiExcludeEndpoint()
@KeylessAccessible()
@RequireAuthentication()
@RequirePermissions(PermissionsEnum.INTEGRATION_WRITE)
async slackQuickSetup(
@UserSession() user: UserSessionData,
@Param('integrationId') integrationId: string,
@Body() body: SlackQuickSetupRequestDto
): Promise<SlackQuickSetupResponseDto> {
return this.slackQuickSetupUsecase.execute(
SlackQuickSetupCommand.create({
environmentId: user.environmentId,
organizationId: user.organizationId,
userId: user._id,
integrationId,
agentId: body.agentId,
configToken: body.configToken,
subscriberId: body.subscriberId,
connectionIdentifier: body.connectionIdentifier,
})
);
}
private assertEnvironmentScopedForApiKey(user: UserSessionData, requestedEnvironmentId?: string): void {
const isEnvironmentScopedScheme = isEnvironmentScopedAuthScheme(user.scheme);
if (!isEnvironmentScopedScheme) {
return;
}
if (requestedEnvironmentId && requestedEnvironmentId !== user.environmentId) {
throw new ForbiddenException(
'This authentication scheme is scoped to a single environment and cannot target a different `_environmentId`. ' +
'Use credentials from the target environment, or authenticate with a session token.'
);
}
}
private async canUserAccessCredentials(user: UserSessionData): Promise<boolean> {
/*
* API-key and keyless auth must never receive decrypted provider credentials, regardless of RBAC state.
* API keys grant ALL_PERMISSIONS in `community.auth.service.ts`, which would otherwise
* allow the RBAC path below to succeed and leak every stored provider secret to any
* caller holding an environment API key.
*/
if (user.scheme === ApiAuthSchemeEnum.API_KEY || user.scheme === ApiAuthSchemeEnum.KEYLESS) {
return false;
}
const organization = await this.organizationRepository.findOne({
_id: user.organizationId,
});
const [isRbacFlagEnabled, isRbacFeatureEnabled] = await Promise.all([
this.featureFlagsService.getFlag({
organization: { _id: user.organizationId },
user: { _id: user._id },
key: FeatureFlagsKeysEnum.IS_RBAC_ENABLED,
defaultValue: false,
}),
getFeatureForTierAsBoolean(
FeatureNameEnum.ACCOUNT_ROLE_BASED_ACCESS_CONTROL_BOOLEAN,
organization?.apiServiceLevel || ApiServiceLevelEnum.FREE
),
]);
const isRbacEnabled = isRbacFlagEnabled && isRbacFeatureEnabled;
if (!isRbacEnabled) {
return true;
}
return user.permissions.includes(PermissionsEnum.INTEGRATION_WRITE);
}
}