Skip to content

The open alternative to Salesforce, designed for AI.

Email campaigns 3/4: record delivery outcomes from webhooks (#25124)

neo773853c6f827c68
diff --git a/packages/twenty-server/.env.example b/packages/twenty-server/.env.example
index b697319c1bb..fa03facee9d 100644
--- a/packages/twenty-server/.env.example
+++ b/packages/twenty-server/.env.example
@@ -123,3 +123,24 @@ FRONTEND_URL=http://localhost:3001
# AI_MODELS_DEFAULT_SMART=openai/gpt-5.2,anthropic/claude-sonnet-4-6
# AI_MODELS_DEFAULT_RECOMMENDED=openai/gpt-5.2,openai/gpt-4.1,anthropic/claude-sonnet-4-6
# AI_MODELS_DEFAULT_DISABLED=
+
+# ———————— Emailing domain (marketing campaigns) ————————
+# LOG fakes registration, verification and sends locally and never contacts a provider.
+# The driver is read from the environment only; setting it in the admin panel has no effect,
+# because the SES config below is validated against the environment at boot.
+# EMAILING_DOMAIN_DRIVER=LOG
+#
+# Required when EMAILING_DOMAIN_DRIVER=AWS_SES:
+# AWS_SES_REGION=
+# AWS_SES_ACCOUNT_ID=
+# AWS_SES_ACCESS_KEY_ID=
+# AWS_SES_SECRET_ACCESS_KEY=
+# Comma-separated SNS topic ARNs allowed to post outbound delivery events:
+# SES_SNS_TOPIC_ARN_ALLOWLIST=
+# Topic that receives DELIVERY, BOUNCE, COMPLAINT, REJECT and RENDERING_FAILURE events.
+# Without it none of them are published and campaign delivery stats stay empty. Bounces
+# and complaints also arrive via EventBridge, so those two are delivered twice:
+# SES_OUTBOUND_SNS_TOPIC_ARN=
+#
+# Required when EMAILING_DOMAIN_DRIVER=RESEND:
+# RESEND_API_KEY=
diff --git a/packages/twenty-server/src/database/commands/cron-register-all.command.ts b/packages/twenty-server/src/database/commands/cron-register-all.command.ts
index 2713b372557..c50c34e6b78 100644
--- a/packages/twenty-server/src/database/commands/cron-register-all.command.ts
+++ b/packages/twenty-server/src/database/commands/cron-register-all.command.ts
@@ -7,6 +7,7 @@ import { MarketplaceCatalogSyncCronCommand } from 'src/engine/core-modules/appli
import { StaleRegistrationCleanupCronCommand } from 'src/engine/core-modules/application/application-oauth/stale-registration-cleanup/commands/stale-registration-cleanup.cron.command';
import { ApplicationVersionCheckCronCommand } from 'src/engine/core-modules/application/application-upgrade/crons/commands/application-version-check.cron.command';
import { BillingReminderCronCommand } from 'src/engine/core-modules/billing/reminders/crons/commands/billing-reminder.cron.command';
+import { CheckEmailingDomainVerificationCronCommand } from 'src/engine/core-modules/emailing-domain/crons/commands/check-emailing-domain-verification.cron.command';
import { EnterpriseKeyValidationCronCommand } from 'src/engine/core-modules/enterprise/cron/command/enterprise-key-validation.cron.command';
import { EventLogCleanupCronCommand } from 'src/engine/core-modules/event-logs/cleanup/commands/event-log-cleanup.cron.command';
import { PendingFileCleanupCronCommand } from 'src/engine/core-modules/file/file-upload/crons/commands/pending-file-cleanup.cron.command';
@@ -65,6 +66,7 @@ export class CronRegisterAllCommand extends CommandRunner {
private readonly checkCustomDomainValidRecordsCronCommand: CheckCustomDomainValidRecordsCronCommand,
private readonly checkPublicDomainsValidRecordsCronCommand: CheckPublicDomainsValidRecordsCronCommand,
+ private readonly checkEmailingDomainVerificationCronCommand: CheckEmailingDomainVerificationCronCommand,
private readonly cronTriggerCronCommand: CronTriggerCronCommand,
private readonly cleanSuspendedWorkspacesCronCommand: CleanSuspendedWorkspacesCronCommand,
private readonly cleanOnboardingWorkspacesCronCommand: CleanOnboardingWorkspacesCronCommand,
@@ -145,6 +147,10 @@ export class CronRegisterAllCommand extends CommandRunner {
name: 'CheckPublicDomainsValidRecords',
command: this.checkPublicDomainsValidRecordsCronCommand,
},
+ {
+ name: 'CheckEmailingDomainVerification',
+ command: this.checkEmailingDomainVerificationCronCommand,
+ },
{
name: 'WorkflowCronTrigger',
command: this.workflowCronTriggerCronCommand,
diff --git a/packages/twenty-server/src/database/commands/database-command.module.ts b/packages/twenty-server/src/database/commands/database-command.module.ts
index 1507df75556..9e91815d71b 100644
--- a/packages/twenty-server/src/database/commands/database-command.module.ts
+++ b/packages/twenty-server/src/database/commands/database-command.module.ts
@@ -36,6 +36,7 @@ import { UserSessionModule } from 'src/engine/core-modules/user-session/user-ses
import { UpgradeStatusCommand } from 'src/engine/core-modules/upgrade/commands/upgrade-status.command';
import { UpgradeModule } from 'src/engine/core-modules/upgrade/upgrade.module';
import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
+import { EmailingDomainModule } from 'src/engine/core-modules/emailing-domain/emailing-domain.module';
import { WorkspaceModule } from 'src/engine/core-modules/workspace/workspace.module';
import { FieldMetadataModule } from 'src/engine/metadata-modules/field-metadata/field-metadata.module';
import { ObjectMetadataModule } from 'src/engine/metadata-modules/object-metadata/object-metadata.module';
@@ -101,6 +102,7 @@ import { WorkflowCoreConsistencyModule } from 'src/modules/workflow/workflow-cor
UpgradeModule,
SecretEncryptionRotationModule,
UserSessionModule,
+ EmailingDomainModule,
],
providers: [
DataSeedWorkspaceCommand,
diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/constants/campaign-provider-outcome.constant.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/constants/campaign-provider-outcome.constant.ts
new file mode 100644
index 00000000000..bfc57d82821
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/constants/campaign-provider-outcome.constant.ts
@@ -0,0 +1,8 @@
+export const CAMPAIGN_PROVIDER_OUTCOME = {
+ DELIVERED: 'DELIVERED',
+ SOFT_BOUNCED: 'SOFT_BOUNCED',
+ BOUNCED: 'BOUNCED',
+ COMPLAINED: 'COMPLAINED',
+ REJECTED: 'REJECTED',
+ RENDERING_FAILED: 'RENDERING_FAILED',
+} as const;
diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/constants/campaign-send-retry-backoff.constant.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/constants/campaign-send-retry-backoff.constant.ts
index 55a8624b718..e79ce0e73d0 100644
--- a/packages/twenty-server/src/engine/core-modules/emailing-domain/constants/campaign-send-retry-backoff.constant.ts
+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/constants/campaign-send-retry-backoff.constant.ts
@@ -2,6 +2,6 @@ import { type QueueJobBackoffOptions } from 'src/engine/core-modules/message-que
export const CAMPAIGN_SEND_RETRY_BACKOFF = {
strategy: 'exponential',
- initialDelayMilliseconds: 30_000,
+ initialDelayMilliseconds: 5_000,
jitter: 0.5,
} as const satisfies QueueJobBackoffOptions;
diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/constants/campaign-send-retry-limit.constant.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/constants/campaign-send-retry-limit.constant.ts
new file mode 100644
index 00000000000..81c10aee3e8
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/constants/campaign-send-retry-limit.constant.ts
@@ -0,0 +1 @@
+export const CAMPAIGN_SEND_RETRY_LIMIT = 3;
diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/constants/check-emailing-domain-verification-cron-pattern.constant.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/constants/check-emailing-domain-verification-cron-pattern.constant.ts
new file mode 100644
index 00000000000..fd51e51a746
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/constants/check-emailing-domain-verification-cron-pattern.constant.ts
@@ -0,0 +1 @@
+export const CHECK_EMAILING_DOMAIN_VERIFICATION_CRON_PATTERN = '0 * * * *';
diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/constants/non-terminal-emailing-domain-statuses.constant.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/constants/non-terminal-emailing-domain-statuses.constant.ts
new file mode 100644
index 00000000000..6fe17d63d18
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/constants/non-terminal-emailing-domain-statuses.constant.ts
@@ -0,0 +1,6 @@
+import { EmailingDomainStatus } from 'src/engine/core-modules/emailing-domain/drivers/types/emailing-domain-status.type';
+
+export const NON_TERMINAL_EMAILING_DOMAIN_STATUSES = [
+ EmailingDomainStatus.PENDING,
+ EmailingDomainStatus.TEMPORARY_FAILURE,
+];
diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/crons/commands/check-emailing-domain-verification.cron.command.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/crons/commands/check-emailing-domain-verification.cron.command.ts
new file mode 100644
index 00000000000..c947a91c1a7
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/crons/commands/check-emailing-domain-verification.cron.command.ts
@@ -0,0 +1,31 @@
+import { CHECK_EMAILING_DOMAIN_VERIFICATION_CRON_PATTERN } from 'src/engine/core-modules/emailing-domain/constants/check-emailing-domain-verification-cron-pattern.constant';
+import { Command, CommandRunner } from 'nest-commander';
+
+import { CheckEmailingDomainVerificationCronJob } from 'src/engine/core-modules/emailing-domain/crons/jobs/check-emailing-domain-verification.cron.job';
+import { InjectMessageQueue } from 'src/engine/core-modules/message-queue/decorators/message-queue.decorator';
+import { MessageQueue } from 'src/engine/core-modules/message-queue/message-queue.constants';
+import { MessageQueueService } from 'src/engine/core-modules/message-queue/services/message-queue.service';
+
+@Command({
+ name: 'cron:emailing-domain:check-verification',
+ description:
+ 'Starts a cron job to refresh pending emailing domain verifications hourly',
+})
+export class CheckEmailingDomainVerificationCronCommand extends CommandRunner {
+ constructor(
+ @InjectMessageQueue(MessageQueue.cronQueue)
+ private readonly messageQueueService: MessageQueueService,
+ ) {
+ super();
+ }
+
+ async run(): Promise<void> {
+ await this.messageQueueService.addCron<undefined>({
+ jobName: CheckEmailingDomainVerificationCronJob.name,
+ data: undefined,
+ options: {
+ repeat: { pattern: CHECK_EMAILING_DOMAIN_VERIFICATION_CRON_PATTERN },
+ },
+ });
+ }
+}
diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/crons/jobs/check-emailing-domain-verification.cron.job.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/crons/jobs/check-emailing-domain-verification.cron.job.ts
new file mode 100644
index 00000000000..aa6650a0d90
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/crons/jobs/check-emailing-domain-verification.cron.job.ts
@@ -0,0 +1,104 @@
+import { CHECK_EMAILING_DOMAIN_VERIFICATION_CRON_PATTERN } from 'src/engine/core-modules/emailing-domain/constants/check-emailing-domain-verification-cron-pattern.constant';
+import { Logger } from '@nestjs/common';
+import { InjectRepository } from '@nestjs/typeorm';
+
+import { In, Repository } from 'typeorm';
+
+import { SentryCronMonitor } from 'src/engine/core-modules/cron/sentry-cron-monitor.decorator';
+import { NON_TERMINAL_EMAILING_DOMAIN_STATUSES } from 'src/engine/core-modules/emailing-domain/constants/non-terminal-emailing-domain-statuses.constant';
+import { EmailingDomainDriverFactory } from 'src/engine/core-modules/emailing-domain/drivers/emailing-domain-driver.factory';
+import { EmailingDomainStatus } from 'src/engine/core-modules/emailing-domain/drivers/types/emailing-domain-status.type';
+import { UnsubscribeHostnameStatus } from 'src/engine/core-modules/emailing-domain/drivers/types/unsubscribe-hostname-status.type';
+import { EmailingDomainEntity } from 'src/engine/core-modules/emailing-domain/emailing-domain.entity';
+import { EmailingDomainService } from 'src/engine/core-modules/emailing-domain/services/emailing-domain.service';
+import { UnsubscribeHostnameService } from 'src/engine/core-modules/emailing-domain/services/unsubscribe-hostname.service';
+import { Process } from 'src/engine/core-modules/message-queue/decorators/process.decorator';
+import { Processor } from 'src/engine/core-modules/message-queue/decorators/processor.decorator';
+import { MessageQueue } from 'src/engine/core-modules/message-queue/message-queue.constants';
+
+@Processor(MessageQueue.cronQueue)
+export class CheckEmailingDomainVerificationCronJob {
+ private readonly logger = new Logger(
+ CheckEmailingDomainVerificationCronJob.name,
+ );
+
+ constructor(
+ @InjectRepository(EmailingDomainEntity)
+ private readonly emailingDomainRepository: Repository<EmailingDomainEntity>,
+ private readonly emailingDomainService: EmailingDomainService,
+ private readonly unsubscribeHostnameService: UnsubscribeHostnameService,
+ private readonly emailingDomainDriverFactory: EmailingDomainDriverFactory,
+ ) {}
+
+ @Process(CheckEmailingDomainVerificationCronJob.name)
+ @SentryCronMonitor(
+ CheckEmailingDomainVerificationCronJob.name,
+ CHECK_EMAILING_DOMAIN_VERIFICATION_CRON_PATTERN,
+ )
+ async handle(): Promise<void> {
+ await this.refreshUnverifiedDomains();
+ await this.refreshPendingUnsubscribeHostnames();
+ await this.reprovisionVerifiedWorkspaces();
+ }
+
+ private async reprovisionVerifiedWorkspaces(): Promise<void> {
+ const verifiedDomains = await this.emailingDomainRepository.find({
+ where: { status: EmailingDomainStatus.VERIFIED },
+ select: ['workspaceId'],
+ });
+
+ const workspaceIds = new Set(
+ verifiedDomains.map((emailingDomain) => emailingDomain.workspaceId),
+ );
+
+ for (const workspaceId of workspaceIds) {
+ await this.emailingDomainDriverFactory
+ .getCurrentDriver()
+ .provisionWorkspace(workspaceId)
+ .catch((error) => {
+ this.logger.error(
+ `[${CheckEmailingDomainVerificationCronJob.name}] Cannot reprovision emailing resources for workspace ${workspaceId}: ${error}`,
+ );
+ });
+ }
+ }
+
+ private async refreshUnverifiedDomains(): Promise<void> {
+ const unverifiedDomains = await this.emailingDomainRepository.find({
+ where: { status: In(NON_TERMINAL_EMAILING_DOMAIN_STATUSES) },
+ select: ['id', 'workspaceId', 'domain'],
+ });
+
+ for (const emailingDomain of unverifiedDomains) {
+ await this.emailingDomainService
+ .verifyEmailingDomain({
+ workspaceId: emailingDomain.workspaceId,
+ emailingDomainId: emailingDomain.id,
+ })
+ .catch((error) => {
+ this.logger.error(
+ `[${CheckEmailingDomainVerificationCronJob.name}] Cannot verify emailing domain ${emailingDomain.domain} of workspace ${emailingDomain.workspaceId}: ${error}`,
+ );
+ });
+ }
+ }
+
+ private async refreshPendingUnsubscribeHostnames(): Promise<void> {
+ const verifiedDomainsWithPendingHostname =
+ await this.emailingDomainRepository.find({
+ where: {
+ status: EmailingDomainStatus.VERIFIED,
+ unsubscribeHostnameStatus: UnsubscribeHostnameStatus.PENDING,
+ },
+ select: ['id', 'workspaceId'],
+ });
+
+ for (const emailingDomain of verifiedDomainsWithPendingHostname) {
+ await this.unsubscribeHostnameService.sync(
+ emailingDomain.workspaceId,
+ emailingDomain.id,
+ { provision: false },
+ );
+ }
+ }
+}
diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/aws-ses/services/aws-ses-account.service.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/aws-ses/services/aws-ses-account.service.ts
new file mode 100644
index 00000000000..8b83f171bde
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/aws-ses/services/aws-ses-account.service.ts
@@ -0,0 +1,24 @@
+import { Injectable } from '@nestjs/common';
+
+import { GetAccountCommand } from '@aws-sdk/client-sesv2';
+
+import { AwsSesClientProvider } from 'src/engine/core-modules/emailing-domain/drivers/aws-ses/providers/aws-ses-client.provider';
+
+type AwsSesAccountState = {
+ isProductionAccessEnabled: boolean;
+};
+
+@Injectable()
+export class AwsSesAccountService {
+ constructor(private readonly awsSesClientProvider: AwsSesClientProvider) {}
+
+ async getAccountState(): Promise<AwsSesAccountState> {
+ const account = await this.awsSesClientProvider
+ .getSESClient()
+ .send(new GetAccountCommand({}));
+
+ return {
+ isProductionAccessEnabled: account.ProductionAccessEnabled === true,
+ };
+ }
+}
diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/aws-ses/services/aws-ses-driver.service.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/aws-ses/services/aws-ses-driver.service.ts
index 9d2487864fc..9188a6e23cb 100644
--- a/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/aws-ses/services/aws-ses-driver.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/aws-ses/services/aws-ses-driver.service.ts
@@ -26,12 +26,18 @@ import { getUnsubscribeBaseUrl } from 'src/engine/core-modules/emailing-domain/d
import { type UnsubscribeContentService } from 'src/engine/core-modules/emailing-domain/services/unsubscribe-content.service';
import { AWS_SES_RESOURCE_NAME_PREFIX } from 'src/engine/core-modules/emailing-domain/drivers/aws-ses/constants/aws-ses-resource-name-prefix.constant';
+import { buildAwsSesVerificationRecords } from 'src/engine/core-modules/emailing-domain/drivers/aws-ses/utils/build-aws-ses-verification-records.util';
import { type AwsSesClientProvider } from 'src/engine/core-modules/emailing-domain/drivers/aws-ses/providers/aws-ses-client.provider';
+import { type AwsSesAccountService } from 'src/engine/core-modules/emailing-domain/drivers/aws-ses/services/aws-ses-account.service';
import { type AwsSesHandleErrorService } from 'src/engine/core-modules/emailing-domain/drivers/aws-ses/services/aws-ses-handle-error.service';
import { AwsSesRegisterDomainService } from 'src/engine/core-modules/emailing-domain/drivers/aws-ses/services/aws-ses-register-domain.service';
import { type AwsSesSendEmailService } from 'src/engine/core-modules/emailing-domain/drivers/aws-ses/services/aws-ses-send-email.service';
+import {
+ EmailingDomainDriverException,
+ EmailingDomainDriverExceptionCode,
+} from 'src/engine/core-modules/emailing-domain/drivers/exceptions/emailing-domain-driver.exception';
import { EmailingDomainStatus } from 'src/engine/core-modules/emailing-domain/drivers/types/emailing-domain-status.type';
-import { type VerificationRecordDTO } from 'src/engine/core-modules/emailing-domain/dtos/verification-record.dto';
+import { type VerificationRecord } from 'src/engine/core-modules/emailing-domain/drivers/types/verifications-record';
export class AwsSesDriver implements EmailingDomainDriverInterface {
private readonly logger = new Logger(AwsSesDriver.name);
@@ -39,6 +45,7 @@ export class AwsSesDriver implements EmailingDomainDriverInterface {
constructor(
private readonly config: AwsSesDriverConfig,
private readonly awsSesClientProvider: AwsSesClientProvider,
+ private readonly awsSesAccountService: AwsSesAccountService,
private readonly awsSesHandleErrorService: AwsSesHandleErrorService,
private readonly awsSesRegisterDomainService: AwsSesRegisterDomainService,
private readonly awsSesSendEmailService: AwsSesSendEmailService,
@@ -60,11 +67,19 @@ export class AwsSesDriver implements EmailingDomainDriverInterface {
await this.enableDkimSigning(input.domain);
}
+ if (status === EmailingDomainStatus.VERIFIED) {
+ await this.assertProductionAccessOrThrow();
+ }
+
return {
status,
verificationRecords: this.withRecordStatus(verificationRecords, status),
};
} catch (error) {
+ if (error instanceof EmailingDomainDriverException) {
+ throw error;
+ }
+
this.logger.error(`Failed to verify domain ${input.domain}: ${error}`);
this.awsSesHandleErrorService.handleAwsSesError(error, 'verifyDomain');
}
@@ -85,16 +100,25 @@ export class AwsSesDriver implements EmailingDomainDriverInterface {
const identityResponse = await sesClient.send(getIdentityCommand);
const status = this.determineVerificationStatus(identityResponse);
- const verificationRecords = this.buildVerificationRecords(
- input.domain,
- identityResponse.DkimAttributes?.Tokens || [],
- );
+ const verificationRecords = buildAwsSesVerificationRecords({
+ domain: input.domain,
+ dkimTokens: identityResponse.DkimAttributes?.Tokens ?? [],
+ region: this.config.region,
+ });
+
+ if (status === EmailingDomainStatus.VERIFIED) {
+ await this.assertProductionAccessOrThrow();
+ }
return {
status,
verificationRecords: this.withRecordStatus(verificationRecords, status),
};
} catch (error) {
+ if (error instanceof EmailingDomainDriverException) {
+ throw error;
+ }
+
if (error instanceof NotFoundException) {
return {
status: EmailingDomainStatus.FAILED,
@@ -229,7 +253,7 @@ export class AwsSesDriver implements EmailingDomainDriverInterface {
): Promise<{
isVerified: boolean;
status: EmailingDomainStatus;
- verificationRecords: VerificationRecordDTO[];
+ verificationRecords: VerificationRecord[];
}> {
const sesClient = this.awsSesClientProvider.getSESClient();
@@ -241,10 +265,11 @@ export class AwsSesDriver implements EmailingDomainDriverInterface {
const isVerified = existingIdentity.VerifiedForSendingStatus === true;
const status = this.determineVerificationStatus(existingIdentity);
- const verificationRecords = this.buildVerificationRecords(
+ const verificationRecords = buildAwsSesVerificationRecords({
domain,
- existingIdentity.DkimAttributes?.Tokens || [],
- );
+ dkimTokens: existingIdentity.DkimAttributes?.Tokens ?? [],
+ region: this.config.region,
+ });
await this.associateResourceWithTenant(domain, tenantName);
@@ -263,7 +288,7 @@ export class AwsSesDriver implements EmailingDomainDriverInterface {
): Promise<{
isVerified: boolean;
status: EmailingDomainStatus;
- verificationRecords: VerificationRecordDTO[];
+ verificationRecords: VerificationRecord[];
}> {
const sesClient = this.awsSesClientProvider.getSESClient();
@@ -273,14 +298,15 @@ export class AwsSesDriver implements EmailingDomainDriverInterface {
});
const createResponse = await sesClient.send(createCommand);
- const dkimTokens = createResponse.DkimAttributes?.Tokens || [];
+ const dkimTokens = createResponse.DkimAttributes?.Tokens ?? [];
await this.associateResourceWithTenant(domain, tenantName);
- const verificationRecords = this.buildVerificationRecords(
+ const verificationRecords = buildAwsSesVerificationRecords({
domain,
dkimTokens,
- );
+ region: this.config.region,
+ });
return {
isVerified: false,
@@ -315,6 +341,20 @@ export class AwsSesDriver implements EmailingDomainDriverInterface {
}
}
+ private async assertProductionAccessOrThrow(): Promise<void> {
+ const { isProductionAccessEnabled } =
+ await this.awsSesAccountService.getAccountState();
+
+ if (isProductionAccessEnabled) {
+ return;
+ }
+
+ throw new EmailingDomainDriverException(
+ 'AWS SES account is in the sandbox and cannot send to unverified recipients',
+ EmailingDomainDriverExceptionCode.SANDBOX_ACCOUNT,
+ );
+ }
+
private async enableDkimSigning(domain: string): Promise<void> {
const sesClient = this.awsSesClientProvider.getSESClient();
@@ -327,17 +367,6 @@ export class AwsSesDriver implements EmailingDomainDriverInterface {
this.logger.log(`Enabled DKIM signing for domain: ${domain}`);
}
- private buildVerificationRecords(
- domain: string,
- dkimTokens: string[],
- ): VerificationRecordDTO[] {
- return dkimTokens.map((token) => ({
- type: 'CNAME' as const,
- key: `${token}._domainkey.${domain}`,
- value: `${token}.dkim.amazonses.com`,
- }));
- }
-
private determineVerificationStatus(identityResponse: {
VerifiedForSendingStatus?: boolean;
DkimAttributes?: {
@@ -362,9 +391,9 @@ export class AwsSesDriver implements EmailingDomainDriverInterface {
}
private withRecordStatus(
- records: VerificationRecordDTO[],
+ records: VerificationRecord[],
status: EmailingDomainStatus,
- ): VerificationRecordDTO[] {
+ ): VerificationRecord[] {
const recordStatus =
status === EmailingDomainStatus.VERIFIED
? 'success'
diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/aws-ses/services/aws-ses-handle-error.service.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/aws-ses/services/aws-ses-handle-error.service.ts
index 53fe1b0feeb..89516f587d6 100644
--- a/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/aws-ses/services/aws-ses-handle-error.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/aws-ses/services/aws-ses-handle-error.service.ts
@@ -1,6 +1,7 @@
import { Injectable } from '@nestjs/common';
import { type AwsSesError } from 'src/engine/core-modules/emailing-domain/drivers/aws-ses/types/aws-ses-error.type';
+import { getAwsSesDriverExceptionCode } from 'src/engine/core-modules/emailing-domain/drivers/aws-ses/utils/get-aws-ses-driver-exception-code.util';
import {
EmailingDomainDriverException,
EmailingDomainDriverExceptionCode,
@@ -11,88 +12,30 @@ export class AwsSesHandleErrorService {
public handleAwsSesError(error: AwsSesError, context?: string): never {
const name = error?.name ?? 'UnknownError';
const message = error?.message ?? 'No message';
- const httpStatus = error?.$metadata?.httpStatusCode;
const suffix = context ? ` (${context})` : '';
-
- if (this.isTemporary(name, httpStatus)) {
- throw new EmailingDomainDriverException(
- `AWS SES temporary error${suffix}: ${message}`,
- EmailingDomainDriverExceptionCode.TEMPORARY_ERROR,
- );
- }
-
- if (this.isInsufficientPermissions(name, httpStatus)) {
- throw new EmailingDomainDriverException(
- `AWS SES insufficient permissions${suffix}: ${message}`,
- EmailingDomainDriverExceptionCode.INSUFFICIENT_PERMISSIONS,
- );
- }
-
- if (this.isConfigurationError(name, httpStatus)) {
- throw new EmailingDomainDriverException(
- `AWS SES configuration error${suffix}: ${message}`,
- EmailingDomainDriverExceptionCode.CONFIGURATION_ERROR,
- );
- }
-
- throw new EmailingDomainDriverException(
- `AWS SES error${suffix}: ${name} - ${message}`,
- EmailingDomainDriverExceptionCode.UNKNOWN,
- );
- }
-
- private isTemporary(name: string, httpStatus?: number): boolean {
- if (httpStatus && httpStatus >= 500) {
- return true;
- }
-
- if (
- name === 'ThrottlingException' ||
- name === 'ServiceUnavailable' ||
- name === 'InternalFailure' ||
- name === 'RequestTimeout' ||
- name === 'TooManyRequestsException'
- ) {
- return true;
- }
-
- return false;
- }
-
- private isInsufficientPermissions(
- name: string,
- httpStatus?: number,
- ): boolean {
- if (httpStatus === 403) {
- return true;
- }
-
- if (
- name === 'AccessDeniedException' ||
- name === 'AccountSuspendedException'
- ) {
- return true;
- }
-
- return false;
- }
-
- private isConfigurationError(name: string, httpStatus?: number): boolean {
- if (httpStatus === 400) {
- return true;
+ const code = getAwsSesDriverExceptionCode(error);
+
+ switch (code) {
+ case EmailingDomainDriverExceptionCode.TEMPORARY_ERROR:
+ throw new EmailingDomainDriverException(
+ `AWS SES temporary error${suffix}: ${message}`,
+ code,
+ );
+ case EmailingDomainDriverExceptionCode.INSUFFICIENT_PERMISSIONS:
+ throw new EmailingDomainDriverException(
+ `AWS SES insufficient permissions${suffix}: ${message}`,
+ code,
+ );
+ case EmailingDomainDriverExceptionCode.CONFIGURATION_ERROR:
+ throw new EmailingDomainDriverException(
+ `AWS SES configuration error${suffix}: ${message}`,
+ code,
+ );
+ default:
+ throw new EmailingDomainDriverException(
+ `AWS SES error${suffix}: ${name} - ${message}`,
+ EmailingDomainDriverExceptionCode.UNKNOWN,
+ );
}
-
- if (
- name === 'InvalidParameterValue' ||
- name === 'InvalidParameterCombination' ||
- name === 'MissingParameter' ||
- name === 'MessageRejected' ||
- name === 'MailFromDomainNotVerifiedException' ||
- name === 'FromEmailAddressNotVerifiedException'
- ) {
- return true;
- }
-
- return false;
}
}
diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/aws-ses/services/aws-ses-outbound-event-destination.service.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/aws-ses/services/aws-ses-outbound-event-destination.service.ts
new file mode 100644
index 00000000000..bbc16a774d6
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/aws-ses/services/aws-ses-outbound-event-destination.service.ts
@@ -0,0 +1,76 @@
+import { Injectable, Logger } from '@nestjs/common';
+
+import {
+ AlreadyExistsException,
+ CreateConfigurationSetEventDestinationCommand,
+ type EventDestinationDefinition,
+ UpdateConfigurationSetEventDestinationCommand,
+} from '@aws-sdk/client-sesv2';
+import { isNonEmptyString } from '@sniptt/guards';
+
+import { AwsSesClientProvider } from 'src/engine/core-modules/emailing-domain/drivers/aws-ses/providers/aws-ses-client.provider';
+import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';
+
+const EVENT_DESTINATION_NAME = 'twenty-outbound-sns';
+
+@Injectable()
+export class AwsSesOutboundEventDestinationService {
+ private readonly logger = new Logger(
+ AwsSesOutboundEventDestinationService.name,
+ );
+
+ constructor(
+ private readonly awsSesClientProvider: AwsSesClientProvider,
+ private readonly twentyConfigService: TwentyConfigService,
+ ) {}
+
+ async upsertEventDestinationOrThrow(
+ configurationSetName: string,
+ ): Promise<void> {
+ const topicArn = this.twentyConfigService.get('SES_OUTBOUND_SNS_TOPIC_ARN');
+
+ if (!isNonEmptyString(topicArn)) {
+ this.logger.warn(
+ 'SES_OUTBOUND_SNS_TOPIC_ARN is not configured, so delivery, reject and rendering-failure events will not reach the outbound webhook. Bounces and complaints still arrive through the EventBridge subscription.',
+ );
+
+ return;
+ }
+
+ const eventDestination: EventDestinationDefinition = {
+ Enabled: true,
+ MatchingEventTypes: [
+ 'DELIVERY',
+ 'BOUNCE',
+ 'COMPLAINT',
+ 'REJECT',
+ 'RENDERING_FAILURE',
+ ],
+ SnsDestination: { TopicArn: topicArn },
+ };
+
+ const sesClient = this.awsSesClientProvider.getSESClient();
+
+ await sesClient
+ .send(
+ new CreateConfigurationSetEventDestinationCommand({
+ ConfigurationSetName: configurationSetName,
+ EventDestinationName: EVENT_DESTINATION_NAME,
+ EventDestination: eventDestination,
+ }),
+ )
+ .catch(async (error) => {
+ if (!(error instanceof AlreadyExistsException)) {
+ throw error;
+ }
+
+ await sesClient.send(
+ new UpdateConfigurationSetEventDestinationCommand({
+ ConfigurationSetName: configurationSetName,
+ EventDestinationName: EVENT_DESTINATION_NAME,
+ EventDestination: eventDestination,
+ }),
+ );
+ });
+ }
+}
diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/aws-ses/services/aws-ses-register-domain.service.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/aws-ses/services/aws-ses-register-domain.service.ts
index 09c830f4708..373325dbd60 100644
--- a/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/aws-ses/services/aws-ses-register-domain.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/aws-ses/services/aws-ses-register-domain.service.ts
@@ -13,6 +13,7 @@ import { AWS_SES_EVENT_BUS_NAME } from 'src/engine/core-modules/emailing-domain/
import { AWS_SES_MAIL_FROM_SUBDOMAIN } from 'src/engine/core-modules/emailing-domain/drivers/aws-ses/constants/aws-ses-mail-from-subdomain.constant';
import { AwsSesClientProvider } from 'src/engine/core-modules/emailing-domain/drivers/aws-ses/providers/aws-ses-client.provider';
import { AwsSesObservabilityService } from 'src/engine/core-modules/emailing-domain/drivers/aws-ses/services/aws-ses-observability.service';
+import { AwsSesOutboundEventDestinationService } from 'src/engine/core-modules/emailing-domain/drivers/aws-ses/services/aws-ses-outbound-event-destination.service';
type ProvisionWorkspaceInput = {
tenantName: string;
@@ -26,6 +27,7 @@ export class AwsSesRegisterDomainService {
constructor(
private readonly awsSesClientProvider: AwsSesClientProvider,
private readonly awsSesObservabilityService: AwsSesObservabilityService,
+ private readonly awsSesOutboundEventDestinationService: AwsSesOutboundEventDestinationService,
) {}
async provisionWorkspaceResources(
@@ -93,6 +95,10 @@ export class AwsSesRegisterDomainService {
}
});
+ await this.awsSesOutboundEventDestinationService.upsertEventDestinationOrThrow(
+ input.configurationSetName,
+ );
+
await this.awsSesObservabilityService.addEventDestination(
input.configurationSetName,
);
diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/aws-ses/utils/__tests__/build-aws-ses-verification-records.util.spec.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/aws-ses/utils/__tests__/build-aws-ses-verification-records.util.spec.ts
new file mode 100644
index 00000000000..e3cf39d2c3d
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/aws-ses/utils/__tests__/build-aws-ses-verification-records.util.spec.ts
@@ -0,0 +1,72 @@
+import { buildAwsSesVerificationRecords } from 'src/engine/core-modules/emailing-domain/drivers/aws-ses/utils/build-aws-ses-verification-records.util';
+
+describe('buildAwsSesVerificationRecords', () => {
+ it('should return one CNAME per DKIM token', () => {
+ const records = buildAwsSesVerificationRecords({
+ domain: 'acme.com',
+ dkimTokens: ['tokenone', 'tokentwo', 'tokenthree'],
+ region: 'eu-west-3',
+ });
+
+ expect(records.filter((record) => record.type === 'CNAME')).toEqual([
+ {
+ type: 'CNAME',
+ key: 'tokenone._domainkey.acme.com',
+ value: 'tokenone.dkim.amazonses.com',
+ },
+ {
+ type: 'CNAME',
+ key: 'tokentwo._domainkey.acme.com',
+ value: 'tokentwo.dkim.amazonses.com',
+ },
+ {
+ type: 'CNAME',
+ key: 'tokenthree._domainkey.acme.com',
+ value: 'tokenthree.dkim.amazonses.com',
+ },
+ ]);
+ });
+
+ it('should return exactly one MX record on the mail from subdomain pointing at the client region', () => {
+ const records = buildAwsSesVerificationRecords({
+ domain: 'acme.com',
+ dkimTokens: [],
+ region: 'us-east-1',
+ });
+
+ expect(records.filter((record) => record.type === 'MX')).toEqual([
+ {
+ type: 'MX',
+ key: 'bounce.acme.com',
+ value: 'feedback-smtp.us-east-1.amazonses.com',
+ priority: 10,
+ },
+ ]);
+ });
+
+ it('should return the SPF record on the mail from subdomain', () => {
+ const records = buildAwsSesVerificationRecords({
+ domain: 'acme.com',
+ dkimTokens: [],
+ region: 'us-east-1',
+ });
+
+ expect(records.filter((record) => record.type === 'TXT')).toEqual([
+ {
+ type: 'TXT',
+ key: 'bounce.acme.com',
+ value: 'v=spf1 include:amazonses.com ~all',
+ },
+ ]);
+ });
+
+ it('should still return the mail from records when SES returned no DKIM token yet', () => {
+ const records = buildAwsSesVerificationRecords({
+ domain: 'acme.com',
+ dkimTokens: [],
+ region: 'eu-west-3',
+ });
+
+ expect(records).toHaveLength(2);
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/aws-ses/utils/__tests__/get-aws-ses-driver-exception-code.util.spec.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/aws-ses/utils/__tests__/get-aws-ses-driver-exception-code.util.spec.ts
new file mode 100644
index 00000000000..93bda16dee0
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/aws-ses/utils/__tests__/get-aws-ses-driver-exception-code.util.spec.ts
@@ -0,0 +1,73 @@
+import { getAwsSesDriverExceptionCode } from 'src/engine/core-modules/emailing-domain/drivers/aws-ses/utils/get-aws-ses-driver-exception-code.util';
+import { EmailingDomainDriverExceptionCode } from 'src/engine/core-modules/emailing-domain/drivers/exceptions/emailing-domain-driver.exception';
+
+describe('getAwsSesDriverExceptionCode', () => {
+ it('should classify a send-rate breach as temporary even though SES answers it with a 4xx status', () => {
+ expect(
+ getAwsSesDriverExceptionCode({
+ name: 'TooManyRequestsException',
+ message: 'Maximum sending rate exceeded.',
+ $metadata: { httpStatusCode: 400 },
+ }),
+ ).toBe(EmailingDomainDriverExceptionCode.TEMPORARY_ERROR);
+ });
+
+ it('should classify a 24-hour quota breach as temporary', () => {
+ expect(
+ getAwsSesDriverExceptionCode({
+ name: 'LimitExceededException',
+ message: 'Daily message quota exceeded.',
+ $metadata: { httpStatusCode: 400 },
+ }),
+ ).toBe(EmailingDomainDriverExceptionCode.TEMPORARY_ERROR);
+ });
+
+ it('should classify a throttling status without a recognized name as temporary', () => {
+ expect(
+ getAwsSesDriverExceptionCode({
+ name: 'SomeUnmappedError',
+ $metadata: { httpStatusCode: 429 },
+ }),
+ ).toBe(EmailingDomainDriverExceptionCode.TEMPORARY_ERROR);
+ });
+
+ it('should classify a server error as temporary', () => {
+ expect(
+ getAwsSesDriverExceptionCode({
+ name: 'SomeUnmappedError',
+ $metadata: { httpStatusCode: 503 },
+ }),
+ ).toBe(EmailingDomainDriverExceptionCode.TEMPORARY_ERROR);
+ });
+
+ it('should classify a denied or suspended account as insufficient permissions', () => {
+ expect(
+ getAwsSesDriverExceptionCode({
+ name: 'AccountSuspendedException',
+ $metadata: { httpStatusCode: 400 },
+ }),
+ ).toBe(EmailingDomainDriverExceptionCode.INSUFFICIENT_PERMISSIONS);
+
+ expect(
+ getAwsSesDriverExceptionCode({
+ name: 'SomeUnmappedError',
+ $metadata: { httpStatusCode: 403 },
+ }),
+ ).toBe(EmailingDomainDriverExceptionCode.INSUFFICIENT_PERMISSIONS);
+ });
+
+ it('should classify a rejected message as a configuration error', () => {
+ expect(
+ getAwsSesDriverExceptionCode({
+ name: 'MessageRejected',
+ $metadata: { httpStatusCode: 400 },
+ }),
+ ).toBe(EmailingDomainDriverExceptionCode.CONFIGURATION_ERROR);
+ });
+
+ it('should classify an error carrying neither a known name nor a status as unknown', () => {
+ expect(getAwsSesDriverExceptionCode({})).toBe(
+ EmailingDomainDriverExceptionCode.UNKNOWN,
+ );
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/aws-ses/utils/build-aws-ses-verification-records.util.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/aws-ses/utils/build-aws-ses-verification-records.util.ts
new file mode 100644
index 00000000000..15cb9a0b38f
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/aws-ses/utils/build-aws-ses-verification-records.util.ts
@@ -0,0 +1,40 @@
+import { AWS_SES_MAIL_FROM_SUBDOMAIN } from 'src/engine/core-modules/emailing-domain/drivers/aws-ses/constants/aws-ses-mail-from-subdomain.constant';
+import { type VerificationRecord } from 'src/engine/core-modules/emailing-domain/drivers/types/verifications-record';
+
+type BuildAwsSesVerificationRecordsArgs = {
+ domain: string;
+ dkimTokens: string[];
+ region: string;
+};
+
+const MAIL_FROM_MX_PRIORITY = 10;
+const MAIL_FROM_SPF_VALUE = 'v=spf1 include:amazonses.com ~all';
+
+export const buildAwsSesVerificationRecords = ({
+ domain,
+ dkimTokens,
+ region,
+}: BuildAwsSesVerificationRecordsArgs): VerificationRecord[] => {
+ const mailFromDomain = `${AWS_SES_MAIL_FROM_SUBDOMAIN}.${domain}`;
+
+ const dkimRecords: VerificationRecord[] = dkimTokens.map((token) => ({
+ type: 'CNAME',
+ key: `${token}._domainkey.${domain}`,
+ value: `${token}.dkim.amazonses.com`,
+ }));
+
+ return [
+ ...dkimRecords,
+ {
+ type: 'MX',
+ key: mailFromDomain,
+ value: `feedback-smtp.${region}.amazonses.com`,
+ priority: MAIL_FROM_MX_PRIORITY,
+ },
+ {
+ type: 'TXT',
+ key: mailFromDomain,
+ value: MAIL_FROM_SPF_VALUE,
+ },
+ ];
+};
diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/aws-ses/utils/get-aws-ses-driver-exception-code.util.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/aws-ses/utils/get-aws-ses-driver-exception-code.util.ts
new file mode 100644
index 00000000000..427f4db05c4
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/aws-ses/utils/get-aws-ses-driver-exception-code.util.ts
@@ -0,0 +1,56 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { type AwsSesError } from 'src/engine/core-modules/emailing-domain/drivers/aws-ses/types/aws-ses-error.type';
+import { EmailingDomainDriverExceptionCode } from 'src/engine/core-modules/emailing-domain/drivers/exceptions/emailing-domain-driver.exception';
+
+const THROTTLING_AND_TRANSIENT_ERROR_NAMES = [
+ 'ThrottlingException',
+ 'Throttling',
+ 'TooManyRequestsException',
+ 'LimitExceededException',
+ 'ServiceUnavailable',
+ 'InternalFailure',
+ 'RequestTimeout',
+];
+
+const INSUFFICIENT_PERMISSIONS_ERROR_NAMES = [
+ 'AccessDeniedException',
+ 'AccountSuspendedException',
+];
+
+const CONFIGURATION_ERROR_NAMES = [
+ 'InvalidParameterValue',
+ 'InvalidParameterCombination',
+ 'MissingParameter',
+ 'MessageRejected',
+ 'MailFromDomainNotVerifiedException',
+ 'FromEmailAddressNotVerifiedException',
+];
+
+export const getAwsSesDriverExceptionCode = (
+ error: AwsSesError,
+): EmailingDomainDriverExceptionCode => {
+ const name = error?.name ?? 'UnknownError';
+ const httpStatus = error?.$metadata?.httpStatusCode;
+
+ if (THROTTLING_AND_TRANSIENT_ERROR_NAMES.includes(name)) {
+ return EmailingDomainDriverExceptionCode.TEMPORARY_ERROR;
+ }
+
+ if (httpStatus === 429 || (isDefined(httpStatus) && httpStatus >= 500)) {
+ return EmailingDomainDriverExceptionCode.TEMPORARY_ERROR;
+ }
+
+ if (
+ httpStatus === 403 ||
+ INSUFFICIENT_PERMISSIONS_ERROR_NAMES.includes(name)
+ ) {
+ return EmailingDomainDriverExceptionCode.INSUFFICIENT_PERMISSIONS;
+ }
+
+ if (httpStatus === 400 || CONFIGURATION_ERROR_NAMES.includes(name)) {
+ return EmailingDomainDriverExceptionCode.CONFIGURATION_ERROR;
+ }
+
+ return EmailingDomainDriverExceptionCode.UNKNOWN;
+};
diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/emailing-domain-driver.factory.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/emailing-domain-driver.factory.ts
index 1ba2e97fc00..aa036d574c9 100644
--- a/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/emailing-domain-driver.factory.ts
+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/emailing-domain-driver.factory.ts
@@ -9,6 +9,7 @@ import {
import { type EmailingDomainDriverInterface } from 'src/engine/core-modules/emailing-domain/drivers/interfaces/emailing-domain-driver.interface';
import { AwsSesClientProvider } from 'src/engine/core-modules/emailing-domain/drivers/aws-ses/providers/aws-ses-client.provider';
+import { AwsSesAccountService } from 'src/engine/core-modules/emailing-domain/drivers/aws-ses/services/aws-ses-account.service';
import { AwsSesRegisterDomainService } from 'src/engine/core-modules/emailing-domain/drivers/aws-ses/services/aws-ses-register-domain.service';
import { AwsSesDriver } from 'src/engine/core-modules/emailing-domain/drivers/aws-ses/services/aws-ses-driver.service';
import { AwsSesHandleErrorService } from 'src/engine/core-modules/emailing-domain/drivers/aws-ses/services/aws-ses-handle-error.service';
@@ -30,6 +31,7 @@ export class EmailingDomainDriverFactory extends DriverFactoryBase<EmailingDomai
twentyConfigService: TwentyConfigService,
configGroupHashService: ConfigGroupHashService,
private readonly awsSesClientProvider: AwsSesClientProvider,
+ private readonly awsSesAccountService: AwsSesAccountService,
private readonly awsSesHandleErrorService: AwsSesHandleErrorService,
private readonly awsSesRegisterDomainService: AwsSesRegisterDomainService,
private readonly awsSesSendEmailService: AwsSesSendEmailService,
@@ -101,6 +103,7 @@ export class EmailingDomainDriverFactory extends DriverFactoryBase<EmailingDomai
return new AwsSesDriver(
awsConfig,
this.awsSesClientProvider,
+ this.awsSesAccountService,
this.awsSesHandleErrorService,
this.awsSesRegisterDomainService,
this.awsSesSendEmailService,
diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/exceptions/emailing-domain-driver.exception.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/exceptions/emailing-domain-driver.exception.ts
index b00338b6351..7e0e34e34f6 100644
--- a/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/exceptions/emailing-domain-driver.exception.ts
+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/exceptions/emailing-domain-driver.exception.ts
@@ -11,6 +11,7 @@ export enum EmailingDomainDriverExceptionCode {
INSUFFICIENT_PERMISSIONS = 'INSUFFICIENT_PERMISSIONS',
CONFIGURATION_ERROR = 'CONFIGURATION_ERROR',
SENDING_SUSPENDED = 'SENDING_SUSPENDED',
+ SANDBOX_ACCOUNT = 'SANDBOX_ACCOUNT',
ALL_RECIPIENTS_SUPPRESSED = 'ALL_RECIPIENTS_SUPPRESSED',
UNSUBSCRIBE_NOT_READY = 'UNSUBSCRIBE_NOT_READY',
UNKNOWN = 'UNKNOWN',
@@ -28,6 +29,8 @@ const getEmailingDomainDriverExceptionUserFriendlyMessage = (
return msg`Email domain configuration error.`;
case EmailingDomainDriverExceptionCode.SENDING_SUSPENDED:
return msg`Sending is currently suspended for this email domain.`;
+ case EmailingDomainDriverExceptionCode.SANDBOX_ACCOUNT:
+ return msg`Your AWS SES account is still in the sandbox, so this domain cannot send to unverified recipients. Request production access from AWS, then verify the domain again.`;
case EmailingDomainDriverExceptionCode.ALL_RECIPIENTS_SUPPRESSED:
return msg`All recipients are suppressed for this email domain.`;
case EmailingDomainDriverExceptionCode.UNSUBSCRIBE_NOT_READY:
diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/log/services/log-emailing-domain-driver.service.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/log/services/log-emailing-domain-driver.service.ts
index bd264a6c333..e1c2e17c43f 100644
--- a/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/log/services/log-emailing-domain-driver.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/log/services/log-emailing-domain-driver.service.ts
@@ -5,6 +5,10 @@ import { isNonEmptyString } from '@sniptt/guards';
import { Repository } from 'typeorm';
import { v4 } from 'uuid';
+import {
+ EmailingDomainDriverException,
+ EmailingDomainDriverExceptionCode,
+} from 'src/engine/core-modules/emailing-domain/drivers/exceptions/emailing-domain-driver.exception';
import { UNSUBSCRIBE_HOSTNAME_PREFIX } from 'src/engine/core-modules/emailing-domain/constants/unsubscribe-hostname-prefix.constant';
import {
type EmailingDomainDriverInterface,
@@ -18,6 +22,8 @@ import { UnsubscribeContentService } from 'src/engine/core-modules/emailing-doma
import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';
import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
+const SIMULATED_PROVIDER = { sendLatencyMs: 50, throttleFailureRatio: 0 };
+
@Injectable()
export class LogEmailingDomainDriver implements EmailingDomainDriverInterface {
private readonly logger = new Logger(LogEmailingDomainDriver.name);
@@ -40,24 +46,24 @@ export class LogEmailingDomainDriver implements EmailingDomainDriverInterface {
async verifyDomain(
input: EmailingDomainResourceInput,
): Promise<EmailingDomainVerificationResult> {
- this.logger.log(
- `[log-driver] verifyDomain(${input.domain}) → VERIFIED (instant)`,
- );
-
- return {
- status: EmailingDomainStatus.VERIFIED,
- verificationRecords: this.buildSyntheticVerificationRecords(input.domain),
- };
+ return this.alwaysVerified('verifyDomain', input.domain);
}
async getDomainStatus(
input: EmailingDomainResourceInput,
): Promise<EmailingDomainVerificationResult> {
- this.logger.log(`[log-driver] getDomainStatus(${input.domain}) → VERIFIED`);
+ return this.alwaysVerified('getDomainStatus', input.domain);
+ }
+
+ private alwaysVerified(
+ operation: string,
+ domain: string,
+ ): EmailingDomainVerificationResult {
+ this.logger.log(`[log-driver] ${operation}(${domain}) → VERIFIED`);
return {
status: EmailingDomainStatus.VERIFIED,
- verificationRecords: this.buildSyntheticVerificationRecords(input.domain),
+ verificationRecords: this.buildSyntheticVerificationRecords(domain),
};
}
@@ -106,9 +112,26 @@ export class LogEmailingDomainDriver implements EmailingDomainDriverInterface {
this.logger.log(`[log-driver] cleanupDomain(${input.domain})`);
}
+ private async simulateProviderCall(): Promise<void> {
+ if (SIMULATED_PROVIDER.sendLatencyMs > 0) {
+ await new Promise((resolve) =>
+ setTimeout(resolve, SIMULATED_PROVIDER.sendLatencyMs),
+ );
+ }
+
+ if (Math.random() < SIMULATED_PROVIDER.throttleFailureRatio) {
+ throw new EmailingDomainDriverException(
+ '[log-driver] simulated provider throttling',
+ EmailingDomainDriverExceptionCode.TEMPORARY_ERROR,
+ );
+ }
+ }
+
async sendEmail(
input: EmailingDomainSendEmailRequest,
): Promise<EmailingDomainSendEmailResult> {
+ await this.simulateProviderCall();
+
const unsubscribeBaseUrl = await this.getUnsubscribeBaseUrl(
input.workspaceId,
);
diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/emailing-domain.module.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/emailing-domain.module.ts
index e9b44e9a874..f5c323988f0 100644
--- a/packages/twenty-server/src/engine/core-modules/emailing-domain/emailing-domain.module.ts
+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/emailing-domain.module.ts
@@ -4,8 +4,12 @@ import { TypeOrmModule } from '@nestjs/typeorm';
import { TypeORMModule } from 'src/database/typeorm/typeorm.module';
import { BillingModule } from 'src/engine/core-modules/billing/billing.module';
import { DnsManagerModule } from 'src/engine/core-modules/dns-manager/dns-manager.module';
+import { CheckEmailingDomainVerificationCronCommand } from 'src/engine/core-modules/emailing-domain/crons/commands/check-emailing-domain-verification.cron.command';
+import { CheckEmailingDomainVerificationCronJob } from 'src/engine/core-modules/emailing-domain/crons/jobs/check-emailing-domain-verification.cron.job';
import { AwsSesClientProvider } from 'src/engine/core-modules/emailing-domain/drivers/aws-ses/providers/aws-ses-client.provider';
+import { AwsSesAccountService } from 'src/engine/core-modules/emailing-domain/drivers/aws-ses/services/aws-ses-account.service';
import { AwsSesObservabilityService } from 'src/engine/core-modules/emailing-domain/drivers/aws-ses/services/aws-ses-observability.service';
+import { AwsSesOutboundEventDestinationService } from 'src/engine/core-modules/emailing-domain/drivers/aws-ses/services/aws-ses-outbound-event-destination.service';
import { AwsSesRegisterDomainService } from 'src/engine/core-modules/emailing-domain/drivers/aws-ses/services/aws-ses-register-domain.service';
import { AwsSesHandleErrorService } from 'src/engine/core-modules/emailing-domain/drivers/aws-ses/services/aws-ses-handle-error.service';
import { AwsSesSendEmailService } from 'src/engine/core-modules/emailing-domain/drivers/aws-ses/services/aws-ses-send-email.service';
@@ -45,8 +49,11 @@ import { provideWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspac
EmailingDomainDriverFactory,
UnsubscribeTokenService,
EmailGroupAccessService,
+ CheckEmailingDomainVerificationCronCommand,
],
providers: [
+ CheckEmailingDomainVerificationCronCommand,
+ CheckEmailingDomainVerificationCronJob,
EmailGroupAccessService,
EmailingDomainService,
EmailingDomainTenantStatusService,
@@ -57,8 +64,10 @@ import { provideWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspac
EmailingDomainDriverFactory,
EmailingDomainWorkspaceCleanupJob,
AwsSesClientProvider,
+ AwsSesAccountService,
AwsSesHandleErrorService,
AwsSesObservabilityService,
+ AwsSesOutboundEventDestinationService,
AwsSesRegisterDomainService,
AwsSesSendEmailService,
LogEmailingDomainDriver,
diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/emailing-domain.resolver.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/emailing-domain.resolver.ts
index 757cbf7a6af..05c48c065b8 100644
--- a/packages/twenty-server/src/engine/core-modules/emailing-domain/emailing-domain.resolver.ts
+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/emailing-domain.resolver.ts
@@ -77,10 +77,10 @@ export class EmailingDomainResolver {
this.emailGroupAccessService.validateEmailGroupAccessOrThrow();
const emailingDomain =
- await this.emailingDomainService.verifyEmailingDomain(
- currentWorkspace,
- id,
- );
+ await this.emailingDomainService.verifyEmailingDomain({
+ workspaceId: currentWorkspace.id,
+ emailingDomainId: id,
+ });
return emailingDomain;
}
diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/services/emailing-domain.service.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/services/emailing-domain.service.ts
index dc45da93bc2..aa45063bad8 100644
--- a/packages/twenty-server/src/engine/core-modules/emailing-domain/services/emailing-domain.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/services/emailing-domain.service.ts
@@ -184,12 +184,15 @@ export class EmailingDomainService {
);
}
- async verifyEmailingDomain(
- workspace: WorkspaceEntity,
- emailingDomainId: string,
- ): Promise<EmailingDomainEntity> {
+ async verifyEmailingDomain({
+ workspaceId,
+ emailingDomainId,
+ }: {
+ workspaceId: string;
+ emailingDomainId: string;
+ }): Promise<EmailingDomainEntity> {
const emailingDomain = await this.findEmailingDomainByIdOrThrow(
- workspace.id,
+ workspaceId,
emailingDomainId,
);
@@ -206,7 +209,7 @@ export class EmailingDomainService {
verificationResult.status === EmailingDomainStatus.VERIFIED;
await this.emailingDomainRepository.update(
- workspace.id,
+ workspaceId,
{ id: emailingDomain.id },
{
status: verificationResult.status,
@@ -215,16 +218,12 @@ export class EmailingDomainService {
},
);
- await this.unsubscribeHostnameService.sync(
- workspace.id,
- emailingDomain.id,
- {
- provision: true,
- },
- );
+ await this.unsubscribeHostnameService.sync(workspaceId, emailingDomain.id, {
+ provision: true,
+ });
return this.unsubscribeHostnameService.withDnsRecords(
- await this.emailingDomainRepository.findOneOrFail(workspace.id, {
+ await this.emailingDomainRepository.findOneOrFail(workspaceId, {
where: { id: emailingDomain.id },
}),
);
diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/services/unsubscribe-content.service.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/services/unsubscribe-content.service.ts
index 0aad56b5bad..72375808c4f 100644
--- a/packages/twenty-server/src/engine/core-modules/emailing-domain/services/unsubscribe-content.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/services/unsubscribe-content.service.ts
@@ -8,7 +8,7 @@ import { buildUnsubscribeHeaders } from 'src/engine/core-modules/emailing-domain
import { appendHtmlFooter } from 'src/engine/core-modules/emailing-domain/utils/append-html-footer.util';
import { buildUnsubscribeHtmlFooter } from 'src/engine/core-modules/emailing-domain/utils/build-unsubscribe-html-footer.util';
import { buildUnsubscribeTextFooter } from 'src/engine/core-modules/emailing-domain/utils/build-unsubscribe-text-footer.util';
-import { buildUnsubscribeUrls } from 'src/engine/core-modules/emailing-domain/utils/build-unsubscribe-urls.util';
+import { buildUnsubscribeWebUrl } from 'src/engine/core-modules/emailing-domain/utils/build-unsubscribe-web-url.util';
@Injectable()
export class UnsubscribeContentService {
@@ -32,24 +32,20 @@ export class UnsubscribeContentService {
: {}),
});
- const unsubscribeUrls = buildUnsubscribeUrls({
+ const webUrl = buildUnsubscribeWebUrl({
unsubscribeBaseUrl,
- domain: email.domain,
token,
});
return {
...email,
- text: `${email.text}${buildUnsubscribeTextFooter(unsubscribeUrls.webUrl)}`,
+ text: `${email.text}${buildUnsubscribeTextFooter(webUrl)}`,
html: isNonEmptyString(email.html)
- ? appendHtmlFooter(
- email.html,
- buildUnsubscribeHtmlFooter(unsubscribeUrls.webUrl),
- )
+ ? appendHtmlFooter(email.html, buildUnsubscribeHtmlFooter(webUrl))
: email.html,
headers: [
...(email.headers ?? []),
- ...buildUnsubscribeHeaders(unsubscribeUrls),
+ ...buildUnsubscribeHeaders({ webUrl }),
],
};
}
diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/types/campaign-provider-outcome.type.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/types/campaign-provider-outcome.type.ts
new file mode 100644
index 00000000000..18bfe50804b
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/types/campaign-provider-outcome.type.ts
@@ -0,0 +1,4 @@
+import { type CAMPAIGN_PROVIDER_OUTCOME } from 'src/engine/core-modules/emailing-domain/constants/campaign-provider-outcome.constant';
+
+export type CampaignProviderOutcome =
+ (typeof CAMPAIGN_PROVIDER_OUTCOME)[keyof typeof CAMPAIGN_PROVIDER_OUTCOME];
diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/types/unsubscribe-urls.type.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/types/unsubscribe-urls.type.ts
deleted file mode 100644
index 1c7362cf20c..00000000000
--- a/packages/twenty-server/src/engine/core-modules/emailing-domain/types/unsubscribe-urls.type.ts
+++ /dev/null
@@ -1,4 +0,0 @@
-export type UnsubscribeUrls = {
- webUrl: string;
- mailtoUrl: string;
-};
diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/utils/build-unsubscribe-headers.util.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/utils/build-unsubscribe-headers.util.ts
index ffd03a47954..fa67c73d85e 100644
--- a/packages/twenty-server/src/engine/core-modules/emailing-domain/utils/build-unsubscribe-headers.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/utils/build-unsubscribe-headers.util.ts
@@ -1,10 +1,12 @@
import { type EmailingDomainHeader } from 'src/engine/core-modules/emailing-domain/drivers/types/emailing-domain-header.type';
-import { type UnsubscribeUrls } from 'src/engine/core-modules/emailing-domain/types/unsubscribe-urls.type';
+
+type BuildUnsubscribeHeadersArgs = {
+ webUrl: string;
+};
export const buildUnsubscribeHeaders = ({
webUrl,
- mailtoUrl,
-}: UnsubscribeUrls): EmailingDomainHeader[] => [
- { name: 'List-Unsubscribe', value: `<${webUrl}>, <${mailtoUrl}>` },
+}: BuildUnsubscribeHeadersArgs): EmailingDomainHeader[] => [
+ { name: 'List-Unsubscribe', value: `<${webUrl}>` },
{ name: 'List-Unsubscribe-Post', value: 'List-Unsubscribe=One-Click' },
];
diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/utils/build-unsubscribe-urls.util.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/utils/build-unsubscribe-urls.util.ts
deleted file mode 100644
index ad5b07506c4..00000000000
--- a/packages/twenty-server/src/engine/core-modules/emailing-domain/utils/build-unsubscribe-urls.util.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-import { UNSUBSCRIBE_MAILBOX_LOCAL_PART } from 'src/engine/core-modules/emailing-domain/constants/unsubscribe-mailbox.constant';
-import { type UnsubscribeUrls } from 'src/engine/core-modules/emailing-domain/types/unsubscribe-urls.type';
-
-type BuildUnsubscribeUrlsArgs = {
- unsubscribeBaseUrl: string;
- domain: string;
- token: string;
-};
-
-export const buildUnsubscribeUrls = ({
- unsubscribeBaseUrl,
- domain,
- token,
-}: BuildUnsubscribeUrlsArgs): UnsubscribeUrls => ({
- webUrl: `${unsubscribeBaseUrl}/emailing/unsubscribe?t=${token}`,
- mailtoUrl: `mailto:${UNSUBSCRIBE_MAILBOX_LOCAL_PART}@${domain}?subject=${token}`,
-});
diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/utils/build-unsubscribe-web-url.util.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/utils/build-unsubscribe-web-url.util.ts
new file mode 100644
index 00000000000..7ae37a9e3aa
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/utils/build-unsubscribe-web-url.util.ts
@@ -0,0 +1,10 @@
+type BuildUnsubscribeWebUrlArgs = {
+ unsubscribeBaseUrl: string;
+ token: string;
+};
+
+export const buildUnsubscribeWebUrl = ({
+ unsubscribeBaseUrl,
+ token,
+}: BuildUnsubscribeWebUrlArgs): string =>
+ `${unsubscribeBaseUrl}/emailing/unsubscribe?t=${token}`;
diff --git a/packages/twenty-server/src/engine/core-modules/message-queue/message-queue-worker-config.constant.ts b/packages/twenty-server/src/engine/core-modules/message-queue/message-queue-worker-config.constant.ts
index e31f30cd7cd..c866ecceb5b 100644
--- a/packages/twenty-server/src/engine/core-modules/message-queue/message-queue-worker-config.constant.ts
+++ b/packages/twenty-server/src/engine/core-modules/message-queue/message-queue-worker-config.constant.ts
@@ -67,6 +67,15 @@ export const MESSAGE_QUEUE_WORKER_CONFIG: Record<
boundedShutdownDrain: false,
},
},
+ [MessageQueue.campaignQueue]: {
+ priority: 6,
+ workerOptions: {
+ concurrency: 10,
+ lockDuration: 30_000,
+ maxStalledCount: 1,
+ boundedShutdownDrain: false,
+ },
+ },
[MessageQueue.calendarQueue]: {
priority: 4,
workerOptions: {
diff --git a/packages/twenty-server/src/engine/core-modules/message-queue/message-queue.constants.ts b/packages/twenty-server/src/engine/core-modules/message-queue/message-queue.constants.ts
index d9fb480f76a..125bca4d2b1 100644
--- a/packages/twenty-server/src/engine/core-modules/message-queue/message-queue.constants.ts
+++ b/packages/twenty-server/src/engine/core-modules/message-queue/message-queue.constants.ts
@@ -8,6 +8,7 @@ export enum MessageQueue {
webhookQueue = 'webhook-queue',
cronQueue = 'cron-queue',
emailQueue = 'email-queue',
+ campaignQueue = 'campaign-queue',
calendarQueue = 'calendar-queue',
connectedAccountSyncWebhookQueue = 'connected-account-sync-webhook-queue',
contactCreationQueue = 'contact-creation-queue',
diff --git a/packages/twenty-server/src/engine/core-modules/twenty-config/config-variables.ts b/packages/twenty-server/src/engine/core-modules/twenty-config/config-variables.ts
index 4dd37ab8b2a..0ec81f11854 100644
--- a/packages/twenty-server/src/engine/core-modules/twenty-config/config-variables.ts
+++ b/packages/twenty-server/src/engine/core-modules/twenty-config/config-variables.ts
@@ -2140,6 +2140,7 @@ export class ConfigVariables {
'Driver used for the emailing domain feature — AWS_SES (requires AWS credentials), RESEND (requires a Resend API key), LOG fakes registration/verification/sends locally',
type: ConfigVariableType.ENUM,
options: Object.values(EmailingDomainDriver),
+ isEnvOnly: true,
})
@CastToUpperSnakeCase()
EMAILING_DOMAIN_DRIVER: EmailingDomainDriver = EmailingDomainDriver.LOG;
@@ -2149,8 +2150,11 @@ export class ConfigVariables {
description: 'AWS region',
type: ConfigVariableType.STRING,
})
+ @ValidateIf(
+ (env) => env.EMAILING_DOMAIN_DRIVER === EmailingDomainDriver.AWS_SES,
+ )
@IsAWSRegion()
- @IsOptional()
+ @IsNotEmpty()
AWS_SES_REGION: AwsRegion;
@ConfigVariablesMetadata({
@@ -2185,7 +2189,11 @@ export class ConfigVariables {
description: 'AWS Account ID for SES ARN construction',
type: ConfigVariableType.STRING,
})
- @IsOptional()
+ @ValidateIf(
+ (env) => env.EMAILING_DOMAIN_DRIVER === EmailingDomainDriver.AWS_SES,
+ )
+ @IsString()
+ @IsNotEmpty()
AWS_SES_ACCOUNT_ID: string;
@ConfigVariablesMetadata({
@@ -2200,12 +2208,23 @@ export class ConfigVariables {
@ConfigVariablesMetadata({
group: ConfigVariablesGroup.AWS_SES_SETTINGS,
description:
- 'Comma-separated list of SNS topic ARNs accepted by the inbound-email webhook (e.g. arn:aws:sns:us-east-1:123:my-inbound).',
+ 'Comma-separated list of SNS topic ARNs accepted by the inbound-email and outbound-event webhooks (e.g. arn:aws:sns:us-east-1:123:my-inbound). Every SNS payload whose topic is absent from this list is rejected.',
type: ConfigVariableType.STRING,
})
@IsOptional()
+ @IsString()
SES_SNS_TOPIC_ARN_ALLOWLIST: string;
+ @ConfigVariablesMetadata({
+ group: ConfigVariablesGroup.AWS_SES_SETTINGS,
+ description:
+ 'SNS topic ARN that receives SES DELIVERY, BOUNCE, COMPLAINT, REJECT and RENDERING_FAILURE events. An SNS event destination pointing at it is added to each workspace SES configuration set, and the topic must be subscribed to /webhooks/messaging/ses/outbound. Bounces and complaints also arrive through the pre-existing EventBridge destination, so those two are delivered twice and deduplicated downstream.',
+ type: ConfigVariableType.STRING,
+ })
+ @IsOptional()
+ @IsString()
+ SES_OUTBOUND_SNS_TOPIC_ARN: string;
+
@ConfigVariablesMetadata({
group: ConfigVariablesGroup.AWS_SES_SETTINGS,
description:
diff --git a/packages/twenty-server/src/modules/emailing/jobs/materialize-campaign.job.ts b/packages/twenty-server/src/modules/emailing/jobs/materialize-campaign.job.ts
index 34f13be794f..ac0d58c468b 100644
--- a/packages/twenty-server/src/modules/emailing/jobs/materialize-campaign.job.ts
+++ b/packages/twenty-server/src/modules/emailing/jobs/materialize-campaign.job.ts
@@ -5,7 +5,7 @@ import { Processor } from 'src/engine/core-modules/message-queue/decorators/proc
import { MessageQueue } from 'src/engine/core-modules/message-queue/message-queue.constants';
import { MessageCampaignMaterializationService } from 'src/modules/emailing/services/message-campaign-materialization.service';
-@Processor(MessageQueue.emailQueue)
+@Processor(MessageQueue.campaignQueue)
export class MaterializeCampaignJob {
constructor(
private readonly messageCampaignMaterializationService: MessageCampaignMaterializationService,
diff --git a/packages/twenty-server/src/modules/emailing/jobs/refresh-campaign-stats.job.ts b/packages/twenty-server/src/modules/emailing/jobs/refresh-campaign-stats.job.ts
index f55a4d019b4..a6ad2f5d080 100644
--- a/packages/twenty-server/src/modules/emailing/jobs/refresh-campaign-stats.job.ts
+++ b/packages/twenty-server/src/modules/emailing/jobs/refresh-campaign-stats.job.ts
@@ -5,7 +5,7 @@ import { Processor } from 'src/engine/core-modules/message-queue/decorators/proc
import { MessageQueue } from 'src/engine/core-modules/message-queue/message-queue.constants';
import { MessageCampaignStatisticsService } from 'src/modules/emailing/services/message-campaign-statistics.service';
-@Processor(MessageQueue.emailQueue)
+@Processor(MessageQueue.campaignQueue)
export class RefreshCampaignStatsJob {
constructor(
private readonly messageCampaignStatisticsService: MessageCampaignStatisticsService,
diff --git a/packages/twenty-server/src/modules/emailing/jobs/send-campaign-email.job.ts b/packages/twenty-server/src/modules/emailing/jobs/send-campaign-email.job.ts
index f63a8627eab..b35d170bcf6 100644
--- a/packages/twenty-server/src/modules/emailing/jobs/send-campaign-email.job.ts
+++ b/packages/twenty-server/src/modules/emailing/jobs/send-campaign-email.job.ts
@@ -5,7 +5,7 @@ import { Process } from 'src/engine/core-modules/message-queue/decorators/proces
import { Processor } from 'src/engine/core-modules/message-queue/decorators/processor.decorator';
import { MessageQueue } from 'src/engine/core-modules/message-queue/message-queue.constants';
-@Processor(MessageQueue.emailQueue)
+@Processor(MessageQueue.campaignQueue)
export class SendCampaignEmailJob {
constructor(
private readonly messageCampaignDeliveryService: MessageCampaignDeliveryService,
diff --git a/packages/twenty-server/src/modules/emailing/services/message-campaign-delivery-feedback.service.ts b/packages/twenty-server/src/modules/emailing/services/message-campaign-delivery-feedback.service.ts
index d3ca4de6cfe..4302a627832 100644
--- a/packages/twenty-server/src/modules/emailing/services/message-campaign-delivery-feedback.service.ts
+++ b/packages/twenty-server/src/modules/emailing/services/message-campaign-delivery-feedback.service.ts
@@ -1,10 +1,23 @@
import { Injectable } from '@nestjs/common';
+import { type QueryDeepPartialEntity } from 'typeorm/query-builder/QueryPartialEntity';
+
import { CampaignDeliveryEntity } from 'src/engine/core-modules/emailing-domain/campaign-delivery.entity';
+import { CAMPAIGN_DELIVERY_STATE } from 'src/engine/core-modules/emailing-domain/constants/campaign-delivery-state.constant';
+import { CAMPAIGN_FAILURE_REASON } from 'src/engine/core-modules/emailing-domain/constants/campaign-failure-reason.constant';
+import { CAMPAIGN_PROVIDER_OUTCOME } from 'src/engine/core-modules/emailing-domain/constants/campaign-provider-outcome.constant';
+import { type CampaignProviderOutcome } from 'src/engine/core-modules/emailing-domain/types/campaign-provider-outcome.type';
import { InjectWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/inject-workspace-scoped-repository.decorator';
import { WorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/workspace-scoped-repository';
import { MessageCampaignLifecycleService } from 'src/modules/emailing/services/message-campaign-lifecycle.service';
-import { isDefined } from 'twenty-shared/utils';
+import { assertUnreachable, isDefined } from 'twenty-shared/utils';
+
+type CampaignDeliveryOutcomeUpdate = Partial<
+ Pick<
+ CampaignDeliveryEntity,
+ 'deliveredAt' | 'bouncedAt' | 'complainedAt' | 'state' | 'failureReason'
+ >
+>;
@Injectable()
export class MessageCampaignDeliveryFeedbackService {
@@ -21,43 +34,67 @@ export class MessageCampaignDeliveryFeedbackService {
}: {
workspaceId: string;
providerMessageId: string;
- outcome: 'DELIVERED' | 'BOUNCED' | 'COMPLAINED';
+ outcome: CampaignProviderOutcome;
}): Promise<void> {
- const delivery = await this.campaignDeliveryRepository.findOneBy(
- workspaceId,
- { providerMessageId },
- );
+ const update = this.buildOutcomeUpdate(outcome);
- if (!isDefined(delivery)) {
+ if (Object.keys(update).length === 0) {
return;
}
- await this.campaignDeliveryRepository.update(
- workspaceId,
- { id: delivery.id },
- this.buildOutcomeStamp(outcome),
- );
+ // Matched and stamped in one statement rather than a lookup followed by an
+ // update: providerMessageId is unique per workspace, so this settles the
+ // same single row, halves the queries a webhook costs, and closes the
+ // window where the row could change between the two.
+ const { raw } = await this.campaignDeliveryRepository
+ .createQueryBuilder()
+ .update()
+ .set(update as QueryDeepPartialEntity<CampaignDeliveryEntity>)
+ .where('"workspaceId" = :workspaceId', { workspaceId })
+ .andWhere('"providerMessageId" = :providerMessageId', {
+ providerMessageId,
+ })
+ .returning(['campaignId'])
+ .execute();
+
+ const [updatedDelivery] = raw as { campaignId: string }[];
+
+ if (!isDefined(updatedDelivery)) {
+ return;
+ }
await this.messageCampaignLifecycleService.scheduleStatsRefresh({
workspaceId,
- campaignId: delivery.campaignId,
+ campaignId: updatedDelivery.campaignId,
});
}
- private buildOutcomeStamp(
- outcome: 'DELIVERED' | 'BOUNCED' | 'COMPLAINED',
- ): Partial<
- Pick<CampaignDeliveryEntity, 'deliveredAt' | 'bouncedAt' | 'complainedAt'>
- > {
+ private buildOutcomeUpdate(
+ outcome: CampaignProviderOutcome,
+ ): CampaignDeliveryOutcomeUpdate {
const occurredAt = new Date();
switch (outcome) {
- case 'DELIVERED':
+ case CAMPAIGN_PROVIDER_OUTCOME.DELIVERED:
return { deliveredAt: occurredAt };
- case 'BOUNCED':
+ case CAMPAIGN_PROVIDER_OUTCOME.BOUNCED:
return { bouncedAt: occurredAt };
- case 'COMPLAINED':
+ case CAMPAIGN_PROVIDER_OUTCOME.COMPLAINED:
return { complainedAt: occurredAt };
+ case CAMPAIGN_PROVIDER_OUTCOME.REJECTED:
+ return {
+ state: CAMPAIGN_DELIVERY_STATE.FAILED,
+ failureReason: CAMPAIGN_FAILURE_REASON.REJECTED,
+ };
+ case CAMPAIGN_PROVIDER_OUTCOME.RENDERING_FAILED:
+ return {
+ state: CAMPAIGN_DELIVERY_STATE.FAILED,
+ failureReason: CAMPAIGN_FAILURE_REASON.RENDERING_FAILED,
+ };
+ case CAMPAIGN_PROVIDER_OUTCOME.SOFT_BOUNCED:
+ return {};
+ default:
+ return assertUnreachable(outcome);
}
}
}
diff --git a/packages/twenty-server/src/modules/emailing/services/message-campaign-lifecycle.service.ts b/packages/twenty-server/src/modules/emailing/services/message-campaign-lifecycle.service.ts
index fcfb677defb..75b669bef6f 100644
--- a/packages/twenty-server/src/modules/emailing/services/message-campaign-lifecycle.service.ts
+++ b/packages/twenty-server/src/modules/emailing/services/message-campaign-lifecycle.service.ts
@@ -51,7 +51,7 @@ export class MessageCampaignLifecycleService {
private readonly workspaceOrmManager: WorkspaceOrmManager,
private readonly userRoleService: UserRoleService,
private readonly messageCampaignStatisticsService: MessageCampaignStatisticsService,
- @InjectMessageQueue(MessageQueue.emailQueue)
+ @InjectMessageQueue(MessageQueue.campaignQueue)
private readonly messageQueueService: MessageQueueService,
@InjectCacheStorage(CacheStorageNamespace.ModuleEmailing)
private readonly cacheStorageService: CacheStorageService,
diff --git a/packages/twenty-server/src/modules/emailing/services/message-campaign-materialization.service.ts b/packages/twenty-server/src/modules/emailing/services/message-campaign-materialization.service.ts
index 3093dba2171..bbd6a5e6301 100644
--- a/packages/twenty-server/src/modules/emailing/services/message-campaign-materialization.service.ts
+++ b/packages/twenty-server/src/modules/emailing/services/message-campaign-materialization.service.ts
@@ -1,3 +1,4 @@
+import { CAMPAIGN_SEND_RETRY_LIMIT } from 'src/engine/core-modules/emailing-domain/constants/campaign-send-retry-limit.constant';
import { CAMPAIGN_SEND_RETRY_BACKOFF } from 'src/engine/core-modules/emailing-domain/constants/campaign-send-retry-backoff.constant';
import { Injectable } from '@nestjs/common';
@@ -60,7 +61,7 @@ export class MessageCampaignMaterializationService {
private readonly campaignDeliveryRepository: WorkspaceScopedRepository<CampaignDeliveryEntity>,
private readonly workspaceOrmManager: WorkspaceOrmManager,
private readonly messageCampaignLifecycleService: MessageCampaignLifecycleService,
- @InjectMessageQueue(MessageQueue.emailQueue)
+ @InjectMessageQueue(MessageQueue.campaignQueue)
private readonly messageQueueService: MessageQueueService,
) {}
@@ -335,7 +336,10 @@ export class MessageCampaignMaterializationService {
recipientEmail: recipient.email,
emailingDomainId,
})),
- { retryLimit: 3, backoff: CAMPAIGN_SEND_RETRY_BACKOFF },
+ {
+ retryLimit: CAMPAIGN_SEND_RETRY_LIMIT,
+ backoff: CAMPAIGN_SEND_RETRY_BACKOFF,
+ },
);
}
diff --git a/packages/twenty-server/src/modules/emailing/services/message-campaign.service.ts b/packages/twenty-server/src/modules/emailing/services/message-campaign.service.ts
index 2ea7bf16ccc..4dc13704f14 100644
--- a/packages/twenty-server/src/modules/emailing/services/message-campaign.service.ts
+++ b/packages/twenty-server/src/modules/emailing/services/message-campaign.service.ts
@@ -1,3 +1,4 @@
+import { CAMPAIGN_SEND_RETRY_LIMIT } from 'src/engine/core-modules/emailing-domain/constants/campaign-send-retry-limit.constant';
import { CAMPAIGN_SEND_RETRY_BACKOFF } from 'src/engine/core-modules/emailing-domain/constants/campaign-send-retry-backoff.constant';
import { Injectable } from '@nestjs/common';
@@ -53,7 +54,7 @@ export class MessageCampaignService {
private readonly campaignDeliveryRepository: WorkspaceScopedRepository<CampaignDeliveryEntity>,
private readonly emailingDomainSenderService: EmailingDomainSenderService,
private readonly workspaceOrmManager: WorkspaceOrmManager,
- @InjectMessageQueue(MessageQueue.emailQueue)
+ @InjectMessageQueue(MessageQueue.campaignQueue)
private readonly messageQueueService: MessageQueueService,
private readonly messageChannelMetadataService: MessageChannelMetadataService,
private readonly userRoleService: UserRoleService,
@@ -133,7 +134,10 @@ export class MessageCampaignService {
emailingDomainId: emailingDomain.id,
recipients,
},
- { retryLimit: 3, backoff: CAMPAIGN_SEND_RETRY_BACKOFF },
+ {
+ retryLimit: CAMPAIGN_SEND_RETRY_LIMIT,
+ backoff: CAMPAIGN_SEND_RETRY_BACKOFF,
+ },
)
.catch(async (error) => {
await this.messageCampaignLifecycleService.transitionCampaignStatus({
diff --git a/packages/twenty-server/src/modules/emailing/utils/resolve-campaign-send-failure.util.ts b/packages/twenty-server/src/modules/emailing/utils/resolve-campaign-send-failure.util.ts
index 532863a48ae..cb02474b468 100644
--- a/packages/twenty-server/src/modules/emailing/utils/resolve-campaign-send-failure.util.ts
+++ b/packages/twenty-server/src/modules/emailing/utils/resolve-campaign-send-failure.util.ts
@@ -56,6 +56,8 @@ export const resolveCampaignSendFailure = (
return failed(CAMPAIGN_FAILURE_REASON.INSUFFICIENT_PERMISSIONS, false);
case EmailingDomainDriverExceptionCode.CONFIGURATION_ERROR:
return failed(CAMPAIGN_FAILURE_REASON.CONFIGURATION_ERROR, false);
+ case EmailingDomainDriverExceptionCode.SANDBOX_ACCOUNT:
+ return failed(CAMPAIGN_FAILURE_REASON.SANDBOX_ACCOUNT, false);
default:
return assertUnreachable(error.code);
}
diff --git a/packages/twenty-server/src/modules/messaging-webhooks/drivers/aws-ses/services/ses-outbound-webhook-driver.service.ts b/packages/twenty-server/src/modules/messaging-webhooks/drivers/aws-ses/services/ses-outbound-webhook-driver.service.ts
index a6017b36713..09cada62d48 100644
--- a/packages/twenty-server/src/modules/messaging-webhooks/drivers/aws-ses/services/ses-outbound-webhook-driver.service.ts
+++ b/packages/twenty-server/src/modules/messaging-webhooks/drivers/aws-ses/services/ses-outbound-webhook-driver.service.ts
@@ -1,16 +1,15 @@
-import { Injectable, Logger } from '@nestjs/common';
+import { Injectable } from '@nestjs/common';
import type SnsPayloadValidator from 'sns-payload-validator';
-import { isDefined, isNonEmptyArray, parseJson } from 'twenty-shared/utils';
+import { isDefined, parseJson } from 'twenty-shared/utils';
-import { EmailingDomainTenantStatus } from 'src/engine/core-modules/emailing-domain/drivers/types/emailing-domain-tenant-status.type';
-import { MessageSuppressionReason } from 'src/engine/core-modules/emailing-domain/types/message-suppression-reason.type';
+import { ExceptionHandlerService } from 'src/engine/core-modules/exception-handler/exception-handler.service';
import { SnsSignatureVerifierService } from 'src/modules/messaging-webhooks/drivers/aws-ses/services/sns-signature-verifier.service';
import { SnsSubscriptionConfirmerService } from 'src/modules/messaging-webhooks/drivers/aws-ses/services/sns-subscription-confirmer.service';
-import { type SesEventBridgeNotification } from 'src/modules/messaging-webhooks/drivers/aws-ses/types/ses-event-bridge-notification.type';
-import { resolveWorkspaceIdFromAwsSesResources } from 'src/modules/messaging-webhooks/drivers/aws-ses/utils/resolve-workspace-id-from-aws-ses-resources.util';
+import { type SesOutboundNotification } from 'src/modules/messaging-webhooks/drivers/aws-ses/types/ses-outbound-notification.type';
+import { normalizeSesOutboundEvent } from 'src/modules/messaging-webhooks/drivers/aws-ses/utils/normalize-ses-outbound-event.util';
+import { OutboundDeliveryEventHandlerService } from 'src/modules/messaging-webhooks/handlers/outbound-delivery-event-handler.service';
import { OutboundSendingStateHandlerService } from 'src/modules/messaging-webhooks/handlers/outbound-sending-state-handler.service';
-import { OutboundSuppressionHandlerService } from 'src/modules/messaging-webhooks/handlers/outbound-suppression-handler.service';
import { MessagingWebhookExceptionCode } from 'src/modules/messaging-webhooks/messaging-webhook-exception-code.enum';
import { MessagingWebhookException } from 'src/modules/messaging-webhooks/messaging-webhook.exception';
@@ -18,12 +17,11 @@ type SnsPayload = SnsPayloadValidator.SnsPayload;
@Injectable()
export class SesOutboundWebhookDriverService {
- private readonly logger = new Logger(SesOutboundWebhookDriverService.name);
-
constructor(
+ private readonly exceptionHandlerService: ExceptionHandlerService,
private readonly snsSignatureVerifierService: SnsSignatureVerifierService,
private readonly snsSubscriptionConfirmerService: SnsSubscriptionConfirmerService,
- private readonly outboundSuppressionHandlerService: OutboundSuppressionHandlerService,
+ private readonly outboundDeliveryEventHandlerService: OutboundDeliveryEventHandlerService,
private readonly outboundSendingStateHandlerService: OutboundSendingStateHandlerService,
) {}
@@ -52,142 +50,40 @@ export class SesOutboundWebhookDriverService {
return;
}
- const event = parseJson<SesEventBridgeNotification>(payload.Message);
+ const notification = parseJson<SesOutboundNotification>(payload.Message);
- if (!isDefined(event)) {
+ if (!isDefined(notification)) {
throw new MessagingWebhookException(
'Invalid SNS notification message',
MessagingWebhookExceptionCode.MESSAGING_WEBHOOK_INVALID_PAYLOAD,
);
}
- if (
- event['detail-type'] === 'Email Bounced' ||
- event['detail-type'] === 'Email Complaint Received'
- ) {
- await this.handleSuppressionEvent(event);
-
- return;
- }
-
- if (
- event['detail-type'] === 'Sending Status Enabled' ||
- event['detail-type'] === 'Sending Status Disabled'
- ) {
- await this.handleSendingStateEvent(event);
-
- return;
+ const event = normalizeSesOutboundEvent(notification);
+
+ switch (event.status) {
+ case 'DELIVERY':
+ await this.outboundDeliveryEventHandlerService.handle({
+ ...event.delivery,
+ dedupeKey: payload.MessageId,
+ });
+
+ return;
+ case 'SENDING_STATE':
+ await this.outboundSendingStateHandlerService.handle(
+ event.sendingState,
+ );
+
+ return;
+ case 'UNPROCESSABLE':
+ this.exceptionHandlerService.captureExceptions([
+ new MessagingWebhookException(
+ `Dropped SES outbound event ${event.eventName}: ${event.reason}`,
+ MessagingWebhookExceptionCode.MESSAGING_WEBHOOK_UNHANDLED_ERROR,
+ ),
+ ]);
+
+ return;
}
-
- this.logger.warn(
- `Ignoring SES event with unsupported detail-type: ${event['detail-type']}`,
- );
}
-
- private async handleSuppressionEvent(
- event: SesEventBridgeNotification,
- ): Promise<void> {
- const suppression = this.resolveSuppression(event);
-
- if (!isDefined(suppression)) {
- return;
- }
-
- const workspaceId = resolveWorkspaceIdFromAwsSesResources(event.resources);
-
- if (!isDefined(workspaceId)) {
- this.logger.warn(
- `Could not resolve workspaceId from SES ${event['detail-type']} event resources: ${JSON.stringify(event.resources)}`,
- );
-
- return;
- }
-
- await this.outboundSuppressionHandlerService.handle({
- workspaceId,
- reason: suppression.reason,
- emailAddresses: suppression.emailAddresses,
- providerMessageId: event.detail?.mail?.messageId ?? null,
- providerEventId: suppression.providerEventId,
- });
- }
-
- private async handleSendingStateEvent(
- event: SesEventBridgeNotification,
- ): Promise<void> {
- const workspaceId = resolveWorkspaceIdFromAwsSesResources(event.resources);
-
- if (!isDefined(workspaceId)) {
- this.logger.warn(
- `Could not resolve workspaceId from SES sending-state event resources: ${JSON.stringify(event.resources)}`,
- );
-
- return;
- }
-
- await this.outboundSendingStateHandlerService.handle({
- workspaceId,
- status:
- event['detail-type'] === 'Sending Status Enabled'
- ? EmailingDomainTenantStatus.ACTIVE
- : EmailingDomainTenantStatus.PAUSED,
- });
- }
-
- private resolveSuppression(event: SesEventBridgeNotification): {
- reason:
- | MessageSuppressionReason.BOUNCE
- | MessageSuppressionReason.COMPLAINT;
- emailAddresses: string[];
- providerEventId: string | null;
- } | null {
- if (event['detail-type'] === 'Email Bounced') {
- const bounce = event.detail?.bounce;
-
- if (bounce?.bounceType !== 'Permanent') {
- return null;
- }
-
- const emailAddresses = this.extractRecipientAddresses(
- bounce.bouncedRecipients,
- );
-
- if (!isNonEmptyArray(emailAddresses)) {
- return null;
- }
-
- return {
- reason: MessageSuppressionReason.BOUNCE,
- emailAddresses,
- providerEventId: bounce.feedbackId ?? null,
- };
- }
-
- if (event['detail-type'] === 'Email Complaint Received') {
- const complaint = event.detail?.complaint;
- const emailAddresses = this.extractRecipientAddresses(
- complaint?.complainedRecipients,
- );
-
- if (!isNonEmptyArray(emailAddresses)) {
- return null;
- }
-
- return {
- reason: MessageSuppressionReason.COMPLAINT,
- emailAddresses,
- providerEventId: complaint?.feedbackId ?? null,
- };
- }
-
- return null;
- }
-
- private extractRecipientAddresses = (
- recipients: { emailAddress: string }[] | undefined,
- ): string[] => {
- return (recipients ?? [])
- .map((recipient) => recipient.emailAddress)
- .filter(isDefined);
- };
}
diff --git a/packages/twenty-server/src/modules/messaging-webhooks/drivers/aws-ses/services/sns-signature-verifier.service.ts b/packages/twenty-server/src/modules/messaging-webhooks/drivers/aws-ses/services/sns-signature-verifier.service.ts
index 9cbdbf55b5b..7306437925e 100644
--- a/packages/twenty-server/src/modules/messaging-webhooks/drivers/aws-ses/services/sns-signature-verifier.service.ts
+++ b/packages/twenty-server/src/modules/messaging-webhooks/drivers/aws-ses/services/sns-signature-verifier.service.ts
@@ -1,5 +1,6 @@
import { Injectable, Logger } from '@nestjs/common';
+import { isNonEmptyArray, isNonEmptyString } from '@sniptt/guards';
import SnsPayloadValidator from 'sns-payload-validator';
import { MessagingWebhookExceptionCode } from 'src/modules/messaging-webhooks/messaging-webhook-exception-code.enum';
@@ -16,14 +17,7 @@ export class SnsSignatureVerifierService {
constructor(private readonly twentyConfigService: TwentyConfigService) {}
async assertAllowedAndSigned(payload: SnsPayload): Promise<void> {
- if (!this.isTopicAllowlisted(payload.TopicArn)) {
- this.logger.warn(`SNS topic ${payload.TopicArn} is not in allowlist`);
-
- throw new MessagingWebhookException(
- 'SNS topic not allowed',
- MessagingWebhookExceptionCode.MESSAGING_WEBHOOK_FORBIDDEN_TOPIC,
- );
- }
+ this.assertTopicAllowlistedOrThrow(payload.TopicArn);
try {
await this.validator.validate(payload);
@@ -40,19 +34,30 @@ export class SnsSignatureVerifierService {
}
}
- private isTopicAllowlisted(topicArn: string): boolean {
+ private assertTopicAllowlistedOrThrow(topicArn: string): void {
const allowlist = this.twentyConfigService.get(
'SES_SNS_TOPIC_ARN_ALLOWLIST',
);
- if (typeof allowlist !== 'string' || allowlist.trim() === '') {
- return false;
- }
-
- return allowlist
+ const allowedTopicArns = (allowlist ?? '')
.split(',')
.map((entry) => entry.trim())
- .filter((entry) => entry.length > 0)
- .includes(topicArn);
+ .filter(isNonEmptyString);
+
+ if (!isNonEmptyArray(allowedTopicArns)) {
+ throw new MessagingWebhookException(
+ 'SES_SNS_TOPIC_ARN_ALLOWLIST is not configured, every SES webhook payload is rejected',
+ MessagingWebhookExceptionCode.MESSAGING_WEBHOOK_NOT_CONFIGURED,
+ );
+ }
+
+ if (!allowedTopicArns.includes(topicArn)) {
+ this.logger.warn(`SNS topic ${topicArn} is not in allowlist`);
+
+ throw new MessagingWebhookException(
+ 'SNS topic not allowed',
+ MessagingWebhookExceptionCode.MESSAGING_WEBHOOK_FORBIDDEN_TOPIC,
+ );
+ }
}
}
diff --git a/packages/twenty-server/src/modules/messaging-webhooks/drivers/aws-ses/types/ses-event-bridge-notification.type.ts b/packages/twenty-server/src/modules/messaging-webhooks/drivers/aws-ses/types/ses-event-bridge-notification.type.ts
index 2a164a16bd0..f3326758b6e 100644
--- a/packages/twenty-server/src/modules/messaging-webhooks/drivers/aws-ses/types/ses-event-bridge-notification.type.ts
+++ b/packages/twenty-server/src/modules/messaging-webhooks/drivers/aws-ses/types/ses-event-bridge-notification.type.ts
@@ -1,37 +1,8 @@
-type SesEventBridgeDetailType =
- | 'Sending Status Enabled'
- | 'Sending Status Disabled'
- | 'Email Bounced'
- | 'Email Complaint Received';
-
-type SesEventBridgeRecipient = {
- emailAddress: string;
-};
+import { type SesOutboundEventPayload } from 'src/modules/messaging-webhooks/drivers/aws-ses/types/ses-outbound-event-payload.type';
export type SesEventBridgeNotification = {
source: 'aws.ses';
- 'detail-type': SesEventBridgeDetailType;
+ 'detail-type': string;
resources?: string[];
- detail?: {
- version?: string;
- data?: {
- origin?: string;
- record?: {
- status?: 'ENABLED' | 'DISABLED';
- cause?: string;
- };
- };
- bounce?: {
- bounceType?: 'Permanent' | 'Transient' | 'Undetermined';
- feedbackId?: string;
- bouncedRecipients?: SesEventBridgeRecipient[];
- };
- complaint?: {
- feedbackId?: string;
- complainedRecipients?: SesEventBridgeRecipient[];
- };
- mail?: {
- messageId?: string;
- };
- };
+ detail?: SesOutboundEventPayload;
};
diff --git a/packages/twenty-server/src/modules/messaging-webhooks/drivers/aws-ses/types/ses-outbound-event-payload.type.ts b/packages/twenty-server/src/modules/messaging-webhooks/drivers/aws-ses/types/ses-outbound-event-payload.type.ts
new file mode 100644
index 00000000000..89c53c8b7da
--- /dev/null
+++ b/packages/twenty-server/src/modules/messaging-webhooks/drivers/aws-ses/types/ses-outbound-event-payload.type.ts
@@ -0,0 +1,27 @@
+type SesOutboundEventRecipient = {
+ emailAddress: string;
+};
+
+export type SesOutboundEventPayload = {
+ version?: string;
+ data?: {
+ origin?: string;
+ record?: {
+ status?: 'ENABLED' | 'DISABLED';
+ cause?: string;
+ };
+ };
+ bounce?: {
+ bounceType?: 'Permanent' | 'Transient' | 'Undetermined';
+ feedbackId?: string;
+ bouncedRecipients?: SesOutboundEventRecipient[];
+ };
+ complaint?: {
+ feedbackId?: string;
+ complainedRecipients?: SesOutboundEventRecipient[];
+ };
+ mail?: {
+ messageId?: string;
+ tags?: Record<string, string[]>;
+ };
+};
diff --git a/packages/twenty-server/src/modules/messaging-webhooks/drivers/aws-ses/types/ses-outbound-notification.type.ts b/packages/twenty-server/src/modules/messaging-webhooks/drivers/aws-ses/types/ses-outbound-notification.type.ts
new file mode 100644
index 00000000000..eacc524d8e2
--- /dev/null
+++ b/packages/twenty-server/src/modules/messaging-webhooks/drivers/aws-ses/types/ses-outbound-notification.type.ts
@@ -0,0 +1,10 @@
+import { type SesEventBridgeNotification } from 'src/modules/messaging-webhooks/drivers/aws-ses/types/ses-event-bridge-notification.type';
+import { type SesOutboundEventPayload } from 'src/modules/messaging-webhooks/drivers/aws-ses/types/ses-outbound-event-payload.type';
+
+type SesEventPublishingNotification = SesOutboundEventPayload & {
+ eventType: string;
+};
+
+export type SesOutboundNotification =
+ | SesEventBridgeNotification
+ | SesEventPublishingNotification;
diff --git a/packages/twenty-server/src/modules/messaging-webhooks/drivers/aws-ses/utils/__tests__/normalize-ses-outbound-event.util.spec.ts b/packages/twenty-server/src/modules/messaging-webhooks/drivers/aws-ses/utils/__tests__/normalize-ses-outbound-event.util.spec.ts
new file mode 100644
index 00000000000..df91ab8cbf9
--- /dev/null
+++ b/packages/twenty-server/src/modules/messaging-webhooks/drivers/aws-ses/utils/__tests__/normalize-ses-outbound-event.util.spec.ts
@@ -0,0 +1,177 @@
+import { CAMPAIGN_PROVIDER_OUTCOME } from 'src/engine/core-modules/emailing-domain/constants/campaign-provider-outcome.constant';
+import { EmailingDomainTenantStatus } from 'src/engine/core-modules/emailing-domain/drivers/types/emailing-domain-tenant-status.type';
+import { MessageSuppressionReason } from 'src/engine/core-modules/emailing-domain/types/message-suppression-reason.type';
+import { normalizeSesOutboundEvent } from 'src/modules/messaging-webhooks/drivers/aws-ses/utils/normalize-ses-outbound-event.util';
+
+const WORKSPACE_ID = '20202020-1c25-4d02-bf25-6aeccf7ea419';
+const CONFIGURATION_SET_ARN = `arn:aws:ses:us-east-1:123456789012:configuration-set/twenty-workspace-${WORKSPACE_ID}`;
+const CONFIGURATION_SET_TAGS = {
+ 'ses:configuration-set': [`twenty-workspace-${WORKSPACE_ID}`],
+};
+
+describe('normalizeSesOutboundEvent', () => {
+ it('should suppress permanently bounced recipients from an EventBridge envelope', () => {
+ const event = normalizeSesOutboundEvent({
+ source: 'aws.ses',
+ 'detail-type': 'Email Bounced',
+ resources: [CONFIGURATION_SET_ARN],
+ detail: {
+ mail: { messageId: 'message-id' },
+ bounce: {
+ bounceType: 'Permanent',
+ feedbackId: 'feedback-id',
+ bouncedRecipients: [{ emailAddress: '[email protected]' }],
+ },
+ },
+ });
+
+ expect(event).toEqual({
+ status: 'DELIVERY',
+ delivery: {
+ workspaceId: WORKSPACE_ID,
+ outcome: CAMPAIGN_PROVIDER_OUTCOME.BOUNCED,
+ suppression: {
+ reason: MessageSuppressionReason.BOUNCE,
+ emailAddresses: ['[email protected]'],
+ },
+ providerMessageId: 'message-id',
+ providerEventId: 'feedback-id',
+ },
+ });
+ });
+
+ it('should suppress complained recipients from a raw SES event-publishing envelope', () => {
+ const event = normalizeSesOutboundEvent({
+ eventType: 'Complaint',
+ mail: { messageId: 'message-id', tags: CONFIGURATION_SET_TAGS },
+ complaint: {
+ feedbackId: 'feedback-id',
+ complainedRecipients: [{ emailAddress: '[email protected]' }],
+ },
+ });
+
+ expect(event).toEqual({
+ status: 'DELIVERY',
+ delivery: {
+ workspaceId: WORKSPACE_ID,
+ outcome: CAMPAIGN_PROVIDER_OUTCOME.COMPLAINED,
+ suppression: {
+ reason: MessageSuppressionReason.COMPLAINT,
+ emailAddresses: ['[email protected]'],
+ },
+ providerMessageId: 'message-id',
+ providerEventId: 'feedback-id',
+ },
+ });
+ });
+
+ it('should suppress permanently bounced recipients from a raw SES event-publishing envelope', () => {
+ const event = normalizeSesOutboundEvent({
+ eventType: 'Bounce',
+ mail: { messageId: 'message-id', tags: CONFIGURATION_SET_TAGS },
+ bounce: {
+ bounceType: 'Permanent',
+ bouncedRecipients: [{ emailAddress: '[email protected]' }],
+ },
+ });
+
+ expect(event).toEqual({
+ status: 'DELIVERY',
+ delivery: {
+ workspaceId: WORKSPACE_ID,
+ outcome: CAMPAIGN_PROVIDER_OUTCOME.BOUNCED,
+ suppression: {
+ reason: MessageSuppressionReason.BOUNCE,
+ emailAddresses: ['[email protected]'],
+ },
+ providerMessageId: 'message-id',
+ providerEventId: null,
+ },
+ });
+ });
+
+ it('should record a transient bounce without suppressing the recipient', () => {
+ const event = normalizeSesOutboundEvent({
+ eventType: 'Bounce',
+ mail: { tags: CONFIGURATION_SET_TAGS },
+ bounce: {
+ bounceType: 'Transient',
+ bouncedRecipients: [{ emailAddress: '[email protected]' }],
+ },
+ });
+
+ expect(event).toEqual({
+ status: 'DELIVERY',
+ delivery: {
+ workspaceId: WORKSPACE_ID,
+ outcome: CAMPAIGN_PROVIDER_OUTCOME.SOFT_BOUNCED,
+ suppression: null,
+ providerMessageId: null,
+ providerEventId: null,
+ },
+ });
+ });
+
+ it('should record a delivery from a raw SES event-publishing envelope', () => {
+ const event = normalizeSesOutboundEvent({
+ eventType: 'Delivery',
+ mail: { messageId: 'message-id', tags: CONFIGURATION_SET_TAGS },
+ });
+
+ expect(event).toEqual({
+ status: 'DELIVERY',
+ delivery: {
+ workspaceId: WORKSPACE_ID,
+ outcome: CAMPAIGN_PROVIDER_OUTCOME.DELIVERED,
+ suppression: null,
+ providerMessageId: 'message-id',
+ providerEventId: null,
+ },
+ });
+ });
+
+ it('should map sending status events to a tenant status', () => {
+ const event = normalizeSesOutboundEvent({
+ source: 'aws.ses',
+ 'detail-type': 'Sending Status Disabled',
+ resources: [CONFIGURATION_SET_ARN],
+ });
+
+ expect(event).toEqual({
+ status: 'SENDING_STATE',
+ sendingState: {
+ workspaceId: WORKSPACE_ID,
+ status: EmailingDomainTenantStatus.PAUSED,
+ },
+ });
+ });
+
+ it('should mark an event whose workspace cannot be resolved as unprocessable', () => {
+ const event = normalizeSesOutboundEvent({
+ eventType: 'Complaint',
+ mail: { tags: { 'ses:configuration-set': ['someone-elses-set'] } },
+ complaint: {
+ complainedRecipients: [{ emailAddress: '[email protected]' }],
+ },
+ });
+
+ expect(event).toEqual({
+ status: 'UNPROCESSABLE',
+ eventName: 'Complaint',
+ reason: 'UNRESOLVED_WORKSPACE',
+ });
+ });
+
+ it('should mark an unknown event name as unprocessable', () => {
+ const event = normalizeSesOutboundEvent({
+ eventType: 'DeliveryDelay',
+ mail: { tags: CONFIGURATION_SET_TAGS },
+ });
+
+ expect(event).toEqual({
+ status: 'UNPROCESSABLE',
+ eventName: 'DeliveryDelay',
+ reason: 'UNSUPPORTED_EVENT_NAME',
+ });
+ });
+});
diff --git a/packages/twenty-server/src/modules/messaging-webhooks/drivers/aws-ses/utils/__tests__/resolve-ses-outbound-delivery-outcome.util.spec.ts b/packages/twenty-server/src/modules/messaging-webhooks/drivers/aws-ses/utils/__tests__/resolve-ses-outbound-delivery-outcome.util.spec.ts
new file mode 100644
index 00000000000..64d1bbff5da
--- /dev/null
+++ b/packages/twenty-server/src/modules/messaging-webhooks/drivers/aws-ses/utils/__tests__/resolve-ses-outbound-delivery-outcome.util.spec.ts
@@ -0,0 +1,162 @@
+import { CAMPAIGN_PROVIDER_OUTCOME } from 'src/engine/core-modules/emailing-domain/constants/campaign-provider-outcome.constant';
+import { MessageSuppressionReason } from 'src/engine/core-modules/emailing-domain/types/message-suppression-reason.type';
+import { type SesOutboundEventPayload } from 'src/modules/messaging-webhooks/drivers/aws-ses/types/ses-outbound-event-payload.type';
+import { resolveSesOutboundDeliveryOutcome } from 'src/modules/messaging-webhooks/drivers/aws-ses/utils/resolve-ses-outbound-delivery-outcome.util';
+
+const resolveOutcome = (eventName: string, payload?: SesOutboundEventPayload) =>
+ resolveSesOutboundDeliveryOutcome({ eventName, payload: payload ?? {} });
+
+describe('resolveSesOutboundDeliveryOutcome', () => {
+ it('should record a delivery without suppressing anyone', () => {
+ expect(resolveOutcome('Email Delivered')).toEqual({
+ outcome: CAMPAIGN_PROVIDER_OUTCOME.DELIVERED,
+ suppression: null,
+ providerEventId: null,
+ });
+ });
+
+ it('should record a rejection as a send-side failure', () => {
+ expect(resolveOutcome('Email Rejected')).toEqual({
+ outcome: CAMPAIGN_PROVIDER_OUTCOME.REJECTED,
+ suppression: null,
+ providerEventId: null,
+ });
+ });
+
+ it('should record a rendering failure as a send-side failure', () => {
+ expect(resolveOutcome('Email Rendering Failed')).toEqual({
+ outcome: CAMPAIGN_PROVIDER_OUTCOME.RENDERING_FAILED,
+ suppression: null,
+ providerEventId: null,
+ });
+ });
+
+ it('should suppress the recipients of a permanent bounce', () => {
+ expect(
+ resolveOutcome('Email Bounced', {
+ bounce: {
+ bounceType: 'Permanent',
+ feedbackId: 'feedback-id',
+ bouncedRecipients: [{ emailAddress: '[email protected]' }],
+ },
+ }),
+ ).toEqual({
+ outcome: CAMPAIGN_PROVIDER_OUTCOME.BOUNCED,
+ suppression: {
+ reason: MessageSuppressionReason.BOUNCE,
+ emailAddresses: ['[email protected]'],
+ },
+ providerEventId: 'feedback-id',
+ });
+ });
+
+ it('should record a transient bounce without suppressing the recipient', () => {
+ expect(
+ resolveOutcome('Email Bounced', {
+ bounce: {
+ bounceType: 'Transient',
+ feedbackId: 'feedback-id',
+ bouncedRecipients: [{ emailAddress: '[email protected]' }],
+ },
+ }),
+ ).toEqual({
+ outcome: CAMPAIGN_PROVIDER_OUTCOME.SOFT_BOUNCED,
+ suppression: null,
+ providerEventId: 'feedback-id',
+ });
+ });
+
+ it('should record an undetermined bounce without suppressing the recipient', () => {
+ expect(
+ resolveOutcome('Email Bounced', {
+ bounce: {
+ bounceType: 'Undetermined',
+ bouncedRecipients: [{ emailAddress: '[email protected]' }],
+ },
+ }),
+ ).toEqual({
+ outcome: CAMPAIGN_PROVIDER_OUTCOME.SOFT_BOUNCED,
+ suppression: null,
+ providerEventId: null,
+ });
+ });
+
+ it('should record a permanent bounce carrying no recipient without suppressing', () => {
+ expect(
+ resolveOutcome('Email Bounced', { bounce: { bounceType: 'Permanent' } }),
+ ).toEqual({
+ outcome: CAMPAIGN_PROVIDER_OUTCOME.BOUNCED,
+ suppression: null,
+ providerEventId: null,
+ });
+ });
+
+ it('should suppress the recipients of a complaint', () => {
+ expect(
+ resolveOutcome('Email Complaint Received', {
+ complaint: {
+ feedbackId: 'complaint-id',
+ complainedRecipients: [{ emailAddress: '[email protected]' }],
+ },
+ }),
+ ).toEqual({
+ outcome: CAMPAIGN_PROVIDER_OUTCOME.COMPLAINED,
+ suppression: {
+ reason: MessageSuppressionReason.COMPLAINT,
+ emailAddresses: ['[email protected]'],
+ },
+ providerEventId: 'complaint-id',
+ });
+ });
+
+ it('should resolve the raw SES event-publishing event names too', () => {
+ expect(resolveOutcome('Delivery')).toEqual({
+ outcome: CAMPAIGN_PROVIDER_OUTCOME.DELIVERED,
+ suppression: null,
+ providerEventId: null,
+ });
+ expect(resolveOutcome('Reject')).toEqual({
+ outcome: CAMPAIGN_PROVIDER_OUTCOME.REJECTED,
+ suppression: null,
+ providerEventId: null,
+ });
+ expect(resolveOutcome('Rendering Failure')).toEqual({
+ outcome: CAMPAIGN_PROVIDER_OUTCOME.RENDERING_FAILED,
+ suppression: null,
+ providerEventId: null,
+ });
+ expect(
+ resolveOutcome('Bounce', {
+ bounce: {
+ bounceType: 'Permanent',
+ bouncedRecipients: [{ emailAddress: '[email protected]' }],
+ },
+ }),
+ ).toEqual({
+ outcome: CAMPAIGN_PROVIDER_OUTCOME.BOUNCED,
+ suppression: {
+ reason: MessageSuppressionReason.BOUNCE,
+ emailAddresses: ['[email protected]'],
+ },
+ providerEventId: null,
+ });
+ expect(
+ resolveOutcome('Complaint', {
+ complaint: {
+ complainedRecipients: [{ emailAddress: '[email protected]' }],
+ },
+ }),
+ ).toEqual({
+ outcome: CAMPAIGN_PROVIDER_OUTCOME.COMPLAINED,
+ suppression: {
+ reason: MessageSuppressionReason.COMPLAINT,
+ emailAddresses: ['[email protected]'],
+ },
+ providerEventId: null,
+ });
+ });
+
+ it('should return null for a sending-state event', () => {
+ expect(resolveOutcome('Sending Status Disabled')).toBeNull();
+ });
+});
diff --git a/packages/twenty-server/src/modules/messaging-webhooks/drivers/aws-ses/utils/normalize-ses-outbound-event.util.ts b/packages/twenty-server/src/modules/messaging-webhooks/drivers/aws-ses/utils/normalize-ses-outbound-event.util.ts
new file mode 100644
index 00000000000..8140b8b69ed
--- /dev/null
+++ b/packages/twenty-server/src/modules/messaging-webhooks/drivers/aws-ses/utils/normalize-ses-outbound-event.util.ts
@@ -0,0 +1,123 @@
+import { isDefined } from 'twenty-shared/utils';
+import { type NormalizedOutboundDeliveryEvent } from 'src/modules/messaging-webhooks/types/normalized-outbound-delivery-event.type';
+import { type NormalizedOutboundSendingStateEvent } from 'src/modules/messaging-webhooks/types/normalized-outbound-sending-state-event.type';
+
+import { EmailingDomainTenantStatus } from 'src/engine/core-modules/emailing-domain/drivers/types/emailing-domain-tenant-status.type';
+import { type SesOutboundEventPayload } from 'src/modules/messaging-webhooks/drivers/aws-ses/types/ses-outbound-event-payload.type';
+import { type SesOutboundNotification } from 'src/modules/messaging-webhooks/drivers/aws-ses/types/ses-outbound-notification.type';
+import { resolveSesOutboundDeliveryOutcome } from 'src/modules/messaging-webhooks/drivers/aws-ses/utils/resolve-ses-outbound-delivery-outcome.util';
+import { resolveWorkspaceIdFromAwsSesResources } from 'src/modules/messaging-webhooks/drivers/aws-ses/utils/resolve-workspace-id-from-aws-ses-resources.util';
+import { resolveWorkspaceIdFromSesOutboundPayload } from 'src/modules/messaging-webhooks/drivers/aws-ses/utils/resolve-workspace-id-from-ses-outbound-payload.util';
+
+const resolveSendingStatus = (
+ eventName: string,
+): EmailingDomainTenantStatus | null => {
+ switch (eventName) {
+ case 'Sending Status Enabled':
+ return EmailingDomainTenantStatus.ACTIVE;
+ case 'Sending Status Disabled':
+ return EmailingDomainTenantStatus.PAUSED;
+ default:
+ return null;
+ }
+};
+
+const classifyOutboundEvent = ({
+ eventName,
+ payload,
+ workspaceId,
+}: {
+ eventName: string;
+ payload: SesOutboundEventPayload;
+ workspaceId: string | null;
+}): NormalizedSesOutboundEvent => {
+ const deliveryOutcome = resolveSesOutboundDeliveryOutcome({
+ eventName,
+ payload,
+ });
+
+ if (isDefined(deliveryOutcome)) {
+ if (!isDefined(workspaceId)) {
+ return {
+ status: 'UNPROCESSABLE',
+ eventName,
+ reason: 'UNRESOLVED_WORKSPACE',
+ };
+ }
+
+ return {
+ status: 'DELIVERY',
+ delivery: {
+ workspaceId,
+ outcome: deliveryOutcome.outcome,
+ suppression: deliveryOutcome.suppression,
+ providerMessageId: payload.mail?.messageId ?? null,
+ providerEventId: deliveryOutcome.providerEventId,
+ },
+ };
+ }
+
+ const sendingStatus = resolveSendingStatus(eventName);
+
+ if (!isDefined(sendingStatus)) {
+ return {
+ status: 'UNPROCESSABLE',
+ eventName,
+ reason: 'UNSUPPORTED_EVENT_NAME',
+ };
+ }
+
+ if (!isDefined(workspaceId)) {
+ return {
+ status: 'UNPROCESSABLE',
+ eventName,
+ reason: 'UNRESOLVED_WORKSPACE',
+ };
+ }
+
+ return {
+ status: 'SENDING_STATE',
+ sendingState: { workspaceId, status: sendingStatus },
+ };
+};
+
+type SesOutboundEventUnprocessableReason =
+ | 'UNSUPPORTED_EVENT_NAME'
+ | 'UNRESOLVED_WORKSPACE';
+
+type NormalizedSesOutboundEvent =
+ | {
+ status: 'DELIVERY';
+ delivery: Omit<NormalizedOutboundDeliveryEvent, 'dedupeKey'>;
+ }
+ | {
+ status: 'SENDING_STATE';
+ sendingState: NormalizedOutboundSendingStateEvent;
+ }
+ | {
+ status: 'UNPROCESSABLE';
+ eventName: string;
+ reason: SesOutboundEventUnprocessableReason;
+ };
+
+export const normalizeSesOutboundEvent = (
+ notification: SesOutboundNotification,
+): NormalizedSesOutboundEvent => {
+ if ('detail-type' in notification) {
+ const payload = notification.detail ?? {};
+
+ return classifyOutboundEvent({
+ eventName: notification['detail-type'],
+ payload,
+ workspaceId:
+ resolveWorkspaceIdFromAwsSesResources(notification.resources) ??
+ resolveWorkspaceIdFromSesOutboundPayload(payload),
+ });
+ }
+
+ return classifyOutboundEvent({
+ eventName: notification.eventType,
+ payload: notification,
+ workspaceId: resolveWorkspaceIdFromSesOutboundPayload(notification),
+ });
+};
diff --git a/packages/twenty-server/src/modules/messaging-webhooks/drivers/aws-ses/utils/parse-workspace-id-from-aws-ses-resource-arn.util.ts b/packages/twenty-server/src/modules/messaging-webhooks/drivers/aws-ses/utils/parse-workspace-id-from-aws-ses-resource-arn.util.ts
index 2cbd7cf6b8b..6c5d61ffb16 100644
--- a/packages/twenty-server/src/modules/messaging-webhooks/drivers/aws-ses/utils/parse-workspace-id-from-aws-ses-resource-arn.util.ts
+++ b/packages/twenty-server/src/modules/messaging-webhooks/drivers/aws-ses/utils/parse-workspace-id-from-aws-ses-resource-arn.util.ts
@@ -1,6 +1,7 @@
-import { AWS_SES_RESOURCE_NAME_PREFIX } from 'src/engine/core-modules/emailing-domain/drivers/aws-ses/constants/aws-ses-resource-name-prefix.constant';
import { isDefined } from 'twenty-shared/utils';
+import { parseWorkspaceIdFromAwsSesResourceName } from 'src/modules/messaging-webhooks/drivers/aws-ses/utils/parse-workspace-id-from-aws-ses-resource-name.util';
+
export const parseWorkspaceIdFromAwsSesResourceArn = (
resourceArn: string,
): string | null => {
@@ -17,13 +18,5 @@ export const parseWorkspaceIdFromAwsSesResourceArn = (
return null;
}
- const expectedPrefix = `${AWS_SES_RESOURCE_NAME_PREFIX}-`;
-
- if (!resourceName.startsWith(expectedPrefix)) {
- return null;
- }
-
- const workspaceId = resourceName.slice(expectedPrefix.length);
-
- return workspaceId.length > 0 ? workspaceId : null;
+ return parseWorkspaceIdFromAwsSesResourceName(resourceName);
};
diff --git a/packages/twenty-server/src/modules/messaging-webhooks/drivers/aws-ses/utils/parse-workspace-id-from-aws-ses-resource-name.util.ts b/packages/twenty-server/src/modules/messaging-webhooks/drivers/aws-ses/utils/parse-workspace-id-from-aws-ses-resource-name.util.ts
new file mode 100644
index 00000000000..3b44841ef8e
--- /dev/null
+++ b/packages/twenty-server/src/modules/messaging-webhooks/drivers/aws-ses/utils/parse-workspace-id-from-aws-ses-resource-name.util.ts
@@ -0,0 +1,15 @@
+import { AWS_SES_RESOURCE_NAME_PREFIX } from 'src/engine/core-modules/emailing-domain/drivers/aws-ses/constants/aws-ses-resource-name-prefix.constant';
+
+export const parseWorkspaceIdFromAwsSesResourceName = (
+ resourceName: string,
+): string | null => {
+ const expectedPrefix = `${AWS_SES_RESOURCE_NAME_PREFIX}-`;
+
+ if (!resourceName.startsWith(expectedPrefix)) {
+ return null;
+ }
+
+ const workspaceId = resourceName.slice(expectedPrefix.length);
+
+ return workspaceId.length > 0 ? workspaceId : null;
+};
diff --git a/packages/twenty-server/src/modules/messaging-webhooks/drivers/aws-ses/utils/resolve-ses-outbound-delivery-outcome.util.ts b/packages/twenty-server/src/modules/messaging-webhooks/drivers/aws-ses/utils/resolve-ses-outbound-delivery-outcome.util.ts
new file mode 100644
index 00000000000..349d8bb4373
--- /dev/null
+++ b/packages/twenty-server/src/modules/messaging-webhooks/drivers/aws-ses/utils/resolve-ses-outbound-delivery-outcome.util.ts
@@ -0,0 +1,83 @@
+import { isNonEmptyArray } from 'twenty-shared/utils';
+
+import { CAMPAIGN_PROVIDER_OUTCOME } from 'src/engine/core-modules/emailing-domain/constants/campaign-provider-outcome.constant';
+import { MessageSuppressionReason } from 'src/engine/core-modules/emailing-domain/types/message-suppression-reason.type';
+import { type SesOutboundEventPayload } from 'src/modules/messaging-webhooks/drivers/aws-ses/types/ses-outbound-event-payload.type';
+import { type OutboundDeliveryOutcome } from 'src/modules/messaging-webhooks/types/outbound-delivery-outcome.type';
+
+const extractRecipientAddresses = (
+ recipients: { emailAddress: string }[] | undefined,
+): string[] => (recipients ?? []).map((recipient) => recipient.emailAddress);
+
+export const resolveSesOutboundDeliveryOutcome = ({
+ eventName,
+ payload,
+}: {
+ eventName: string;
+ payload: SesOutboundEventPayload;
+}): OutboundDeliveryOutcome | null => {
+ switch (eventName) {
+ case 'Email Delivered':
+ case 'Delivery':
+ return {
+ outcome: CAMPAIGN_PROVIDER_OUTCOME.DELIVERED,
+ suppression: null,
+ providerEventId: null,
+ };
+ case 'Email Rejected':
+ case 'Reject':
+ return {
+ outcome: CAMPAIGN_PROVIDER_OUTCOME.REJECTED,
+ suppression: null,
+ providerEventId: null,
+ };
+ case 'Email Rendering Failed':
+ case 'Rendering Failure':
+ return {
+ outcome: CAMPAIGN_PROVIDER_OUTCOME.RENDERING_FAILED,
+ suppression: null,
+ providerEventId: null,
+ };
+ case 'Email Bounced':
+ case 'Bounce': {
+ const bounce = payload.bounce;
+ const emailAddresses = extractRecipientAddresses(
+ bounce?.bouncedRecipients,
+ );
+ const providerEventId = bounce?.feedbackId ?? null;
+
+ if (bounce?.bounceType !== 'Permanent') {
+ return {
+ outcome: CAMPAIGN_PROVIDER_OUTCOME.SOFT_BOUNCED,
+ suppression: null,
+ providerEventId,
+ };
+ }
+
+ return {
+ outcome: CAMPAIGN_PROVIDER_OUTCOME.BOUNCED,
+ suppression: isNonEmptyArray(emailAddresses)
+ ? { reason: MessageSuppressionReason.BOUNCE, emailAddresses }
+ : null,
+ providerEventId,
+ };
+ }
+ case 'Email Complaint Received':
+ case 'Complaint': {
+ const complaint = payload.complaint;
+ const emailAddresses = extractRecipientAddresses(
+ complaint?.complainedRecipients,
+ );
+
+ return {
+ outcome: CAMPAIGN_PROVIDER_OUTCOME.COMPLAINED,
+ suppression: isNonEmptyArray(emailAddresses)
+ ? { reason: MessageSuppressionReason.COMPLAINT, emailAddresses }
+ : null,
+ providerEventId: complaint?.feedbackId ?? null,
+ };
+ }
+ default:
+ return null;
+ }
+};
diff --git a/packages/twenty-server/src/modules/messaging-webhooks/drivers/aws-ses/utils/resolve-workspace-id-from-ses-outbound-payload.util.ts b/packages/twenty-server/src/modules/messaging-webhooks/drivers/aws-ses/utils/resolve-workspace-id-from-ses-outbound-payload.util.ts
new file mode 100644
index 00000000000..766c356b9b0
--- /dev/null
+++ b/packages/twenty-server/src/modules/messaging-webhooks/drivers/aws-ses/utils/resolve-workspace-id-from-ses-outbound-payload.util.ts
@@ -0,0 +1,24 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { type SesOutboundEventPayload } from 'src/modules/messaging-webhooks/drivers/aws-ses/types/ses-outbound-event-payload.type';
+import { parseWorkspaceIdFromAwsSesResourceName } from 'src/modules/messaging-webhooks/drivers/aws-ses/utils/parse-workspace-id-from-aws-ses-resource-name.util';
+
+const CONFIGURATION_SET_MAIL_TAG_KEY = 'ses:configuration-set';
+
+export const resolveWorkspaceIdFromSesOutboundPayload = (
+ payload: SesOutboundEventPayload,
+): string | null => {
+ const configurationSetNames =
+ payload.mail?.tags?.[CONFIGURATION_SET_MAIL_TAG_KEY] ?? [];
+
+ for (const configurationSetName of configurationSetNames) {
+ const workspaceId =
+ parseWorkspaceIdFromAwsSesResourceName(configurationSetName);
+
+ if (isDefined(workspaceId)) {
+ return workspaceId;
+ }
+ }
+
+ return null;
+};
diff --git a/packages/twenty-server/src/modules/messaging-webhooks/drivers/resend/services/resend-webhook-driver.service.ts b/packages/twenty-server/src/modules/messaging-webhooks/drivers/resend/services/resend-webhook-driver.service.ts
index 75968be968e..d882974774d 100644
--- a/packages/twenty-server/src/modules/messaging-webhooks/drivers/resend/services/resend-webhook-driver.service.ts
+++ b/packages/twenty-server/src/modules/messaging-webhooks/drivers/resend/services/resend-webhook-driver.service.ts
@@ -1,16 +1,16 @@
import { Injectable, Logger } from '@nestjs/common';
import { isNonEmptyString } from '@sniptt/guards';
-import { isDefined, isNonEmptyArray, parseJson } from 'twenty-shared/utils';
+import { isDefined, parseJson } from 'twenty-shared/utils';
import { RESEND_WORKSPACE_TAG_NAME } from 'src/engine/core-modules/emailing-domain/drivers/resend/constants/resend-workspace-tag-name.constant';
-import { MessageSuppressionReason } from 'src/engine/core-modules/emailing-domain/types/message-suppression-reason.type';
import { ResendWebhookVerifierService } from 'src/modules/messaging-webhooks/drivers/resend/services/resend-webhook-verifier.service';
import { type ResendWebhookHeaders } from 'src/modules/messaging-webhooks/drivers/resend/types/resend-webhook-headers.type';
import { type ResendWebhookEvent } from 'src/modules/messaging-webhooks/drivers/resend/types/resend-webhook-event.type';
import { getResendEventTagValue } from 'src/modules/messaging-webhooks/drivers/resend/utils/get-resend-event-tag-value.util';
+import { resolveResendOutboundDeliveryOutcome } from 'src/modules/messaging-webhooks/drivers/resend/utils/resolve-resend-outbound-delivery-outcome.util';
import { InboundMailHandlerService } from 'src/modules/messaging-webhooks/handlers/inbound-mail-handler.service';
-import { OutboundSuppressionHandlerService } from 'src/modules/messaging-webhooks/handlers/outbound-suppression-handler.service';
+import { OutboundDeliveryEventHandlerService } from 'src/modules/messaging-webhooks/handlers/outbound-delivery-event-handler.service';
import { MessagingWebhookExceptionCode } from 'src/modules/messaging-webhooks/messaging-webhook-exception-code.enum';
import { MessagingWebhookException } from 'src/modules/messaging-webhooks/messaging-webhook.exception';
import { INBOUND_EMAIL_MESSAGE_SOURCE } from 'src/modules/messaging/message-import-manager/drivers/inbound-email/constants/inbound-email-message-source.constant';
@@ -21,13 +21,22 @@ export class ResendWebhookDriverService {
constructor(
private readonly resendWebhookVerifierService: ResendWebhookVerifierService,
- private readonly outboundSuppressionHandlerService: OutboundSuppressionHandlerService,
+ private readonly outboundDeliveryEventHandlerService: OutboundDeliveryEventHandlerService,
private readonly inboundMailHandlerService: InboundMailHandlerService,
) {}
async handle(rawBody: Buffer, headers: ResendWebhookHeaders): Promise<void> {
this.resendWebhookVerifierService.assertSigned(rawBody, headers);
+ const { svixId } = headers;
+
+ if (!isNonEmptyString(svixId)) {
+ throw new MessagingWebhookException(
+ 'Resend webhook payload has no svix-id header',
+ MessagingWebhookExceptionCode.MESSAGING_WEBHOOK_INVALID_PAYLOAD,
+ );
+ }
+
const event = parseJson<ResendWebhookEvent>(rawBody.toString('utf8'));
if (!isDefined(event) || !isNonEmptyString(event.type)) {
@@ -37,39 +46,28 @@ export class ResendWebhookDriverService {
);
}
- switch (event.type) {
- case 'email.bounced':
- if (event.data?.bounce?.type !== 'Permanent') {
- return;
- }
- await this.handleSuppressionEvent(
- event,
- MessageSuppressionReason.BOUNCE,
- );
-
- return;
- case 'email.complained':
- await this.handleSuppressionEvent(
- event,
- MessageSuppressionReason.COMPLAINT,
- );
-
- return;
- case 'email.received':
- await this.handleReceivedEvent(event);
-
- return;
- default:
- return;
+ if (event.type === 'email.received') {
+ await this.handleReceivedEvent(event);
+
+ return;
}
+
+ await this.handleDeliveryEvent({ event, dedupeKey: svixId });
}
- private async handleSuppressionEvent(
- event: ResendWebhookEvent,
- reason:
- | MessageSuppressionReason.BOUNCE
- | MessageSuppressionReason.COMPLAINT,
- ): Promise<void> {
+ private async handleDeliveryEvent({
+ event,
+ dedupeKey,
+ }: {
+ event: ResendWebhookEvent;
+ dedupeKey: string;
+ }): Promise<void> {
+ const deliveryOutcome = resolveResendOutboundDeliveryOutcome(event);
+
+ if (!isDefined(deliveryOutcome)) {
+ return;
+ }
+
const workspaceId = getResendEventTagValue(
event.data?.tags,
RESEND_WORKSPACE_TAG_NAME,
@@ -83,18 +81,13 @@ export class ResendWebhookDriverService {
return;
}
- const emailAddresses = event.data?.to ?? [];
-
- if (!isNonEmptyArray(emailAddresses)) {
- return;
- }
-
- await this.outboundSuppressionHandlerService.handle({
+ await this.outboundDeliveryEventHandlerService.handle({
workspaceId,
- reason,
- emailAddresses,
+ outcome: deliveryOutcome.outcome,
+ suppression: deliveryOutcome.suppression,
providerMessageId: event.data?.email_id ?? null,
- providerEventId: event.data?.email_id ?? null,
+ providerEventId: deliveryOutcome.providerEventId,
+ dedupeKey,
});
}
diff --git a/packages/twenty-server/src/modules/messaging-webhooks/drivers/resend/utils/__tests__/resolve-resend-outbound-delivery-outcome.util.spec.ts b/packages/twenty-server/src/modules/messaging-webhooks/drivers/resend/utils/__tests__/resolve-resend-outbound-delivery-outcome.util.spec.ts
new file mode 100644
index 00000000000..42e78e84fde
--- /dev/null
+++ b/packages/twenty-server/src/modules/messaging-webhooks/drivers/resend/utils/__tests__/resolve-resend-outbound-delivery-outcome.util.spec.ts
@@ -0,0 +1,130 @@
+import { CAMPAIGN_PROVIDER_OUTCOME } from 'src/engine/core-modules/emailing-domain/constants/campaign-provider-outcome.constant';
+import { MessageSuppressionReason } from 'src/engine/core-modules/emailing-domain/types/message-suppression-reason.type';
+import { type ResendWebhookEvent } from 'src/modules/messaging-webhooks/drivers/resend/types/resend-webhook-event.type';
+import { resolveResendOutboundDeliveryOutcome } from 'src/modules/messaging-webhooks/drivers/resend/utils/resolve-resend-outbound-delivery-outcome.util';
+
+const buildEvent = (
+ type: string,
+ data?: ResendWebhookEvent['data'],
+): ResendWebhookEvent => ({ type, data });
+
+describe('resolveResendOutboundDeliveryOutcome', () => {
+ it('should record a delivery without suppressing anyone', () => {
+ expect(
+ resolveResendOutboundDeliveryOutcome(
+ buildEvent('email.delivered', { email_id: 'email-id' }),
+ ),
+ ).toEqual({
+ outcome: CAMPAIGN_PROVIDER_OUTCOME.DELIVERED,
+ suppression: null,
+ providerEventId: 'email-id',
+ });
+ });
+
+ it('should record a send failure without suppressing the recipient', () => {
+ expect(
+ resolveResendOutboundDeliveryOutcome(
+ buildEvent('email.failed', {
+ email_id: 'email-id',
+ }),
+ ),
+ ).toEqual({
+ outcome: CAMPAIGN_PROVIDER_OUTCOME.REJECTED,
+ suppression: null,
+ providerEventId: 'email-id',
+ });
+ });
+
+ it('should suppress the recipients of a permanent bounce', () => {
+ expect(
+ resolveResendOutboundDeliveryOutcome(
+ buildEvent('email.bounced', {
+ email_id: 'email-id',
+ bounce: { type: 'Permanent' },
+ }),
+ ),
+ ).toEqual({
+ outcome: CAMPAIGN_PROVIDER_OUTCOME.BOUNCED,
+ suppression: {
+ reason: MessageSuppressionReason.BOUNCE,
+ emailAddresses: ['[email protected]'],
+ },
+ providerEventId: 'email-id',
+ });
+ });
+
+ it('should record a transient bounce without suppressing the recipient', () => {
+ expect(
+ resolveResendOutboundDeliveryOutcome(
+ buildEvent('email.bounced', {
+ email_id: 'email-id',
+ bounce: { type: 'Transient' },
+ }),
+ ),
+ ).toEqual({
+ outcome: CAMPAIGN_PROVIDER_OUTCOME.SOFT_BOUNCED,
+ suppression: null,
+ providerEventId: 'email-id',
+ });
+ });
+
+ it('should suppress the recipients of a complaint', () => {
+ expect(
+ resolveResendOutboundDeliveryOutcome(
+ buildEvent('email.complained', {
+ email_id: 'email-id',
+ }),
+ ),
+ ).toEqual({
+ outcome: CAMPAIGN_PROVIDER_OUTCOME.COMPLAINED,
+ suppression: {
+ reason: MessageSuppressionReason.COMPLAINT,
+ emailAddresses: ['[email protected]'],
+ },
+ providerEventId: 'email-id',
+ });
+ });
+
+ it('should not suppress anyone when the bounce cannot be attributed to a single recipient', () => {
+ expect(
+ resolveResendOutboundDeliveryOutcome(
+ buildEvent('email.bounced', {
+ email_id: 'email-id',
+ bounce: { type: 'Permanent' },
+ }),
+ ),
+ ).toEqual({
+ outcome: CAMPAIGN_PROVIDER_OUTCOME.BOUNCED,
+ suppression: null,
+ providerEventId: 'email-id',
+ });
+ });
+
+ it('should not suppress the to recipient when a copied address makes the bounce ambiguous', () => {
+ expect(
+ resolveResendOutboundDeliveryOutcome(
+ buildEvent('email.bounced', {
+ email_id: 'email-id',
+ bounce: { type: 'Permanent' },
+ }),
+ ),
+ ).toEqual({
+ outcome: CAMPAIGN_PROVIDER_OUTCOME.BOUNCED,
+ suppression: null,
+ providerEventId: 'email-id',
+ });
+ });
+
+ it('should return null for an inbound event', () => {
+ expect(
+ resolveResendOutboundDeliveryOutcome(buildEvent('email.received')),
+ ).toBeNull();
+ });
+});
diff --git a/packages/twenty-server/src/modules/messaging-webhooks/drivers/resend/utils/resolve-resend-outbound-delivery-outcome.util.ts b/packages/twenty-server/src/modules/messaging-webhooks/drivers/resend/utils/resolve-resend-outbound-delivery-outcome.util.ts
new file mode 100644
index 00000000000..44d69a40fa3
--- /dev/null
+++ b/packages/twenty-server/src/modules/messaging-webhooks/drivers/resend/utils/resolve-resend-outbound-delivery-outcome.util.ts
@@ -0,0 +1,65 @@
+import { isNonEmptyArray } from 'twenty-shared/utils';
+
+import { CAMPAIGN_PROVIDER_OUTCOME } from 'src/engine/core-modules/emailing-domain/constants/campaign-provider-outcome.constant';
+import { MessageSuppressionReason } from 'src/engine/core-modules/emailing-domain/types/message-suppression-reason.type';
+import { type ResendWebhookEvent } from 'src/modules/messaging-webhooks/drivers/resend/types/resend-webhook-event.type';
+import { type OutboundDeliveryOutcome } from 'src/modules/messaging-webhooks/types/outbound-delivery-outcome.type';
+
+export const resolveResendOutboundDeliveryOutcome = (
+ event: ResendWebhookEvent,
+): OutboundDeliveryOutcome | null => {
+ const providerEventId = event.data?.email_id ?? null;
+ const envelopeRecipients = [
+ ...(event.data?.to ?? []),
+ ...(event.data?.cc ?? []),
+ ...(event.data?.bcc ?? []),
+ ];
+ const emailAddresses =
+ envelopeRecipients.length === 1 ? envelopeRecipients : [];
+
+ if (event.type === 'email.delivered') {
+ return {
+ outcome: CAMPAIGN_PROVIDER_OUTCOME.DELIVERED,
+ suppression: null,
+ providerEventId,
+ };
+ }
+
+ if (event.type === 'email.failed') {
+ return {
+ outcome: CAMPAIGN_PROVIDER_OUTCOME.REJECTED,
+ suppression: null,
+ providerEventId,
+ };
+ }
+
+ if (event.type === 'email.bounced') {
+ if (event.data?.bounce?.type !== 'Permanent') {
+ return {
+ outcome: CAMPAIGN_PROVIDER_OUTCOME.SOFT_BOUNCED,
+ suppression: null,
+ providerEventId,
+ };
+ }
+
+ return {
+ outcome: CAMPAIGN_PROVIDER_OUTCOME.BOUNCED,
+ suppression: isNonEmptyArray(emailAddresses)
+ ? { reason: MessageSuppressionReason.BOUNCE, emailAddresses }
+ : null,
+ providerEventId,
+ };
+ }
+
+ if (event.type === 'email.complained') {
+ return {
+ outcome: CAMPAIGN_PROVIDER_OUTCOME.COMPLAINED,
+ suppression: isNonEmptyArray(emailAddresses)
+ ? { reason: MessageSuppressionReason.COMPLAINT, emailAddresses }
+ : null,
+ providerEventId,
+ };
+ }
+
+ return null;
+};
diff --git a/packages/twenty-server/src/modules/messaging-webhooks/handlers/outbound-delivery-event-handler.service.ts b/packages/twenty-server/src/modules/messaging-webhooks/handlers/outbound-delivery-event-handler.service.ts
new file mode 100644
index 00000000000..333731e44c3
--- /dev/null
+++ b/packages/twenty-server/src/modules/messaging-webhooks/handlers/outbound-delivery-event-handler.service.ts
@@ -0,0 +1,30 @@
+import { Injectable } from '@nestjs/common';
+
+import { CAMPAIGN_SEND_RETRY_BACKOFF } from 'src/engine/core-modules/emailing-domain/constants/campaign-send-retry-backoff.constant';
+import { InjectMessageQueue } from 'src/engine/core-modules/message-queue/decorators/message-queue.decorator';
+import { MessageQueue } from 'src/engine/core-modules/message-queue/message-queue.constants';
+import { MessageQueueService } from 'src/engine/core-modules/message-queue/services/message-queue.service';
+import { MessagingOutboundDeliveryEventJob } from 'src/modules/messaging-webhooks/jobs/messaging-outbound-delivery-event.job';
+import { type NormalizedOutboundDeliveryEvent } from 'src/modules/messaging-webhooks/types/normalized-outbound-delivery-event.type';
+
+const DELIVERY_EVENT_RETRY_LIMIT = 5;
+
+@Injectable()
+export class OutboundDeliveryEventHandlerService {
+ constructor(
+ @InjectMessageQueue(MessageQueue.campaignQueue)
+ private readonly messageQueueService: MessageQueueService,
+ ) {}
+
+ async handle(event: NormalizedOutboundDeliveryEvent): Promise<void> {
+ await this.messageQueueService.add<NormalizedOutboundDeliveryEvent>(
+ MessagingOutboundDeliveryEventJob.name,
+ event,
+ {
+ id: event.dedupeKey,
+ retryLimit: DELIVERY_EVENT_RETRY_LIMIT,
+ backoff: CAMPAIGN_SEND_RETRY_BACKOFF,
+ },
+ );
+ }
+}
diff --git a/packages/twenty-server/src/modules/messaging-webhooks/handlers/outbound-delivery-event-processor.service.ts b/packages/twenty-server/src/modules/messaging-webhooks/handlers/outbound-delivery-event-processor.service.ts
new file mode 100644
index 00000000000..7b4d05309af
--- /dev/null
+++ b/packages/twenty-server/src/modules/messaging-webhooks/handlers/outbound-delivery-event-processor.service.ts
@@ -0,0 +1,55 @@
+import { Injectable } from '@nestjs/common';
+
+import { isDefined } from 'twenty-shared/utils';
+
+import { MessageSuppressionSource } from 'src/engine/core-modules/emailing-domain/types/message-suppression-source.type';
+import { MessageCampaignDeliveryFeedbackService } from 'src/modules/emailing/services/message-campaign-delivery-feedback.service';
+import { MessageSuppressionService } from 'src/modules/emailing/services/message-suppression.service';
+import { MessagingWebhookExceptionCode } from 'src/modules/messaging-webhooks/messaging-webhook-exception-code.enum';
+import { MessagingWebhookException } from 'src/modules/messaging-webhooks/messaging-webhook.exception';
+import { type NormalizedOutboundDeliveryEvent } from 'src/modules/messaging-webhooks/types/normalized-outbound-delivery-event.type';
+
+@Injectable()
+export class OutboundDeliveryEventProcessorService {
+ constructor(
+ private readonly messageSuppressionService: MessageSuppressionService,
+ private readonly messageCampaignDeliveryFeedbackService: MessageCampaignDeliveryFeedbackService,
+ ) {}
+
+ async process(event: NormalizedOutboundDeliveryEvent): Promise<void> {
+ const { suppression } = event;
+
+ if (isDefined(suppression)) {
+ const results = await Promise.allSettled(
+ suppression.emailAddresses.map((emailAddress) =>
+ this.messageSuppressionService.suppress({
+ workspaceId: event.workspaceId,
+ emailAddress,
+ reason: suppression.reason,
+ source: MessageSuppressionSource.WEBHOOK,
+ providerEventId: event.providerEventId,
+ }),
+ ),
+ );
+
+ if (results.some((result) => result.status === 'rejected')) {
+ throw new MessagingWebhookException(
+ `Failed to suppress one or more recipients for ${suppression.reason} event in workspace ${event.workspaceId}`,
+ MessagingWebhookExceptionCode.MESSAGING_WEBHOOK_UNHANDLED_ERROR,
+ );
+ }
+ }
+
+ if (!isDefined(event.providerMessageId)) {
+ return;
+ }
+
+ await this.messageCampaignDeliveryFeedbackService.recordProviderOutcomeByProviderMessageId(
+ {
+ workspaceId: event.workspaceId,
+ providerMessageId: event.providerMessageId,
+ outcome: event.outcome,
+ },
+ );
+ }
+}
diff --git a/packages/twenty-server/src/modules/messaging-webhooks/handlers/outbound-suppression-handler.service.ts b/packages/twenty-server/src/modules/messaging-webhooks/handlers/outbound-suppression-handler.service.ts
deleted file mode 100644
index 78d4cbf2d07..00000000000
--- a/packages/twenty-server/src/modules/messaging-webhooks/handlers/outbound-suppression-handler.service.ts
+++ /dev/null
@@ -1,50 +0,0 @@
-import { Injectable } from '@nestjs/common';
-
-import { isDefined } from 'twenty-shared/utils';
-
-import { MessageSuppressionReason } from 'src/engine/core-modules/emailing-domain/types/message-suppression-reason.type';
-import { MessageSuppressionSource } from 'src/engine/core-modules/emailing-domain/types/message-suppression-source.type';
-import { MessageCampaignDeliveryFeedbackService } from 'src/modules/emailing/services/message-campaign-delivery-feedback.service';
-import { MessageSuppressionService } from 'src/modules/emailing/services/message-suppression.service';
-import { type NormalizedOutboundSuppressionEvent } from 'src/modules/messaging-webhooks/types/normalized-outbound-suppression-event.type';
-
-@Injectable()
-export class OutboundSuppressionHandlerService {
- constructor(
- private readonly messageSuppressionService: MessageSuppressionService,
- private readonly messageCampaignDeliveryFeedbackService: MessageCampaignDeliveryFeedbackService,
- ) {}
-
- async handle(event: NormalizedOutboundSuppressionEvent): Promise<void> {
- if (isDefined(event.providerMessageId)) {
- await this.messageCampaignDeliveryFeedbackService.recordProviderOutcomeByProviderMessageId(
- {
- workspaceId: event.workspaceId,
- providerMessageId: event.providerMessageId,
- outcome:
- event.reason === MessageSuppressionReason.COMPLAINT
- ? 'COMPLAINED'
- : 'BOUNCED',
- },
- );
- }
-
- const results = await Promise.allSettled(
- event.emailAddresses.map((emailAddress) =>
- this.messageSuppressionService.suppress({
- workspaceId: event.workspaceId,
- emailAddress,
- reason: event.reason,
- source: MessageSuppressionSource.WEBHOOK,
- providerEventId: event.providerEventId,
- }),
- ),
- );
-
- if (results.some((result) => result.status === 'rejected')) {
- throw new Error(
- `Failed to suppress one or more recipients for ${event.reason} event in workspace ${event.workspaceId}`,
- );
- }
- }
-}
diff --git a/packages/twenty-server/src/modules/messaging-webhooks/jobs/messaging-outbound-delivery-event.job.ts b/packages/twenty-server/src/modules/messaging-webhooks/jobs/messaging-outbound-delivery-event.job.ts
new file mode 100644
index 00000000000..68080892516
--- /dev/null
+++ b/packages/twenty-server/src/modules/messaging-webhooks/jobs/messaging-outbound-delivery-event.job.ts
@@ -0,0 +1,17 @@
+import { Process } from 'src/engine/core-modules/message-queue/decorators/process.decorator';
+import { Processor } from 'src/engine/core-modules/message-queue/decorators/processor.decorator';
+import { MessageQueue } from 'src/engine/core-modules/message-queue/message-queue.constants';
+import { OutboundDeliveryEventProcessorService } from 'src/modules/messaging-webhooks/handlers/outbound-delivery-event-processor.service';
+import { type NormalizedOutboundDeliveryEvent } from 'src/modules/messaging-webhooks/types/normalized-outbound-delivery-event.type';
+
+@Processor(MessageQueue.campaignQueue)
+export class MessagingOutboundDeliveryEventJob {
+ constructor(
+ private readonly outboundDeliveryEventProcessorService: OutboundDeliveryEventProcessorService,
+ ) {}
+
+ @Process(MessagingOutboundDeliveryEventJob.name)
+ async handle(data: NormalizedOutboundDeliveryEvent): Promise<void> {
+ await this.outboundDeliveryEventProcessorService.process(data);
+ }
+}
diff --git a/packages/twenty-server/src/modules/messaging-webhooks/messaging-webhooks.module.ts b/packages/twenty-server/src/modules/messaging-webhooks/messaging-webhooks.module.ts
index bdd72822c66..fd27f3ea058 100644
--- a/packages/twenty-server/src/modules/messaging-webhooks/messaging-webhooks.module.ts
+++ b/packages/twenty-server/src/modules/messaging-webhooks/messaging-webhooks.module.ts
@@ -11,8 +11,10 @@ import { SnsSignatureVerifierService } from 'src/modules/messaging-webhooks/driv
import { SnsSubscriptionConfirmerService } from 'src/modules/messaging-webhooks/drivers/aws-ses/services/sns-subscription-confirmer.service';
import { InboundMailHandlerService } from 'src/modules/messaging-webhooks/handlers/inbound-mail-handler.service';
import { InboundUnsubscribeHandlerService } from 'src/modules/messaging-webhooks/handlers/inbound-unsubscribe-handler.service';
+import { OutboundDeliveryEventHandlerService } from 'src/modules/messaging-webhooks/handlers/outbound-delivery-event-handler.service';
+import { OutboundDeliveryEventProcessorService } from 'src/modules/messaging-webhooks/handlers/outbound-delivery-event-processor.service';
import { OutboundSendingStateHandlerService } from 'src/modules/messaging-webhooks/handlers/outbound-sending-state-handler.service';
-import { OutboundSuppressionHandlerService } from 'src/modules/messaging-webhooks/handlers/outbound-suppression-handler.service';
+import { MessagingOutboundDeliveryEventJob } from 'src/modules/messaging-webhooks/jobs/messaging-outbound-delivery-event.job';
import { MessagingWebhooksController } from 'src/modules/messaging-webhooks/messaging-webhooks.controller';
@Module({
@@ -21,8 +23,10 @@ import { MessagingWebhooksController } from 'src/modules/messaging-webhooks/mess
providers: [
InboundMailHandlerService,
InboundUnsubscribeHandlerService,
+ OutboundDeliveryEventHandlerService,
+ OutboundDeliveryEventProcessorService,
OutboundSendingStateHandlerService,
- OutboundSuppressionHandlerService,
+ MessagingOutboundDeliveryEventJob,
SnsSignatureVerifierService,
SnsSubscriptionConfirmerService,
SesInboundWebhookDriverService,
diff --git a/packages/twenty-server/src/modules/messaging-webhooks/types/normalized-outbound-delivery-event.type.ts b/packages/twenty-server/src/modules/messaging-webhooks/types/normalized-outbound-delivery-event.type.ts
new file mode 100644
index 00000000000..00c07f8e413
--- /dev/null
+++ b/packages/twenty-server/src/modules/messaging-webhooks/types/normalized-outbound-delivery-event.type.ts
@@ -0,0 +1,16 @@
+import { type MessageSuppressionReason } from 'src/engine/core-modules/emailing-domain/types/message-suppression-reason.type';
+import { type CampaignProviderOutcome } from 'src/engine/core-modules/emailing-domain/types/campaign-provider-outcome.type';
+
+export type NormalizedOutboundDeliveryEvent = {
+ workspaceId: string;
+ outcome: CampaignProviderOutcome;
+ suppression: {
+ reason:
+ | MessageSuppressionReason.BOUNCE
+ | MessageSuppressionReason.COMPLAINT;
+ emailAddresses: string[];
+ } | null;
+ providerMessageId: string | null;
+ providerEventId: string | null;
+ dedupeKey: string;
+};
diff --git a/packages/twenty-server/src/modules/messaging-webhooks/types/normalized-outbound-suppression-event.type.ts b/packages/twenty-server/src/modules/messaging-webhooks/types/normalized-outbound-suppression-event.type.ts
deleted file mode 100644
index c1af02f194d..00000000000
--- a/packages/twenty-server/src/modules/messaging-webhooks/types/normalized-outbound-suppression-event.type.ts
+++ /dev/null
@@ -1,9 +0,0 @@
-import { type MessageSuppressionReason } from 'src/engine/core-modules/emailing-domain/types/message-suppression-reason.type';
-
-export type NormalizedOutboundSuppressionEvent = {
- workspaceId: string;
- reason: MessageSuppressionReason.BOUNCE | MessageSuppressionReason.COMPLAINT;
- emailAddresses: string[];
- providerMessageId: string | null;
- providerEventId: string | null;
-};
diff --git a/packages/twenty-server/src/modules/messaging-webhooks/types/outbound-delivery-outcome.type.ts b/packages/twenty-server/src/modules/messaging-webhooks/types/outbound-delivery-outcome.type.ts
new file mode 100644
index 00000000000..5284ffdcbc6
--- /dev/null
+++ b/packages/twenty-server/src/modules/messaging-webhooks/types/outbound-delivery-outcome.type.ts
@@ -0,0 +1,6 @@
+import { type NormalizedOutboundDeliveryEvent } from 'src/modules/messaging-webhooks/types/normalized-outbound-delivery-event.type';
+
+export type OutboundDeliveryOutcome = Pick<
+ NormalizedOutboundDeliveryEvent,
+ 'outcome' | 'suppression' | 'providerEventId'
+>;
diff --git a/packages/twenty-server/test/integration/resend/suites/resend-webhook.integration-spec.ts b/packages/twenty-server/test/integration/resend/suites/resend-webhook.integration-spec.ts
index 5763015720f..91713dbac09 100644
--- a/packages/twenty-server/test/integration/resend/suites/resend-webhook.integration-spec.ts
+++ b/packages/twenty-server/test/integration/resend/suites/resend-webhook.integration-spec.ts
@@ -16,6 +16,10 @@ const SIGNING_SECRET = `whsec_${SECRET_BYTES.toString('base64')}`;
const RESEND_WEBHOOK_PATH = '/webhooks/messaging/resend';
+const SUPPRESSION_WAIT_TIMEOUT_MS = 20_000;
+const SUPPRESSION_POLL_INTERVAL_MS = 250;
+const SUPPRESSION_SETTLE_MS = 5_000;
+
const signRawBody = ({
svixId,
svixTimestamp,
@@ -51,7 +55,7 @@ const postResendWebhook = (
describe('Resend webhook (integration)', () => {
let unsubscribeTokenService: UnsubscribeTokenService;
- const findSuppressionReasons = async (emailAddress: string) => {
+ const readSuppressionReasons = async (emailAddress: string) => {
const suppressions = await getCoreRepository<MessageSuppressionEntity>(
MessageSuppressionEntity,
).findBy({ workspaceId: SEED_APPLE_WORKSPACE_ID, emailAddress });
@@ -59,6 +63,29 @@ describe('Resend webhook (integration)', () => {
return suppressions.map((suppression) => suppression.reason);
};
+ const waitForSuppressionReasons = async (emailAddress: string) => {
+ const deadline = Date.now() + SUPPRESSION_WAIT_TIMEOUT_MS;
+ let reasons = await readSuppressionReasons(emailAddress);
+
+ while (reasons.length === 0 && Date.now() < deadline) {
+ await new Promise((resolve) =>
+ setTimeout(resolve, SUPPRESSION_POLL_INTERVAL_MS),
+ );
+
+ reasons = await readSuppressionReasons(emailAddress);
+ }
+
+ return reasons;
+ };
+
+ const readSuppressionReasonsAfterSettle = async (emailAddress: string) => {
+ await new Promise((resolve) =>
+ setTimeout(resolve, SUPPRESSION_SETTLE_MS),
+ );
+
+ return readSuppressionReasons(emailAddress);
+ };
+
beforeAll(async () => {
await updateConfigVariable({
input: { key: 'RESEND_WEBHOOK_SIGNING_SECRET', value: SIGNING_SECRET },
@@ -86,7 +113,7 @@ describe('Resend webhook (integration)', () => {
);
expect(response.status).toBe(200);
- expect(await findSuppressionReasons(emailAddress)).toEqual([
+ expect(await waitForSuppressionReasons(emailAddress)).toEqual([
MessageSuppressionReason.BOUNCE,
]);
}, 60000);
@@ -106,7 +133,7 @@ describe('Resend webhook (integration)', () => {
);
expect(response.status).toBe(200);
- expect(await findSuppressionReasons(emailAddress)).toEqual([
+ expect(await waitForSuppressionReasons(emailAddress)).toEqual([
MessageSuppressionReason.COMPLAINT,
]);
}, 60000);
@@ -127,7 +154,9 @@ describe('Resend webhook (integration)', () => {
);
expect(response.status).toBe(200);
- expect(await findSuppressionReasons(emailAddress)).toEqual([]);
+ expect(
+ await readSuppressionReasonsAfterSettle(emailAddress),
+ ).toEqual([]);
}, 60000);
it('suppresses nothing for a bounce without a workspace tag', async () => {
@@ -145,7 +174,9 @@ describe('Resend webhook (integration)', () => {
);
expect(response.status).toBe(200);
- expect(await findSuppressionReasons(emailAddress)).toEqual([]);
+ expect(
+ await readSuppressionReasonsAfterSettle(emailAddress),
+ ).toEqual([]);
}, 60000);
it('suppresses the sender of a received email addressed to the unsubscribe mailbox', async () => {
@@ -166,7 +197,7 @@ describe('Resend webhook (integration)', () => {
);
expect(response.status).toBe(200);
- expect(await findSuppressionReasons(emailAddress)).toEqual([
+ expect(await waitForSuppressionReasons(emailAddress)).toEqual([
MessageSuppressionReason.UNSUBSCRIBE,
]);
}, 60000);