Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

---
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,11 +55,11 @@ export function AdminCommandSearch() {
<button
type="button"
onClick={() => setOpen(true)}
className="flex h-7 items-center gap-2 rounded-md border border-border bg-muted/40 px-2 text-[13px] text-muted-foreground transition-colors hover:bg-muted hover:text-foreground sm:w-64"
className="flex h-7 shrink-0 items-center gap-2 rounded-md border border-border bg-muted/40 px-2 text-[13px] text-muted-foreground transition-colors hover:bg-muted hover:text-foreground sm:w-64"
>
<Search className="size-3.5" />
<span className="hidden flex-1 text-left sm:inline">Search users, teams, domains…</span>
<kbd className="hidden rounded border border-border bg-background px-1 font-mono text-[10px] sm:inline">⌘K</kbd>
<Search className="size-3.5 shrink-0" />
<span className="hidden min-w-0 flex-1 truncate whitespace-nowrap text-left sm:inline">Search users, teams, domains…</span>
<kbd className="hidden shrink-0 rounded border border-border bg-background px-1 font-mono text-[10px] sm:inline">⌘K</kbd>
</button>

<Dialog
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export const DeleteDomain: React.FC<{ domain: Domain }> = ({ 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"],
});
Expand All @@ -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.");
},
},
);
}
Expand Down
16 changes: 14 additions & 2 deletions apps/web/src/app/(dashboard)/domains/[domainId]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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.");
},
},
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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."
}`
: ""}
</p>
</div>
Expand Down
9 changes: 8 additions & 1 deletion apps/web/src/components/DeleteResource.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,14 @@ export const DeleteResource = <
<FormItem>
<FormControl>
<div className="relative">
<Input placeholder={`${resourceName}`} {...field} />
<Input
placeholder={`${resourceName}`}
autoCapitalize="none"
autoCorrect="off"
autoComplete="off"
spellCheck={false}
{...field}
/>
</div>
</FormControl>
{formState.errors.confirmation ? (
Expand Down
49 changes: 29 additions & 20 deletions apps/web/src/server/aws/ses.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
13 changes: 11 additions & 2 deletions apps/web/src/server/service/domain-region-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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) {
Expand Down
35 changes: 35 additions & 0 deletions apps/web/src/server/service/domain-region-service.unit.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 } }));
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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);
Expand Down
43 changes: 38 additions & 5 deletions apps/web/src/server/service/domain-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand All @@ -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,
Expand Down Expand Up @@ -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;
Expand All @@ -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",
Expand All @@ -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",
Expand Down Expand Up @@ -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<Domain, "name" | "subdomain" | "dkimSelector" | "publicKey" | "region">,
): Promise<string[]> {
Expand Down Expand Up @@ -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),
Expand Down Expand Up @@ -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);
Expand All @@ -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);
Expand Down
4 changes: 3 additions & 1 deletion apps/web/src/server/service/domain-service.unit.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 () => {
Expand Down
Loading
Loading