import { env } from "cloudflare:workers";
const DEV_FORGE_HOST = "localhost";
const DEV_EDITOR_HOST = "editor.localhost";
function within(host: string, domain: string | undefined): boolean {
const base = (domain ?? "")
.trim()
.toLowerCase()
.replace(/^\.+|\.+$/g, "");
return base !== "" && (host === base || host.endsWith(`.${base}`));
}
/**
* Why an EDITOR_ORIGIN is unsafe, or null. It must be its own host: never the forge host (cookies and
* pages), and never under SITES_DOMAIN or PAGES_DOMAIN, where user content could frame or impersonate it.
*/
export function editorOriginProblem(origin: URL, forgeHost: string): string | null {
const host = origin.hostname.toLowerCase();
if (host === forgeHost.toLowerCase()) return "EDITOR_ORIGIN must not be the forge host";
if (within(host, env.SITES_DOMAIN)) return "EDITOR_ORIGIN must not be under SITES_DOMAIN (user content)";
if (within(host, env.PAGES_DOMAIN)) return "EDITOR_ORIGIN must not be under PAGES_DOMAIN (user content)";
if (origin.protocol !== "https:" && !within(host, "localhost")) return "EDITOR_ORIGIN must use https";
return null;
}
let validated: { raw: string; url: URL | null } | null = null;
/** The configured editor origin, validated once per isolate; an unsafe value disables the editor. */
function configured(): URL | null {
if (!env.EDITOR_ORIGIN) return null;
if (validated?.raw === env.EDITOR_ORIGIN) return validated.url;
let url: URL | null = null;
try {
url = new URL(env.EDITOR_ORIGIN);
const problem = editorOriginProblem(url, new URL(env.PUBLIC_URL).hostname);
if (problem) {
console.error(`Editor disabled: ${problem} (got ${url.origin})`);
url = null;
}