peppa/packages/core/src/edge-dns.ts

166 lines
7.7 KiB
TypeScript

// PEP-231: addresses without the Mac. The server has its own Cloudflare tunnel (cloudflared in
// compose, profile `edge`) with one ingress rule — everything to the server's Traefik. Which names
// reach it is decided by DNS: the platform's address, Bugsink, `<slug>-staging|prod` of every
// project and the hosts of recent deploys get a CNAME to `<tunnel>.cfargotunnel.com`. A record
// pointing to another tunnel (the Mac's) is moved; any other record (A, AAAA, a foreign CNAME) is
// left alone and reported. Nothing is deleted. Without CLOUDFLARE_* nothing happens.
import { projects, releases, type Db } from "@peppa/db";
import { and, gt, isNotNull, isNull } from "drizzle-orm";
export interface EdgeConfig {
api: string;
token: string;
accountId: string;
zoneId: string;
tunnelId: string;
/** One level under it only: Cloudflare's certificate covers `*.telecom.quest`. */
domain: string;
/** Where the tunnel sends everything: the server's Traefik. */
service: string;
}
export const EDGE_COMMENT = "peppa-factory";
const RECENT_DEPLOY_MS = 30 * 24 * 3600_000;
/** The configuration from env, or null when Cloudflare is not set up (or PEPPA_EDGE_DNS=off). */
export function edgeConfig(env: NodeJS.ProcessEnv = process.env): EdgeConfig | null {
if (env.PEPPA_EDGE_DNS === "off") return null;
const { CLOUDFLARE_API_TOKEN: token, CLOUDFLARE_ACCOUNT_ID: accountId, CLOUDFLARE_ZONE_ID: zoneId, CLOUDFLARE_TUNNEL_ID: tunnelId } = env;
if (!token || !accountId || !zoneId || !tunnelId) return null;
return {
api: (env.CLOUDFLARE_API_URL ?? "https://api.cloudflare.com/client/v4").replace(/\/$/, ""),
token,
accountId,
zoneId,
tunnelId,
domain: env.PEPPA_DEPLOY_DOMAIN ?? "telecom.quest",
service: env.PEPPA_EDGE_SERVICE ?? "http://127.0.0.1:8880",
};
}
/** Same rule as the deploy script: exactly one label under the domain. */
export function edgeHostAllowed(host: string, domain: string): boolean {
const h = host.toLowerCase().replace(/\.$/, "");
if (!h.endsWith(`.${domain}`)) return false;
return /^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/.test(h.slice(0, -domain.length - 1));
}
const hostOf = (url: string | undefined) => {
if (!url) return null;
try {
return new URL(url).hostname;
} catch {
return null;
}
};
/** Names that must reach the server, sorted. */
export async function edgeHosts(db: Db, domain: string, o: { now?: number; env?: NodeJS.ProcessEnv } = {}): Promise<string[]> {
const env = o.env ?? process.env;
const now = o.now ?? Date.now();
const platformKey = env.PEPPA_PLATFORM_KEY ?? "PEP";
const names = new Set<string>();
for (const h of [hostOf(env.PEPPA_WEB_URL), hostOf(env.BUGSINK_PUBLIC_URL ?? "https://bugsink.telecom.quest")]) if (h) names.add(h);
for (const p of await db.select({ slug: projects.slug, key: projects.key }).from(projects).where(isNull(projects.deletedAt))) {
if (p.key === platformKey) continue;
for (const env of ["staging", "prod"]) names.add(`${p.slug}-${env}.${domain}`);
}
const recent = await db
.select({ host: releases.host })
.from(releases)
.where(and(isNotNull(releases.host), gt(releases.createdAt, new Date(now - RECENT_DEPLOY_MS))));
for (const r of recent) if (r.host) names.add(r.host.toLowerCase());
return [...names].filter((h) => edgeHostAllowed(h, domain)).sort();
}
interface CfRecord {
id: string;
type: string;
name: string;
content: string;
}
export class CloudflareError extends Error {}
async function cf<T>(cfg: EdgeConfig, method: string, path: string, body?: unknown): Promise<T> {
const res = await fetch(`${cfg.api}${path}`, {
method,
headers: { authorization: `Bearer ${cfg.token}`, "content-type": "application/json" },
body: body === undefined ? undefined : JSON.stringify(body),
signal: AbortSignal.timeout(20_000),
});
const json = (await res.json().catch(() => null)) as { success?: boolean; result?: T; errors?: Array<{ message?: string }> } | null;
if (!res.ok || !json?.success) {
// Never the token: only the path and Cloudflare's messages.
const why = json?.errors?.map((e) => e.message).filter(Boolean).join("; ") || `HTTP ${res.status}`;
throw new CloudflareError(`Cloudflare ${method} ${path.replace(/\?.*/, "")}: ${why}`);
}
return json.result as T;
}
export const tunnelTarget = (cfg: Pick<EdgeConfig, "tunnelId">) => `${cfg.tunnelId}.cfargotunnel.com`;
export interface EdgeSyncResult {
ingress: "ok" | "set" | "planned";
ok: string[];
created: string[];
/** host → the tunnel it pointed to before. */
moved: Array<{ host: string; from: string }>;
/** host → what is there (left alone). */
conflicts: Array<{ host: string; record: string }>;
}
/** The tunnel's only ingress rule: everything to the server's Traefik. */
async function syncIngress(cfg: EdgeConfig, dryRun: boolean): Promise<EdgeSyncResult["ingress"]> {
const path = `/accounts/${cfg.accountId}/cfd_tunnel/${cfg.tunnelId}/configurations`;
const cur = await cf<{ config?: { ingress?: Array<{ hostname?: string; service?: string }> } }>(cfg, "GET", path);
const ingress = cur?.config?.ingress ?? [];
if (ingress.length === 1 && !ingress[0]!.hostname && ingress[0]!.service === cfg.service) return "ok";
if (dryRun) return "planned";
await cf(cfg, "PUT", path, { config: { ingress: [{ service: cfg.service }] } });
return "set";
}
/** Bring the tunnel's ingress and the DNS of `hosts` to the server's tunnel. */
export async function syncEdge(cfg: EdgeConfig, hosts: string[], o: { dryRun?: boolean } = {}): Promise<EdgeSyncResult> {
const dryRun = !!o.dryRun;
const target = tunnelTarget(cfg);
const out: EdgeSyncResult = { ingress: await syncIngress(cfg, dryRun), ok: [], created: [], moved: [], conflicts: [] };
const zone = `/zones/${cfg.zoneId}/dns_records`;
for (const host of hosts) {
const records = await cf<CfRecord[]>(cfg, "GET", `${zone}?name=${encodeURIComponent(host)}`);
if (records.length === 0) {
if (!dryRun) await cf(cfg, "POST", zone, { type: "CNAME", name: host, content: target, proxied: true, ttl: 1, comment: EDGE_COMMENT });
out.created.push(host);
continue;
}
const cname = records.length === 1 && records[0]!.type === "CNAME" ? records[0]! : null;
if (cname && cname.content.toLowerCase() === target) {
out.ok.push(host);
} else if (cname && cname.content.toLowerCase().endsWith(".cfargotunnel.com")) {
if (!dryRun) await cf(cfg, "PUT", `${zone}/${cname.id}`, { type: "CNAME", name: host, content: target, proxied: true, ttl: 1, comment: EDGE_COMMENT });
out.moved.push({ host, from: cname.content });
} else {
out.conflicts.push({ host, record: records.map((r) => `${r.type} ${r.content}`).join(", ") });
}
}
return out;
}
/** A new remotely managed tunnel; returns its id and the connector token (keep it secret). */
export async function createEdgeTunnel(cfg: Omit<EdgeConfig, "tunnelId" | "zoneId" | "domain" | "service">, name: string): Promise<{ id: string; token: string }> {
const full = cfg as EdgeConfig;
const t = await cf<{ id: string }>(full, "POST", `/accounts/${cfg.accountId}/cfd_tunnel`, { name, config_src: "cloudflare" });
const token = await cf<string>(full, "GET", `/accounts/${cfg.accountId}/cfd_tunnel/${t.id}/token`);
return { id: t.id, token };
}
export function formatEdgeSync(r: EdgeSyncResult, dryRun = false): string {
const lines = [`${dryRun ? "(dry run) " : ""}ingress: ${r.ingress}`];
for (const h of r.created) lines.push(`+ ${h}${dryRun ? " (будет создано)" : ""}`);
for (const m of r.moved) lines.push(`~ ${m.host} ← ${m.from}${dryRun ? " (будет переписано)" : ""}`);
for (const c of r.conflicts) lines.push(`! ${c.host}: ${c.record} — не трогаю`);
lines.push(`уже на сервере: ${r.ok.length}`);
return lines.join("\n");
}