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
635 changes: 622 additions & 13 deletions addons/dns/action.ts

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions addons/dns/addon.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ export const DNS_ADDON: AddonDefinition = {
docs: "docs/dns.md",
added: "2.0.0",
changed: [
{ in: "2.2.0", note: "Each site now has a DNS tab and an upgraded SSL/TLS status card. Administrators can delegate site-scoped Read or Site Write DNS access (including safe verification TXT records and Let's Encrypt retries on self-signed sites) to Site Managers and Users under Addons -> Access." },
{ in: "2.2.0", note: "DNS profiles now separate a domain's HTTP role (Site, Redirect, or DNS-only) from its independent Mail role (None, Mailcow, Google Workspace, DMARC, or custom record templates). Existing combinatorial profiles such as Web and Mailcow migrate automatically without changing live DNS records, and Mailcow now has its own tab that stays hidden behind a Connect Mailcow card until linked." },
{ in: "2.2.0", note: "Cloudflare zone-wide edge settings (SSL/TLS mode, Always Use HTTPS, Let's Encrypt and webmail Full SSL rules, and WAF skip IPs) moved out of DNS profiles into Firewall's Cloudflare edge tab. Existing zone options migrate automatically on upgrade." },
{ in: "2.2.0", note: "With Panel Tweaks' automatic SSL on, a new site whose DNS zone was just created now waits for its nameservers (shown to copy) instead of requesting a certificate that would fail. With DNS also on Automatic, self-signed sites made outside Create Site in the last 15 minutes, such as with clpctl, are queued for a certificate request once DNS is ready." },
Expand All @@ -30,6 +31,7 @@ export const DNS_ADDON: AddonDefinition = {
actionNeeded: DNS_ACTIONS,
handler: handle,
action: runDnsAction,
delegatable: true,
// From the page a new site lands on and from its SSL/TLS page, by whoever
// can open them; root refuses a site that is not the caller's.
selfScopedRoutes: ["GET /api/session", "POST /api/provision", "GET /api/site"],
Expand Down
111 changes: 105 additions & 6 deletions addons/dns/app/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
import { errorBlock, htmlResponse, jsonResponse, newCsrfToken, validateDomain, readMutation } from "../../../lib/app-http";
import { errorMessage } from "../../../lib/errors";
import { errorBlock, htmlResponse, jsonResponse, newCsrfToken, redirectResponse, validateDomain, readMutation } from "../../../lib/app-http";
import { embedLandingUrl } from "../../../lib/shadow-embed";
import { visibleAddonTabSlugs } from "../../../lib/delegated-access";
import { dnsService } from "./service";
import { dashboardContent, dashboardView, layout } from "./views";
import { siteFragment, siteLayout, siteView } from "./site-view";
import type { WebVerb } from "../../../lib/gateway-protocol";

const CHANGES: Record<string, WebVerb<"dns">> = {
Expand Down Expand Up @@ -49,29 +53,124 @@ export async function handle(
path: string,
notice?: { current: string; latest: string } | null,
_server?: unknown,
auth?: { user: string; roles: string[] } | null,
auth?: { user: string; roles: string[]; accessLevel?: "read" | "write" } | null,
): Promise<Response> {
const url = new URL(req.url);
const admin = auth === undefined ? true : Boolean(auth?.roles.includes("ROLE_ADMIN"));
const canWrite = admin || auth?.accessLevel === "write";
const canReadSite = admin || auth?.accessLevel === "read" || auth?.accessLevel === "write";
// Cached site reads are kept per viewer and access level, so one person's answer never reaches another.
const viewer = admin ? "admin" : `user:${auth?.user ?? ""}:${auth?.accessLevel ?? ""}`;

if (req.method === "GET" && path === "/api/session") return jsonResponse({ ok: true }, { csrf: newCsrfToken() });
if (req.method === "POST" && path === "/api/provision") return provision(req, auth);
if (req.method === "GET" && path === "/api/site") {
const domain = validateDomain(new URL(req.url).searchParams.get("domain"));
const domain = validateDomain(url.searchParams.get("domain"));
if (!domain) return jsonResponse({ ok: false, error: "invalid domain" }, { status: 400 });
if (!auth?.user) return jsonResponse({ ok: false, error: "not found" }, { status: 404 });
const result = await dnsService.siteStatus(domain, auth.roles.includes("ROLE_ADMIN") ? undefined : auth.user);
const result = await dnsService.siteStatus(domain, admin ? undefined : auth.user);
return jsonResponse(result, { status: result.ok ? 200 : 400 });
}
if (req.method === "GET" && path === "/api/panel-host-helper") {
const result = await dnsService.panelHostHelper();

// Delegated site-scoped DNS tab and SSL/TLS card routes.
if (req.method === "GET" && path === "/api/site/detail") {
if (!canReadSite) return jsonResponse({ ok: false, error: "access denied" }, { status: 403 });
const domain = validateDomain(url.searchParams.get("domain"));
if (!domain) return jsonResponse({ ok: false, error: "invalid domain" }, { status: 400 });
const result = await dnsService.siteDetail(domain, { viewer, cached: url.searchParams.get("cached") === "1" });
return jsonResponse(result, { status: result.ok ? 200 : 400 });
}
if (req.method === "POST" && (path === "/api/site/sync" || path === "/api/site/retry-ssl")) {
if (!canWrite) return jsonResponse({ ok: false, error: "Site Write access required" }, { status: 403 });
const body = await readMutation(req, 4 * 1024);
if (body instanceof Response) return body;
const domain = validateDomain(body.domain);
if (!domain) return jsonResponse({ ok: false, error: "invalid domain" }, { status: 400 });
const result = path === "/api/site/sync"
? await dnsService.siteSync(domain)
: await dnsService.siteRetrySsl(domain);
if (!result.ok || !result.data) return jsonResponse(result, { status: 400 });
return jsonResponse({
ok: true,
data: result.data.detail,
notice: result.data.notice,
html: siteView(result.data.detail, { canWrite }),
});
}
if ((req.method === "POST" || req.method === "DELETE") && path === "/api/site/txt") {
if (!canWrite) return jsonResponse({ ok: false, error: "Site Write access required" }, { status: 403 });
const body = await readMutation(req, 8 * 1024);
if (body instanceof Response) return body;
const domain = validateDomain(body.domain);
if (!domain) return jsonResponse({ ok: false, error: "invalid domain" }, { status: 400 });
const result = req.method === "POST"
? await dnsService.siteTxtAdd(domain, {
name: typeof body.name === "string" ? body.name : "",
content: typeof body.content === "string" ? body.content : "",
})
: await dnsService.siteTxtDelete(domain, typeof body.id === "string" ? body.id : "");
if (!result.ok || !result.data) return jsonResponse(result, { status: 400 });
return jsonResponse({
ok: true,
data: result.data.detail,
notice: result.data.notice,
html: siteView(result.data.detail, { canWrite }),
});
}
if (req.method === "GET" && path === "/fragment") {
if (!canReadSite) return jsonResponse({ ok: false, error: "access denied" }, { status: 403 });
const csrf = newCsrfToken();
const domain = validateDomain(url.searchParams.get("domain"));
if (!domain) return jsonResponse({ ok: false, error: "that is not a valid hostname" }, { status: 400 });
const result = await dnsService.siteDetail(domain, { viewer });
if (!result.ok || !result.data) {
const message = result.error ?? "DNS status unavailable";
return jsonResponse({ ok: false, error: message }, { status: /not one of yours|access denied/i.test(message) ? 403 : /no site/i.test(message) ? 404 : 400 });
}
return jsonResponse(siteFragment(`DNS — ${domain}`, siteView(result.data, { canWrite })), { csrf });
}
if (req.method === "GET" && path === "/") {
const selected = url.searchParams.get("domain");
if (selected) {
if (!canReadSite) return jsonResponse({ ok: false, error: "access denied" }, { status: 403 });
const csrf = newCsrfToken();
const target = validateDomain(selected);
if (target && url.searchParams.get("embed") !== "0") {
return redirectResponse(embedLandingUrl(target, "dns"));
}
if (!target) {
return htmlResponse(siteLayout("Invalid site", errorBlock("That is not a valid hostname."), notice, undefined, admin), { status: 400, csrf });
}
try {
const page = await dnsService.sitePage(target, { viewer });
const slugs = visibleAddonTabSlugs(auth?.roles, auth?.user);
const context = slugs ? { ...page.context, addonSlugs: slugs } : page.context;
return htmlResponse(
siteLayout(`DNS — ${target}`, siteView(page.detail, { canWrite }), notice, context, admin),
{ csrf },
);
} catch (error) {
const message = errorMessage(error);
const status = /not one of yours|access denied/i.test(message) ? 403 : /not found|no site/i.test(message) ? 404 : 500;
return htmlResponse(siteLayout("DNS", errorBlock(message), notice, undefined, admin), { status, csrf });
}
}
if (!admin) return jsonResponse({ ok: false, error: "administrator role required" }, { status: 403 });
const csrf = newCsrfToken();
const result = await dnsService.state();
if (!result.ok || !result.data) {
return htmlResponse(layout("DNS", errorBlock(result.error ?? "DNS state is unavailable"), notice), { status: 500, csrf });
}
return htmlResponse(layout("DNS", dashboardView(result.data), notice), { csrf });
}

// Everything below is strictly administrator-only (fleet, profiles, connections, DNS-only domains, Mailcow, panel host).
if (!admin) return jsonResponse({ ok: false, error: "administrator role required" }, { status: 403 });

if (req.method === "GET" && path === "/api/panel-host-helper") {
const result = await dnsService.panelHostHelper();
return jsonResponse(result, { status: result.ok ? 200 : 400 });
}
if (req.method === "POST" && CHANGES[path]) {
const body = await readMutation(req, 256 * 1024);
if (body instanceof Response) return body;
Expand Down
115 changes: 112 additions & 3 deletions addons/dns/app/service.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,96 @@
import { callGatewayAction, type ActionResult } from "../../../lib/gateway-client";
import type { WebVerb } from "../../../lib/gateway-protocol";
import type { DnsReply, PanelHostHelper, ProvisionReply, SiteDnsStatus } from "../action";
import { fetchPanelInfo } from "../../../lib/snapshot-reader";
import type { SiteContext } from "../../../lib/site-context";
import type { DnsReply, PanelHostHelper, ProvisionReply, SiteDnsDetail, SiteDnsStatus } from "../action";

/** Verbs that read Cloudflare and Mailcow wait for them; everything else is a file write. */
const SLOW = new Set<WebVerb<"dns">>(["check", "confirm", "save-connection", "remove-connection", "save-mailcow", "remove-mailcow", "save-server", "remove-records"]);

/** How long a live site read is reused, so reopening a site's tabs does not read the provider each time. */
const DETAIL_TTL = 60_000;
const DETAIL_MAX = 200;
const detailCache = new Map<string, { at: number; result: ActionResult<SiteDnsDetail> }>();
let detailGeneration = 0;

export interface SiteDetailOptions {
previewUser?: string;
/** Answer from the last stored check, with no provider call. */
cached?: boolean;
/** Who is asking, so one viewer's answer is never another's. */
viewer?: string;
}

function detailKey(domain: string, options: SiteDetailOptions): string {
return JSON.stringify([domain, options.viewer ?? "", options.previewUser ?? "", options.cached === true]);
}

/** Forgets cached site reads for `domain`, or for every site after a fleet change. */
export function forgetSiteDetail(domain?: string): void {
detailGeneration++;
if (!domain) {
detailCache.clear();
return;
}
for (const key of [...detailCache.keys()]) {
if ((JSON.parse(key) as unknown[])[0] === domain) detailCache.delete(key);
}
}

async function siteDetail(domain: string, options: SiteDetailOptions = {}): Promise<ActionResult<SiteDnsDetail>> {
// Only admins reuse reads: a non-admin's answer depends on site ownership,
// which CloudPanel can change without telling us. Cached-flag reads already
// skip provider calls at root, and previews must reflect policy edits at once.
const useCache = options.viewer === "admin" && !options.cached && !options.previewUser;
const key = detailKey(domain, options);
const now = Date.now();
const generation = detailGeneration;
if (useCache) {
const hit = detailCache.get(key);
if (hit && now - hit.at < DETAIL_TTL) return hit.result;
}
const result = await callGatewayAction(
"dns", "site-detail",
[
`--domain=${domain}`,
...(options.previewUser ? [`--preview-user=${options.previewUser}`] : []),
...(options.cached ? ["--cached"] : []),
],
undefined, { timeout: 60_000 },
);
if (!result.ok || !useCache || generation !== detailGeneration) return result;
for (const [cachedKey, entry] of detailCache) {
if (now - entry.at >= DETAIL_TTL) detailCache.delete(cachedKey);
}
if (detailCache.size >= DETAIL_MAX) detailCache.delete(detailCache.keys().next().value!);
detailCache.set(key, { at: now, result });
Comment thread
7heMech marked this conversation as resolved.
Resolved
return result;
}

/** Runs a site write and drops that site's cached reads, whatever the answer. */
async function siteWrite<T>(domain: string, write: Promise<ActionResult<T>>): Promise<ActionResult<T>> {
try {
return await write;
} finally {
forgetSiteDetail(domain);
}
}

export interface DnsSitePage {
detail: SiteDnsDetail;
context: SiteContext;
}

export const dnsService = {
state: (): Promise<ActionResult<DnsReply>> => callGatewayAction("dns", "list"),
panelHostHelper: (): Promise<ActionResult<PanelHostHelper>> => callGatewayAction("dns", "panel-host-helper"),
change: (verb: WebVerb<"dns">, body: unknown): Promise<ActionResult<DnsReply>> =>
callGatewayAction("dns", verb, [], JSON.stringify(body), { timeout: SLOW.has(verb) ? 300_000 : 120_000 }),
async change(verb: WebVerb<"dns">, body: unknown): Promise<ActionResult<DnsReply>> {
try {
return await callGatewayAction("dns", verb, [], JSON.stringify(body), { timeout: SLOW.has(verb) ? 300_000 : 120_000 });
} finally {
forgetSiteDetail();
}
},
siteStatus: (domain: string, asUser?: string): Promise<ActionResult<SiteDnsStatus>> =>
callGatewayAction("dns", "site-status", [`--domain=${domain}`, ...(asUser ? [`--as-user=${asUser}`] : [])]),
provision: (domain: string, options: { asUser?: string; ssl?: boolean }): Promise<ActionResult<ProvisionReply>> =>
Expand All @@ -18,4 +99,32 @@ export const dnsService = {
[`--domain=${domain}`, ...(options.asUser ? [`--as-user=${options.asUser}`] : []), ...(options.ssl ? ["--ssl"] : [])],
undefined, { timeout: 280_000 },
),
siteDetail,
async sitePage(domain: string, options: SiteDetailOptions = {}): Promise<DnsSitePage> {
const [panel, res] = await Promise.all([
fetchPanelInfo(),
siteDetail(domain, options),
]);
if (!res.ok || !res.data) throw new Error(res.error ?? `DNS status for ${domain} could not be read`);
const panelSite = panel.sites.find((candidate) => candidate.domain.toLowerCase() === domain.toLowerCase());
if (!panelSite) throw new Error(`CloudPanel site not found: ${domain}`);
return {
detail: res.data,
context: {
domain: panelSite.domain,
user: panelSite.user,
type: panelSite.type,
varnishCache: panelSite.varnishCache,
...(panel.publicIp ? { publicIp: panel.publicIp } : {}),
},
};
},
siteSync: (domain: string): Promise<ActionResult<{ detail: SiteDnsDetail; notice: string }>> =>
siteWrite(domain, callGatewayAction("dns", "site-sync", [`--domain=${domain}`], undefined, { timeout: 120_000 })),
siteRetrySsl: (domain: string): Promise<ActionResult<{ detail: SiteDnsDetail; notice: string }>> =>
siteWrite(domain, callGatewayAction("dns", "site-retry-ssl", [`--domain=${domain}`], undefined, { timeout: 210_000 })),
siteTxtAdd: (domain: string, body: { name: string; content: string }): Promise<ActionResult<{ detail: SiteDnsDetail; notice: string }>> =>
siteWrite(domain, callGatewayAction("dns", "site-txt-add", [`--domain=${domain}`], JSON.stringify(body), { timeout: 60_000 })),
siteTxtDelete: (domain: string, id: string): Promise<ActionResult<{ detail: SiteDnsDetail; notice: string }>> =>
siteWrite(domain, callGatewayAction("dns", "site-txt-delete", [`--domain=${domain}`], JSON.stringify({ id }), { timeout: 60_000 })),
};
Loading