Skip to content

The open alternative to Salesforce, designed for AI.

Extract provider-neutral webhook handlers from SES-specific services (#24200)

Félix Malfaita7b46d9ee54a
diff --git a/packages/twenty-server/src/modules/messaging-webhooks/drivers/aws-ses/services/ses-inbound-webhook-driver.service.ts b/packages/twenty-server/src/modules/messaging-webhooks/drivers/aws-ses/services/ses-inbound-webhook-driver.service.ts
new file mode 100644
index 00000000000..45b270e88ef
--- /dev/null
+++ b/packages/twenty-server/src/modules/messaging-webhooks/drivers/aws-ses/services/ses-inbound-webhook-driver.service.ts
@@ -0,0 +1,90 @@
+import { Injectable, Logger } from '@nestjs/common';
+
+import type SnsPayloadValidator from 'sns-payload-validator';
+import { isDefined, parseJson } from 'twenty-shared/utils';
+
+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 SesInboundNotification } from 'src/modules/messaging-webhooks/drivers/aws-ses/types/sns-message.type';
+import { InboundMailHandlerService } from 'src/modules/messaging-webhooks/handlers/inbound-mail-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 { type NormalizedInboundMailNotification } from 'src/modules/messaging-webhooks/types/normalized-inbound-mail-notification.type';
+import { INBOUND_EMAIL_MESSAGE_SOURCE } from 'src/modules/messaging/message-import-manager/drivers/inbound-email/constants/inbound-email-message-source.constant';
+import { type InboundEmailMessageReference } from 'src/modules/messaging/message-import-manager/drivers/inbound-email/types/inbound-email-message-reference.type';
+
+type SnsPayload = SnsPayloadValidator.SnsPayload;
+
+@Injectable()
+export class SesInboundWebhookDriverService {
+ private readonly logger = new Logger(SesInboundWebhookDriverService.name);
+
+ constructor(
+ private readonly snsSignatureVerifierService: SnsSignatureVerifierService,
+ private readonly snsSubscriptionConfirmerService: SnsSubscriptionConfirmerService,
+ private readonly inboundMailHandlerService: InboundMailHandlerService,
+ ) {}
+
+ async handle(rawBody: Buffer): Promise<void> {
+ const payload = parseJson<SnsPayload>(rawBody.toString('utf8'));
+
+ if (!isDefined(payload)) {
+ throw new MessagingWebhookException(
+ 'Invalid SNS payload',
+ MessagingWebhookExceptionCode.MESSAGING_WEBHOOK_INVALID_PAYLOAD,
+ );
+ }
+
+ await this.snsSignatureVerifierService.assertAllowedAndSigned(payload);
+
+ if (
+ payload.Type === 'SubscriptionConfirmation' ||
+ payload.Type === 'UnsubscribeConfirmation'
+ ) {
+ await this.snsSubscriptionConfirmerService.confirm(payload.SubscribeURL);
+
+ return;
+ }
+
+ if (payload.Type !== 'Notification') {
+ return;
+ }
+
+ const notification = parseJson<SesInboundNotification>(payload.Message);
+
+ if (!isDefined(notification)) {
+ throw new MessagingWebhookException(
+ 'Invalid SNS notification message',
+ MessagingWebhookExceptionCode.MESSAGING_WEBHOOK_INVALID_PAYLOAD,
+ );
+ }
+
+ await this.inboundMailHandlerService.handle(
+ this.normalizeNotification(notification, payload.MessageId),
+ );
+ }
+
+ private normalizeNotification(
+ notification: SesInboundNotification,
+ snsMessageId: string,
+ ): NormalizedInboundMailNotification {
+ const action = notification.receipt?.action;
+ const recipients = notification.receipt?.recipients ?? [];
+ const subject = notification.mail?.commonHeaders?.subject ?? null;
+
+ if (action?.type !== 'S3') {
+ this.logger.warn(
+ `SNS message ${snsMessageId} has unsupported action type ${action?.type}`,
+ );
+
+ return { recipients, subject, message: null, dedupeKey: snsMessageId };
+ }
+
+ const message: InboundEmailMessageReference = {
+ source: INBOUND_EMAIL_MESSAGE_SOURCE.SES_S3,
+ reference: action.objectKey,
+ };
+
+ return { recipients, subject, message, dedupeKey: snsMessageId };
+ }
+}
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
new file mode 100644
index 00000000000..a6017b36713
--- /dev/null
+++ b/packages/twenty-server/src/modules/messaging-webhooks/drivers/aws-ses/services/ses-outbound-webhook-driver.service.ts
@@ -0,0 +1,193 @@
+import { Injectable, Logger } from '@nestjs/common';
+
+import type SnsPayloadValidator from 'sns-payload-validator';
+import { isDefined, isNonEmptyArray, 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 { 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 { 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';
+
+type SnsPayload = SnsPayloadValidator.SnsPayload;
+
+@Injectable()
+export class SesOutboundWebhookDriverService {
+ private readonly logger = new Logger(SesOutboundWebhookDriverService.name);
+
+ constructor(
+ private readonly snsSignatureVerifierService: SnsSignatureVerifierService,
+ private readonly snsSubscriptionConfirmerService: SnsSubscriptionConfirmerService,
+ private readonly outboundSuppressionHandlerService: OutboundSuppressionHandlerService,
+ private readonly outboundSendingStateHandlerService: OutboundSendingStateHandlerService,
+ ) {}
+
+ async handle(rawBody: Buffer): Promise<void> {
+ const payload = parseJson<SnsPayload>(rawBody.toString('utf8'));
+
+ if (!isDefined(payload)) {
+ throw new MessagingWebhookException(
+ 'Invalid SNS payload',
+ MessagingWebhookExceptionCode.MESSAGING_WEBHOOK_INVALID_PAYLOAD,
+ );
+ }
+
+ await this.snsSignatureVerifierService.assertAllowedAndSigned(payload);
+
+ if (
+ payload.Type === 'SubscriptionConfirmation' ||
+ payload.Type === 'UnsubscribeConfirmation'
+ ) {
+ await this.snsSubscriptionConfirmerService.confirm(payload.SubscribeURL);
+
+ return;
+ }
+
+ if (payload.Type !== 'Notification') {
+ return;
+ }
+
+ const event = parseJson<SesEventBridgeNotification>(payload.Message);
+
+ if (!isDefined(event)) {
+ 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;
+ }
+
+ 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/services/sns-signature-verifier.service.ts b/packages/twenty-server/src/modules/messaging-webhooks/drivers/aws-ses/services/sns-signature-verifier.service.ts
similarity index 100%
rename from packages/twenty-server/src/modules/messaging-webhooks/services/sns-signature-verifier.service.ts
rename to packages/twenty-server/src/modules/messaging-webhooks/drivers/aws-ses/services/sns-signature-verifier.service.ts
diff --git a/packages/twenty-server/src/modules/messaging-webhooks/services/sns-subscription-confirmer.service.ts b/packages/twenty-server/src/modules/messaging-webhooks/drivers/aws-ses/services/sns-subscription-confirmer.service.ts
similarity index 100%
rename from packages/twenty-server/src/modules/messaging-webhooks/services/sns-subscription-confirmer.service.ts
rename to packages/twenty-server/src/modules/messaging-webhooks/drivers/aws-ses/services/sns-subscription-confirmer.service.ts
diff --git a/packages/twenty-server/src/modules/messaging-webhooks/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
similarity index 100%
rename from packages/twenty-server/src/modules/messaging-webhooks/types/ses-event-bridge-notification.type.ts
rename to packages/twenty-server/src/modules/messaging-webhooks/drivers/aws-ses/types/ses-event-bridge-notification.type.ts
diff --git a/packages/twenty-server/src/modules/messaging-webhooks/types/sns-message.type.ts b/packages/twenty-server/src/modules/messaging-webhooks/drivers/aws-ses/types/sns-message.type.ts
similarity index 100%
rename from packages/twenty-server/src/modules/messaging-webhooks/types/sns-message.type.ts
rename to packages/twenty-server/src/modules/messaging-webhooks/drivers/aws-ses/types/sns-message.type.ts
diff --git a/packages/twenty-server/src/modules/messaging-webhooks/utils/__tests__/parse-workspace-id-from-aws-ses-resource-arn.util.spec.ts b/packages/twenty-server/src/modules/messaging-webhooks/drivers/aws-ses/utils/__tests__/parse-workspace-id-from-aws-ses-resource-arn.util.spec.ts
similarity index 95%
rename from packages/twenty-server/src/modules/messaging-webhooks/utils/__tests__/parse-workspace-id-from-aws-ses-resource-arn.util.spec.ts
rename to packages/twenty-server/src/modules/messaging-webhooks/drivers/aws-ses/utils/__tests__/parse-workspace-id-from-aws-ses-resource-arn.util.spec.ts
index 1fa90ac23ae..6ed8f6d2c2f 100644
--- a/packages/twenty-server/src/modules/messaging-webhooks/utils/__tests__/parse-workspace-id-from-aws-ses-resource-arn.util.spec.ts
+++ b/packages/twenty-server/src/modules/messaging-webhooks/drivers/aws-ses/utils/__tests__/parse-workspace-id-from-aws-ses-resource-arn.util.spec.ts
@@ -1,4 +1,4 @@
-import { parseWorkspaceIdFromAwsSesResourceArn } from 'src/modules/messaging-webhooks/utils/parse-workspace-id-from-aws-ses-resource-arn.util';
+import { parseWorkspaceIdFromAwsSesResourceArn } from 'src/modules/messaging-webhooks/drivers/aws-ses/utils/parse-workspace-id-from-aws-ses-resource-arn.util';
describe('parseWorkspaceIdFromAwsSesResourceArn', () => {
// Tenant ARNs have an AWS-assigned opaque id segment after the tenant name
diff --git a/packages/twenty-server/src/modules/messaging-webhooks/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
similarity index 100%
rename from packages/twenty-server/src/modules/messaging-webhooks/utils/parse-workspace-id-from-aws-ses-resource-arn.util.ts
rename to packages/twenty-server/src/modules/messaging-webhooks/drivers/aws-ses/utils/parse-workspace-id-from-aws-ses-resource-arn.util.ts
diff --git a/packages/twenty-server/src/modules/messaging-webhooks/utils/resolve-workspace-id-from-aws-ses-resources.util.ts b/packages/twenty-server/src/modules/messaging-webhooks/drivers/aws-ses/utils/resolve-workspace-id-from-aws-ses-resources.util.ts
similarity index 84%
rename from packages/twenty-server/src/modules/messaging-webhooks/utils/resolve-workspace-id-from-aws-ses-resources.util.ts
rename to packages/twenty-server/src/modules/messaging-webhooks/drivers/aws-ses/utils/resolve-workspace-id-from-aws-ses-resources.util.ts
index 5d6a84b143b..b35de6d4559 100644
--- a/packages/twenty-server/src/modules/messaging-webhooks/utils/resolve-workspace-id-from-aws-ses-resources.util.ts
+++ b/packages/twenty-server/src/modules/messaging-webhooks/drivers/aws-ses/utils/resolve-workspace-id-from-aws-ses-resources.util.ts
@@ -1,6 +1,6 @@
import { isDefined, isNonEmptyArray } from 'twenty-shared/utils';
-import { parseWorkspaceIdFromAwsSesResourceArn } from 'src/modules/messaging-webhooks/utils/parse-workspace-id-from-aws-ses-resource-arn.util';
+import { parseWorkspaceIdFromAwsSesResourceArn } from 'src/modules/messaging-webhooks/drivers/aws-ses/utils/parse-workspace-id-from-aws-ses-resource-arn.util';
export const resolveWorkspaceIdFromAwsSesResources = (
resources: string[] | undefined,
diff --git a/packages/twenty-server/src/modules/messaging-webhooks/handlers/inbound-mail-handler.service.ts b/packages/twenty-server/src/modules/messaging-webhooks/handlers/inbound-mail-handler.service.ts
new file mode 100644
index 00000000000..9ded40df3ee
--- /dev/null
+++ b/packages/twenty-server/src/modules/messaging-webhooks/handlers/inbound-mail-handler.service.ts
@@ -0,0 +1,58 @@
+import { Injectable, Logger } from '@nestjs/common';
+
+import { isDefined } from 'twenty-shared/utils';
+
+import { UNSUBSCRIBE_MAILBOX_LOCAL_PART } from 'src/engine/core-modules/emailing-domain/constants/unsubscribe-mailbox.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 { InboundUnsubscribeHandlerService } from 'src/modules/messaging-webhooks/handlers/inbound-unsubscribe-handler.service';
+import { type NormalizedInboundMailNotification } from 'src/modules/messaging-webhooks/types/normalized-inbound-mail-notification.type';
+import {
+ MessagingInboundEmailImportJob,
+ type MessagingInboundEmailImportJobData,
+} from 'src/modules/messaging/message-import-manager/jobs/messaging-inbound-email-import.job';
+
+@Injectable()
+export class InboundMailHandlerService {
+ private readonly logger = new Logger(InboundMailHandlerService.name);
+
+ constructor(
+ @InjectMessageQueue(MessageQueue.messagingQueue)
+ private readonly messageQueueService: MessageQueueService,
+ private readonly inboundUnsubscribeHandlerService: InboundUnsubscribeHandlerService,
+ ) {}
+
+ async handle(notification: NormalizedInboundMailNotification): Promise<void> {
+ if (this.isAddressedToUnsubscribeMailbox(notification.recipients)) {
+ await this.inboundUnsubscribeHandlerService.handle(notification.subject);
+
+ return;
+ }
+
+ if (!isDefined(notification.message)) {
+ this.logger.warn(
+ `Inbound mail notification ${notification.dedupeKey} has no retrievable message content`,
+ );
+
+ return;
+ }
+
+ await this.messageQueueService.add<MessagingInboundEmailImportJobData>(
+ MessagingInboundEmailImportJob.name,
+ {
+ s3Key: notification.message.reference,
+ envelopeRecipients: notification.recipients,
+ },
+ { id: notification.dedupeKey },
+ );
+ }
+
+ private isAddressedToUnsubscribeMailbox(recipients: string[]): boolean {
+ return recipients.some(
+ (recipient) =>
+ recipient.split('@')[0]?.toLowerCase() ===
+ UNSUBSCRIBE_MAILBOX_LOCAL_PART,
+ );
+ }
+}
diff --git a/packages/twenty-server/src/modules/messaging-webhooks/services/ses-inbound-unsubscribe-handler.service.ts b/packages/twenty-server/src/modules/messaging-webhooks/handlers/inbound-unsubscribe-handler.service.ts
similarity index 80%
rename from packages/twenty-server/src/modules/messaging-webhooks/services/ses-inbound-unsubscribe-handler.service.ts
rename to packages/twenty-server/src/modules/messaging-webhooks/handlers/inbound-unsubscribe-handler.service.ts
index 46b013f49fc..9b4a27aa9d0 100644
--- a/packages/twenty-server/src/modules/messaging-webhooks/services/ses-inbound-unsubscribe-handler.service.ts
+++ b/packages/twenty-server/src/modules/messaging-webhooks/handlers/inbound-unsubscribe-handler.service.ts
@@ -3,26 +3,21 @@ import { Injectable, Logger } from '@nestjs/common';
import { isNonEmptyString } from '@sniptt/guards';
import { isDefined } from 'twenty-shared/utils';
-import { MessageSuppressionService } from 'src/modules/emailing/services/message-suppression.service';
import { UnsubscribeTokenService } from 'src/engine/core-modules/emailing-domain/services/unsubscribe-token.service';
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 { type SesInboundNotification } from 'src/modules/messaging-webhooks/types/sns-message.type';
+import { MessageSuppressionService } from 'src/modules/emailing/services/message-suppression.service';
@Injectable()
-export class SesInboundUnsubscribeHandlerService {
- private readonly logger = new Logger(
- SesInboundUnsubscribeHandlerService.name,
- );
+export class InboundUnsubscribeHandlerService {
+ private readonly logger = new Logger(InboundUnsubscribeHandlerService.name);
constructor(
private readonly unsubscribeTokenService: UnsubscribeTokenService,
private readonly messageSuppressionService: MessageSuppressionService,
) {}
- async handle(notification: SesInboundNotification): Promise<void> {
- const subject = notification.mail?.commonHeaders?.subject;
-
+ async handle(subject: string | null): Promise<void> {
if (!isNonEmptyString(subject)) {
this.logger.warn('Unsubscribe email received without a token subject');
diff --git a/packages/twenty-server/src/modules/messaging-webhooks/handlers/outbound-sending-state-handler.service.ts b/packages/twenty-server/src/modules/messaging-webhooks/handlers/outbound-sending-state-handler.service.ts
new file mode 100644
index 00000000000..8113153647e
--- /dev/null
+++ b/packages/twenty-server/src/modules/messaging-webhooks/handlers/outbound-sending-state-handler.service.ts
@@ -0,0 +1,18 @@
+import { Injectable } from '@nestjs/common';
+
+import { EmailingDomainTenantStatusService } from 'src/engine/core-modules/emailing-domain/services/emailing-domain-tenant-status.service';
+import { type NormalizedOutboundSendingStateEvent } from 'src/modules/messaging-webhooks/types/normalized-outbound-sending-state-event.type';
+
+@Injectable()
+export class OutboundSendingStateHandlerService {
+ constructor(
+ private readonly emailingDomainTenantStatusService: EmailingDomainTenantStatusService,
+ ) {}
+
+ async handle(event: NormalizedOutboundSendingStateEvent): Promise<void> {
+ await this.emailingDomainTenantStatusService.setTenantStatusForWorkspace(
+ event.workspaceId,
+ event.status,
+ );
+ }
+}
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
new file mode 100644
index 00000000000..a3ff16ef910
--- /dev/null
+++ b/packages/twenty-server/src/modules/messaging-webhooks/handlers/outbound-suppression-handler.service.ts
@@ -0,0 +1,51 @@
+import { Injectable } from '@nestjs/common';
+
+import { isDefined } from 'twenty-shared/utils';
+
+import { CAMPAIGN_MESSAGE_DELIVERY_STATUS } from 'src/engine/core-modules/emailing-domain/constants/campaign.constant';
+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 { MessageCampaignService } from 'src/modules/emailing/services/message-campaign.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 messageCampaignService: MessageCampaignService,
+ ) {}
+
+ async handle(event: NormalizedOutboundSuppressionEvent): Promise<void> {
+ if (isDefined(event.providerMessageId)) {
+ await this.messageCampaignService.recordDeliveryFailureByProviderMessageId(
+ {
+ workspaceId: event.workspaceId,
+ providerMessageId: event.providerMessageId,
+ deliveryStatus:
+ event.reason === MessageSuppressionReason.COMPLAINT
+ ? CAMPAIGN_MESSAGE_DELIVERY_STATUS.COMPLAINED
+ : CAMPAIGN_MESSAGE_DELIVERY_STATUS.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/messaging-webhooks.controller.ts b/packages/twenty-server/src/modules/messaging-webhooks/messaging-webhooks.controller.ts
index 49be8b69f98..6540c6c997e 100644
--- a/packages/twenty-server/src/modules/messaging-webhooks/messaging-webhooks.controller.ts
+++ b/packages/twenty-server/src/modules/messaging-webhooks/messaging-webhooks.controller.ts
@@ -10,22 +10,22 @@ import {
import { type Request } from 'express';
import { ApiPath } from 'twenty-shared/types';
+import { isDefined } from 'twenty-shared/utils';
+import { NoPermissionGuard } from 'src/engine/guards/no-permission.guard';
+import { PublicEndpointGuard } from 'src/engine/guards/public-endpoint.guard';
+import { SesInboundWebhookDriverService } from 'src/modules/messaging-webhooks/drivers/aws-ses/services/ses-inbound-webhook-driver.service';
+import { SesOutboundWebhookDriverService } from 'src/modules/messaging-webhooks/drivers/aws-ses/services/ses-outbound-webhook-driver.service';
import { MessagingWebhookApiExceptionFilter } from 'src/modules/messaging-webhooks/filters/messaging-webhook-api-exception.filter';
import { MessagingWebhookExceptionCode } from 'src/modules/messaging-webhooks/messaging-webhook-exception-code.enum';
import { MessagingWebhookException } from 'src/modules/messaging-webhooks/messaging-webhook.exception';
-import { SesInboundWebhookRouterService } from 'src/modules/messaging-webhooks/services/ses-inbound-webhook-router.service';
-import { SesOutboundWebhookRouterService } from 'src/modules/messaging-webhooks/services/ses-outbound-webhook-router.service';
-import { NoPermissionGuard } from 'src/engine/guards/no-permission.guard';
-import { PublicEndpointGuard } from 'src/engine/guards/public-endpoint.guard';
-import { isDefined } from 'twenty-shared/utils';
@Controller()
@UseFilters(MessagingWebhookApiExceptionFilter)
export class MessagingWebhooksController {
constructor(
- private readonly sesInboundWebhookRouterService: SesInboundWebhookRouterService,
- private readonly sesOutboundWebhookRouterService: SesOutboundWebhookRouterService,
+ private readonly sesInboundWebhookDriverService: SesInboundWebhookDriverService,
+ private readonly sesOutboundWebhookDriverService: SesOutboundWebhookDriverService,
) {}
@Post(`${ApiPath.Webhooks}/messaging/ses/inbound`)
@@ -41,7 +41,7 @@ export class MessagingWebhooksController {
);
}
- await this.sesInboundWebhookRouterService.route(request.rawBody);
+ await this.sesInboundWebhookDriverService.handle(request.rawBody);
}
@Post(`${ApiPath.Webhooks}/messaging/ses/outbound`)
@@ -57,6 +57,6 @@ export class MessagingWebhooksController {
);
}
- await this.sesOutboundWebhookRouterService.route(request.rawBody);
+ await this.sesOutboundWebhookDriverService.handle(request.rawBody);
}
}
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 25c3d62648d..a475d76d501 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
@@ -1,30 +1,30 @@
import { Module } from '@nestjs/common';
import { EmailingDomainModule } from 'src/engine/core-modules/emailing-domain/emailing-domain.module';
+import { TwentyConfigModule } from 'src/engine/core-modules/twenty-config/twenty-config.module';
import { EmailingModule } from 'src/modules/emailing/emailing.module';
+import { SesInboundWebhookDriverService } from 'src/modules/messaging-webhooks/drivers/aws-ses/services/ses-inbound-webhook-driver.service';
+import { SesOutboundWebhookDriverService } from 'src/modules/messaging-webhooks/drivers/aws-ses/services/ses-outbound-webhook-driver.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 { InboundMailHandlerService } from 'src/modules/messaging-webhooks/handlers/inbound-mail-handler.service';
+import { InboundUnsubscribeHandlerService } from 'src/modules/messaging-webhooks/handlers/inbound-unsubscribe-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 { MessagingWebhooksController } from 'src/modules/messaging-webhooks/messaging-webhooks.controller';
-import { SesInboundMailHandlerService } from 'src/modules/messaging-webhooks/services/ses-inbound-mail-handler.service';
-import { SesInboundUnsubscribeHandlerService } from 'src/modules/messaging-webhooks/services/ses-inbound-unsubscribe-handler.service';
-import { SesInboundWebhookRouterService } from 'src/modules/messaging-webhooks/services/ses-inbound-webhook-router.service';
-import { SesOutboundSendingStateHandlerService } from 'src/modules/messaging-webhooks/services/ses-outbound-sending-state-handler.service';
-import { SesOutboundSuppressionHandlerService } from 'src/modules/messaging-webhooks/services/ses-outbound-suppression-handler.service';
-import { SesOutboundWebhookRouterService } from 'src/modules/messaging-webhooks/services/ses-outbound-webhook-router.service';
-import { SnsSignatureVerifierService } from 'src/modules/messaging-webhooks/services/sns-signature-verifier.service';
-import { SnsSubscriptionConfirmerService } from 'src/modules/messaging-webhooks/services/sns-subscription-confirmer.service';
-import { TwentyConfigModule } from 'src/engine/core-modules/twenty-config/twenty-config.module';
@Module({
imports: [TwentyConfigModule, EmailingDomainModule, EmailingModule],
controllers: [MessagingWebhooksController],
providers: [
+ InboundMailHandlerService,
+ InboundUnsubscribeHandlerService,
+ OutboundSendingStateHandlerService,
+ OutboundSuppressionHandlerService,
SnsSignatureVerifierService,
SnsSubscriptionConfirmerService,
- SesInboundMailHandlerService,
- SesInboundUnsubscribeHandlerService,
- SesOutboundSendingStateHandlerService,
- SesOutboundSuppressionHandlerService,
- SesInboundWebhookRouterService,
- SesOutboundWebhookRouterService,
+ SesInboundWebhookDriverService,
+ SesOutboundWebhookDriverService,
],
})
export class MessagingWebhooksModule {}
diff --git a/packages/twenty-server/src/modules/messaging-webhooks/services/ses-inbound-mail-handler.service.ts b/packages/twenty-server/src/modules/messaging-webhooks/services/ses-inbound-mail-handler.service.ts
deleted file mode 100644
index 65f48b188a7..00000000000
--- a/packages/twenty-server/src/modules/messaging-webhooks/services/ses-inbound-mail-handler.service.ts
+++ /dev/null
@@ -1,63 +0,0 @@
-import { Injectable, Logger } from '@nestjs/common';
-
-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 { SesInboundUnsubscribeHandlerService } from 'src/modules/messaging-webhooks/services/ses-inbound-unsubscribe-handler.service';
-import { type SesInboundNotification } from 'src/modules/messaging-webhooks/types/sns-message.type';
-import { resolveInboundMailIntent } from 'src/modules/messaging-webhooks/utils/resolve-inbound-mail-intent.util';
-import {
- MessagingInboundEmailImportJob,
- type MessagingInboundEmailImportJobData,
-} from 'src/modules/messaging/message-import-manager/jobs/messaging-inbound-email-import.job';
-
-@Injectable()
-export class SesInboundMailHandlerService {
- private readonly logger = new Logger(SesInboundMailHandlerService.name);
-
- constructor(
- @InjectMessageQueue(MessageQueue.messagingQueue)
- private readonly messageQueueService: MessageQueueService,
- private readonly sesInboundUnsubscribeHandlerService: SesInboundUnsubscribeHandlerService,
- ) {}
-
- async handle(
- notification: SesInboundNotification,
- snsMessageId: string,
- ): Promise<void> {
- switch (resolveInboundMailIntent(notification)) {
- case 'UNSUBSCRIBE':
- await this.sesInboundUnsubscribeHandlerService.handle(notification);
-
- return;
- case 'IMPORT':
- await this.enqueueInboundEmailImport(notification, snsMessageId);
-
- return;
- }
- }
-
- private async enqueueInboundEmailImport(
- notification: SesInboundNotification,
- snsMessageId: string,
- ): Promise<void> {
- const { receipt } = notification;
-
- if (receipt?.action?.type !== 'S3') {
- this.logger.warn(
- `SNS message ${snsMessageId} has unsupported action type ${receipt?.action?.type}`,
- );
-
- return;
- }
-
- await this.messageQueueService.add<MessagingInboundEmailImportJobData>(
- MessagingInboundEmailImportJob.name,
- {
- s3Key: receipt.action.objectKey,
- envelopeRecipients: receipt.recipients,
- },
- { id: snsMessageId },
- );
- }
-}
diff --git a/packages/twenty-server/src/modules/messaging-webhooks/services/ses-inbound-webhook-router.service.ts b/packages/twenty-server/src/modules/messaging-webhooks/services/ses-inbound-webhook-router.service.ts
deleted file mode 100644
index 91856ce2249..00000000000
--- a/packages/twenty-server/src/modules/messaging-webhooks/services/ses-inbound-webhook-router.service.ts
+++ /dev/null
@@ -1,62 +0,0 @@
-import { Injectable } from '@nestjs/common';
-
-import type SnsPayloadValidator from 'sns-payload-validator';
-import { isDefined, parseJson } from 'twenty-shared/utils';
-
-import { MessagingWebhookExceptionCode } from 'src/modules/messaging-webhooks/messaging-webhook-exception-code.enum';
-import { MessagingWebhookException } from 'src/modules/messaging-webhooks/messaging-webhook.exception';
-import { SesInboundMailHandlerService } from 'src/modules/messaging-webhooks/services/ses-inbound-mail-handler.service';
-import { SnsSignatureVerifierService } from 'src/modules/messaging-webhooks/services/sns-signature-verifier.service';
-import { SnsSubscriptionConfirmerService } from 'src/modules/messaging-webhooks/services/sns-subscription-confirmer.service';
-import { type SesInboundNotification } from 'src/modules/messaging-webhooks/types/sns-message.type';
-
-type SnsPayload = SnsPayloadValidator.SnsPayload;
-
-@Injectable()
-export class SesInboundWebhookRouterService {
- constructor(
- private readonly snsSignatureVerifierService: SnsSignatureVerifierService,
- private readonly snsSubscriptionConfirmerService: SnsSubscriptionConfirmerService,
- private readonly sesInboundMailHandlerService: SesInboundMailHandlerService,
- ) {}
-
- async route(rawBody: Buffer): Promise<void> {
- const payload = parseJson<SnsPayload>(rawBody.toString('utf8'));
-
- if (!isDefined(payload)) {
- throw new MessagingWebhookException(
- 'Invalid SNS payload',
- MessagingWebhookExceptionCode.MESSAGING_WEBHOOK_INVALID_PAYLOAD,
- );
- }
-
- await this.snsSignatureVerifierService.assertAllowedAndSigned(payload);
-
- if (
- payload.Type === 'SubscriptionConfirmation' ||
- payload.Type === 'UnsubscribeConfirmation'
- ) {
- await this.snsSubscriptionConfirmerService.confirm(payload.SubscribeURL);
-
- return;
- }
-
- if (payload.Type !== 'Notification') {
- return;
- }
-
- const notification = parseJson<SesInboundNotification>(payload.Message);
-
- if (!isDefined(notification)) {
- throw new MessagingWebhookException(
- 'Invalid SNS notification message',
- MessagingWebhookExceptionCode.MESSAGING_WEBHOOK_INVALID_PAYLOAD,
- );
- }
-
- await this.sesInboundMailHandlerService.handle(
- notification,
- payload.MessageId,
- );
- }
-}
diff --git a/packages/twenty-server/src/modules/messaging-webhooks/services/ses-outbound-sending-state-handler.service.ts b/packages/twenty-server/src/modules/messaging-webhooks/services/ses-outbound-sending-state-handler.service.ts
deleted file mode 100644
index 60f61f824ea..00000000000
--- a/packages/twenty-server/src/modules/messaging-webhooks/services/ses-outbound-sending-state-handler.service.ts
+++ /dev/null
@@ -1,40 +0,0 @@
-import { Injectable, Logger } from '@nestjs/common';
-
-import { EmailingDomainTenantStatus } from 'src/engine/core-modules/emailing-domain/drivers/types/emailing-domain-tenant-status.type';
-import { EmailingDomainTenantStatusService } from 'src/engine/core-modules/emailing-domain/services/emailing-domain-tenant-status.service';
-import { type SesEventBridgeNotification } from 'src/modules/messaging-webhooks/types/ses-event-bridge-notification.type';
-import { resolveWorkspaceIdFromAwsSesResources } from 'src/modules/messaging-webhooks/utils/resolve-workspace-id-from-aws-ses-resources.util';
-import { isDefined } from 'twenty-shared/utils';
-
-@Injectable()
-export class SesOutboundSendingStateHandlerService {
- private readonly logger = new Logger(
- SesOutboundSendingStateHandlerService.name,
- );
-
- constructor(
- private readonly emailingDomainTenantStatusService: EmailingDomainTenantStatusService,
- ) {}
-
- async handle(event: SesEventBridgeNotification): Promise<void> {
- const targetStatus =
- event['detail-type'] === 'Sending Status Enabled'
- ? EmailingDomainTenantStatus.ACTIVE
- : EmailingDomainTenantStatus.PAUSED;
-
- 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.emailingDomainTenantStatusService.setTenantStatusForWorkspace(
- workspaceId,
- targetStatus,
- );
- }
-}
diff --git a/packages/twenty-server/src/modules/messaging-webhooks/services/ses-outbound-suppression-handler.service.ts b/packages/twenty-server/src/modules/messaging-webhooks/services/ses-outbound-suppression-handler.service.ts
deleted file mode 100644
index 99ad64fa80b..00000000000
--- a/packages/twenty-server/src/modules/messaging-webhooks/services/ses-outbound-suppression-handler.service.ts
+++ /dev/null
@@ -1,129 +0,0 @@
-import { Injectable, Logger } from '@nestjs/common';
-
-import { isDefined, isNonEmptyArray } from 'twenty-shared/utils';
-
-import { CAMPAIGN_MESSAGE_DELIVERY_STATUS } from 'src/engine/core-modules/emailing-domain/constants/campaign.constant';
-import { MessageCampaignService } from 'src/modules/emailing/services/message-campaign.service';
-import { MessageSuppressionService } from 'src/modules/emailing/services/message-suppression.service';
-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 { type SesEventBridgeNotification } from 'src/modules/messaging-webhooks/types/ses-event-bridge-notification.type';
-import { resolveWorkspaceIdFromAwsSesResources } from 'src/modules/messaging-webhooks/utils/resolve-workspace-id-from-aws-ses-resources.util';
-
-@Injectable()
-export class SesOutboundSuppressionHandlerService {
- private readonly logger = new Logger(
- SesOutboundSuppressionHandlerService.name,
- );
-
- constructor(
- private readonly messageSuppressionService: MessageSuppressionService,
- private readonly messageCampaignService: MessageCampaignService,
- ) {}
-
- async handle(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;
- }
-
- const providerMessageId = event.detail?.mail?.messageId;
-
- if (isDefined(providerMessageId)) {
- await this.messageCampaignService.recordDeliveryFailureByProviderMessageId(
- {
- workspaceId,
- providerMessageId,
- deliveryStatus:
- event['detail-type'] === 'Email Complaint Received'
- ? CAMPAIGN_MESSAGE_DELIVERY_STATUS.COMPLAINED
- : CAMPAIGN_MESSAGE_DELIVERY_STATUS.BOUNCED,
- },
- );
- }
-
- const results = await Promise.allSettled(
- suppression.emailAddresses.map((emailAddress) =>
- this.messageSuppressionService.suppress({
- workspaceId,
- emailAddress,
- reason: suppression.reason,
- source: MessageSuppressionSource.WEBHOOK,
- providerEventId: suppression.providerEventId,
- }),
- ),
- );
-
- if (results.some((result) => result.status === 'rejected')) {
- throw new Error(
- `Failed to suppress one or more recipients for ${event['detail-type']} event in workspace ${workspaceId}`,
- );
- }
- }
-
- private resolveSuppression(event: SesEventBridgeNotification): {
- reason: MessageSuppressionReason;
- 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/services/ses-outbound-webhook-router.service.ts b/packages/twenty-server/src/modules/messaging-webhooks/services/ses-outbound-webhook-router.service.ts
deleted file mode 100644
index 92c03c52552..00000000000
--- a/packages/twenty-server/src/modules/messaging-webhooks/services/ses-outbound-webhook-router.service.ts
+++ /dev/null
@@ -1,70 +0,0 @@
-import { Injectable } from '@nestjs/common';
-
-import type SnsPayloadValidator from 'sns-payload-validator';
-import { isDefined, parseJson } from 'twenty-shared/utils';
-
-import { MessagingWebhookExceptionCode } from 'src/modules/messaging-webhooks/messaging-webhook-exception-code.enum';
-import { MessagingWebhookException } from 'src/modules/messaging-webhooks/messaging-webhook.exception';
-import { SesOutboundSendingStateHandlerService } from 'src/modules/messaging-webhooks/services/ses-outbound-sending-state-handler.service';
-import { SesOutboundSuppressionHandlerService } from 'src/modules/messaging-webhooks/services/ses-outbound-suppression-handler.service';
-import { SnsSignatureVerifierService } from 'src/modules/messaging-webhooks/services/sns-signature-verifier.service';
-import { SnsSubscriptionConfirmerService } from 'src/modules/messaging-webhooks/services/sns-subscription-confirmer.service';
-import { type SesEventBridgeNotification } from 'src/modules/messaging-webhooks/types/ses-event-bridge-notification.type';
-
-type SnsPayload = SnsPayloadValidator.SnsPayload;
-
-@Injectable()
-export class SesOutboundWebhookRouterService {
- constructor(
- private readonly snsSignatureVerifierService: SnsSignatureVerifierService,
- private readonly snsSubscriptionConfirmerService: SnsSubscriptionConfirmerService,
- private readonly sesOutboundSendingStateHandlerService: SesOutboundSendingStateHandlerService,
- private readonly sesOutboundSuppressionHandlerService: SesOutboundSuppressionHandlerService,
- ) {}
-
- async route(rawBody: Buffer): Promise<void> {
- const payload = parseJson<SnsPayload>(rawBody.toString('utf8'));
-
- if (!isDefined(payload)) {
- throw new MessagingWebhookException(
- 'Invalid SNS payload',
- MessagingWebhookExceptionCode.MESSAGING_WEBHOOK_INVALID_PAYLOAD,
- );
- }
-
- await this.snsSignatureVerifierService.assertAllowedAndSigned(payload);
-
- if (
- payload.Type === 'SubscriptionConfirmation' ||
- payload.Type === 'UnsubscribeConfirmation'
- ) {
- await this.snsSubscriptionConfirmerService.confirm(payload.SubscribeURL);
-
- return;
- }
-
- if (payload.Type !== 'Notification') {
- return;
- }
-
- const event = parseJson<SesEventBridgeNotification>(payload.Message);
-
- if (!isDefined(event)) {
- 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.sesOutboundSuppressionHandlerService.handle(event);
-
- return;
- }
-
- await this.sesOutboundSendingStateHandlerService.handle(event);
- }
-}
diff --git a/packages/twenty-server/src/modules/messaging-webhooks/types/normalized-inbound-mail-notification.type.ts b/packages/twenty-server/src/modules/messaging-webhooks/types/normalized-inbound-mail-notification.type.ts
new file mode 100644
index 00000000000..f51c165aa4b
--- /dev/null
+++ b/packages/twenty-server/src/modules/messaging-webhooks/types/normalized-inbound-mail-notification.type.ts
@@ -0,0 +1,8 @@
+import { type InboundEmailMessageReference } from 'src/modules/messaging/message-import-manager/drivers/inbound-email/types/inbound-email-message-reference.type';
+
+export type NormalizedInboundMailNotification = {
+ recipients: string[];
+ subject: string | null;
+ message: InboundEmailMessageReference | null;
+ dedupeKey: string;
+};
diff --git a/packages/twenty-server/src/modules/messaging-webhooks/types/normalized-outbound-sending-state-event.type.ts b/packages/twenty-server/src/modules/messaging-webhooks/types/normalized-outbound-sending-state-event.type.ts
new file mode 100644
index 00000000000..3291b6def34
--- /dev/null
+++ b/packages/twenty-server/src/modules/messaging-webhooks/types/normalized-outbound-sending-state-event.type.ts
@@ -0,0 +1,6 @@
+import { type EmailingDomainTenantStatus } from 'src/engine/core-modules/emailing-domain/drivers/types/emailing-domain-tenant-status.type';
+
+export type NormalizedOutboundSendingStateEvent = {
+ workspaceId: string;
+ status: EmailingDomainTenantStatus;
+};
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
new file mode 100644
index 00000000000..c1af02f194d
--- /dev/null
+++ b/packages/twenty-server/src/modules/messaging-webhooks/types/normalized-outbound-suppression-event.type.ts
@@ -0,0 +1,9 @@
+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/ses-inbound-mail-intent.type.ts b/packages/twenty-server/src/modules/messaging-webhooks/types/ses-inbound-mail-intent.type.ts
deleted file mode 100644
index edf409cd281..00000000000
--- a/packages/twenty-server/src/modules/messaging-webhooks/types/ses-inbound-mail-intent.type.ts
+++ /dev/null
@@ -1 +0,0 @@
-export type SesInboundMailIntent = 'UNSUBSCRIBE' | 'IMPORT';
diff --git a/packages/twenty-server/src/modules/messaging-webhooks/utils/resolve-inbound-mail-intent.util.ts b/packages/twenty-server/src/modules/messaging-webhooks/utils/resolve-inbound-mail-intent.util.ts
deleted file mode 100644
index e2abdadfc02..00000000000
--- a/packages/twenty-server/src/modules/messaging-webhooks/utils/resolve-inbound-mail-intent.util.ts
+++ /dev/null
@@ -1,16 +0,0 @@
-import { UNSUBSCRIBE_MAILBOX_LOCAL_PART } from 'src/engine/core-modules/emailing-domain/constants/unsubscribe-mailbox.constant';
-import { type SesInboundMailIntent } from 'src/modules/messaging-webhooks/types/ses-inbound-mail-intent.type';
-import { type SesInboundNotification } from 'src/modules/messaging-webhooks/types/sns-message.type';
-
-export const resolveInboundMailIntent = (
- notification: SesInboundNotification,
-): SesInboundMailIntent => {
- const isAddressedToUnsubscribeMailbox = (
- notification.receipt?.recipients ?? []
- ).some(
- (recipient) =>
- recipient.split('@')[0]?.toLowerCase() === UNSUBSCRIBE_MAILBOX_LOCAL_PART,
- );
-
- return isAddressedToUnsubscribeMailbox ? 'UNSUBSCRIBE' : 'IMPORT';
-};
diff --git a/packages/twenty-server/src/modules/messaging/message-import-manager/drivers/inbound-email/constants/inbound-email-message-source.constant.ts b/packages/twenty-server/src/modules/messaging/message-import-manager/drivers/inbound-email/constants/inbound-email-message-source.constant.ts
new file mode 100644
index 00000000000..16e4175ba9d
--- /dev/null
+++ b/packages/twenty-server/src/modules/messaging/message-import-manager/drivers/inbound-email/constants/inbound-email-message-source.constant.ts
@@ -0,0 +1,3 @@
+export const INBOUND_EMAIL_MESSAGE_SOURCE = {
+ SES_S3: 'SES_S3',
+} as const;
diff --git a/packages/twenty-server/src/modules/messaging/message-import-manager/drivers/inbound-email/types/inbound-email-message-reference.type.ts b/packages/twenty-server/src/modules/messaging/message-import-manager/drivers/inbound-email/types/inbound-email-message-reference.type.ts
new file mode 100644
index 00000000000..dfe8511e8c0
--- /dev/null
+++ b/packages/twenty-server/src/modules/messaging/message-import-manager/drivers/inbound-email/types/inbound-email-message-reference.type.ts
@@ -0,0 +1,6 @@
+import { type InboundEmailMessageSource } from 'src/modules/messaging/message-import-manager/drivers/inbound-email/types/inbound-email-message-source.type';
+
+export type InboundEmailMessageReference = {
+ source: InboundEmailMessageSource;
+ reference: string;
+};
diff --git a/packages/twenty-server/src/modules/messaging/message-import-manager/drivers/inbound-email/types/inbound-email-message-source.type.ts b/packages/twenty-server/src/modules/messaging/message-import-manager/drivers/inbound-email/types/inbound-email-message-source.type.ts
new file mode 100644
index 00000000000..ea6d1c058f0
--- /dev/null
+++ b/packages/twenty-server/src/modules/messaging/message-import-manager/drivers/inbound-email/types/inbound-email-message-source.type.ts
@@ -0,0 +1,4 @@
+import { type INBOUND_EMAIL_MESSAGE_SOURCE } from 'src/modules/messaging/message-import-manager/drivers/inbound-email/constants/inbound-email-message-source.constant';
+
+export type InboundEmailMessageSource =
+ (typeof INBOUND_EMAIL_MESSAGE_SOURCE)[keyof typeof INBOUND_EMAIL_MESSAGE_SOURCE];