This commit is contained in:
Mateusz Gruszczyński committed 2026-11-28 15:54:56 +01:00
1 parent 9a6c21fa04
commit 5b6d4a7903
41 files changed
+3299 -677

No files matched your search

+124 -22
View File
@@ -5,8 +5,21 @@
const codes = [400, 401, 403, 404, 408, 413, 429, 500, 502, 503, 504];
const STATUS_NAMES = { 200: "OK", 204: "No Content", 400: "Bad Request", 401: "Unauthorized", 403: "Forbidden", 404: "Not Found", 408: "Request Timeout", 410: "Gone", 413: "Payload Too Large", 429: "Too Many Requests", 500: "Internal Server Error", 502: "Bad Gateway", 503: "Service Unavailable", 504: "Gateway Timeout" };
const statusLabel = code => `${code} ${STATUS_NAMES[code] || ""}`.trim();
function pageEditor(parent, key, value = null) {
const row = el("div", undefined, "page-editor"), heading = label("strong", key, "page-label"); row.append(heading);
const CLOUDFLARE_KINDS = ["cloudflare", "cloudflare_welcome", "cloudflare_placeholder"];
const PAGE_KIND_CARDS = [["", "pageInherit", "pageKindInheritHelp"], ["welcome", "pageWelcome", "notfoundKindWelcomeHelp"], ["builtin", "pageBuiltin", "notfoundKindBuiltinHelp"], ["cloudflare", "notfoundKindCloudflare", "notfoundKindCloudflareHelp"], ["empty", "pageEmpty", "notfoundKindEmptyHelp"], ["html", "pageHtml", "notfoundKindHtmlHelp"]];
let pageCardSerial = 0;
// One default-response slot rendered as a compact row: the summary line shows
// the slot, when it is used and its current response; the selected row opens
// its controls (response type chips, Cloudflare variant, status, own HTML).
// options: slot (preview/saved HTML key), vhostId, scope, title (literal row
// title), whenKey, naturalStatus, onSelect, onChange.
function pageEditor(parent, key, value = null, options = {}) {
const row = el("div", undefined, "page-editor"), heading = options.title ? el("b", options.title, "page-label") : label("b", key, "page-label");
const summary = el("button", undefined, "page-editor-summary"); summary.type = "button"; summary.setAttribute("aria-expanded", "false");
const copy = el("span", undefined, "page-editor-head"); copy.append(heading); if (options.whenKey) copy.append(label("small", options.whenKey, "page-when"));
const kindPill = el("span", "", "pill page-kind-pill"), statusPill = el("span", "", "pill page-status-pill");
const badges = el("span", undefined, "page-editor-badges"); badges.append(kindPill, statusPill); summary.append(el("span", undefined, "page-editor-dot"), copy, badges);
row.append(summary); row.dataset.pageSlot = options.slot || "";
const mode = el("select"), status = el("select"), html = el("textarea"), file = el("input");
mode.setAttribute("aria-label", t(key)); mode.className = "page-mode";
mode.append(option("", "pageInherit"), option("welcome", "pageWelcome"), option("builtin", "pageBuiltin"), option("cloudflare", "pageCloudflare"), option("cloudflare_welcome", "pageCloudflareWelcome"), option("cloudflare_placeholder", "pageCloudflarePlaceholder"), option("empty", "pageEmpty"), option("html", "pageHtml"));
@@ -17,35 +30,111 @@
status.value = value?.status ?? ""; html.value = value?.html || ""; html.rows = 5; html.maxLength = 32768; html.spellcheck = false; html.className = "page-html"; html.setAttribute("aria-label", t("pageHtmlSource"));
file.type = "file"; file.accept = ".html,.htm,text/html,text/plain"; file.setAttribute("aria-label", t("pageUploadHtml"));
const source = el("div", undefined, "page-source"); source.append(label("span", "pageUploadHtml", "fine"), file, html);
function sync() { if (mode.value && status.value === "204") mode.value = "empty"; status.disabled = !mode.value; source.hidden = mode.value !== "html"; }
for (const event of ["change", "input"]) { mode.addEventListener(event, sync); status.addEventListener(event, sync); }
file.addEventListener("change", async () => { try { const chosen = file.files[0]; if (!chosen) return; if (chosen.size > 32768) throw new Error(t("pageTooLarge")); html.value = await chosen.text(); html.dispatchEvent(new Event("input", { bubbles: true })); } catch (error) { toast(error.message, true); } finally { file.value = ""; } });
row.append(mode, status, source); parent.append(row); sync();
const controls = el("div", undefined, "page-editor-controls"); controls.hidden = true;
// Chips drive the (hidden) select, which stays the single source of truth.
const name = `page-kind-${++pageCardSerial}`, chips = el("div", undefined, "page-kind-chips"); chips.setAttribute("role", "radiogroup"); chips.setAttribute("aria-label", t(key));
for (const [kind, titleKey, helpKey] of PAGE_KIND_CARDS) {
const chip = el("label", undefined, "page-kind-chip"), radio = el("input"); radio.type = "radio"; radio.name = name; radio.value = kind;
chip.append(radio, label("span", titleKey)); chip.title = t(helpKey); chip.dataset.i18nTitle = helpKey; chips.append(chip);
radio.addEventListener("change", () => { if (!radio.checked) return; mode.value = kind === "cloudflare" ? variant.value : kind; mode.dispatchEvent(new Event("change", { bubbles: true })); });
}
const help = el("p", "", "fine page-kind-help");
const variant = el("select"); variant.className = "page-variant"; variant.append(option("cloudflare", "notfoundVariantError"), option("cloudflare_welcome", "notfoundVariantWelcome"), option("cloudflare_placeholder", "notfoundVariantPlaceholder"));
variant.addEventListener("change", () => { mode.value = variant.value; mode.dispatchEvent(new Event("change", { bubbles: true })); });
const variantField = el("label", undefined, "page-variant-field"); variantField.append(label("span", "notfoundCloudflareVariant"), variant);
const statusField = el("label", undefined, "page-status-field"); statusField.append(label("span", "pageStatus"), status);
const fields = el("div", undefined, "page-editor-fields"); fields.append(variantField, statusField);
mode.hidden = true; controls.append(chips, help, mode, fields, source);
row.append(controls);
function sync() {
if (mode.value && status.value === "204") mode.value = "empty"; status.disabled = !mode.value; source.hidden = mode.value !== "html";
const group = CLOUDFLARE_KINDS.includes(mode.value) ? "cloudflare" : mode.value;
for (const radio of chips.querySelectorAll("input")) { radio.checked = radio.value === group; radio.closest(".page-kind-chip").classList.toggle("is-selected", radio.checked); }
variantField.hidden = group !== "cloudflare"; if (group === "cloudflare") variant.value = mode.value;
const helpKey = PAGE_KIND_CARDS.find(([kind]) => kind === group)?.[2] || "pageKindInheritHelp"; help.dataset.i18n = helpKey; help.textContent = t(helpKey);
kindPill.textContent = mode.selectedOptions[0]?.textContent || ""; kindPill.classList.toggle("live", !!mode.value);
statusPill.textContent = mode.value && status.value ? statusLabel(Number(status.value)) : ""; statusPill.hidden = !statusPill.textContent;
row.classList.toggle("is-custom", !!mode.value);
options.onChange?.(api);
}
for (const event of ["change", "input"]) { mode.addEventListener(event, sync); status.addEventListener(event, sync); html.addEventListener(event, () => options.onChange?.(api)); }
file.addEventListener("change", async () => { try { const chosen = file.files[0]; if (!chosen) return; if (chosen.size > 32768) throw new Error(t("pageTooLarge")); html.value = await chosen.text(); html.dispatchEvent(new Event("input", { bubbles: true })); } catch (error) { toast(error.message, true); } });
summary.addEventListener("click", () => { if (!controls.hidden && row.classList.contains("is-previewed")) { api.setOpen(false); return; } options.onSelect?.(api); api.setOpen(true); });
controls.addEventListener("focusin", () => options.onSelect?.(api));
parent.append(row);
function setMode(kind) {
if (mode.value === kind && (kind || !status.value)) return;
mode.value = kind;
if (!kind) status.value = "";
mode.dispatchEvent(new Event("change", { bubbles: true }));
}
const styled = () => mode.value === "cloudflare" || mode.value === "cloudflare_welcome" || mode.value === "cloudflare_placeholder";
const styled = () => CLOUDFLARE_KINDS.includes(mode.value);
const bodyless = () => mode.value === "empty" && status.value === "204";
return {
row, setCloudflare: () => {
const api = {
row, key, slot: options.slot || "", scope: options.scope || "global", vhostId: options.vhostId || null, naturalStatus: options.naturalStatus || 404,
title: () => heading.textContent,
setOpen(open) { controls.hidden = !open; row.classList.toggle("is-open", open); summary.setAttribute("aria-expanded", String(open)); },
state: () => ({ kind: mode.value, status: status.value ? Number(status.value) : null, html: html.value }),
setCloudflare: () => {
if (bodyless() || styled()) return;
if (mode.value === "welcome" && key !== "customErrorPages") {
setMode(key === "pageUnknownHost" || key === "pageMissingPath" ? "cloudflare_placeholder" : "cloudflare_welcome");
} else setMode("cloudflare");
}, reset: () => setMode(""),
isCloudflare: () => styled() || bodyless(),
read() { if (!mode.value) return null; const markup = mode.value === "html" ? html.value : ""; if (new TextEncoder().encode(markup).length > 32768) throw new Error(t("pageTooLarge")); return { kind: mode.value, status: status.value ? Number(status.value) : null, html: markup }; }
read() { if (!mode.value) return null; const markup = mode.value === "html" ? html.value : ""; if (new TextEncoder().encode(markup).length > 32768) { api.setOpen(true); throw new Error(t("pageTooLarge")); } return { kind: mode.value, status: status.value ? Number(status.value) : null, html: markup }; }
};
sync();
return api;
}
// One shared preview for all slots of an editor: the selected slot is shown
// through the sandboxed /api/pages/preview (saved HTML for custom pages).
function previewPane(parent, savedPage) {
const pane = el("aside", undefined, "page-preview-pane"), headRow = el("div", undefined, "page-preview-head"), titleNode = el("strong", ""), open = el("a", t("notfoundPreviewOpen"), "page-preview-open");
open.dataset.i18n = "notfoundPreviewOpen"; open.target = "_blank"; open.rel = "noopener noreferrer";
headRow.append(label("span", "notfoundPreview", "small-label"), titleNode, open);
const frame = el("iframe"); frame.setAttribute("sandbox", ""); frame.referrerPolicy = "no-referrer"; frame.title = t("notfoundPreview"); frame.loading = "lazy";
const note = el("p", "", "fine page-preview-note");
pane.append(headRow, frame, note); parent.append(pane);
let current = null, timer = null;
const inheritKey = editor => editor.scope === "vhost" ? "pagePreviewInheritVhost" : { direct_ip: "pagePreviewInheritDirectIp", unknown_host: "pagePreviewInheritUnknown" }[editor.slot] || "pagePreviewInheritError";
function render() {
if (!current) return;
const state = current.state(), status = state.status || current.naturalStatus;
titleNode.textContent = current.title();
for (const node of parent.querySelectorAll(".page-editor.is-previewed")) node.classList.remove("is-previewed");
current.row.classList.add("is-previewed");
let url = "", noteKey = "";
if (!state.kind) noteKey = inheritKey(current);
else if (state.kind === "empty") noteKey = "notfoundPreviewEmpty";
else if (state.kind === "html") {
const saved = savedPage(current);
if (saved?.kind !== "html") noteKey = "pagePreviewHtmlUnsaved";
else {
const params = new URLSearchParams({ kind: "html", status: String(status), slot: current.slot }); if (current.vhostId) params.set("vhost", current.vhostId);
url = `/api/pages/preview?${params}`; if (saved.html !== state.html) noteKey = "notfoundPreviewHtmlSaved";
}
} else url = `/api/pages/preview?${new URLSearchParams({ kind: state.kind, status: String(status) })}`;
note.hidden = !noteKey; if (noteKey) { note.dataset.i18n = noteKey; note.textContent = t(noteKey); }
frame.hidden = !url; open.hidden = !url;
if (url) { open.href = url; if (frame.dataset.src !== url) { frame.dataset.src = url; frame.src = url; } }
}
return {
select(editor) { current = editor; render(); },
changed(editor) { if (editor === current) { clearTimeout(timer); timer = setTimeout(render, 150); } }
};
}
function errorsEditor(parent, values = {}) {
const details = el("details", undefined, "pages-errors"); details.append(label("summary", "customErrorPages")); parent.append(details);
const rows = new Map(); for (const code of codes) { const group = el("div"); details.append(group); const editor = pageEditor(group, "customErrorPages", values[code]); editor.row.querySelector("strong").removeAttribute("data-i18n"); editor.row.querySelector("strong").textContent = statusLabel(code); rows.set(code, editor); }
function errorsEditor(parent, values = {}, context = {}) {
const details = el("details", undefined, "pages-errors"), summary = el("summary"), count = el("span", "", "pill");
summary.append(label("span", "customErrorPages"), count); details.append(summary, label("p", "pageErrorsWhen", "fine page-when")); parent.append(details);
const list = el("div", undefined, "page-editor-list"); details.append(list);
const rows = new Map(); for (const code of codes) { const editor = pageEditor(list, "customErrorPages", values[code], { ...context, slot: `error-${code}`, naturalStatus: code, title: statusLabel(code) }); rows.set(code, editor); }
const updateCount = () => { const custom = [...rows.values()].filter(editor => editor.state().kind).length; count.textContent = `${custom} / ${codes.length}`; count.classList.toggle("live", custom > 0); };
details.addEventListener("change", updateCount); updateCount();
if ([...rows.values()].some(editor => editor.state().kind)) details.open = true;
return {
setAllCloudflare() { for (const editor of rows.values()) editor.setCloudflare(); details.open = true; },
resetAll() { for (const editor of rows.values()) editor.reset(); details.open = false; },
setAllCloudflare() { for (const editor of rows.values()) editor.setCloudflare(); details.open = true; updateCount(); },
resetAll() { for (const editor of rows.values()) editor.reset(); details.open = false; updateCount(); },
allCloudflare: () => [...rows.values()].every(editor => editor.isCloudflare()),
read() { return Object.fromEntries([...rows].map(([code, editor]) => [code, editor.read()]).filter(([, page]) => page)); }
};
@@ -62,7 +151,16 @@
parent.append(wrapper);
return toggle;
}
function vhostEditor(parent, values = {}) {
function workspace(parent, savedPage) {
const box = el("div", undefined, "pages-workspace"), editors = el("div", undefined, "pages-editors"); box.append(editors); parent.append(box);
const preview = previewPane(box, savedPage); let open = null;
const select = editor => { if (open && open !== editor) open.setOpen(false); open = editor; preview.select(editor); };
return { editors, context: { onSelect: select, onChange: editor => preview.changed(editor) }, preview: { select(editor) { select(editor); editor.setOpen(true); }, changed: preview.changed } };
}
function vhostEditor(outer, values = {}, options = {}) {
const vhostId = options.vhostId || "";
const savedVhostPage = editor => { const pages = (envelope?.config.vhosts || []).find(item => item.id === vhostId)?.pages; if (!pages || !vhostId) return null; return editor.slot.startsWith("error-") ? pages.errors?.[Number(editor.slot.slice(6))] : pages[editor.slot]; };
const space = workspace(outer, savedVhostPage), parent = space.editors, context = { ...space.context, scope: "vhost", vhostId };
let applying = false;
const bulk = bulkCloudflareSwitch(parent, checked => {
applying = true;
@@ -80,7 +178,7 @@
} finally { applying = false; }
syncBulk();
});
const response = pageEditor(parent, "pageStaticHost", values.response), fallback = pageEditor(parent, "pageMissingPath", values.fallback);
const response = pageEditor(parent, "pageStaticHost", values.response, { ...context, slot: "response", naturalStatus: 200, whenKey: "pageStaticHostWhen" }), fallback = pageEditor(parent, "pageMissingPath", values.fallback, { ...context, slot: "fallback", naturalStatus: 404, whenKey: "pageMissingPathWhen" });
const interception = el("section", undefined, "php-origin-errors");
const toggle = el("label", undefined, "check"), enabled = document.createElement("input");
enabled.type = "checkbox"; enabled.className = "switch"; enabled.checked = (values.intercept_statuses || []).length > 0;
@@ -94,7 +192,7 @@
const sync = () => { statuses.disabled = !enabled.checked; };
enabled.addEventListener("change", sync); sync();
interception.append(toggle, codesLabel, hint); parent.append(interception);
const errors = errorsEditor(parent, values.errors);
const errors = errorsEditor(parent, values.errors, context);
const syncBulk = () => {
const selected = statuses.value.split(/[\s,]+/).filter(Boolean);
bulk.checked = response.isCloudflare() && fallback.isCloudflare() && errors.allCloudflare()
@@ -105,6 +203,7 @@
parent.addEventListener("input", onEditorChange);
syncBulk();
parent.append(label("p", "pagesSafetyHint", "fine"));
space.preview.select(response);
return {
read: () => {
const selectedTokens = enabled.checked ? statuses.value.split(/[\s,]+/).filter(Boolean) : [];
@@ -130,7 +229,10 @@
} finally { applying = false; }
globalSync();
});
const ip = pageEditor(parent, "pageDirectIp", values.direct_ip), unknown = pageEditor(parent, "pageUnknownHost", values.unknown_host), errors = errorsEditor(parent, values.errors);
const savedGlobalPage = editor => { const pages = envelope?.config.pages || {}; return editor.slot.startsWith("error-") ? pages.errors?.[Number(editor.slot.slice(6))] : pages[editor.slot]; };
const space = workspace(parent, savedGlobalPage), context = space.context;
const ip = pageEditor(space.editors, "pageDirectIp", values.direct_ip, { ...context, slot: "direct_ip", naturalStatus: 200, whenKey: "pageDirectIpWhen" }), unknown = pageEditor(space.editors, "pageUnknownHost", values.unknown_host, { ...context, slot: "unknown_host", naturalStatus: 404, whenKey: "pageUnknownHostWhen" }), errors = errorsEditor(space.editors, values.errors, context);
space.preview.select(ip);
globalSync = event => { if (!applying && event?.target !== bulk) bulk.checked = ip.isCloudflare() && unknown.isCloudflare() && errors.allCloudflare(); };
parent.addEventListener("change", globalSync);
parent.addEventListener("input", globalSync);
@@ -371,7 +473,7 @@
const row = el("div", undefined, "acl-rule acl-profile-rule");
const actionLabel = el("label", undefined, "acl-profile-rule-action-field"); actionLabel.append(i18n("span", "aclAction"));
const actionSelect = el("select"); actionSelect.className = "acl-profile-rule-action";
for (const actionValue of ["allow", "deny"]) { const option = el("option", t(actionValue === "allow" ? "aclAllow" : "vhDeny")); option.value = actionValue; actionSelect.append(option); }
for (const actionValue of ["allow", "deny"]) { const option = el("option", t(actionValue === "allow" ? "aclAllow" : "aclDeny")); option.value = actionValue; actionSelect.append(option); }
actionSelect.value = value.action || fallbackAction; actionLabel.append(actionSelect);
const actionBadge = el("span", "", "acl-profile-rule-action-badge"); actionLabel.append(actionBadge);
const typeLabel = el("label"); typeLabel.append(i18n("span", "aclRuleType"));
@@ -427,7 +529,7 @@
const select = row.querySelector(".acl-profile-rule-action"), badge = row.querySelector(".acl-profile-rule-action-badge");
if (!custom && convert) select.value = expected;
select.hidden = !custom; badge.hidden = custom;
if (!custom) { badge.textContent = t(expected === "allow" ? "aclAllow" : "vhDeny"); badge.classList.toggle("is-allow", expected === "allow"); badge.classList.toggle("is-deny", expected === "deny"); }
if (!custom) { badge.textContent = t(expected === "allow" ? "aclAllow" : "aclDeny"); badge.classList.toggle("is-allow", expected === "allow"); badge.classList.toggle("is-deny", expected === "deny"); }
}
syncRulesText();
}
@@ -512,7 +614,7 @@
const select = row.querySelector(".acl-profile-rule-action");
if (select?.options?.length >= 2) {
select.options[0].textContent = t("aclAllow");
select.options[1].textContent = t("vhDeny");
select.options[1].textContent = t("aclDeny");
}
const remove = row.querySelector(".acl-profile-rule-remove");
if (remove) remove.textContent = t("remove");