Skip to content
Open
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { deleteManagedEmailProvider } from "@/lib/managed-email-onboarding";
import { createSmartRouteHandler } from "@/route-handlers/smart-route-handler";
import { adaptSchema, adminAuthTypeSchema, yupNumber, yupObject, yupString } from "@stackframe/stack-shared/dist/schema-fields";

export const POST = createSmartRouteHandler({
metadata: {
hidden: true,
},
request: yupObject({
auth: yupObject({
type: adminAuthTypeSchema.defined(),
tenancy: adaptSchema.defined(),
}).defined(),
body: yupObject({
resend_domain_id: yupString().defined(),
}).defined(),
Comment thread
mantrakp04 marked this conversation as resolved.
method: yupString().oneOf(["POST"]).defined(),
}),
response: yupObject({
statusCode: yupNumber().oneOf([200]).defined(),
bodyType: yupString().oneOf(["json"]).defined(),
body: yupObject({
status: yupString().oneOf(["deleted"]).defined(),
}).defined(),
}),
handler: async ({ auth, body }) => {
const result = await deleteManagedEmailProvider({
tenancy: auth.tenancy,
resendDomainId: body.resend_domain_id,
});

return {
statusCode: 200,
bodyType: "json",
body: {
status: result.status,
},
};
},
});
25 changes: 25 additions & 0 deletions apps/backend/src/lib/managed-email-domains.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -224,3 +224,28 @@ export async function listManagedEmailDomainsForTenancy(tenancyId: string): Prom
`);
return rows.map(mapRow);
}

export async function deleteManagedEmailDomainById(id: string): Promise<ManagedEmailDomain | null> {
const rows = await globalPrismaClient.$queryRaw<ManagedEmailDomainRow[]>(Prisma.sql`
DELETE FROM "ManagedEmailDomain"
WHERE "id" = ${id}
RETURNING *
`);
if (rows.length === 0) {
return null;
}
return mapRow(rows[0]!);
}

export async function countManagedEmailDomainsBySubdomainExcludingId(options: {
subdomain: string,
excludeId: string,
}): Promise<number> {
const rows = await globalPrismaClient.$queryRaw<{ count: bigint }[]>(Prisma.sql`
SELECT COUNT(*)::bigint AS count
FROM "ManagedEmailDomain"
WHERE "subdomain" = ${options.subdomain}
AND "id" <> ${options.excludeId}
`);
Comment thread
mantrakp04 marked this conversation as resolved.
return Number(rows[0]?.count ?? 0n);
}
84 changes: 83 additions & 1 deletion apps/backend/src/lib/managed-email-onboarding.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import {
getManagedEmailDomainByTenancyAndSubdomain,
listManagedEmailDomainsForTenancy,
markManagedEmailDomainApplied,
countManagedEmailDomainsBySubdomainExcludingId,
deleteManagedEmailDomainById,
updateManagedEmailDomainWebhookStatus,
} from "@/lib/managed-email-domains";
import { Tenancy } from "@/lib/tenancies";
Expand Down Expand Up @@ -225,6 +227,26 @@ async function createDnsimpleZone(subdomain: string): Promise<DnsimpleZone> {
};
}

async function deleteDnsimpleZoneByName(zoneName: string): Promise<{ status: "deleted" | "not_found" }> {
const dnsimpleBaseUrl = getDnsimpleBaseUrl();
const dnsimpleAccountId = getDnsimpleAccountId();
const response = await fetch(`${dnsimpleBaseUrl}/${encodeURIComponent(dnsimpleAccountId)}/zones/${encodeURIComponent(zoneName)}`, {
method: "DELETE",
headers: getDnsimpleHeaders(),
});
if (response.status === 404) {
return { status: "not_found" };
}
if (!response.ok) {
const responseBody = await response.text();
throw new StatusError(
502,
`DNSimple returned ${response.status} when deleting managed email zone ${zoneName}: ${responseBody.slice(0, 500)}`,
);
}
return { status: "deleted" };
}

async function createOrReuseDnsimpleZone(subdomain: string): Promise<DnsimpleZone> {
const existingZones = await listDnsimpleZones(subdomain);
if (existingZones.length > 1) {
Expand Down Expand Up @@ -650,6 +672,67 @@ export async function applyManagedEmailProvider(options: {
return { status: "applied" };
}

function isManagedEmailDomainInUseForTenancy(options: {
tenancy: Tenancy,
subdomain: string,
senderLocalPart: string,
}): boolean {
const emailServer = options.tenancy.config.emails.server;
return emailServer.provider === "managed"
&& emailServer.managedSubdomain === options.subdomain
&& emailServer.managedSenderLocalPart === options.senderLocalPart;
}

export async function deleteManagedEmailProvider(options: {
tenancy: Tenancy,
resendDomainId: string,
}): Promise<{ status: "deleted" }> {
const domain = await getManagedEmailDomainByResendDomainId(options.resendDomainId);
if (!domain || domain.tenancyId !== options.tenancy.id) {
throw new StatusError(404, "Managed domain not found for this project/branch");
}
if (isManagedEmailDomainInUseForTenancy({
tenancy: options.tenancy,
subdomain: domain.subdomain,
senderLocalPart: domain.senderLocalPart,
})) {
throw new StatusError(409, "Cannot delete a managed domain that is currently in use for sending email");
}

// External cleanup must succeed before we drop the DB row; otherwise a failure here
// would leak provider-side resources with no record left to retry against.
if (!shouldUseMockManagedEmailOnboarding()) {
const resendApiKey = getEnvVariable("STACK_RESEND_API_KEY");
const resendResponse = await fetch(`https://api.resend.com/domains/${encodeURIComponent(domain.resendDomainId)}`, {
method: "DELETE",
headers: {
"Authorization": `Bearer ${resendApiKey}`,
},
});
if (!resendResponse.ok && resendResponse.status !== 404) {
const responseBody = await resendResponse.text();
throw new StatusError(
502,
`Upstream email provider returned ${resendResponse.status} when deleting managed domain ${domain.resendDomainId}: ${responseBody.slice(0, 500)}`,
);
}

// createOrReuseDnsimpleZone lets multiple ManagedEmailDomain rows share a zone (when
// two tenancies pick the same subdomain). Only delete the zone if this row is the
// last one referencing it.
const remaining = await countManagedEmailDomainsBySubdomainExcludingId({
subdomain: domain.subdomain,
excludeId: domain.id,
});
if (remaining === 0) {
await deleteDnsimpleZoneByName(domain.subdomain);
}
Comment thread
mantrakp04 marked this conversation as resolved.
}

await deleteManagedEmailDomainById(domain.id);
return { status: "deleted" };
}

export async function processResendDomainWebhookEvent(options: {
domainId: string,
providerStatusRaw: string,
Expand Down Expand Up @@ -691,4 +774,3 @@ async function saveManagedEmailProviderConfig(options: {
},
});
}

Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Loading