import { env } from "cloudflare:workers"; import { all, first, run } from "../db"; import { badRequest, conflict } from "../errors"; import { claimDomainFromSites } from "../sites/site"; import { hostKey, isForgeRelatedHost, isValidHostname, pagesDomain, PAGES_LIMITS, siteUrl, slotKey } from "./config"; import type { PagesDeploymentRow, PagesSiteRow, PagesSource, SitePointer } from "./config"; import { createCustomHostname, customDomainsEnabled, deleteCustomHostname, domainStatus, getCustomHostname, } from "./domains"; import { unpublish } from "./deploy"; import type { RepoRow } from "~/lib/types"; /** Unverified domain claims lapse so a squatter cannot block the domain's real owner. */ const UNVERIFIED_CLAIM_MS = 72 * 60 * 60 * 1000; export type SiteSettings = { source: PagesSource; branch: string; folder: string; artifactName: string; spa: boolean; previews: boolean; }; export type PagesDeploymentView = { id: string; environment: PagesDeploymentRow["environment"]; prNumber: number | null; source: PagesDeploymentRow["source"]; ref: string; sha: string; status: PagesDeploymentRow["status"]; fileCount: number; totalBytes: number; error: string | null; createdAt: number; completedAt: number | null; url: string | null; }; function toView(repo: RepoRow, row: PagesDeploymentRow): PagesDeploymentView { return { id: row.id, environment: row.environment, prNumber: row.pr_number, source: row.source, ref: row.ref.replace(/^refs\/heads\//, ""), sha: row.sha, status: row.status, fileCount: row.file_count, totalBytes: row.total_bytes, error: row.error, createdAt: row.created_at, completedAt: row.completed_at, url: siteUrl(repo.owner_name, repo.name, row.environment === "preview" ? row.pr_number : null), }; } export async function listDeployments(repo: RepoRow): Promise { const rows = await all( "SELECT * FROM pages_deployments WHERE repo_id = ? ORDER BY created_at DESC LIMIT ?", repo.id, PAGES_LIMITS.historyLimit, ); return rows.map((row) => toView(repo, row)); } const FOLDER = /^[A-Za-z0-9._\-/]*$/; export async function saveSite(repo: RepoRow, settings: SiteSettings): Promise { if (repo.visibility !== "public") throw badRequest("Pages can only publish public repositories"); const folder = settings.folder.trim().replace(/^\/+|\/+$/g, ""); if (!FOLDER.test(folder) || folder.split("/").includes("..")) throw badRequest("Invalid folder"); const now = Date.now(); await run( `INSERT INTO pages_sites (repo_id, source, branch, folder, artifact_name, spa, previews, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT (repo_id) DO UPDATE SET source = excluded.source, branch = excluded.branch, folder = excluded.folder, artifact_name = excluded.artifact_name, spa = excluded.spa, previews = excluded.previews, updated_at = excluded.updated_at`, repo.id, settings.source, settings.branch, folder, settings.artifactName, settings.spa ? 1 : 0, settings.previews ? 1 : 0, now, now, ); const slot = slotKey(repo.owner_name, repo.name, null); const current = await env.KV.get(slot, "json"); if (current) await env.KV.put(slot, JSON.stringify({ ...current, spa: settings.spa })); } async function clearDomain(site: PagesSiteRow): Promise { if (site.custom_domain) await env.KV.delete(hostKey(site.custom_domain)); if (site.custom_hostname_id && customDomainsEnabled()) await deleteCustomHostname(site.custom_hostname_id); } export async function disableSite(repo: RepoRow, site: PagesSiteRow): Promise { await clearDomain(site); await unpublish(repo); await run("DELETE FROM pages_sites WHERE repo_id = ?", repo.id); } async function releaseStaleClaim(hostname: string, repoId: string): Promise { const found = await first("SELECT * FROM pages_sites WHERE custom_domain = ?", hostname); const holder = found && found.repo_id !== repoId ? found : null; const stale = holder !== null && holder.domain_status !== "active" && Date.now() - (holder.domain_claimed_at ?? holder.updated_at) > UNVERIFIED_CLAIM_MS; if (holder && !stale) throw conflict("That domain is already used by another site"); await claimDomainFromSites(hostname); if (!holder) return; await clearDomain(holder); await run( "UPDATE pages_sites SET custom_domain = NULL, custom_hostname_id = NULL, domain_status = NULL, domain_claimed_at = NULL WHERE repo_id = ? AND custom_domain = ?", holder.repo_id, hostname, ); } /** * Registers a Cloudflare for SaaS custom hostname. The KV mapping that makes the domain serve the site is only * written by `refreshDomain` once Cloudflare reports the hostname and its TXT-validated certificate active. */ export async function setDomain(repo: RepoRow, site: PagesSiteRow, input: string | null): Promise { const hostname = input?.trim().toLowerCase() || null; if (hostname === site.custom_domain) return; if (hostname) { if (!customDomainsEnabled()) throw badRequest("Custom domains are not configured on this forge"); const domain = pagesDomain(); if ( !isValidHostname(hostname) || isForgeRelatedHost(hostname) || (domain && (hostname === domain || hostname.endsWith(`.${domain}`))) ) { throw badRequest("Enter a valid domain you control"); } await releaseStaleClaim(hostname, repo.id); } await clearDomain(site); if (!hostname) { await run( "UPDATE pages_sites SET custom_domain = NULL, custom_hostname_id = NULL, domain_status = NULL, domain_claimed_at = NULL, updated_at = ? WHERE repo_id = ?", Date.now(), repo.id, ); return; } const created = await createCustomHostname(hostname); const now = Date.now(); await run( "UPDATE pages_sites SET custom_domain = ?, custom_hostname_id = ?, domain_status = ?, domain_claimed_at = ?, updated_at = ? WHERE repo_id = ?", hostname, created.id, domainStatus(created), now, now, repo.id, ); } export type DomainDetails = { status: string; errors: string[]; verification: { type: string; name: string; value: string } | null; }; export async function refreshDomain(repo: RepoRow, site: PagesSiteRow): Promise { if (!site.custom_hostname_id || !customDomainsEnabled()) return null; const hostname = await getCustomHostname(site.custom_hostname_id); const status = domainStatus(hostname); if (status !== site.domain_status) { await run("UPDATE pages_sites SET domain_status = ? WHERE repo_id = ?", status, repo.id); } if (site.custom_domain) { const key = hostKey(site.custom_domain); if (status === "active" && hostname.hostname === site.custom_domain) { await env.KV.put(key, JSON.stringify({ owner: repo.owner_name, repo: repo.name })); } else if (hostname.status !== "active" || hostname.hostname !== site.custom_domain) { // A certificate renewal keeps the hostname active and the site serving; anything else unpublishes it. await env.KV.delete(key); } } const record = hostname.ssl?.txt_name && hostname.ssl.txt_value ? { txt_name: hostname.ssl.txt_name, txt_value: hostname.ssl.txt_value } : hostname.ssl?.validation_records?.find((item) => item.txt_name && item.txt_value); return { status, errors: hostname.verification_errors ?? [], verification: status === "active" ? null : record?.txt_name && record.txt_value ? { type: "txt", name: record.txt_name, value: record.txt_value } : (hostname.ownership_verification ?? null), }; }