diff --git a/apps/backend/src/app/api/latest/emails/send-email/route.tsx b/apps/backend/src/app/api/latest/emails/send-email/route.tsx index 55ab4aae3..df56b365f 100644 --- a/apps/backend/src/app/api/latest/emails/send-email/route.tsx +++ b/apps/backend/src/app/api/latest/emails/send-email/route.tsx @@ -63,9 +63,6 @@ export const POST = createSmartRouteHandler({ if (!getEnvVariable("STACK_FREESTYLE_API_KEY")) { throw new StatusError(500, "STACK_FREESTYLE_API_KEY is not set"); } - if (auth.tenancy.config.emails.server.isShared) { - throw new KnownErrors.RequiresCustomEmailServer(); - } if ((body.user_ids && body.all_users) || (!body.user_ids && !body.all_users)) { throw new KnownErrors.SchemaError("Exactly one of user_ids or all_users must be provided"); } diff --git a/apps/backend/src/lib/email-queue-step.tsx b/apps/backend/src/lib/email-queue-step.tsx index 7d26c5ead..f9584c1cc 100644 --- a/apps/backend/src/lib/email-queue-step.tsx +++ b/apps/backend/src/lib/email-queue-step.tsx @@ -1,7 +1,7 @@ import { EmailOutbox, EmailOutboxSkippedReason, Prisma } from "@/generated/prisma/client"; import { calculateCapacityRate, getEmailCapacityBoostExpiresAt, getEmailDeliveryStatsForTenancy } from "@/lib/email-delivery-stats"; import { getEmailThemeForThemeId, renderEmailsForTenancyBatched } from "@/lib/email-rendering"; -import { EmailOutboxRecipient, getEmailConfig, } from "@/lib/emails"; +import { EmailOutboxRecipient, getEmailConfig, isCustomEmailForSharedServer, wrapSharedDevEmail, } from "@/lib/emails"; import { generateUnsubscribeLink, getNotificationCategoryById, hasNotificationEnabled, listNotificationCategories } from "@/lib/notification-categories"; import { arePlanLimitsEnforced, getBillingTeamId } from "@/lib/plan-entitlements"; import { getHexclaveServerApp } from "@/hexclave"; @@ -735,15 +735,24 @@ async function processSingleEmail(context: TenancyProcessingContext, row: EmailO return; } } + const baseContent = { + subject: row.renderedSubject ?? "", + html: row.renderedHtml ?? undefined, + text: row.renderedText ?? undefined, + }; + const emailContent = context.emailConfig.type === "shared" && isCustomEmailForSharedServer(recipient, row.createdWith, row.emailProgrammaticCallTemplateId) + ? wrapSharedDevEmail(baseContent) + : baseContent; + const result = getEnvBoolean("STACK_EMAIL_BRANCHING_DISABLE_QUEUE_SENDING") ? Result.error({ errorType: "email-sending-disabled", canRetry: false, message: "Email sending is disabled", rawError: new Error("Email sending is disabled") }) : await lowLevelSendEmailDirectWithoutRetries({ tenancyId: context.tenancy.id, emailConfig: context.emailConfig, to: resolution.emails, - subject: row.renderedSubject ?? "", - html: row.renderedHtml ?? undefined, - text: row.renderedText ?? undefined, + subject: emailContent.subject, + html: emailContent.html, + text: emailContent.text, }); if (result.status === "error") { const newAttemptCount = row.sendRetries + 1; diff --git a/apps/backend/src/lib/emails.tsx b/apps/backend/src/lib/emails.tsx index d0557a6dc..86efa3920 100644 --- a/apps/backend/src/lib/emails.tsx +++ b/apps/backend/src/lib/emails.tsx @@ -98,6 +98,48 @@ export async function sendEmailFromDefaultTemplate(options: { }); } +const DEFAULT_TEMPLATE_ID_SET: ReadonlySet = new Set(Object.values(DEFAULT_TEMPLATE_IDS)); + +/** Whether an outbox email is project-defined custom content that should get the shared-server dev wrapper. */ +export function isCustomEmailForSharedServer(recipient: EmailOutboxRecipient, createdWith: EmailOutboxCreatedWith, programmaticCallTemplateId: string | null): boolean { + // Hexclave's own system notifications (credential-scanning alerts, internal feedback) send raw HTML to bare + // "custom-emails" addresses and must go out verbatim; the send-email API always targets the project's users. + if (recipient.type === "custom-emails") { + return false; + } + if (createdWith === EmailOutboxCreatedWith.DRAFT) { + return true; + } + return programmaticCallTemplateId === null || !DEFAULT_TEMPLATE_ID_SET.has(programmaticCallTemplateId); +} + +export function wrapSharedDevEmail(content: { subject: string, html?: string, text?: string }): { subject: string, html?: string, text?: string } { + const wrappedSubject = `[Hexclave dev email] ${content.subject}`; + + const noticeHtml = `
` + + `This is a development email from an app built on Hexclave.
` + + `The app hasn't configured its own email server yet, so it was sent through Hexclave's shared development email server. If this is your app, set up a custom email server in your Hexclave dashboard to send emails from your own domain. If you don't recognize this app, you can ignore this email.` + + `
`; + + const noticeText = `[Development email from an app built on Hexclave]\n` + + `The app hasn't configured its own email server yet, so it was sent through Hexclave's shared development email server. If this is your app, set up a custom email server in your Hexclave dashboard to send emails from your own domain. If you don't recognize this app, you can ignore this email.\n\n`; + + return { + subject: wrappedSubject, + html: content.html === undefined ? undefined : injectDevNoticeIntoHtml(content.html, noticeHtml), + text: content.text === undefined ? undefined : noticeText + content.text, + }; +} + +// Insert the notice just inside so it stays valid markup for full HTML documents; fall back to prepending for fragments. +function injectDevNoticeIntoHtml(html: string, noticeHtml: string): string { + const bodyOpenTag = /]*>/i; + if (bodyOpenTag.test(html)) { + return html.replace(bodyOpenTag, (match) => match + noticeHtml); + } + return noticeHtml + html; +} + export async function getEmailConfig(tenancy: Tenancy): Promise { const projectEmailConfig = tenancy.config.emails.server; diff --git a/apps/e2e/tests/backend/endpoints/api/v1/send-email.test.ts b/apps/e2e/tests/backend/endpoints/api/v1/send-email.test.ts index 9c6999c6d..a681babaa 100644 --- a/apps/e2e/tests/backend/endpoints/api/v1/send-email.test.ts +++ b/apps/e2e/tests/backend/endpoints/api/v1/send-email.test.ts @@ -1,3 +1,4 @@ +import { DEFAULT_TEMPLATE_IDS } from "@hexclave/shared/dist/helpers/emails"; import { randomUUID } from "crypto"; import { describe } from "vitest"; import { it } from "../../../../helpers"; @@ -80,43 +81,6 @@ describe("invalid requests", () => { `); }); - it("should return 400 when using shared email config", async ({ expect }) => { - await Project.createAndSwitch(); - const createUserResponse = await niceBackendFetch("/api/v1/users", { - method: "POST", - accessType: "server", - body: { - primary_email: "test@example.com", - }, - }); - const response = await niceBackendFetch( - "/api/v1/emails/send-email", - { - method: "POST", - accessType: "server", - body: { - user_ids: [createUserResponse.body.id], - html: "

Test email

", - subject: "Test Subject", - notification_category_name: "Marketing", - } - } - ); - expect(response).toMatchInlineSnapshot(` - NiceResponse { - "status": 400, - "body": { - "code": "REQUIRES_CUSTOM_EMAIL_SERVER", - "error": "This action requires a custom SMTP server. Please edit your email server configuration and try again.", - }, - "headers": Headers { - "x-stack-known-error": "REQUIRES_CUSTOM_EMAIL_SERVER", -