From 8a2a29c17a08d03c571a3d83aa3e9519ac28607d Mon Sep 17 00:00:00 2001 From: TheRealToxicDev Date: Tue, 20 Oct 2026 18:54:37 -0600 Subject: [PATCH] fix: more known issues --- CHANGELOG.md | 4 ++ .../_components/admin-command-search.tsx | 8 +-- .../domains/[domainId]/delete-domain.tsx | 5 +- .../(dashboard)/domains/[domainId]/page.tsx | 16 +++++- .../domains/[domainId]/region-move-card.tsx | 6 ++- apps/web/src/components/DeleteResource.tsx | 9 +++- apps/web/src/server/aws/ses.ts | 49 +++++++++++-------- .../server/service/domain-region-service.ts | 13 ++++- .../domain-region-service.unit.test.ts | 35 +++++++++++++ apps/web/src/server/service/domain-service.ts | 43 ++++++++++++++-- .../service/domain-service.unit.test.ts | 4 +- .../server/service/inbound-domain-service.ts | 19 ++++++- 12 files changed, 173 insertions(+), 38 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ffd12b5..24c56d7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -39,6 +39,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed - Batch sends now respect an API key's domain restriction +- Moving a domain that receives email to another sending region keeps receiving working: the identity it receives through is kept, and removed when receiving is turned off or the domain is deleted +- Deleting a domain works again when its Amazon SES identity is already gone, shows an error if it fails, and accepts the name typed in any case (phone keyboards capitalise it) +- **Verify again** on a verified domain now re-checks its DNS straight away, updates the problem banner, and says what it found. Record rows show a problem the DNS monitor found instead of an old "Verified" +- Moving a domain to another region now waits until its MX record points at the new region. Before, a move could finish with the MX still on the old region, which sent bounces and complaints to the wrong place - Installing the repo with pnpm 9 no longer fails on Prisma Studio's pnpm 8 requirement, so the web tests run in CI again --- diff --git a/apps/web/src/app/(dashboard)/admin/_components/admin-command-search.tsx b/apps/web/src/app/(dashboard)/admin/_components/admin-command-search.tsx index 8dff35b..92f7ab8 100644 --- a/apps/web/src/app/(dashboard)/admin/_components/admin-command-search.tsx +++ b/apps/web/src/app/(dashboard)/admin/_components/admin-command-search.tsx @@ -55,11 +55,11 @@ export function AdminCommandSearch() { = ({ domain }) => { .object({ confirmation: z.string().min(1, "Please type the domain name to confirm"), }) - .refine((data) => data.confirmation === domain.name, { + .refine((data) => data.confirmation.trim().toLowerCase() === domain.name.toLowerCase(), { message: "Domain name does not match", path: ["confirmation"], }); @@ -33,6 +33,9 @@ export const DeleteDomain: React.FC<{ domain: Domain }> = ({ domain }) => { toast.success(`Domain ${domain.name} deleted`); router.replace("/domains"); }, + onError: (error) => { + toast.error(error.message || "Couldn't delete this domain. Try again."); + }, }, ); } diff --git a/apps/web/src/app/(dashboard)/domains/[domainId]/page.tsx b/apps/web/src/app/(dashboard)/domains/[domainId]/page.tsx index e89e0eb..41c074d 100644 --- a/apps/web/src/app/(dashboard)/domains/[domainId]/page.tsx +++ b/apps/web/src/app/(dashboard)/domains/[domainId]/page.tsx @@ -80,8 +80,20 @@ export default function DomainItemPage({ verifyQuery.mutate( { id: Number(domainId) }, { - onSettled: () => { - domainQuery.refetch(); + onSuccess: async () => { + const { data } = await domainQuery.refetch(); + if (!data || data.isVerifying) return; + const issues = Array.isArray(data.dnsIssues) ? (data.dnsIssues as string[]) : []; + if (data.status !== DomainStatus.SUCCESS) { + toast.error("Some records still aren't right. Check the table below."); + } else if (issues.length) { + toast.warning(`Verified with SES, but ${issues.length === 1 ? "1 DNS record needs" : `${issues.length} DNS records need`} fixing.`); + } else { + toast.success("All records check out."); + } + }, + onError: (error) => { + toast.error(error.message || "Couldn't check the records. Try again."); }, }, ); diff --git a/apps/web/src/app/(dashboard)/domains/[domainId]/region-move-card.tsx b/apps/web/src/app/(dashboard)/domains/[domainId]/region-move-card.tsx index 006ee3e..2fd1bc2 100644 --- a/apps/web/src/app/(dashboard)/domains/[domainId]/region-move-card.tsx +++ b/apps/web/src/app/(dashboard)/domains/[domainId]/region-move-card.tsx @@ -146,7 +146,11 @@ export function RegionMoveCard({ domain }: { domain: DomainResponse }) { ? ` The previous region (${domain.retiredRegion}) is retired after ${format( new Date(new Date(domain.retiredRegionAt).getTime() + 24 * 60 * 60 * 1000), "MMM d, HH:mm", - )}; you can remove its old DKIM record after that.` + )}; ${ + domain.inboundEnabled && !domain.inboundDkimSelector + ? "keep its old DKIM record, because the mail you receive still uses it." + : "you can remove its old DKIM record after that." + }` : ""}

diff --git a/apps/web/src/components/DeleteResource.tsx b/apps/web/src/components/DeleteResource.tsx index dc249a9..bc2afea 100644 --- a/apps/web/src/components/DeleteResource.tsx +++ b/apps/web/src/components/DeleteResource.tsx @@ -163,7 +163,14 @@ export const DeleteResource = <
- +
{formState.errors.confirmation ? ( diff --git a/apps/web/src/server/aws/ses.ts b/apps/web/src/server/aws/ses.ts index c4f0daa..e04e632 100644 --- a/apps/web/src/server/aws/ses.ts +++ b/apps/web/src/server/aws/ses.ts @@ -165,32 +165,41 @@ export async function deleteDomain( sesTenantId?: string ) { const sesClient = getSesClient(region); + const isNotFound = (error: unknown) => (error as { name?: string })?.name === "NotFoundException"; if (sesTenantId) { - const tenantResourceAssociationCommand = - new DeleteTenantResourceAssociationCommand({ - TenantName: sesTenantId, - ResourceArn: await getIdentityArn(domain, region), - }); - - const tenantResourceAssociationResponse = await sesClient.send( - tenantResourceAssociationCommand - ); - - if (tenantResourceAssociationResponse.$metadata.httpStatusCode !== 200) { - logger.error( - { tenantResourceAssociationResponse }, - "Failed to delete tenant resource association" + try { + const tenantResourceAssociationResponse = await sesClient.send( + new DeleteTenantResourceAssociationCommand({ + TenantName: sesTenantId, + ResourceArn: await getIdentityArn(domain, region), + }) ); - throw new Error("Failed to delete tenant resource association"); + + if (tenantResourceAssociationResponse.$metadata.httpStatusCode !== 200) { + logger.error( + { tenantResourceAssociationResponse }, + "Failed to delete tenant resource association" + ); + throw new Error("Failed to delete tenant resource association"); + } + } catch (error) { + if (!isNotFound(error)) throw error; } } - const command = new DeleteEmailIdentityCommand({ - EmailIdentity: domain, - }); - const response = await sesClient.send(command); - return response.$metadata.httpStatusCode === 200; + try { + const response = await sesClient.send( + new DeleteEmailIdentityCommand({ EmailIdentity: domain }) + ); + return response.$metadata.httpStatusCode === 200; + } catch (error) { + if (isNotFound(error)) { + logger.info({ domain, region }, "SES identity already gone; treating as deleted"); + return true; + } + throw error; + } } export async function getDomainIdentity(domain: string, region: string) { diff --git a/apps/web/src/server/service/domain-region-service.ts b/apps/web/src/server/service/domain-region-service.ts index 4202ee8..dd28d83 100644 --- a/apps/web/src/server/service/domain-region-service.ts +++ b/apps/web/src/server/service/domain-region-service.ts @@ -5,6 +5,8 @@ import { logger } from "~/server/logger/log"; import { ByteSendApiError } from "../public-api/api-error"; import type { DomainDnsRecord } from "~/types/domain"; import { SesSettingsService } from "./ses-settings-service"; +import { env } from "~/env"; +import { receivesThroughKeptIdentity } from "./inbound-domain-service"; import { checkDkimDnsRecord, checkMxDnsRecord, @@ -145,7 +147,9 @@ export class DomainRegionService { const dnsPrecheck: { dkim: DnsCheckResult; mx: DnsCheckResult } = { dkim: dkimDns, mx: mxDns }; const dkimStatus = parseDomainStatus(identity.DkimAttributes?.Status?.toString()); - const mailFromStatus = parseDomainStatus(identity.MailFromAttributes?.MailFromDomainStatus?.toString()); + const sesMailFromStatus = parseDomainStatus(identity.MailFromAttributes?.MailFromDomainStatus?.toString()); + const mailFromStatus = + sesMailFromStatus === DomainStatus.SUCCESS && mxDns !== "found" ? DomainStatus.PENDING : sesMailFromStatus; const identityVerified = parseDomainStatus(identity.VerificationStatus?.toString()) === DomainStatus.SUCCESS; if (identityVerified && dkimStatus === DomainStatus.SUCCESS && mailFromStatus === DomainStatus.SUCCESS) { @@ -189,7 +193,12 @@ export class DomainRegionService { if (!domain.retiredRegion || !domain.retiredRegionAt) return false; if (now - domain.retiredRegionAt.getTime() < RETIRE_OLD_REGION_AFTER_MS) return false; - if (domain.retiredRegion !== domain.region) { + const keepForReceiving = domain.retiredRegion === env.INBOUND_REGION && receivesThroughKeptIdentity(domain); + if (keepForReceiving) { + logger.info({ domainId: domain.id, region: domain.retiredRegion }, "[DomainRegionService]: Kept the old identity because the domain receives mail through it"); + } + + if (domain.retiredRegion !== domain.region && !keepForReceiving) { try { await ses.deleteDomain(domain.name, domain.retiredRegion, domain.sesTenantId ?? undefined); } catch (error) { diff --git a/apps/web/src/server/service/domain-region-service.unit.test.ts b/apps/web/src/server/service/domain-region-service.unit.test.ts index a312c4d..c2b9223 100644 --- a/apps/web/src/server/service/domain-region-service.unit.test.ts +++ b/apps/web/src/server/service/domain-region-service.unit.test.ts @@ -11,6 +11,7 @@ const { mockSes, mockDb, mockGetSetting, mockEmitDomainEvent, mockCheckDkim, moc })); vi.mock("~/server/aws/ses", () => mockSes); +vi.mock("~/env", () => ({ env: { INBOUND_REGION: "us-east-1" } })); vi.mock("~/server/db", () => ({ db: mockDb })); vi.mock("~/server/logger/log", () => ({ logger: { info: vi.fn(), error: vi.fn() } })); vi.mock("~/server/service/ses-settings-service", () => ({ SesSettingsService: { getSetting: mockGetSetting } })); @@ -146,6 +147,25 @@ describe("DomainRegionService.refresh", () => { expect(mockEmitDomainEvent).not.toHaveBeenCalled(); }); + it("keeps waiting while the MX still points at the old region, even if SES reports MAIL FROM verified", async () => { + mockSes.getDomainIdentity.mockResolvedValue({ + VerificationStatus: "SUCCESS", + DkimAttributes: { Status: "SUCCESS" }, + MailFromAttributes: { MailFromDomainStatus: "SUCCESS" }, + }); + mockCheckMx.mockResolvedValue("not_found"); + + const result = await DomainRegionService.refresh(moving); + + expect(result.switched).toBe(false); + expect(mockCheckMx).toHaveBeenCalledWith(expect.any(String), "eu-west-2"); + expect(mockDb.domain.update).toHaveBeenCalledWith({ + where: { id: 1 }, + data: { pendingDkimStatus: "SUCCESS", pendingMailFromStatus: "PENDING" }, + }); + expect(mockEmitDomainEvent).not.toHaveBeenCalled(); + }); + it("switches region, selector and key once the new identity is fully verified", async () => { mockSes.getDomainIdentity.mockResolvedValue({ VerificationStatus: "SUCCESS", @@ -181,6 +201,21 @@ describe("DomainRegionService.retireOldRegionIfDue", () => { mockDb.domain.update.mockResolvedValue(retired); }); + it("keeps the old identity when the domain receives mail through it", async () => { + const receiving = { ...retired, inboundEnabled: true, inboundSubdomain: "reply", inboundDkimSelector: null }; + const done = await DomainRegionService.retireOldRegionIfDue(receiving, switchedAt.getTime() + RETIRE_OLD_REGION_AFTER_MS + 1); + expect(done).toBe(true); + expect(mockSes.deleteDomain).not.toHaveBeenCalled(); + expect(mockDb.domain.update).toHaveBeenCalledWith({ where: { id: 1 }, data: { retiredRegion: null, retiredRegionAt: null } }); + }); + + it("still retires the old identity when receiving has its own", async () => { + mockSes.deleteDomain.mockResolvedValue(true); + const receiving = { ...retired, inboundEnabled: true, inboundSubdomain: "reply", inboundDkimSelector: "bytesend-inbound" }; + await DomainRegionService.retireOldRegionIfDue(receiving, switchedAt.getTime() + RETIRE_OLD_REGION_AFTER_MS + 1); + expect(mockSes.deleteDomain).toHaveBeenCalledWith("example.com", "us-east-1", undefined); + }); + it("waits out the grace period before deleting the old identity", async () => { const done = await DomainRegionService.retireOldRegionIfDue(retired, switchedAt.getTime() + 60_000); expect(done).toBe(false); diff --git a/apps/web/src/server/service/domain-service.ts b/apps/web/src/server/service/domain-service.ts index 67c4a47..83355c3 100644 --- a/apps/web/src/server/service/domain-service.ts +++ b/apps/web/src/server/service/domain-service.ts @@ -8,6 +8,8 @@ import { NotificationEmitter } from "./notification-emitter"; import util from "util"; import * as tldts from "tldts"; import * as ses from "~/server/aws/ses"; +import { deleteReceivingIdentity } from "../aws/ses-receiving"; +import { receivesThroughKeptIdentity } from "./inbound-domain-service"; import { db } from "~/server/db"; import { env } from "~/env"; import { renderDomainVerificationStatusEmail } from "~/server/email-templates"; @@ -16,7 +18,7 @@ import { sendMail } from "~/server/mailer"; import { getRedis, redisKey } from "~/server/redis"; import { SesSettingsService } from "./ses-settings-service"; import { ByteSendApiError } from "../public-api/api-error"; -import { ApiKey, DomainStatus, type Domain } from "@prisma/client"; +import { ApiKey, DomainStatus, Prisma, type Domain } from "@prisma/client"; import { type DomainPayload, type DomainWebhookEventType, @@ -73,8 +75,12 @@ export function buildDnsRecords(domain: Domain): DomainDnsRecord[] { const mailDomain = `mail${subdomainSuffix}`; const dkimSelector = domain.dkimSelector ?? "bytesend"; + const dnsIssues = Array.isArray(domain.dnsIssues) ? (domain.dnsIssues as string[]) : []; + const brokenNow = (record: "MX" | "DKIM" | "SPF") => dnsIssues.some((issue) => issue.startsWith(record)); const spfStatus = parseDomainStatus(domain.spfDetails); - const dkimStatus = parseDomainStatus(domain.dkimStatus); + const dkimStatus = brokenNow("DKIM") ? DomainStatus.FAILED : parseDomainStatus(domain.dkimStatus); + const mxStatus = brokenNow("MX") ? DomainStatus.FAILED : spfStatus; + const spfTxtStatus = brokenNow("SPF") ? DomainStatus.FAILED : spfStatus; const dmarcStatus = domain.dmarcAdded ? DomainStatus.SUCCESS : DomainStatus.NOT_STARTED; @@ -86,7 +92,7 @@ export function buildDnsRecords(domain: Domain): DomainDnsRecord[] { value: `feedback-smtp.${domain.region}.amazonses.com`, ttl: "Auto", priority: "10", - status: spfStatus, + status: mxStatus, }, { type: "TXT", @@ -100,7 +106,7 @@ export function buildDnsRecords(domain: Domain): DomainDnsRecord[] { name: mailDomain, value: "v=spf1 include:amazonses.com ~all", ttl: "Auto", - status: spfStatus, + status: spfTxtStatus, }, { type: "TXT", @@ -208,6 +214,17 @@ export async function checkMxDnsRecord( * Re-checks the DNS records a verified domain needs and describes anything missing or wrong. * Uses the same record names and checks as verification, so a domain that verified passes. */ +async function recheckDnsHealth(domain: Domain) { + const issues = await checkDomainDnsHealth(domain); + const now = new Date(); + const dnsIssuesSince = issues.length ? (domain.dnsIssuesSince ?? now) : null; + await db.domain.update({ + where: { id: domain.id }, + data: { dnsIssues: issues.length ? issues : Prisma.DbNull, dnsIssuesSince, dnsCheckedAt: now }, + }); + return { dnsIssues: issues.length ? issues : null, dnsIssuesSince, dnsCheckedAt: now }; +} + export async function checkDomainDnsHealth( domain: Pick, ): Promise { @@ -805,8 +822,11 @@ export async function refreshDomainVerification( } } + const dnsHealth = updatedDomain.status === DomainStatus.SUCCESS ? await recheckDnsHealth(updatedDomain) : null; + const normalizedDomain = { ...updatedDomain, + ...dnsHealth, dkimStatus: dkimStatus ?? null, spfDetails: spfDetails ?? null, dmarcAdded: Boolean(dmarcRecord), @@ -920,7 +940,12 @@ export async function deleteDomain(id: number) { throw new Error("Error in deleting domain"); } - for (const extraRegion of [domain.pendingRegion, domain.retiredRegion]) { + const extraRegions = new Set([ + domain.pendingRegion, + domain.retiredRegion, + receivesThroughKeptIdentity(domain) ? env.INBOUND_REGION : null, + ]); + for (const extraRegion of extraRegions) { if (!extraRegion || extraRegion === domain.region) continue; try { await ses.deleteDomain(domain.name, extraRegion, domain.sesTenantId ?? undefined); @@ -932,6 +957,14 @@ export async function deleteDomain(id: number) { } } + if (domain.inboundEnabled && domain.inboundSubdomain && domain.inboundDkimSelector) { + try { + await deleteReceivingIdentity(`${domain.inboundSubdomain}.${domain.name}`); + } catch (error) { + logger.error({ err: error, domainId: id }, "[DomainService]: Failed to delete receiving identity"); + } + } + const deletedRecord = await db.domain.delete({ where: { id } }); try { await clearDomainVerificationState(id); diff --git a/apps/web/src/server/service/domain-service.unit.test.ts b/apps/web/src/server/service/domain-service.unit.test.ts index 534e7fe..b169933 100644 --- a/apps/web/src/server/service/domain-service.unit.test.ts +++ b/apps/web/src/server/service/domain-service.unit.test.ts @@ -338,7 +338,9 @@ describe("domain-service", () => { ]); expect(mockSendMail).toHaveBeenCalledTimes(2); - expect(mockDb.domain.update).toHaveBeenCalledTimes(2); + const updates = mockDb.domain.update.mock.calls.map(([args]) => args.data); + expect(updates.filter((data) => "status" in data)).toHaveLength(2); + expect(updates.filter((data) => "dnsCheckedAt" in data)).toHaveLength(2); }); it("logs and continues when sending the status email fails", async () => { diff --git a/apps/web/src/server/service/inbound-domain-service.ts b/apps/web/src/server/service/inbound-domain-service.ts index 443c318..ac6a701 100644 --- a/apps/web/src/server/service/inbound-domain-service.ts +++ b/apps/web/src/server/service/inbound-domain-service.ts @@ -3,6 +3,8 @@ import { TRPCError } from "@trpc/server"; import type { Domain } from "@prisma/client"; import { env } from "~/env"; import { db } from "../db"; +import * as ses from "../aws/ses"; +import { logger } from "../logger/log"; import { createReceivingIdentity, deleteReceivingIdentity, inboundMxHost, isIdentityVerified } from "../aws/ses-receiving"; const LABEL = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/; @@ -26,6 +28,10 @@ export const RECEIVING_DOMAIN_SELECT = { inboundPublicKey: true, } as const; +export function receivesThroughKeptIdentity(domain: Pick) { + return domain.inboundEnabled && !domain.inboundDkimSelector && domain.region !== env.INBOUND_REGION; +} + export function receivingFqdn(domain: Pick) { return domain.inboundSubdomain ? `${domain.inboundSubdomain}.${domain.name}` : null; } @@ -101,10 +107,21 @@ export async function checkReceiving(teamId: number, domainId: number) { } export async function disableReceiving(teamId: number, domainId: number) { - const domain = await db.domain.findFirst({ where: { id: domainId, teamId }, select: RECEIVING_DOMAIN_SELECT }); + const domain = await db.domain.findFirst({ + where: { id: domainId, teamId }, + select: { ...RECEIVING_DOMAIN_SELECT, pendingRegion: true, retiredRegion: true, sesTenantId: true }, + }); if (!domain) throw new TRPCError({ code: "NOT_FOUND", message: "Domain not found" }); const fqdn = receivingFqdn(domain); if (fqdn && domain.inboundDkimSelector) await deleteReceivingIdentity(fqdn); + const keptIdentityStillNeeded = domain.retiredRegion === env.INBOUND_REGION || domain.pendingRegion === env.INBOUND_REGION; + if (receivesThroughKeptIdentity(domain) && !keptIdentityStillNeeded) { + try { + await ses.deleteDomain(domain.name, env.INBOUND_REGION, domain.sesTenantId ?? undefined); + } catch (error) { + logger.error({ err: error, domainId: domain.id }, "[InboundDomain]: Failed to delete the identity kept for receiving"); + } + } return db.domain.update({ where: { id: domain.id }, data: {