/** * Talk to the hosting control plane about this instance's custom domain. * Only platform-provisioned instances (seeded `custom_domain:api_url` + * `credits:project_id`) can; the parent holds the Cloudflare credentials. */ import type { Kysely } from "kysely"; import { OptionsRepository } from "#db/repositories/options.js"; import type { Database } from "#db/types.js"; export interface PlatformDomainRecord { type: string; name: string; value: string; note?: string; } export interface PlatformDomainResult { success: boolean; error?: string; domain?: string; status?: string; sslStatus?: string | null; active?: boolean; records?: PlatformDomainRecord[]; reset?: boolean; defaultUrl?: string; } export class NotManagedError extends Error {} export async function platformCustomDomain( db: Kysely, body: { domain?: string; action: "check" | "reset" }, ): Promise { const options = new OptionsRepository(db); const map = await options.getMany(["custom_domain:api_url", "credits:project_id"]); const apiUrl = map.get("custom_domain:api_url") ?? ""; const project = map.get("credits:project_id") ?? ""; if (!apiUrl || !project) { throw new NotManagedError( "Custom domains are managed by your hosting platform, which isn't configured for this instance.", ); } const res = await fetch(apiUrl, { method: "POST", headers: { "Content-Type": "application/json", "X-EmDash-Request": "1" }, body: JSON.stringify({ project, domain: body.domain ?? "", action: body.action }), }); let parsed: unknown = null; try { parsed = JSON.parse(await res.text()); } catch { parsed = null; } // The plugin route wraps its result as { success, data: { success, ... } }. const inner = parsed && typeof parsed === "object" && "data" in parsed ? (parsed as { data?: unknown }).data : parsed; const result = (inner && typeof inner === "object" ? inner : {}) as PlatformDomainResult; if (!res.ok || result.success === false) { return { success: false, error: result.error ?? "The hosting platform rejected the request." }; } return { ...result, success: true }; }