-
Notifications
You must be signed in to change notification settings - Fork 516
Managed email domain deletion and Cloudflare DNS import UX #1442
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
mantrakp04
wants to merge
2
commits into
dev
Choose a base branch
from
feat/managed-email-domain-delete-cloudflare-dns
base: dev
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
40 changes: 40 additions & 0 deletions
40
apps/backend/src/app/api/latest/internal/emails/managed-onboarding/delete/route.tsx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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(), | ||
| 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, | ||
| }, | ||
| }; | ||
| }, | ||
| }); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -8,6 +8,8 @@ import { | |
| getManagedEmailDomainByTenancyAndSubdomain, | ||
| listManagedEmailDomainsForTenancy, | ||
| markManagedEmailDomainApplied, | ||
| countManagedEmailDomainsBySubdomainExcludingId, | ||
| deleteManagedEmailDomainById, | ||
| updateManagedEmailDomainWebhookStatus, | ||
| } from "@/lib/managed-email-domains"; | ||
| import { Tenancy } from "@/lib/tenancies"; | ||
|
|
@@ -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)}`, | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. we should never ever return messages with internal information |
||
| ); | ||
| } | ||
| return { status: "deleted" }; | ||
| } | ||
|
|
||
| async function createOrReuseDnsimpleZone(subdomain: string): Promise<DnsimpleZone> { | ||
| const existingZones = await listDnsimpleZones(subdomain); | ||
| if (existingZones.length > 1) { | ||
|
|
@@ -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); | ||
| } | ||
|
mantrakp04 marked this conversation as resolved.
|
||
| } | ||
|
|
||
| await deleteManagedEmailDomainById(domain.id); | ||
| return { status: "deleted" }; | ||
| } | ||
|
|
||
| export async function processResendDomainWebhookEvent(options: { | ||
| domainId: string, | ||
| providerStatusRaw: string, | ||
|
|
@@ -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.
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.