The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Add Resend as a community emailing domain driver (#24202)
Félix Malfait0f5fc0c4ee57
diff --git a/packages/twenty-front/src/generated-admin/graphql.ts b/packages/twenty-front/src/generated-admin/graphql.tsindex b4eda91c5bd..9b560bb76eb 100644--- a/packages/twenty-front/src/generated-admin/graphql.ts+++ b/packages/twenty-front/src/generated-admin/graphql.ts@@ -363,6 +363,7 @@ export enum ConfigVariablesGroup {LOGIC_FUNCTION_CONFIG = 'LOGIC_FUNCTION_CONFIG',MICROSOFT_AUTH = 'MICROSOFT_AUTH',RATE_LIMITING = 'RATE_LIMITING',+ RESEND_SETTINGS = 'RESEND_SETTINGS',SERVER_CONFIG = 'SERVER_CONFIG',SSL = 'SSL',STORAGE_CONFIG = 'STORAGE_CONFIG',diff --git a/packages/twenty-front/src/pages/settings/communications/SettingsWorkspaceCommunicationGroupChannelDetail.tsx b/packages/twenty-front/src/pages/settings/communications/SettingsWorkspaceCommunicationGroupChannelDetail.tsxindex e45ec188f03..94f19ccfabf 100644--- a/packages/twenty-front/src/pages/settings/communications/SettingsWorkspaceCommunicationGroupChannelDetail.tsx+++ b/packages/twenty-front/src/pages/settings/communications/SettingsWorkspaceCommunicationGroupChannelDetail.tsx@@ -112,19 +112,9 @@ export const SettingsWorkspaceCommunicationGroupChannelDetail = () => {}),);- const isDomainVerified =- verificationRecords.length > 0 &&- verificationRecords.every((record) => record.status === 'success');+ const domainStatus = emailingDomain?.status ?? EmailingDomainStatus.PENDING;- const hasFailedRecord = verificationRecords.some(- (record) => record.status === 'error',- );-- const domainStatus = isDomainVerified- ? EmailingDomainStatus.VERIFIED- : hasFailedRecord- ? EmailingDomainStatus.FAILED- : EmailingDomainStatus.PENDING;+ const isDomainVerified = domainStatus === EmailingDomainStatus.VERIFIED;const displayName = channel.displayName ?? '';diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/constants/community-emailing-domain-drivers.constant.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/constants/community-emailing-domain-drivers.constant.tsnew file mode 100644index 00000000000..b7860908140--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/constants/community-emailing-domain-drivers.constant.ts@@ -0,0 +1,6 @@+import { EmailingDomainDriver } from 'src/engine/core-modules/emailing-domain/drivers/types/emailing-domain-driver.type';++export const COMMUNITY_EMAILING_DOMAIN_DRIVERS = [+ EmailingDomainDriver.RESEND,+ EmailingDomainDriver.LOG,+];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.tsindex bd283b637b7..9d2487864fc 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@@ -14,12 +14,6 @@ import {PutEmailIdentityDkimAttributesCommand,} from '@aws-sdk/client-sesv2';-import { isNonEmptyString } from '@sniptt/guards';--import {- EmailingDomainDriverException,- EmailingDomainDriverExceptionCode,-} from 'src/engine/core-modules/emailing-domain/drivers/exceptions/emailing-domain-driver.exception';import { type AwsSesDriverConfig } from 'src/engine/core-modules/emailing-domain/drivers/interfaces/driver-config.interface';import {type EmailingDomainDriverInterface,@@ -28,8 +22,7 @@ import {} from 'src/engine/core-modules/emailing-domain/drivers/interfaces/emailing-domain-driver.interface';import { type EmailingDomainSendEmailRequest } from 'src/engine/core-modules/emailing-domain/drivers/types/emailing-domain-send-email-input.type';import { type EmailingDomainSendEmailResult } from 'src/engine/core-modules/emailing-domain/drivers/types/emailing-domain-send-email-result.type';-import { UnsubscribeHostnameStatus } from 'src/engine/core-modules/emailing-domain/drivers/types/unsubscribe-hostname-status.type';-import { type EmailingDomainEntity } from 'src/engine/core-modules/emailing-domain/emailing-domain.entity';+import { getUnsubscribeBaseUrl } from 'src/engine/core-modules/emailing-domain/drivers/utils/get-unsubscribe-base-url.util';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';@@ -137,7 +130,7 @@ export class AwsSesDriver implements EmailingDomainDriverInterface {async sendEmail(input: EmailingDomainSendEmailRequest,): Promise<EmailingDomainSendEmailResult> {- const unsubscribeBaseUrl = this.getUnsubscribeBaseUrl(input.emailingDomain);+ const unsubscribeBaseUrl = getUnsubscribeBaseUrl(input.emailingDomain);const emailToSend = this.unsubscribeContentService.addTo(input,unsubscribeBaseUrl,@@ -149,21 +142,6 @@ export class AwsSesDriver implements EmailingDomainDriverInterface {});}- private getUnsubscribeBaseUrl(emailingDomain: EmailingDomainEntity): string {- if (- emailingDomain.unsubscribeHostnameStatus !==- UnsubscribeHostnameStatus.ACTIVE ||- !isNonEmptyString(emailingDomain.unsubscribeHostname)- ) {- throw new EmailingDomainDriverException(- `Cannot send email for ${emailingDomain.domain}: unsubscribe domain is not active (status: ${emailingDomain.unsubscribeHostnameStatus})`,- EmailingDomainDriverExceptionCode.UNSUBSCRIBE_NOT_READY,- );- }-- return `https://${emailingDomain.unsubscribeHostname}`;- }-async cleanupDomain(input: EmailingDomainResourceInput): Promise<void> {const sesClient = this.awsSesClientProvider.getSESClient();const tenantName = this.buildTenantName(input.workspaceId);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.tsindex 63d2ed32fc2..1ba2e97fc00 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@@ -1,6 +1,11 @@import { Injectable } from '@nestjs/common';-import { type AwsSesDriverConfig } from 'src/engine/core-modules/emailing-domain/drivers/interfaces/driver-config.interface';+import { isNonEmptyString } from '@sniptt/guards';++import {+ type AwsSesDriverConfig,+ type ResendDriverConfig,+} from 'src/engine/core-modules/emailing-domain/drivers/interfaces/driver-config.interface';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';@@ -9,7 +14,10 @@ import { AwsSesDriver } from 'src/engine/core-modules/emailing-domain/drivers/awimport { 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';import { LogEmailingDomainDriver } from 'src/engine/core-modules/emailing-domain/drivers/log/services/log-emailing-domain-driver.service';+import { ResendApiClientService } from 'src/engine/core-modules/emailing-domain/drivers/resend/services/resend-api-client.service';+import { ResendDriver } from 'src/engine/core-modules/emailing-domain/drivers/resend/services/resend-driver.service';import { EmailingDomainDriver } from 'src/engine/core-modules/emailing-domain/drivers/types/emailing-domain-driver.type';+import { EmailGroupAccessService } from 'src/engine/core-modules/emailing-domain/services/email-group-access.service';import { UnsubscribeContentService } from 'src/engine/core-modules/emailing-domain/services/unsubscribe-content.service';import { DriverFactoryBase } from 'src/engine/core-modules/twenty-config/dynamic-factory.base';import { ConfigVariablesGroup } from 'src/engine/core-modules/twenty-config/enums/config-variables-group.enum';@@ -26,11 +34,19 @@ export class EmailingDomainDriverFactory extends DriverFactoryBase<EmailingDomaiprivate readonly awsSesRegisterDomainService: AwsSesRegisterDomainService,private readonly awsSesSendEmailService: AwsSesSendEmailService,private readonly logEmailingDomainDriver: LogEmailingDomainDriver,+ private readonly resendApiClientService: ResendApiClientService,private readonly unsubscribeContentService: UnsubscribeContentService,+ private readonly emailGroupAccessService: EmailGroupAccessService,) {super(twentyConfigService, configGroupHashService);}+ override getCurrentDriver(): EmailingDomainDriverInterface {+ this.emailGroupAccessService.validateEmailGroupAccessOrThrow();++ return super.getCurrentDriver();+ }+protected buildConfigKey(): string {const driver = this.twentyConfigService.get('EMAILING_DOMAIN_DRIVER');@@ -42,6 +58,13 @@ export class EmailingDomainDriverFactory extends DriverFactoryBase<EmailingDomaireturn `aws-ses|${awsConfigHash}`;}+ case EmailingDomainDriver.RESEND: {+ const resendConfigHash = this.configGroupHashService.computeHash(+ ConfigVariablesGroup.RESEND_SETTINGS,+ );++ return `resend|${resendConfigHash}`;+ }case EmailingDomainDriver.LOG:return 'log';default:@@ -85,6 +108,23 @@ export class EmailingDomainDriverFactory extends DriverFactoryBase<EmailingDomai);}+ case EmailingDomainDriver.RESEND: {+ const domainRegion = this.twentyConfigService.get(+ 'RESEND_DOMAIN_REGION',+ );++ const resendConfig: ResendDriverConfig = {+ driver: EmailingDomainDriver.RESEND,+ ...(isNonEmptyString(domainRegion) ? { domainRegion } : {}),+ };++ return new ResendDriver(+ resendConfig,+ this.resendApiClientService,+ this.unsubscribeContentService,+ );+ }+case EmailingDomainDriver.LOG:return this.logEmailingDomainDriver;diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/interfaces/driver-config.interface.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/interfaces/driver-config.interface.tsindex 4abb8b8bf1d..fd970f47cbd 100644--- a/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/interfaces/driver-config.interface.ts+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/interfaces/driver-config.interface.ts@@ -12,3 +12,8 @@ export interface AwsSesDriverConfig extends BaseDriverConfig {secretAccessKey?: string;sessionToken?: string;}++export interface ResendDriverConfig extends BaseDriverConfig {+ driver: EmailingDomainDriver.RESEND;+ domainRegion?: string;+}diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/resend/constants/resend-workspace-tag-name.constant.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/resend/constants/resend-workspace-tag-name.constant.tsnew file mode 100644index 00000000000..1461df619ed--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/resend/constants/resend-workspace-tag-name.constant.ts@@ -0,0 +1,3 @@+// Attached to every send and echoed back in Resend webhook payloads, so+// outbound events can be attributed to a workspace without provider state.+export const RESEND_WORKSPACE_TAG_NAME = 'workspace_id';diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/resend/services/resend-api-client.service.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/resend/services/resend-api-client.service.tsnew file mode 100644index 00000000000..498084d1593--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/resend/services/resend-api-client.service.ts@@ -0,0 +1,162 @@+import { Injectable } from '@nestjs/common';++import { isNonEmptyString } from '@sniptt/guards';+import { isDefined, parseJson } from 'twenty-shared/utils';++import {+ EmailingDomainDriverException,+ EmailingDomainDriverExceptionCode,+} from 'src/engine/core-modules/emailing-domain/drivers/exceptions/emailing-domain-driver.exception';+import { type ResendDomain } from 'src/engine/core-modules/emailing-domain/drivers/resend/types/resend-domain.type';+import { type ResendErrorBody } from 'src/engine/core-modules/emailing-domain/drivers/resend/types/resend-error-body.type';+import { type ResendReceivedEmail } from 'src/engine/core-modules/emailing-domain/drivers/resend/types/resend-received-email.type';+import { type ResendSendEmailPayload } from 'src/engine/core-modules/emailing-domain/drivers/resend/types/resend-send-email-payload.type';+import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';++const RESEND_API_BASE_URL = 'https://api.resend.com';++@Injectable()+export class ResendApiClientService {+ constructor(private readonly twentyConfigService: TwentyConfigService) {}++ async sendEmail(payload: ResendSendEmailPayload): Promise<{ id: string }> {+ return this.requestJson<{ id: string }>('POST', '/emails', payload);+ }++ async createDomain(payload: {+ name: string;+ region?: string;+ }): Promise<ResendDomain> {+ return this.requestJson<ResendDomain>('POST', '/domains', payload);+ }++ async getDomain(domainId: string): Promise<ResendDomain> {+ return this.requestJson<ResendDomain>('GET', `/domains/${domainId}`);+ }++ async listDomains(): Promise<{ data: ResendDomain[] }> {+ return this.requestJson<{ data: ResendDomain[] }>('GET', '/domains');+ }++ async verifyDomain(domainId: string): Promise<void> {+ await this.performRequest('POST', `/domains/${domainId}/verify`);+ }++ async deleteDomain(domainId: string): Promise<void> {+ await this.performRequest('DELETE', `/domains/${domainId}`);+ }++ async getReceivedEmail(emailId: string): Promise<ResendReceivedEmail> {+ return this.requestJson<ResendReceivedEmail>(+ 'GET',+ `/emails/receiving/${emailId}`,+ );+ }++ // raw download URLs are pre-signed by Resend and require no Authorization+ async downloadRawEmail(downloadUrl: string): Promise<Buffer> {+ const response = await fetch(downloadUrl);++ if (!response.ok) {+ throw new EmailingDomainDriverException(+ `Failed to download raw email content (status ${response.status})`,+ EmailingDomainDriverExceptionCode.TEMPORARY_ERROR,+ );+ }++ return Buffer.from(await response.arrayBuffer());+ }++ private getApiKeyOrThrow(): string {+ const apiKey = this.twentyConfigService.get('RESEND_API_KEY');++ if (!isNonEmptyString(apiKey)) {+ throw new EmailingDomainDriverException(+ 'RESEND_API_KEY is not configured',+ EmailingDomainDriverExceptionCode.CONFIGURATION_ERROR,+ );+ }++ return apiKey;+ }++ private async requestJson<T>(+ method: string,+ path: string,+ body?: object,+ ): Promise<T> {+ const responseText = await this.performRequest(method, path, body);+ const parsedResponse = parseJson<T>(responseText);++ if (!isDefined(parsedResponse)) {+ throw new EmailingDomainDriverException(+ `Resend API ${method} ${path} returned an unparsable response`,+ EmailingDomainDriverExceptionCode.UNKNOWN,+ );+ }++ return parsedResponse;+ }++ private async performRequest(+ method: string,+ path: string,+ body?: object,+ ): Promise<string> {+ const response = await fetch(`${RESEND_API_BASE_URL}${path}`, {+ method,+ headers: {+ Authorization: `Bearer ${this.getApiKeyOrThrow()}`,+ 'Content-Type': 'application/json',+ },+ body: body ? JSON.stringify(body) : undefined,+ });++ const responseText = await response.text();++ if (!response.ok) {+ throw this.buildException(response.status, responseText, method, path);+ }++ return responseText;+ }++ private buildException(+ status: number,+ responseText: string,+ method: string,+ path: string,+ ): EmailingDomainDriverException {+ const errorBody = parseJson<ResendErrorBody>(responseText);+ const providerMessage = isNonEmptyString(errorBody?.message)+ ? `: ${errorBody.message}`+ : '';++ return new EmailingDomainDriverException(+ `Resend API ${method} ${path} failed with status ${status}${providerMessage}`,+ this.mapStatusToExceptionCode(status),+ );+ }++ private mapStatusToExceptionCode(+ status: number,+ ): EmailingDomainDriverExceptionCode {+ if (status === 404) {+ return EmailingDomainDriverExceptionCode.NOT_FOUND;+ }++ if (status === 401 || status === 403) {+ return EmailingDomainDriverExceptionCode.INSUFFICIENT_PERMISSIONS;+ }++ if (status === 429 || status >= 500) {+ return EmailingDomainDriverExceptionCode.TEMPORARY_ERROR;+ }++ if (status >= 400) {+ return EmailingDomainDriverExceptionCode.CONFIGURATION_ERROR;+ }++ return EmailingDomainDriverExceptionCode.UNKNOWN;+ }+}diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/resend/services/resend-driver.service.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/resend/services/resend-driver.service.tsnew file mode 100644index 00000000000..6cecf7f98f5--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/resend/services/resend-driver.service.ts@@ -0,0 +1,205 @@+import { Logger } from '@nestjs/common';++import { isNonEmptyString } from '@sniptt/guards';+import { isDefined, isNonEmptyArray } from 'twenty-shared/utils';++import {+ EmailingDomainDriverException,+ EmailingDomainDriverExceptionCode,+} from 'src/engine/core-modules/emailing-domain/drivers/exceptions/emailing-domain-driver.exception';+import {+ type EmailingDomainDriverInterface,+ type EmailingDomainResourceInput,+ type EmailingDomainVerificationResult,+} from 'src/engine/core-modules/emailing-domain/drivers/interfaces/emailing-domain-driver.interface';+import { type ResendDriverConfig } from 'src/engine/core-modules/emailing-domain/drivers/interfaces/driver-config.interface';+import { type ResendApiClientService } from 'src/engine/core-modules/emailing-domain/drivers/resend/services/resend-api-client.service';+import { type ResendDomain } from 'src/engine/core-modules/emailing-domain/drivers/resend/types/resend-domain.type';+import { type ResendSendEmailPayload } from 'src/engine/core-modules/emailing-domain/drivers/resend/types/resend-send-email-payload.type';+import { mapResendDomainRecords } from 'src/engine/core-modules/emailing-domain/drivers/resend/utils/map-resend-domain-records.util';+import { mapResendSendingStatus } from 'src/engine/core-modules/emailing-domain/drivers/resend/utils/map-resend-sending-status.util';+import { RESEND_WORKSPACE_TAG_NAME } from 'src/engine/core-modules/emailing-domain/drivers/resend/constants/resend-workspace-tag-name.constant';+import { EmailingDomainStatus } from 'src/engine/core-modules/emailing-domain/drivers/types/emailing-domain-status.type';+import { type EmailingDomainSendEmailRequest } from 'src/engine/core-modules/emailing-domain/drivers/types/emailing-domain-send-email-input.type';+import { type EmailingDomainSendEmailResult } from 'src/engine/core-modules/emailing-domain/drivers/types/emailing-domain-send-email-result.type';+import { getUnsubscribeBaseUrl } from 'src/engine/core-modules/emailing-domain/drivers/utils/get-unsubscribe-base-url.util';+import { type UnsubscribeContentService } from 'src/engine/core-modules/emailing-domain/services/unsubscribe-content.service';++export class ResendDriver implements EmailingDomainDriverInterface {+ private readonly logger = new Logger(ResendDriver.name);++ constructor(+ private readonly config: ResendDriverConfig,+ private readonly resendApiClientService: ResendApiClientService,+ private readonly unsubscribeContentService: UnsubscribeContentService,+ ) {}++ // Resend has no per-workspace resources: domains are account-level and+ // workspace attribution travels on each send as a tag.+ async provisionWorkspace(workspaceId: string): Promise<void> {+ this.logger.log(+ `No Resend resources to provision for workspace ${workspaceId}`,+ );+ }++ async deprovisionWorkspace(workspaceId: string): Promise<void> {+ this.logger.log(+ `No Resend resources to deprovision for workspace ${workspaceId}`,+ );+ }++ async registerDomain(_input: EmailingDomainResourceInput): Promise<void> {+ // the return-path subdomain is configured by Resend at domain creation+ }++ async verifyDomain(+ input: EmailingDomainResourceInput,+ ): Promise<EmailingDomainVerificationResult> {+ const domain = await this.findOrCreateDomain(input.domain);++ const currentDomain = await this.resendApiClientService.getDomain(+ domain.id,+ );++ if (+ mapResendSendingStatus(currentDomain) === EmailingDomainStatus.VERIFIED+ ) {+ return this.toVerificationResult(currentDomain);+ }++ await this.resendApiClientService.verifyDomain(domain.id);++ const refreshedDomain = await this.resendApiClientService.getDomain(+ domain.id,+ );++ return this.toVerificationResult(refreshedDomain);+ }++ async getDomainStatus(+ input: EmailingDomainResourceInput,+ ): Promise<EmailingDomainVerificationResult> {+ const domain = await this.findDomainByName(input.domain);++ if (!isDefined(domain)) {+ return {+ status: EmailingDomainStatus.FAILED,+ verificationRecords: [],+ };+ }++ const detailedDomain = await this.resendApiClientService.getDomain(+ domain.id,+ );++ return this.toVerificationResult(detailedDomain);+ }++ async cleanupDomain(input: EmailingDomainResourceInput): Promise<void> {+ const domain = await this.findDomainByName(input.domain);++ if (!isDefined(domain)) {+ return;+ }++ await this.resendApiClientService.deleteDomain(domain.id).catch((error) => {+ if (+ error instanceof EmailingDomainDriverException &&+ error.code === EmailingDomainDriverExceptionCode.NOT_FOUND+ ) {+ return;+ }+ throw error;+ });+ }++ async sendEmail(+ input: EmailingDomainSendEmailRequest,+ ): Promise<EmailingDomainSendEmailResult> {+ if (!isNonEmptyArray(input.to)) {+ throw new EmailingDomainDriverException(+ 'sendEmail requires at least one recipient',+ EmailingDomainDriverExceptionCode.CONFIGURATION_ERROR,+ );+ }++ const unsubscribeBaseUrl = getUnsubscribeBaseUrl(input.emailingDomain);+ const emailToSend = this.unsubscribeContentService.addTo(+ input,+ unsubscribeBaseUrl,+ );++ const payload: ResendSendEmailPayload = {+ from: emailToSend.from,+ to: emailToSend.to,+ cc: emailToSend.cc,+ bcc: emailToSend.bcc,+ reply_to: emailToSend.replyTo,+ subject: emailToSend.subject,+ text: emailToSend.text,+ html: emailToSend.html,+ headers: isNonEmptyArray(emailToSend.headers)+ ? Object.fromEntries(+ emailToSend.headers.map((header) => [header.name, header.value]),+ )+ : undefined,+ tags: [{ name: RESEND_WORKSPACE_TAG_NAME, value: input.workspaceId }],+ attachments: isNonEmptyArray(emailToSend.attachments)+ ? emailToSend.attachments.map((attachment) => ({+ filename: attachment.filename,+ content: attachment.content.toString('base64'),+ content_type: attachment.contentType,+ }))+ : undefined,+ };++ const { id } = await this.resendApiClientService.sendEmail(payload);++ this.logger.log(`Sent email ${id} from ${emailToSend.from} via Resend`);++ return {+ messageId: id,+ deliveredRecipients: {+ to: emailToSend.to,+ cc: emailToSend.cc ?? [],+ bcc: emailToSend.bcc ?? [],+ },+ };+ }++ private async findOrCreateDomain(domainName: string): Promise<ResendDomain> {+ const existingDomain = await this.findDomainByName(domainName);++ if (isDefined(existingDomain)) {+ return existingDomain;+ }++ return this.resendApiClientService.createDomain({+ name: domainName,+ ...(isNonEmptyString(this.config.domainRegion)+ ? { region: this.config.domainRegion }+ : {}),+ });+ }++ private async findDomainByName(+ domainName: string,+ ): Promise<ResendDomain | null> {+ const { data } = await this.resendApiClientService.listDomains();++ return (+ data.find(+ (domain) => domain.name.toLowerCase() === domainName.toLowerCase(),+ ) ?? null+ );+ }++ private toVerificationResult(+ domain: ResendDomain,+ ): EmailingDomainVerificationResult {+ return {+ status: mapResendSendingStatus(domain),+ verificationRecords: mapResendDomainRecords(domain.records),+ };+ }+}diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/resend/types/resend-domain-record.type.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/resend/types/resend-domain-record.type.tsnew file mode 100644index 00000000000..d9fd7697d2b--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/resend/types/resend-domain-record.type.ts@@ -0,0 +1,8 @@+export type ResendDomainRecord = {+ record: string;+ name: string;+ type: string;+ value: string;+ status?: string;+ priority?: number;+};diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/resend/types/resend-domain.type.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/resend/types/resend-domain.type.tsnew file mode 100644index 00000000000..820b8e4f9ff--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/resend/types/resend-domain.type.ts@@ -0,0 +1,9 @@+import { type ResendDomainRecord } from 'src/engine/core-modules/emailing-domain/drivers/resend/types/resend-domain-record.type';++export type ResendDomain = {+ id: string;+ name: string;+ status: string;+ region?: string;+ records?: ResendDomainRecord[];+};diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/resend/types/resend-error-body.type.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/resend/types/resend-error-body.type.tsnew file mode 100644index 00000000000..7dbac24109e--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/resend/types/resend-error-body.type.ts@@ -0,0 +1,5 @@+export type ResendErrorBody = {+ statusCode?: number;+ name?: string;+ message?: string;+};diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/resend/types/resend-received-email.type.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/resend/types/resend-received-email.type.tsnew file mode 100644index 00000000000..c02fcf895f6--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/resend/types/resend-received-email.type.ts@@ -0,0 +1,11 @@+export type ResendReceivedEmail = {+ id: string;+ from: string;+ to: string[];+ cc?: string[];+ bcc?: string[];+ subject?: string;+ message_id?: string;+ created_at?: string;+ raw?: { download_url: string; expires_at: string };+};diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/resend/types/resend-send-email-payload.type.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/resend/types/resend-send-email-payload.type.tsnew file mode 100644index 00000000000..941e176a0a9--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/resend/types/resend-send-email-payload.type.ts@@ -0,0 +1,13 @@+export type ResendSendEmailPayload = {+ from: string;+ to: string[];+ cc?: string[];+ bcc?: string[];+ reply_to?: string[];+ subject: string;+ text: string;+ html?: string;+ headers?: Record<string, string>;+ tags?: { name: string; value: string }[];+ attachments?: { filename: string; content: string; content_type?: string }[];+};diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/resend/utils/__tests__/map-resend-domain-records.util.spec.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/resend/utils/__tests__/map-resend-domain-records.util.spec.tsnew file mode 100644index 00000000000..989363c35b5--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/resend/utils/__tests__/map-resend-domain-records.util.spec.ts@@ -0,0 +1,66 @@+import { mapResendDomainRecords } from 'src/engine/core-modules/emailing-domain/drivers/resend/utils/map-resend-domain-records.util';++describe('mapResendDomainRecords', () => {+ it('should map DNS records with per-record statuses and MX priority', () => {+ expect(+ mapResendDomainRecords([+ {+ record: 'SPF',+ name: 'send.example.com',+ type: 'TXT',+ value: 'v=spf1 include:amazonses.com ~all',+ status: 'verified',+ },+ {+ record: 'SPF',+ name: 'send.example.com',+ type: 'MX',+ value: 'feedback-smtp.us-east-1.amazonses.com',+ priority: 10,+ status: 'not_started',+ },+ {+ record: 'DKIM',+ name: 'resend._domainkey.example.com',+ type: 'TXT',+ value: 'p=abc',+ status: 'failed',+ },+ ]),+ ).toEqual([+ {+ type: 'TXT',+ key: 'send.example.com',+ value: 'v=spf1 include:amazonses.com ~all',+ status: 'success',+ },+ {+ type: 'MX',+ key: 'send.example.com',+ value: 'feedback-smtp.us-east-1.amazonses.com',+ priority: 10,+ status: 'pending',+ },+ {+ type: 'TXT',+ key: 'resend._domainkey.example.com',+ value: 'p=abc',+ status: 'error',+ },+ ]);+ });++ it('should drop unsupported record types and handle missing records', () => {+ expect(+ mapResendDomainRecords([+ {+ record: 'Custom',+ name: 'x.example.com',+ type: 'A',+ value: '1.2.3.4',+ },+ ]),+ ).toEqual([]);+ expect(mapResendDomainRecords(undefined)).toEqual([]);+ });+});diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/resend/utils/__tests__/map-resend-domain-status.util.spec.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/resend/utils/__tests__/map-resend-domain-status.util.spec.tsnew file mode 100644index 00000000000..33d387e73f0--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/resend/utils/__tests__/map-resend-domain-status.util.spec.ts@@ -0,0 +1,20 @@+import { mapResendDomainStatus } from 'src/engine/core-modules/emailing-domain/drivers/resend/utils/map-resend-domain-status.util';+import { EmailingDomainStatus } from 'src/engine/core-modules/emailing-domain/drivers/types/emailing-domain-status.type';++describe('mapResendDomainStatus', () => {+ it('should map provider statuses to emailing domain statuses', () => {+ expect(mapResendDomainStatus('verified')).toBe(+ EmailingDomainStatus.VERIFIED,+ );+ expect(mapResendDomainStatus('failure')).toBe(EmailingDomainStatus.FAILED);+ expect(mapResendDomainStatus('failed')).toBe(EmailingDomainStatus.FAILED);+ expect(mapResendDomainStatus('temporary_failure')).toBe(+ EmailingDomainStatus.TEMPORARY_FAILURE,+ );+ expect(mapResendDomainStatus('not_started')).toBe(+ EmailingDomainStatus.PENDING,+ );+ expect(mapResendDomainStatus('pending')).toBe(EmailingDomainStatus.PENDING);+ expect(mapResendDomainStatus(undefined)).toBe(EmailingDomainStatus.PENDING);+ });+});diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/resend/utils/__tests__/map-resend-sending-status.util.spec.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/resend/utils/__tests__/map-resend-sending-status.util.spec.tsnew file mode 100644index 00000000000..69141d8b5f5--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/resend/utils/__tests__/map-resend-sending-status.util.spec.ts@@ -0,0 +1,107 @@+import { mapResendSendingStatus } from 'src/engine/core-modules/emailing-domain/drivers/resend/utils/map-resend-sending-status.util';+import { EmailingDomainStatus } from 'src/engine/core-modules/emailing-domain/drivers/types/emailing-domain-status.type';++const sendingRecord = (status: string) => ({+ record: 'SPF',+ name: 'send.example.com',+ type: 'TXT',+ value: 'v=spf1 include:amazonses.com ~all',+ status,+});++const receivingRecord = (status: string) => ({+ record: 'MX',+ name: 'example.com',+ type: 'MX',+ value: 'inbound.resend.com',+ priority: 10,+ status,+});++describe('mapResendSendingStatus', () => {+ it('should report a fully verified domain as verified', () => {+ expect(+ mapResendSendingStatus({+ id: 'dom_1',+ name: 'example.com',+ status: 'verified',+ }),+ ).toBe(EmailingDomainStatus.VERIFIED);+ });++ it('should report a partially verified domain as verified when sending records are verified', () => {+ expect(+ mapResendSendingStatus({+ id: 'dom_1',+ name: 'example.com',+ status: 'partially_verified',+ records: [+ sendingRecord('verified'),+ { ...sendingRecord('verified'), record: 'DKIM' },+ receivingRecord('pending'),+ ],+ }),+ ).toBe(EmailingDomainStatus.VERIFIED);+ });++ it('should stay pending while sending records are pending', () => {+ expect(+ mapResendSendingStatus({+ id: 'dom_1',+ name: 'example.com',+ status: 'partially_verified',+ records: [+ sendingRecord('verified'),+ { ...sendingRecord('pending'), record: 'DKIM' },+ receivingRecord('verified'),+ ],+ }),+ ).toBe(EmailingDomainStatus.PENDING);+ });++ it('should report failure when a sending record failed', () => {+ expect(+ mapResendSendingStatus({+ id: 'dom_1',+ name: 'example.com',+ status: 'partially_failed',+ records: [+ sendingRecord('failure'),+ { ...sendingRecord('verified'), record: 'DKIM' },+ ],+ }),+ ).toBe(EmailingDomainStatus.FAILED);+ });++ it('should report temporary failure when a sending record is temporarily failing', () => {+ expect(+ mapResendSendingStatus({+ id: 'dom_1',+ name: 'example.com',+ status: 'temporary_failure',+ records: [+ sendingRecord('temporary_failure'),+ { ...sendingRecord('verified'), record: 'DKIM' },+ ],+ }),+ ).toBe(EmailingDomainStatus.TEMPORARY_FAILURE);+ });++ it('should fall back to the aggregate status without records', () => {+ expect(+ mapResendSendingStatus({+ id: 'dom_1',+ name: 'example.com',+ status: 'failure',+ }),+ ).toBe(EmailingDomainStatus.FAILED);+ expect(+ mapResendSendingStatus({+ id: 'dom_1',+ name: 'example.com',+ status: 'pending',+ records: [receivingRecord('pending')],+ }),+ ).toBe(EmailingDomainStatus.PENDING);+ });+});diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/resend/utils/map-resend-domain-records.util.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/resend/utils/map-resend-domain-records.util.tsnew file mode 100644index 00000000000..d42fc86c163--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/resend/utils/map-resend-domain-records.util.ts@@ -0,0 +1,42 @@+import { isDefined } from 'twenty-shared/utils';++import { type ResendDomainRecord } from 'src/engine/core-modules/emailing-domain/drivers/resend/types/resend-domain-record.type';+import { type VerificationRecord } from 'src/engine/core-modules/emailing-domain/drivers/types/verifications-record';++const mapResendRecordStatus = (status: string | undefined): string => {+ switch (status) {+ case 'verified':+ return 'success';+ case 'failure':+ case 'failed':+ return 'error';+ default:+ return 'pending';+ }+};++const isVerificationRecordType = (+ type: string,+): type is VerificationRecord['type'] => {+ return type === 'TXT' || type === 'CNAME' || type === 'MX';+};++export const mapResendDomainRecords = (+ records: ResendDomainRecord[] | undefined,+): VerificationRecord[] => {+ return (records ?? [])+ .filter(+ (+ record,+ ): record is ResendDomainRecord & {+ type: VerificationRecord['type'];+ } => isVerificationRecordType(record.type),+ )+ .map((record) => ({+ type: record.type,+ key: record.name,+ value: record.value,+ ...(isDefined(record.priority) ? { priority: record.priority } : {}),+ status: mapResendRecordStatus(record.status),+ }));+};diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/resend/utils/map-resend-domain-status.util.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/resend/utils/map-resend-domain-status.util.tsnew file mode 100644index 00000000000..fb5d626ccc8--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/resend/utils/map-resend-domain-status.util.ts@@ -0,0 +1,17 @@+import { EmailingDomainStatus } from 'src/engine/core-modules/emailing-domain/drivers/types/emailing-domain-status.type';++export const mapResendDomainStatus = (+ status: string | undefined,+): EmailingDomainStatus => {+ switch (status) {+ case 'verified':+ return EmailingDomainStatus.VERIFIED;+ case 'failure':+ case 'failed':+ return EmailingDomainStatus.FAILED;+ case 'temporary_failure':+ return EmailingDomainStatus.TEMPORARY_FAILURE;+ default:+ return EmailingDomainStatus.PENDING;+ }+};diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/resend/utils/map-resend-sending-status.util.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/resend/utils/map-resend-sending-status.util.tsnew file mode 100644index 00000000000..8b4e64122dc--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/resend/utils/map-resend-sending-status.util.ts@@ -0,0 +1,45 @@+import { isNonEmptyArray } from 'twenty-shared/utils';++import { type ResendDomain } from 'src/engine/core-modules/emailing-domain/drivers/resend/types/resend-domain.type';+import { mapResendDomainStatus } from 'src/engine/core-modules/emailing-domain/drivers/resend/utils/map-resend-domain-status.util';+import { EmailingDomainStatus } from 'src/engine/core-modules/emailing-domain/drivers/types/emailing-domain-status.type';++const SENDING_RECORD_LABELS = ['SPF', 'DKIM'];++// A domain with receiving enabled reports partially_verified while its MX+// record is pending even though sending is fully set up, so outbound+// readiness is derived from the sending records rather than the aggregate+// domain status.+export const mapResendSendingStatus = (+ domain: ResendDomain,+): EmailingDomainStatus => {+ if (domain.status === 'verified') {+ return EmailingDomainStatus.VERIFIED;+ }++ const sendingRecords = (domain.records ?? []).filter((record) =>+ SENDING_RECORD_LABELS.includes(record.record.toUpperCase()),+ );++ if (!isNonEmptyArray(sendingRecords)) {+ return mapResendDomainStatus(domain.status);+ }++ if (sendingRecords.every((record) => record.status === 'verified')) {+ return EmailingDomainStatus.VERIFIED;+ }++ if (+ sendingRecords.some(+ (record) => record.status === 'failure' || record.status === 'failed',+ )+ ) {+ return EmailingDomainStatus.FAILED;+ }++ if (sendingRecords.some((record) => record.status === 'temporary_failure')) {+ return EmailingDomainStatus.TEMPORARY_FAILURE;+ }++ return EmailingDomainStatus.PENDING;+};diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/types/emailing-domain-driver.type.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/types/emailing-domain-driver.type.tsindex 6752897f272..8baf11cae97 100644--- a/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/types/emailing-domain-driver.type.ts+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/types/emailing-domain-driver.type.ts@@ -1,4 +1,5 @@export enum EmailingDomainDriver {AWS_SES = 'AWS_SES',+ RESEND = 'RESEND',LOG = 'LOG',}diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/utils/get-unsubscribe-base-url.util.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/utils/get-unsubscribe-base-url.util.tsnew file mode 100644index 00000000000..cdeb0b8ef67--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/utils/get-unsubscribe-base-url.util.ts@@ -0,0 +1,25 @@+import { isNonEmptyString } from '@sniptt/guards';++import {+ EmailingDomainDriverException,+ EmailingDomainDriverExceptionCode,+} from 'src/engine/core-modules/emailing-domain/drivers/exceptions/emailing-domain-driver.exception';+import { UnsubscribeHostnameStatus } from 'src/engine/core-modules/emailing-domain/drivers/types/unsubscribe-hostname-status.type';+import { type EmailingDomainEntity } from 'src/engine/core-modules/emailing-domain/emailing-domain.entity';++export const getUnsubscribeBaseUrl = (+ emailingDomain: EmailingDomainEntity,+): string => {+ if (+ emailingDomain.unsubscribeHostnameStatus !==+ UnsubscribeHostnameStatus.ACTIVE ||+ !isNonEmptyString(emailingDomain.unsubscribeHostname)+ ) {+ throw new EmailingDomainDriverException(+ `Cannot send email for ${emailingDomain.domain}: unsubscribe domain is not active (status: ${emailingDomain.unsubscribeHostnameStatus})`,+ EmailingDomainDriverExceptionCode.UNSUBSCRIBE_NOT_READY,+ );+ }++ return `https://${emailingDomain.unsubscribeHostname}`;+};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.tsindex 24b7ea88863..e9b44e9a874 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@@ -11,6 +11,7 @@ import { AwsSesHandleErrorService } from 'src/engine/core-modules/emailing-domaiimport { AwsSesSendEmailService } from 'src/engine/core-modules/emailing-domain/drivers/aws-ses/services/aws-ses-send-email.service';import { EmailingDomainDriverFactory } from 'src/engine/core-modules/emailing-domain/drivers/emailing-domain-driver.factory';import { LogEmailingDomainDriver } from 'src/engine/core-modules/emailing-domain/drivers/log/services/log-emailing-domain-driver.service';+import { ResendApiClientService } from 'src/engine/core-modules/emailing-domain/drivers/resend/services/resend-api-client.service';import { EmailGroupAccessService } from 'src/engine/core-modules/emailing-domain/services/email-group-access.service';import { EmailingDomainEntity } from 'src/engine/core-modules/emailing-domain/emailing-domain.entity';import { EmailingDomainResolver } from 'src/engine/core-modules/emailing-domain/emailing-domain.resolver';@@ -61,6 +62,7 @@ import { provideWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspacAwsSesRegisterDomainService,AwsSesSendEmailService,LogEmailingDomainDriver,+ ResendApiClientService,provideWorkspaceScopedRepository(EmailingDomainEntity),],})diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/services/email-group-access.service.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/services/email-group-access.service.tsindex 2b4e814f900..ec166733c2a 100644--- a/packages/twenty-server/src/engine/core-modules/emailing-domain/services/email-group-access.service.ts+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/services/email-group-access.service.ts@@ -7,16 +7,16 @@ import {EmailGroupAccessException,EmailGroupAccessExceptionCode,} from 'src/engine/core-modules/emailing-domain/exceptions/email-group-access.exception';+import { COMMUNITY_EMAILING_DOMAIN_DRIVERS } from 'src/engine/core-modules/emailing-domain/constants/community-emailing-domain-drivers.constant';import { EnterprisePlanService } from 'src/engine/core-modules/enterprise/services/enterprise-plan.service';+import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';-// Self-hosted instances gate email group behind a valid Enterprise plan.-// Cloud instances (billing enabled) meter usage with credits at send time-// instead, so access itself is unrestricted here.@Injectable()export class EmailGroupAccessService {constructor(private readonly billingService: BillingService,private readonly enterprisePlanService: EnterprisePlanService,+ private readonly twentyConfigService: TwentyConfigService,) {}validateEmailGroupAccessOrThrow(): void {@@ -24,6 +24,14 @@ export class EmailGroupAccessService {return;}+ if (+ COMMUNITY_EMAILING_DOMAIN_DRIVERS.includes(+ this.twentyConfigService.get('EMAILING_DOMAIN_DRIVER'),+ )+ ) {+ return;+ }+if (!this.enterprisePlanService.isValid()) {throw new EmailGroupAccessException('Email group requires an Enterprise plan',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.tsindex 849f6192802..7cf519c4dbc 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@@ -2087,7 +2087,7 @@ export class ConfigVariables {@ConfigVariablesMetadata({group: ConfigVariablesGroup.AWS_SES_SETTINGS,description:- 'Driver used for the emailing domain feature — AWS_SES for production (requires AWS credentials), LOG fakes registration/verification/sends locally',+ '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),})@@ -2175,6 +2175,34 @@ export class ConfigVariables {@IsOptional()TATAMI_SNS_TOPIC_ARN: string;+ @ConfigVariablesMetadata({+ group: ConfigVariablesGroup.RESEND_SETTINGS,+ isSensitive: true,+ description: 'Resend API key used when EMAILING_DOMAIN_DRIVER is RESEND',+ type: ConfigVariableType.STRING,+ })+ @IsOptional()+ RESEND_API_KEY: string;++ @ConfigVariablesMetadata({+ group: ConfigVariablesGroup.RESEND_SETTINGS,+ isSensitive: true,+ description:+ 'Signing secret of the Resend webhook endpoint that targets /webhooks/messaging/resend (whsec_...)',+ type: ConfigVariableType.STRING,+ })+ @IsOptional()+ RESEND_WEBHOOK_SIGNING_SECRET: string;++ @ConfigVariablesMetadata({+ group: ConfigVariablesGroup.RESEND_SETTINGS,+ description:+ 'Region Resend provisions new emailing domains in (us-east-1, eu-west-1, sa-east-1 or ap-northeast-1). Leave empty for the Resend default.',+ type: ConfigVariableType.STRING,+ })+ @IsOptional()+ RESEND_DOMAIN_REGION: string;+@ConfigVariablesMetadata({group: ConfigVariablesGroup.ADVANCED_SETTINGS,description: 'Timeout in milliseconds for primary database queries',diff --git a/packages/twenty-server/src/engine/core-modules/twenty-config/constants/config-variables-group-metadata.ts b/packages/twenty-server/src/engine/core-modules/twenty-config/constants/config-variables-group-metadata.tsindex d0f59581bde..df525cd36d7 100644--- a/packages/twenty-server/src/engine/core-modules/twenty-config/constants/config-variables-group-metadata.ts+++ b/packages/twenty-server/src/engine/core-modules/twenty-config/constants/config-variables-group-metadata.ts@@ -140,4 +140,11 @@ export const CONFIG_VARIABLES_GROUP_METADATA: Record<isHiddenOnLoad: true,isHiddenInAdminPanel: true,},+ [ConfigVariablesGroup.RESEND_SETTINGS]: {+ position: 2200,+ description:+ 'Configure Resend settings for emailing domains (mass outbound and email group inbound)',+ isHiddenOnLoad: true,+ isHiddenInAdminPanel: true,+ },};diff --git a/packages/twenty-server/src/engine/core-modules/twenty-config/enums/config-variables-group.enum.ts b/packages/twenty-server/src/engine/core-modules/twenty-config/enums/config-variables-group.enum.tsindex f14e954956e..d4b691930ac 100644--- a/packages/twenty-server/src/engine/core-modules/twenty-config/enums/config-variables-group.enum.ts+++ b/packages/twenty-server/src/engine/core-modules/twenty-config/enums/config-variables-group.enum.ts@@ -18,4 +18,5 @@ export enum ConfigVariablesGroup {ANALYTICS_CONFIG = 'ANALYTICS_CONFIG',TOKENS_DURATION = 'TOKENS_DURATION',AWS_SES_SETTINGS = 'AWS_SES_SETTINGS',+ RESEND_SETTINGS = 'RESEND_SETTINGS',}diff --git a/packages/twenty-server/src/engine/metadata-modules/message-channel/message-channel-metadata.service.ts b/packages/twenty-server/src/engine/metadata-modules/message-channel/message-channel-metadata.service.tsindex 3655f18ab81..0710a898b09 100644--- a/packages/twenty-server/src/engine/metadata-modules/message-channel/message-channel-metadata.service.ts+++ b/packages/twenty-server/src/engine/metadata-modules/message-channel/message-channel-metadata.service.ts@@ -225,18 +225,25 @@ export class MessageChannelMetadataService {const inboundEmailDomain = this.twentyConfigService.get('INBOUND_EMAIL_DOMAIN',);- const storageType = this.twentyConfigService.get('STORAGE_TYPE');+ const emailingDomainDriver = this.twentyConfigService.get(+ 'EMAILING_DOMAIN_DRIVER',+ );const isEmailingDomainInDemoMode =- this.twentyConfigService.get('EMAILING_DOMAIN_DRIVER') ===- EmailingDomainDriver.LOG;+ emailingDomainDriver === EmailingDomainDriver.LOG;++ const isInboundMessageStoreConfigured =+ emailingDomainDriver === EmailingDomainDriver.RESEND+ ? isNonEmptyString(this.twentyConfigService.get('RESEND_API_KEY'))+ : this.twentyConfigService.get('STORAGE_TYPE') ===+ StorageDriverType.S_3;if (!isEmailingDomainInDemoMode &&(!isNonEmptyString(inboundEmailDomain) ||- storageType !== StorageDriverType.S_3)+ !isInboundMessageStoreConfigured)) {throw new MessageChannelException(- 'Email handles are not configured: INBOUND_EMAIL_DOMAIN must be set and STORAGE_TYPE must be S3',+ 'Email handles are not configured: INBOUND_EMAIL_DOMAIN must be set, plus S3 storage for the AWS_SES driver or RESEND_API_KEY for the RESEND driver',MessageChannelExceptionCode.EMAIL_GROUP_NOT_CONFIGURED,);}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.tsnew file mode 100644index 00000000000..75968be968e--- /dev/null+++ b/packages/twenty-server/src/modules/messaging-webhooks/drivers/resend/services/resend-webhook-driver.service.ts@@ -0,0 +1,129 @@+import { Injectable, Logger } from '@nestjs/common';++import { isNonEmptyString } from '@sniptt/guards';+import { isDefined, isNonEmptyArray, 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 { InboundMailHandlerService } from 'src/modules/messaging-webhooks/handlers/inbound-mail-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';+import { INBOUND_EMAIL_MESSAGE_SOURCE } from 'src/modules/messaging/message-import-manager/drivers/inbound-email/constants/inbound-email-message-source.constant';++@Injectable()+export class ResendWebhookDriverService {+ private readonly logger = new Logger(ResendWebhookDriverService.name);++ constructor(+ private readonly resendWebhookVerifierService: ResendWebhookVerifierService,+ private readonly outboundSuppressionHandlerService: OutboundSuppressionHandlerService,+ private readonly inboundMailHandlerService: InboundMailHandlerService,+ ) {}++ async handle(rawBody: Buffer, headers: ResendWebhookHeaders): Promise<void> {+ this.resendWebhookVerifierService.assertSigned(rawBody, headers);++ const event = parseJson<ResendWebhookEvent>(rawBody.toString('utf8'));++ if (!isDefined(event) || !isNonEmptyString(event.type)) {+ throw new MessagingWebhookException(+ 'Invalid Resend webhook payload',+ MessagingWebhookExceptionCode.MESSAGING_WEBHOOK_INVALID_PAYLOAD,+ );+ }++ 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;+ }+ }++ private async handleSuppressionEvent(+ event: ResendWebhookEvent,+ reason:+ | MessageSuppressionReason.BOUNCE+ | MessageSuppressionReason.COMPLAINT,+ ): Promise<void> {+ const workspaceId = getResendEventTagValue(+ event.data?.tags,+ RESEND_WORKSPACE_TAG_NAME,+ );++ if (!isNonEmptyString(workspaceId)) {+ this.logger.warn(+ `Ignoring Resend ${event.type} event without a ${RESEND_WORKSPACE_TAG_NAME} tag`,+ );++ return;+ }++ const emailAddresses = event.data?.to ?? [];++ if (!isNonEmptyArray(emailAddresses)) {+ return;+ }++ await this.outboundSuppressionHandlerService.handle({+ workspaceId,+ reason,+ emailAddresses,+ providerMessageId: event.data?.email_id ?? null,+ providerEventId: event.data?.email_id ?? null,+ });+ }++ private async handleReceivedEvent(event: ResendWebhookEvent): Promise<void> {+ const emailId = event.data?.email_id;++ if (!isNonEmptyString(emailId)) {+ throw new MessagingWebhookException(+ 'Resend email.received event has no email_id',+ MessagingWebhookExceptionCode.MESSAGING_WEBHOOK_INVALID_PAYLOAD,+ );+ }++ // received_for carries the envelope recipients; to/cc cover mail+ // delivered through aliases or group expansion+ const recipients = [+ ...(event.data?.received_for ?? []),+ ...(event.data?.to ?? []),+ ...(event.data?.cc ?? []),+ ];++ await this.inboundMailHandlerService.handle({+ recipients,+ subject: event.data?.subject ?? null,+ message: {+ source: INBOUND_EMAIL_MESSAGE_SOURCE.RESEND,+ reference: emailId,+ },+ dedupeKey: emailId,+ });+ }+}diff --git a/packages/twenty-server/src/modules/messaging-webhooks/drivers/resend/services/resend-webhook-verifier.service.ts b/packages/twenty-server/src/modules/messaging-webhooks/drivers/resend/services/resend-webhook-verifier.service.tsnew file mode 100644index 00000000000..24964ba8968--- /dev/null+++ b/packages/twenty-server/src/modules/messaging-webhooks/drivers/resend/services/resend-webhook-verifier.service.ts@@ -0,0 +1,78 @@+import { Injectable, Logger } from '@nestjs/common';++import { isNonEmptyString } from '@sniptt/guards';++import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';+import { type ResendWebhookHeaders } from 'src/modules/messaging-webhooks/drivers/resend/types/resend-webhook-headers.type';+import { verifySvixSignature } from 'src/modules/messaging-webhooks/drivers/resend/utils/verify-svix-signature.util';+import { MessagingWebhookExceptionCode } from 'src/modules/messaging-webhooks/messaging-webhook-exception-code.enum';+import { MessagingWebhookException } from 'src/modules/messaging-webhooks/messaging-webhook.exception';++const TIMESTAMP_TOLERANCE_SECONDS = 5 * 60;++@Injectable()+export class ResendWebhookVerifierService {+ private readonly logger = new Logger(ResendWebhookVerifierService.name);++ constructor(private readonly twentyConfigService: TwentyConfigService) {}++ assertSigned(rawBody: Buffer, headers: ResendWebhookHeaders): void {+ const signingSecret = this.twentyConfigService.get(+ 'RESEND_WEBHOOK_SIGNING_SECRET',+ );++ if (!isNonEmptyString(signingSecret)) {+ throw new MessagingWebhookException(+ 'RESEND_WEBHOOK_SIGNING_SECRET is not configured',+ MessagingWebhookExceptionCode.MESSAGING_WEBHOOK_NOT_CONFIGURED,+ );+ }++ const { svixId, svixTimestamp, svixSignature } = headers;++ if (+ !isNonEmptyString(svixId) ||+ !isNonEmptyString(svixTimestamp) ||+ !isNonEmptyString(svixSignature)+ ) {+ throw new MessagingWebhookException(+ 'Missing Svix signature headers',+ MessagingWebhookExceptionCode.MESSAGING_WEBHOOK_INVALID_SIGNATURE,+ );+ }++ this.assertTimestampWithinTolerance(svixTimestamp);++ const isSigned = verifySvixSignature({+ signingSecret,+ svixId,+ svixTimestamp,+ svixSignature,+ rawBody,+ });++ if (!isSigned) {+ this.logger.warn('Resend webhook signature verification failed');++ throw new MessagingWebhookException(+ 'Resend webhook signature invalid',+ MessagingWebhookExceptionCode.MESSAGING_WEBHOOK_INVALID_SIGNATURE,+ );+ }+ }++ private assertTimestampWithinTolerance(svixTimestamp: string): void {+ const timestampSeconds = Number.parseInt(svixTimestamp, 10);+ const nowSeconds = Math.floor(Date.now() / 1000);++ if (+ !Number.isFinite(timestampSeconds) ||+ Math.abs(nowSeconds - timestampSeconds) > TIMESTAMP_TOLERANCE_SECONDS+ ) {+ throw new MessagingWebhookException(+ 'Resend webhook timestamp outside tolerance',+ MessagingWebhookExceptionCode.MESSAGING_WEBHOOK_INVALID_SIGNATURE,+ );+ }+ }+}diff --git a/packages/twenty-server/src/modules/messaging-webhooks/drivers/resend/types/resend-webhook-event-tags.type.ts b/packages/twenty-server/src/modules/messaging-webhooks/drivers/resend/types/resend-webhook-event-tags.type.tsnew file mode 100644index 00000000000..d13215b146c--- /dev/null+++ b/packages/twenty-server/src/modules/messaging-webhooks/drivers/resend/types/resend-webhook-event-tags.type.ts@@ -0,0 +1,5 @@+// tags are documented as an object map but have historically also appeared+// as { name, value } entries, so both shapes are accepted+export type ResendWebhookEventTags =+ | Record<string, string>+ | { name?: string; value?: string }[];diff --git a/packages/twenty-server/src/modules/messaging-webhooks/drivers/resend/types/resend-webhook-event.type.ts b/packages/twenty-server/src/modules/messaging-webhooks/drivers/resend/types/resend-webhook-event.type.tsnew file mode 100644index 00000000000..eccb9f2aa18--- /dev/null+++ b/packages/twenty-server/src/modules/messaging-webhooks/drivers/resend/types/resend-webhook-event.type.ts@@ -0,0 +1,22 @@+import { type ResendWebhookEventTags } from 'src/modules/messaging-webhooks/drivers/resend/types/resend-webhook-event-tags.type';++export type ResendWebhookEvent = {+ type: string;+ created_at?: string;+ data?: {+ email_id?: string;+ from?: string;+ to?: string[];+ cc?: string[];+ bcc?: string[];+ received_for?: string[];+ subject?: string;+ message_id?: string;+ tags?: ResendWebhookEventTags;+ bounce?: {+ type?: 'Permanent' | 'Transient' | 'Undetermined';+ subType?: string;+ message?: string;+ };+ };+};diff --git a/packages/twenty-server/src/modules/messaging-webhooks/drivers/resend/types/resend-webhook-headers.type.ts b/packages/twenty-server/src/modules/messaging-webhooks/drivers/resend/types/resend-webhook-headers.type.tsnew file mode 100644index 00000000000..bed64b289c3--- /dev/null+++ b/packages/twenty-server/src/modules/messaging-webhooks/drivers/resend/types/resend-webhook-headers.type.ts@@ -0,0 +1,5 @@+export type ResendWebhookHeaders = {+ svixId: string | undefined;+ svixTimestamp: string | undefined;+ svixSignature: string | undefined;+};diff --git a/packages/twenty-server/src/modules/messaging-webhooks/drivers/resend/utils/__tests__/verify-svix-signature.util.spec.ts b/packages/twenty-server/src/modules/messaging-webhooks/drivers/resend/utils/__tests__/verify-svix-signature.util.spec.tsnew file mode 100644index 00000000000..bb3f56ef81a--- /dev/null+++ b/packages/twenty-server/src/modules/messaging-webhooks/drivers/resend/utils/__tests__/verify-svix-signature.util.spec.ts@@ -0,0 +1,110 @@+import { createHmac } from 'crypto';++import { verifySvixSignature } from 'src/modules/messaging-webhooks/drivers/resend/utils/verify-svix-signature.util';++const SECRET_BYTES = Buffer.from('resend-signing-secret-material');+const SIGNING_SECRET = `whsec_${SECRET_BYTES.toString('base64')}`;++const signPayload = ({+ svixId,+ svixTimestamp,+ rawBody,+}: {+ svixId: string;+ svixTimestamp: string;+ rawBody: Buffer;+}): string => {+ return createHmac('sha256', SECRET_BYTES)+ .update(`${svixId}.${svixTimestamp}.${rawBody.toString('utf8')}`)+ .digest('base64');+};++describe('verifySvixSignature', () => {+ const svixId = 'msg_123';+ const svixTimestamp = '1700000000';+ const rawBody = Buffer.from('{"type":"email.bounced"}');++ it('should accept a signature computed with the whsec_-prefixed secret', () => {+ const signature = signPayload({ svixId, svixTimestamp, rawBody });++ expect(+ verifySvixSignature({+ signingSecret: SIGNING_SECRET,+ svixId,+ svixTimestamp,+ svixSignature: `v1,${signature}`,+ rawBody,+ }),+ ).toBe(true);+ });++ it('should accept a secret without the whsec_ prefix', () => {+ const signature = signPayload({ svixId, svixTimestamp, rawBody });++ expect(+ verifySvixSignature({+ signingSecret: SECRET_BYTES.toString('base64'),+ svixId,+ svixTimestamp,+ svixSignature: `v1,${signature}`,+ rawBody,+ }),+ ).toBe(true);+ });++ it('should accept the matching entry among several space-separated signatures', () => {+ const signature = signPayload({ svixId, svixTimestamp, rawBody });++ expect(+ verifySvixSignature({+ signingSecret: SIGNING_SECRET,+ svixId,+ svixTimestamp,+ svixSignature: `v1,${Buffer.from('other').toString('base64')} v1,${signature}`,+ rawBody,+ }),+ ).toBe(true);+ });++ it('should reject a signature over a different body', () => {+ const signature = signPayload({ svixId, svixTimestamp, rawBody });++ expect(+ verifySvixSignature({+ signingSecret: SIGNING_SECRET,+ svixId,+ svixTimestamp,+ svixSignature: `v1,${signature}`,+ rawBody: Buffer.from('{"type":"tampered"}'),+ }),+ ).toBe(false);+ });++ it('should reject a signature computed with another secret', () => {+ const signature = createHmac('sha256', Buffer.from('other-secret'))+ .update(`${svixId}.${svixTimestamp}.${rawBody.toString('utf8')}`)+ .digest('base64');++ expect(+ verifySvixSignature({+ signingSecret: SIGNING_SECRET,+ svixId,+ svixTimestamp,+ svixSignature: `v1,${signature}`,+ rawBody,+ }),+ ).toBe(false);+ });++ it('should reject malformed signature headers', () => {+ expect(+ verifySvixSignature({+ signingSecret: SIGNING_SECRET,+ svixId,+ svixTimestamp,+ svixSignature: 'v1',+ rawBody,+ }),+ ).toBe(false);+ });+});diff --git a/packages/twenty-server/src/modules/messaging-webhooks/drivers/resend/utils/get-resend-event-tag-value.util.ts b/packages/twenty-server/src/modules/messaging-webhooks/drivers/resend/utils/get-resend-event-tag-value.util.tsnew file mode 100644index 00000000000..255c9f1a984--- /dev/null+++ b/packages/twenty-server/src/modules/messaging-webhooks/drivers/resend/utils/get-resend-event-tag-value.util.ts@@ -0,0 +1,22 @@+import { isNonEmptyString } from '@sniptt/guards';++import { type ResendWebhookEventTags } from 'src/modules/messaging-webhooks/drivers/resend/types/resend-webhook-event-tags.type';++export const getResendEventTagValue = (+ tags: ResendWebhookEventTags | undefined,+ tagName: string,+): string | null => {+ if (!tags) {+ return null;+ }++ if (Array.isArray(tags)) {+ const matchingTag = tags.find((tag) => tag.name === tagName);++ return isNonEmptyString(matchingTag?.value) ? matchingTag.value : null;+ }++ const value = tags[tagName];++ return isNonEmptyString(value) ? value : null;+};diff --git a/packages/twenty-server/src/modules/messaging-webhooks/drivers/resend/utils/verify-svix-signature.util.ts b/packages/twenty-server/src/modules/messaging-webhooks/drivers/resend/utils/verify-svix-signature.util.tsnew file mode 100644index 00000000000..53b31fd46da--- /dev/null+++ b/packages/twenty-server/src/modules/messaging-webhooks/drivers/resend/utils/verify-svix-signature.util.ts@@ -0,0 +1,46 @@+import { createHmac, timingSafeEqual } from 'crypto';++import { isNonEmptyString } from '@sniptt/guards';++const SIGNING_SECRET_PREFIX = 'whsec_';++// Svix signatures are an HMAC-SHA256 over `${id}.${timestamp}.${body}` keyed+// with the base64 secret after `whsec_`, carried base64-encoded in the+// space-separated `v1,<sig>` entries of the signature header.+export const verifySvixSignature = ({+ signingSecret,+ svixId,+ svixTimestamp,+ svixSignature,+ rawBody,+}: {+ signingSecret: string;+ svixId: string;+ svixTimestamp: string;+ svixSignature: string;+ rawBody: Buffer;+}): boolean => {+ const secretKey = Buffer.from(+ signingSecret.startsWith(SIGNING_SECRET_PREFIX)+ ? signingSecret.slice(SIGNING_SECRET_PREFIX.length)+ : signingSecret,+ 'base64',+ );++ const expectedSignature = createHmac('sha256', secretKey)+ .update(`${svixId}.${svixTimestamp}.${rawBody.toString('utf8')}`)+ .digest();++ return svixSignature+ .split(' ')+ .map((entry) => entry.split(',')[1])+ .filter(isNonEmptyString)+ .some((candidate) => {+ const candidateSignature = Buffer.from(candidate, 'base64');++ return (+ candidateSignature.length === expectedSignature.length &&+ timingSafeEqual(candidateSignature, expectedSignature)+ );+ });+};diff --git a/packages/twenty-server/src/modules/messaging-webhooks/messaging-webhook-exception-code.enum.ts b/packages/twenty-server/src/modules/messaging-webhooks/messaging-webhook-exception-code.enum.tsindex 93de20c2f54..067b9c71d4b 100644--- a/packages/twenty-server/src/modules/messaging-webhooks/messaging-webhook-exception-code.enum.ts+++ b/packages/twenty-server/src/modules/messaging-webhooks/messaging-webhook-exception-code.enum.ts@@ -6,4 +6,5 @@ export enum MessagingWebhookExceptionCode {MESSAGING_WEBHOOK_INVALID_SUBSCRIBE_URL = 'MESSAGING_WEBHOOK_INVALID_SUBSCRIBE_URL',MESSAGING_WEBHOOK_SUBSCRIPTION_CONFIRMATION_FAILED = 'MESSAGING_WEBHOOK_SUBSCRIPTION_CONFIRMATION_FAILED',MESSAGING_WEBHOOK_UNHANDLED_ERROR = 'MESSAGING_WEBHOOK_UNHANDLED_ERROR',+ MESSAGING_WEBHOOK_NOT_CONFIGURED = 'MESSAGING_WEBHOOK_NOT_CONFIGURED',}diff --git a/packages/twenty-server/src/modules/messaging-webhooks/messaging-webhook.exception.ts b/packages/twenty-server/src/modules/messaging-webhooks/messaging-webhook.exception.tsindex 266189bf28b..93f16436fc0 100644--- a/packages/twenty-server/src/modules/messaging-webhooks/messaging-webhook.exception.ts+++ b/packages/twenty-server/src/modules/messaging-webhooks/messaging-webhook.exception.ts@@ -15,6 +15,7 @@ const getMessagingWebhookExceptionUserFriendlyMessage = (return msg`The webhook request could not be processed.`;case MessagingWebhookExceptionCode.MESSAGING_WEBHOOK_FORBIDDEN_TOPIC:case MessagingWebhookExceptionCode.MESSAGING_WEBHOOK_INVALID_SIGNATURE:+ case MessagingWebhookExceptionCode.MESSAGING_WEBHOOK_NOT_CONFIGURED:return msg`The webhook request could not be authenticated.`;case MessagingWebhookExceptionCode.MESSAGING_WEBHOOK_SUBSCRIPTION_CONFIRMATION_FAILED:case MessagingWebhookExceptionCode.MESSAGING_WEBHOOK_UNHANDLED_ERROR: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.tsindex 6540c6c997e..38a68eb6fdd 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@@ -14,6 +14,7 @@ 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 { ResendWebhookDriverService } from 'src/modules/messaging-webhooks/drivers/resend/services/resend-webhook-driver.service';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';@@ -26,6 +27,7 @@ export class MessagingWebhooksController {constructor(private readonly sesInboundWebhookDriverService: SesInboundWebhookDriverService,private readonly sesOutboundWebhookDriverService: SesOutboundWebhookDriverService,+ private readonly resendWebhookDriverService: ResendWebhookDriverService,) {}@Post(`${ApiPath.Webhooks}/messaging/ses/inbound`)@@ -59,4 +61,30 @@ export class MessagingWebhooksController {await this.sesOutboundWebhookDriverService.handle(request.rawBody);}++ @Post(`${ApiPath.Webhooks}/messaging/resend`)+ @UseGuards(PublicEndpointGuard, NoPermissionGuard)+ @HttpCode(200)+ async handleResendWebhook(+ @Req() request: RawBodyRequest<Request>,+ ): Promise<void> {+ if (!isDefined(request.rawBody)) {+ throw new MessagingWebhookException(+ 'Missing Resend payload',+ MessagingWebhookExceptionCode.MESSAGING_WEBHOOK_MISSING_REQUEST_BODY,+ );+ }++ await this.resendWebhookDriverService.handle(request.rawBody, {+ svixId: this.getHeader(request, 'svix-id'),+ svixTimestamp: this.getHeader(request, 'svix-timestamp'),+ svixSignature: this.getHeader(request, 'svix-signature'),+ });+ }++ private getHeader(request: Request, name: string): string | undefined {+ const value = request.headers[name];++ return Array.isArray(value) ? value[0] : value;+ }}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.tsindex a475d76d501..bdd72822c66 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@@ -3,6 +3,8 @@ 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 { ResendWebhookDriverService } from 'src/modules/messaging-webhooks/drivers/resend/services/resend-webhook-driver.service';+import { ResendWebhookVerifierService } from 'src/modules/messaging-webhooks/drivers/resend/services/resend-webhook-verifier.service';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';@@ -25,6 +27,8 @@ import { MessagingWebhooksController } from 'src/modules/messaging-webhooks/messSnsSubscriptionConfirmerService,SesInboundWebhookDriverService,SesOutboundWebhookDriverService,+ ResendWebhookVerifierService,+ ResendWebhookDriverService,],})export class MessagingWebhooksModule {}diff --git a/packages/twenty-server/src/modules/messaging-webhooks/utils/get-messaging-webhook-exception-status-code.util.ts b/packages/twenty-server/src/modules/messaging-webhooks/utils/get-messaging-webhook-exception-status-code.util.tsindex e066a82a8ff..19b4320c3bf 100644--- a/packages/twenty-server/src/modules/messaging-webhooks/utils/get-messaging-webhook-exception-status-code.util.ts+++ b/packages/twenty-server/src/modules/messaging-webhooks/utils/get-messaging-webhook-exception-status-code.util.ts@@ -13,6 +13,7 @@ export const getMessagingWebhookExceptionStatusCode = (return 400;case MessagingWebhookExceptionCode.MESSAGING_WEBHOOK_FORBIDDEN_TOPIC:case MessagingWebhookExceptionCode.MESSAGING_WEBHOOK_INVALID_SIGNATURE:+ case MessagingWebhookExceptionCode.MESSAGING_WEBHOOK_NOT_CONFIGURED:return 403;case MessagingWebhookExceptionCode.MESSAGING_WEBHOOK_SUBSCRIPTION_CONFIRMATION_FAILED:case MessagingWebhookExceptionCode.MESSAGING_WEBHOOK_UNHANDLED_ERROR: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.tsindex 16e4175ba9d..c60aa7645d0 100644--- 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@@ -1,3 +1,4 @@export const INBOUND_EMAIL_MESSAGE_SOURCE = {SES_S3: 'SES_S3',+ RESEND: 'RESEND',} as const;diff --git a/packages/twenty-server/src/modules/messaging/message-import-manager/drivers/inbound-email/messaging-inbound-email-driver.module.ts b/packages/twenty-server/src/modules/messaging/message-import-manager/drivers/inbound-email/messaging-inbound-email-driver.module.tsindex da69082817b..fce4c4a539d 100644--- a/packages/twenty-server/src/modules/messaging/message-import-manager/drivers/inbound-email/messaging-inbound-email-driver.module.ts+++ b/packages/twenty-server/src/modules/messaging/message-import-manager/drivers/inbound-email/messaging-inbound-email-driver.module.ts@@ -1,6 +1,7 @@import { Module } from '@nestjs/common';import { TypeOrmModule } from '@nestjs/typeorm';+import { ResendApiClientService } from 'src/engine/core-modules/emailing-domain/drivers/resend/services/resend-api-client.service';import { TwentyConfigModule } from 'src/engine/core-modules/twenty-config/twenty-config.module';import { ConnectedAccountEntity } from 'src/engine/metadata-modules/connected-account/entities/connected-account.entity';import { MessageChannelEntity } from 'src/engine/metadata-modules/message-channel/entities/message-channel.entity';@@ -9,6 +10,7 @@ import { InboundEmailS3ClientProvider } from 'src/modules/messaging/message-impoimport { InboundEmailParserService } from 'src/modules/messaging/message-import-manager/drivers/inbound-email/services/inbound-email-parser.service';import { InboundEmailStorageService } from 'src/modules/messaging/message-import-manager/drivers/inbound-email/services/inbound-email-storage.service';import { InboundEmailMessageSourceResolverService } from 'src/modules/messaging/message-import-manager/drivers/inbound-email/sources/inbound-email-message-source-resolver.service';+import { ResendInboundEmailMessageSourceService } from 'src/modules/messaging/message-import-manager/drivers/inbound-email/sources/resend-inbound-email-message-source.service';import { SesS3InboundEmailMessageSourceService } from 'src/modules/messaging/message-import-manager/drivers/inbound-email/sources/ses-s3-inbound-email-message-source.service';@Module({@@ -22,6 +24,8 @@ import { SesS3InboundEmailMessageSourceService } from 'src/modules/messaging/mesInboundEmailStorageService,InboundEmailParserService,SesS3InboundEmailMessageSourceService,+ ResendApiClientService,+ ResendInboundEmailMessageSourceService,InboundEmailMessageSourceResolverService,],exports: [diff --git a/packages/twenty-server/src/modules/messaging/message-import-manager/drivers/inbound-email/sources/inbound-email-message-source-resolver.service.ts b/packages/twenty-server/src/modules/messaging/message-import-manager/drivers/inbound-email/sources/inbound-email-message-source-resolver.service.tsindex 7fed32fcd39..9328fd9c9b5 100644--- a/packages/twenty-server/src/modules/messaging/message-import-manager/drivers/inbound-email/sources/inbound-email-message-source-resolver.service.ts+++ b/packages/twenty-server/src/modules/messaging/message-import-manager/drivers/inbound-email/sources/inbound-email-message-source-resolver.service.ts@@ -1,6 +1,7 @@import { Injectable } from '@nestjs/common';import { type InboundEmailMessageSourceInterface } from 'src/modules/messaging/message-import-manager/drivers/inbound-email/sources/inbound-email-message-source.interface';+import { ResendInboundEmailMessageSourceService } from 'src/modules/messaging/message-import-manager/drivers/inbound-email/sources/resend-inbound-email-message-source.service';import { SesS3InboundEmailMessageSourceService } from 'src/modules/messaging/message-import-manager/drivers/inbound-email/sources/ses-s3-inbound-email-message-source.service';import { INBOUND_EMAIL_MESSAGE_SOURCE } from 'src/modules/messaging/message-import-manager/drivers/inbound-email/constants/inbound-email-message-source.constant';import { type InboundEmailMessageSource } from 'src/modules/messaging/message-import-manager/drivers/inbound-email/types/inbound-email-message-source.type';@@ -9,6 +10,7 @@ import { type InboundEmailMessageSource } from 'src/modules/messaging/message-imexport class InboundEmailMessageSourceResolverService {constructor(private readonly sesS3InboundEmailMessageSourceService: SesS3InboundEmailMessageSourceService,+ private readonly resendInboundEmailMessageSourceService: ResendInboundEmailMessageSourceService,) {}resolve(@@ -17,6 +19,8 @@ export class InboundEmailMessageSourceResolverService {switch (source) {case INBOUND_EMAIL_MESSAGE_SOURCE.SES_S3:return this.sesS3InboundEmailMessageSourceService;+ case INBOUND_EMAIL_MESSAGE_SOURCE.RESEND:+ return this.resendInboundEmailMessageSourceService;default:throw new Error(`Unsupported inbound email message source: ${source}`);}diff --git a/packages/twenty-server/src/modules/messaging/message-import-manager/drivers/inbound-email/sources/resend-inbound-email-message-source.service.ts b/packages/twenty-server/src/modules/messaging/message-import-manager/drivers/inbound-email/sources/resend-inbound-email-message-source.service.tsnew file mode 100644index 00000000000..544bd4f79bf--- /dev/null+++ b/packages/twenty-server/src/modules/messaging/message-import-manager/drivers/inbound-email/sources/resend-inbound-email-message-source.service.ts@@ -0,0 +1,61 @@+import { Injectable } from '@nestjs/common';++import { msg } from '@lingui/core/macro';+import { isNonEmptyString } from '@sniptt/guards';++import {+ EmailingDomainDriverException,+ EmailingDomainDriverExceptionCode,+} from 'src/engine/core-modules/emailing-domain/drivers/exceptions/emailing-domain-driver.exception';+import { ResendApiClientService } from 'src/engine/core-modules/emailing-domain/drivers/resend/services/resend-api-client.service';+import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';+import { InboundEmailParserService } from 'src/modules/messaging/message-import-manager/drivers/inbound-email/services/inbound-email-parser.service';+import { type InboundEmailMessageSourceInterface } from 'src/modules/messaging/message-import-manager/drivers/inbound-email/sources/inbound-email-message-source.interface';+import { type MessageWithParticipants } from 'src/modules/messaging/message-import-manager/types/message';++// Resend stores received emails on their side; the reference is the received+// email id from the email.received webhook, and the raw MIME is fetched+// through a pre-signed download URL.+@Injectable()+export class ResendInboundEmailMessageSourceService implements InboundEmailMessageSourceInterface {+ constructor(+ private readonly twentyConfigService: TwentyConfigService,+ private readonly resendApiClientService: ResendApiClientService,+ private readonly inboundEmailParserService: InboundEmailParserService,+ ) {}++ isConfigured(): boolean {+ return isNonEmptyString(this.twentyConfigService.get('RESEND_API_KEY'));+ }++ async fetchMessage(reference: string): Promise<MessageWithParticipants> {+ const receivedEmail =+ await this.resendApiClientService.getReceivedEmail(reference);++ const downloadUrl = receivedEmail.raw?.download_url;++ if (!isNonEmptyString(downloadUrl)) {+ throw new EmailingDomainDriverException(+ `Received email ${reference} has no raw content download URL`,+ EmailingDomainDriverExceptionCode.NOT_FOUND,+ {+ userFriendlyMessage: msg`The received email content is no longer available.`,+ },+ );+ }++ const rawMessage =+ await this.resendApiClientService.downloadRawEmail(downloadUrl);++ const { message } = await this.inboundEmailParserService.parse(+ rawMessage,+ reference,+ );++ return message;+ }++ async cleanup(_reference: string): Promise<void> {+ // Resend retains received emails on their side; nothing to delete+ }+}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.tsnew file mode 100644index 00000000000..5763015720f--- /dev/null+++ b/packages/twenty-server/test/integration/resend/suites/resend-webhook.integration-spec.ts@@ -0,0 +1,216 @@+import { createHmac, randomUUID } from 'node:crypto';++import request from 'supertest';++import { MessageSuppressionEntity } from 'src/engine/core-modules/emailing-domain/message-suppression.entity';+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 { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';++import { updateConfigVariable } from 'test/integration/twenty-config/utils/update-config-variable.util';+import { getAppProviderByClassName } from 'test/integration/utils/get-app-provider-by-class-name.util';+import { getCoreRepository } from 'test/integration/utils/get-core-repository.util';++const SECRET_BYTES = Buffer.from('resend-integration-signing-secret');+const SIGNING_SECRET = `whsec_${SECRET_BYTES.toString('base64')}`;++const RESEND_WEBHOOK_PATH = '/webhooks/messaging/resend';++const signRawBody = ({+ svixId,+ svixTimestamp,+ rawBody,+}: {+ svixId: string;+ svixTimestamp: string;+ rawBody: string;+}) =>+ createHmac('sha256', SECRET_BYTES)+ .update(`${svixId}.${svixTimestamp}.${rawBody}`)+ .digest('base64');++const postResendWebhook = (+ rawBody: string,+ { signed = true }: { signed?: boolean } = {},+) => {+ const svixId = `msg_${randomUUID()}`;+ const svixTimestamp = `${Math.floor(Date.now() / 1000)}`;+ const signature = signed+ ? signRawBody({ svixId, svixTimestamp, rawBody })+ : Buffer.from('invalid-signature-material').toString('base64');++ return request(`http://localhost:${APP_PORT}`)+ .post(RESEND_WEBHOOK_PATH)+ .set('Content-Type', 'application/json')+ .set('svix-id', svixId)+ .set('svix-timestamp', svixTimestamp)+ .set('svix-signature', `v1,${signature}`)+ .send(rawBody);+};++describe('Resend webhook (integration)', () => {+ let unsubscribeTokenService: UnsubscribeTokenService;++ const findSuppressionReasons = async (emailAddress: string) => {+ const suppressions = await getCoreRepository<MessageSuppressionEntity>(+ MessageSuppressionEntity,+ ).findBy({ workspaceId: SEED_APPLE_WORKSPACE_ID, emailAddress });++ return suppressions.map((suppression) => suppression.reason);+ };++ beforeAll(async () => {+ await updateConfigVariable({+ input: { key: 'RESEND_WEBHOOK_SIGNING_SECRET', value: SIGNING_SECRET },+ });++ unsubscribeTokenService =+ getAppProviderByClassName<UnsubscribeTokenService>(+ 'UnsubscribeTokenService',+ );+ }, 60000);++ it('suppresses recipients of a permanently bounced email', async () => {+ const emailAddress = `bounce-${randomUUID()}@acme.com`;++ const response = await postResendWebhook(+ JSON.stringify({+ type: 'email.bounced',+ data: {+ email_id: `email_${randomUUID()}`,+ to: [emailAddress],+ bounce: { type: 'Permanent' },+ tags: { workspace_id: SEED_APPLE_WORKSPACE_ID },+ },+ }),+ );++ expect(response.status).toBe(200);+ expect(await findSuppressionReasons(emailAddress)).toEqual([+ MessageSuppressionReason.BOUNCE,+ ]);+ }, 60000);++ it('suppresses recipients of a complained email carrying array-shaped tags', async () => {+ const emailAddress = `complaint-${randomUUID()}@acme.com`;++ const response = await postResendWebhook(+ JSON.stringify({+ type: 'email.complained',+ data: {+ email_id: `email_${randomUUID()}`,+ to: [emailAddress],+ tags: [{ name: 'workspace_id', value: SEED_APPLE_WORKSPACE_ID }],+ },+ }),+ );++ expect(response.status).toBe(200);+ expect(await findSuppressionReasons(emailAddress)).toEqual([+ MessageSuppressionReason.COMPLAINT,+ ]);+ }, 60000);++ it('suppresses nothing for a transient bounce', async () => {+ const emailAddress = `transient-${randomUUID()}@acme.com`;++ const response = await postResendWebhook(+ JSON.stringify({+ type: 'email.bounced',+ data: {+ email_id: `email_${randomUUID()}`,+ to: [emailAddress],+ bounce: { type: 'Transient' },+ tags: { workspace_id: SEED_APPLE_WORKSPACE_ID },+ },+ }),+ );++ expect(response.status).toBe(200);+ expect(await findSuppressionReasons(emailAddress)).toEqual([]);+ }, 60000);++ it('suppresses nothing for a bounce without a workspace tag', async () => {+ const emailAddress = `untagged-${randomUUID()}@acme.com`;++ const response = await postResendWebhook(+ JSON.stringify({+ type: 'email.bounced',+ data: {+ email_id: `email_${randomUUID()}`,+ to: [emailAddress],+ bounce: { type: 'Permanent' },+ },+ }),+ );++ expect(response.status).toBe(200);+ expect(await findSuppressionReasons(emailAddress)).toEqual([]);+ }, 60000);++ it('suppresses the sender of a received email addressed to the unsubscribe mailbox', async () => {+ const emailAddress = `unsub-${randomUUID()}@acme.com`;++ const response = await postResendWebhook(+ JSON.stringify({+ type: 'email.received',+ data: {+ email_id: `email_${randomUUID()}`,+ received_for: ['[email protected]'],+ subject: unsubscribeTokenService.sign({+ workspaceId: SEED_APPLE_WORKSPACE_ID,+ emailAddress,+ }),+ },+ }),+ );++ expect(response.status).toBe(200);+ expect(await findSuppressionReasons(emailAddress)).toEqual([+ MessageSuppressionReason.UNSUBSCRIBE,+ ]);+ }, 60000);++ it('ignores event types it does not handle', async () => {+ const response = await postResendWebhook(+ JSON.stringify({+ type: 'email.delivered',+ data: { email_id: `email_${randomUUID()}` },+ }),+ );++ expect(response.status).toBe(200);+ }, 60000);++ it('rejects a payload whose signature does not verify', async () => {+ const response = await postResendWebhook(+ JSON.stringify({+ type: 'email.bounced',+ data: {+ email_id: `email_${randomUUID()}`,+ to: [`rejected-${randomUUID()}@acme.com`],+ bounce: { type: 'Permanent' },+ tags: { workspace_id: SEED_APPLE_WORKSPACE_ID },+ },+ }),+ { signed: false },+ );++ expect(response.status).toBe(403);+ }, 60000);++ it('rejects a payload without Svix signature headers', async () => {+ const response = await request(`http://localhost:${APP_PORT}`)+ .post(RESEND_WEBHOOK_PATH)+ .set('Content-Type', 'application/json')+ .send(JSON.stringify({ type: 'email.bounced' }));++ expect(response.status).toBe(403);+ }, 60000);++ it('rejects a correctly signed body that is not valid JSON', async () => {+ const response = await postResendWebhook('not-json');++ expect(response.status).toBe(400);+ }, 60000);+});