Improve Caddyfile editor for demo-style configs
Publish Docker image / build (push) Failing after 6s
Publish Docker image / build (push) Failing after 6s
This commit is contained in:
1 parent
d672ad3f47
commit
e9035bf6fe
7 files changed
+1130
-47
No files matched your search
+740
-45
@@ -40,7 +40,7 @@ function dedent(array $lines): array {
|
||||
}
|
||||
|
||||
function parseCaddyfile(string $content): array {
|
||||
$result = ['global' => '', 'sites' => []];
|
||||
$result = ['global' => '', 'snippets' => [], 'sites' => []];
|
||||
$lines = explode("\n", $content);
|
||||
$n = count($lines);
|
||||
$i = 0;
|
||||
@@ -62,7 +62,7 @@ function parseCaddyfile(string $content): array {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Site block: address(es) {
|
||||
// Site block or reusable snippet: address(es) { / (snippet-name) {
|
||||
if (preg_match('/^(.+?)\s*\{(.*)$/', $trimmed, $m)) {
|
||||
$address = trim($m[1]);
|
||||
$block = trim($m[2]) !== '' ? [trim($m[2])] : [];
|
||||
@@ -72,7 +72,12 @@ function parseCaddyfile(string $content): array {
|
||||
if ($depth > 0) $block[] = $lines[$i];
|
||||
$i++;
|
||||
}
|
||||
$result['sites'][] = ['address' => $address, 'body' => implode("\n", dedent($block))];
|
||||
$entry = ['address' => $address, 'body' => implode("\n", dedent($block))];
|
||||
if (preg_match('/^\(([A-Za-z0-9_.-]+)\)$/', $address, $sm)) {
|
||||
$result['snippets'][] = ['name' => $sm[1], 'body' => $entry['body']];
|
||||
} else {
|
||||
$result['sites'][] = $entry;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -81,9 +86,15 @@ function parseCaddyfile(string $content): array {
|
||||
return $result;
|
||||
}
|
||||
|
||||
function buildCaddyfile(string $global, array $sites): string {
|
||||
function buildCaddyfile(string $global, array $snippets, array $sites): string {
|
||||
$out = '';
|
||||
if (trim($global) !== '') $out .= "{\n" . $global . "\n}\n\n";
|
||||
foreach ($snippets as $snippet) {
|
||||
$name = trim((string)($snippet['name'] ?? ''));
|
||||
if ($name === '') continue;
|
||||
$body = (string)($snippet['body'] ?? '');
|
||||
$out .= "({$name}) {\n" . $body . "\n}\n\n";
|
||||
}
|
||||
foreach ($sites as $site) {
|
||||
$out .= trim($site['address']) . " {\n" . $site['body'] . "\n}\n\n";
|
||||
}
|
||||
@@ -179,19 +190,30 @@ if (isset($_GET['action'])) {
|
||||
} else {
|
||||
$raw = '';
|
||||
}
|
||||
echo json_encode(['ok' => true, 'data' => parseCaddyfile($raw)]);
|
||||
echo json_encode(['ok' => true, 'data' => parseCaddyfile($raw), 'raw' => $raw]);
|
||||
exit;
|
||||
|
||||
case 'save':
|
||||
$input = json_decode(file_get_contents('php://input'), true);
|
||||
if (!$input) { echo json_encode(['ok' => false, 'error' => 'Invalid JSON']); exit; }
|
||||
|
||||
$cf = buildCaddyfile($input['global'] ?? '', $input['sites'] ?? []);
|
||||
if (($input['mode'] ?? 'structured') === 'raw') {
|
||||
$cf = (string)($input['raw'] ?? '');
|
||||
} else {
|
||||
$cf = buildCaddyfile($input['global'] ?? '', $input['snippets'] ?? [], $input['sites'] ?? []);
|
||||
}
|
||||
$result = caddyLoad($cf);
|
||||
if ($result['ok']) file_put_contents(CADDYFILE_STORE, $cf);
|
||||
echo json_encode($result);
|
||||
exit;
|
||||
|
||||
case 'parse_raw':
|
||||
$input = json_decode(file_get_contents('php://input'), true);
|
||||
if (!$input) { echo json_encode(['ok' => false, 'error' => 'Invalid JSON']); exit; }
|
||||
$raw = (string)($input['raw'] ?? '');
|
||||
echo json_encode(['ok' => true, 'data' => parseCaddyfile($raw)]);
|
||||
exit;
|
||||
|
||||
case 'check_upstreams':
|
||||
$input = json_decode(file_get_contents('php://input'), true);
|
||||
$targets = $input['targets'] ?? [];
|
||||
@@ -388,6 +410,48 @@ main {
|
||||
}
|
||||
.toggle-wrap input { accent-color: var(--accent); cursor: pointer; }
|
||||
.toggle-hint { font-size: 0.75rem; color: var(--muted); }
|
||||
.help-text { font-size: 0.78rem; color: var(--muted); line-height: 1.5; margin-bottom: 0.75rem; }
|
||||
|
||||
.mode-bar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.mode-label {
|
||||
font-size: 0.82rem;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.mode-buttons {
|
||||
display: inline-flex;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.mode-btn {
|
||||
border: none;
|
||||
border-right: 1px solid var(--border);
|
||||
background: rgba(255,255,255,0.04);
|
||||
color: var(--muted);
|
||||
padding: 0.45rem 0.8rem;
|
||||
font-size: 0.82rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.mode-btn:last-child { border-right: none; }
|
||||
.mode-btn.active {
|
||||
background: rgba(124,140,248,0.18);
|
||||
color: var(--accent);
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.mode-note {
|
||||
font-size: 0.78rem;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
/* ── Code editor ── */
|
||||
textarea.code {
|
||||
@@ -408,6 +472,105 @@ textarea.code {
|
||||
}
|
||||
textarea.code:focus { border-color: var(--accent); }
|
||||
|
||||
.form-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
|
||||
gap: 0.75rem;
|
||||
margin-bottom: 0.75rem;
|
||||
}
|
||||
.field label {
|
||||
display: block;
|
||||
font-size: 0.74rem;
|
||||
color: var(--muted);
|
||||
margin-bottom: 0.25rem;
|
||||
}
|
||||
.field input {
|
||||
width: 100%;
|
||||
background: #0d0f18;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 6px;
|
||||
color: var(--text);
|
||||
font-size: 0.84rem;
|
||||
padding: 0.5rem 0.6rem;
|
||||
outline: none;
|
||||
}
|
||||
.field input:focus { border-color: var(--accent); }
|
||||
.check-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.45rem;
|
||||
color: var(--muted);
|
||||
font-size: 0.8rem;
|
||||
min-height: 2.4rem;
|
||||
}
|
||||
.check-row input { accent-color: var(--accent); }
|
||||
.builder {
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
padding: 0.85rem;
|
||||
margin-bottom: 0.85rem;
|
||||
background: rgba(255,255,255,0.025);
|
||||
}
|
||||
.builder-title {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
margin-bottom: 0.7rem;
|
||||
}
|
||||
.builder-title strong { font-size: 0.86rem; flex: 1; }
|
||||
.quick-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.45rem;
|
||||
flex-wrap: wrap;
|
||||
margin-bottom: 0.65rem;
|
||||
}
|
||||
.quick-actions-title {
|
||||
color: var(--muted);
|
||||
font-size: 0.76rem;
|
||||
margin-right: 0.15rem;
|
||||
}
|
||||
.route-summary {
|
||||
display: flex;
|
||||
gap: 0.4rem;
|
||||
flex-wrap: wrap;
|
||||
margin-bottom: 0.75rem;
|
||||
}
|
||||
.route-pill {
|
||||
font-size: 0.74rem;
|
||||
color: var(--muted);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 999px;
|
||||
padding: 0.18rem 0.5rem;
|
||||
background: rgba(255,255,255,0.035);
|
||||
}
|
||||
.route-pill strong { color: var(--text); font-weight: 600; }
|
||||
.snippet-list { display: flex; flex-direction: column; gap: 0.75rem; }
|
||||
.snippet-card {
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
padding: 0.75rem;
|
||||
background: rgba(255,255,255,0.025);
|
||||
}
|
||||
.snippet-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
margin-bottom: 0.65rem;
|
||||
}
|
||||
.snippet-name {
|
||||
flex: 1;
|
||||
background: #0d0f18;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 6px;
|
||||
color: var(--accent);
|
||||
font-family: 'JetBrains Mono', monospace;
|
||||
font-size: 0.84rem;
|
||||
padding: 0.45rem 0.6rem;
|
||||
min-width: 0;
|
||||
}
|
||||
.snippet-name:focus { border-color: var(--accent); outline: none; }
|
||||
|
||||
/* ── Site cards ── */
|
||||
.sites-bar {
|
||||
display: flex;
|
||||
@@ -463,6 +626,15 @@ textarea.code:focus { border-color: var(--accent); }
|
||||
}
|
||||
|
||||
#no-sites { color: var(--muted); font-size: 0.875rem; padding: 0.25rem 0; display: none; }
|
||||
#no-snippets { color: var(--muted); font-size: 0.875rem; padding: 0.25rem 0; display: none; }
|
||||
|
||||
@media (max-width: 640px) {
|
||||
header { align-items: flex-start; flex-wrap: wrap; }
|
||||
header h1 { flex-basis: 100%; }
|
||||
main { padding: 1rem; }
|
||||
.site-card-header, .snippet-head { align-items: flex-start; flex-wrap: wrap; }
|
||||
.site-address, .snippet-name { flex-basis: 100%; }
|
||||
}
|
||||
|
||||
/* ── Buttons ── */
|
||||
.btn {
|
||||
@@ -561,6 +733,28 @@ textarea.code:focus { border-color: var(--accent); }
|
||||
</header>
|
||||
|
||||
<main>
|
||||
<div class="mode-bar">
|
||||
<span class="mode-label">Editor mode</span>
|
||||
<div class="mode-buttons">
|
||||
<button class="mode-btn active" id="mode-structured" onclick="switchMode('structured')">Structured</button>
|
||||
<button class="mode-btn" id="mode-raw" onclick="switchMode('raw')">Raw Caddyfile</button>
|
||||
</div>
|
||||
<span class="mode-note" id="mode-note">Structured mode is safer; raw mode is an escape hatch for advanced Caddyfile edits.</span>
|
||||
</div>
|
||||
|
||||
<div class="panel" id="raw-panel" style="display:none;">
|
||||
<div class="panel-header" onclick="togglePanel('raw')">
|
||||
<span class="chev open" id="raw-chev">▶</span>
|
||||
<span class="panel-title">Raw Caddyfile</span>
|
||||
</div>
|
||||
<div class="panel-body" id="raw-body">
|
||||
<div class="toggle-hint" style="margin-bottom:0.75rem;">Deploy still goes through the Caddy admin API. Switching back to structured mode reparses the file and may normalize comments or formatting.</div>
|
||||
<textarea class="code" id="raw-editor" rows="20"
|
||||
placeholder="{ admin :2019 } example.com { reverse_proxy localhost:3000 }"></textarea>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="structured-editor">
|
||||
<!-- Global Options -->
|
||||
<div class="panel">
|
||||
<div class="panel-header" onclick="togglePanel('global')">
|
||||
@@ -573,15 +767,35 @@ textarea.code:focus { border-color: var(--accent); }
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Reusable Snippets -->
|
||||
<div class="panel">
|
||||
<div class="panel-header" onclick="togglePanel('snippets')">
|
||||
<span class="chev open" id="snippets-chev">▶</span>
|
||||
<span class="panel-title">Reusable Snippets</span>
|
||||
<span class="badge" id="snippet-count">0</span>
|
||||
</div>
|
||||
<div class="panel-body" id="snippets-body">
|
||||
<div class="help-text">Top-level Caddyfile snippets like <code>(cors-origin)</code>. Use imports from site blocks or generated host routes.</div>
|
||||
<div class="toolbar">
|
||||
<button class="btn btn-sm" onclick="addSnippet()">+ Add Snippet</button>
|
||||
<button class="btn btn-sm" onclick="ensureCorsSnippet()">Add CORS Template</button>
|
||||
</div>
|
||||
<div class="snippet-list" id="snippets-container"></div>
|
||||
<div id="no-snippets">No reusable snippets configured.</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Sites -->
|
||||
<div>
|
||||
<div class="sites-bar">
|
||||
<span class="sites-bar-title">Sites</span>
|
||||
<button class="btn btn-sm" onclick="addWildcardSite()">+ Wildcard Site</button>
|
||||
<button class="btn btn-sm" onclick="addSite()">+ Add Site</button>
|
||||
</div>
|
||||
<div id="sites-container"></div>
|
||||
<div id="no-sites">No sites configured. Click "+ Add Site" to create one.</div>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
|
||||
<!-- Upstream warning modal -->
|
||||
@@ -600,7 +814,10 @@ textarea.code:focus { border-color: var(--accent); }
|
||||
<div id="toast"></div>
|
||||
|
||||
<script>
|
||||
let snippets = [];
|
||||
let sites = [];
|
||||
let currentMode = 'structured';
|
||||
let structuredDirty = false;
|
||||
|
||||
// ─── Init ────────────────────────────────────────────────────────────────────
|
||||
async function init() {
|
||||
@@ -612,8 +829,12 @@ async function init() {
|
||||
const d = await loadRes.json();
|
||||
if (!d.ok) throw new Error(d.error);
|
||||
document.getElementById('global-editor').value = d.data.global;
|
||||
sites = d.data.sites;
|
||||
document.getElementById('raw-editor').value = d.raw || '';
|
||||
snippets = d.data.snippets || [];
|
||||
sites = d.data.sites || [];
|
||||
structuredDirty = false;
|
||||
|
||||
renderSnippets();
|
||||
renderSites();
|
||||
|
||||
try {
|
||||
@@ -643,7 +864,7 @@ function setEditable(enabled, reason) {
|
||||
|
||||
// ─── Deploy ───────────────────────────────────────────────────────────────────
|
||||
async function preDeploy() {
|
||||
collectSites();
|
||||
if (currentMode === 'structured') collectStructured();
|
||||
|
||||
// Extract all reverse_proxy targets from all site bodies
|
||||
const targets = extractUpstreams();
|
||||
@@ -682,10 +903,17 @@ async function doDeploy() {
|
||||
|
||||
|
||||
try {
|
||||
const payload = {
|
||||
global: document.getElementById('global-editor').value,
|
||||
sites: sites,
|
||||
};
|
||||
const payload = currentMode === 'raw'
|
||||
? {
|
||||
mode: 'raw',
|
||||
raw: document.getElementById('raw-editor').value,
|
||||
}
|
||||
: {
|
||||
mode: 'structured',
|
||||
global: document.getElementById('global-editor').value,
|
||||
snippets: snippets,
|
||||
sites: sites,
|
||||
};
|
||||
const r = await fetch('?action=save', {
|
||||
method: 'POST',
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
@@ -696,6 +924,10 @@ async function doDeploy() {
|
||||
setStatus('Deploy failed', 'error');
|
||||
toast(d.error, 'error');
|
||||
} else {
|
||||
if (currentMode === 'structured') {
|
||||
document.getElementById('raw-editor').value = buildCaddyfileFromStructured();
|
||||
structuredDirty = false;
|
||||
}
|
||||
setStatus('Deployed', 'ok');
|
||||
toast('Deployed successfully', 'ok');
|
||||
}
|
||||
@@ -712,38 +944,208 @@ function extractUpstreams() {
|
||||
const targets = [];
|
||||
const seen = new Set();
|
||||
|
||||
sites.forEach(s => {
|
||||
const body = s.body || '';
|
||||
// Match: reverse_proxy [to] [scheme://]host[:port] ...
|
||||
const lines = body.split('\n');
|
||||
lines.forEach(line => {
|
||||
const m = line.match(/^\s*reverse_proxy\s+(?:to\s+)?(.+)/);
|
||||
if (!m) return;
|
||||
// Split on whitespace to handle multiple backends
|
||||
m[1].split(/\s+/).forEach(part => {
|
||||
// Strip scheme
|
||||
part = part.replace(/^https?:\/\//, '');
|
||||
// Stop at block open or empty
|
||||
if (!part || part === '{') return;
|
||||
const colonIdx = part.lastIndexOf(':');
|
||||
let host, port;
|
||||
if (colonIdx > 0 && /^\d+$/.test(part.slice(colonIdx + 1))) {
|
||||
host = part.slice(0, colonIdx);
|
||||
port = parseInt(part.slice(colonIdx + 1), 10);
|
||||
} else {
|
||||
host = part;
|
||||
port = 80;
|
||||
}
|
||||
if (!host || host.includes('{')) return; // skip Caddy placeholders
|
||||
const key = host + ':' + port;
|
||||
if (!seen.has(key)) { seen.add(key); targets.push({ host, port }); }
|
||||
});
|
||||
const content = currentMode === 'raw'
|
||||
? document.getElementById('raw-editor').value
|
||||
: sites.map(s => s.body || '').join('\n');
|
||||
|
||||
content.split('\n').forEach(line => {
|
||||
const m = line.match(/^\s*reverse_proxy\s+(?:to\s+)?(.+)/);
|
||||
if (!m) return;
|
||||
m[1].split(/\s+/).forEach(part => {
|
||||
part = part.replace(/^https?:\/\//, '');
|
||||
if (!part || part === '{') return;
|
||||
const colonIdx = part.lastIndexOf(':');
|
||||
let host, port;
|
||||
if (colonIdx > 0 && /^\d+$/.test(part.slice(colonIdx + 1))) {
|
||||
host = part.slice(0, colonIdx);
|
||||
port = parseInt(part.slice(colonIdx + 1), 10);
|
||||
} else {
|
||||
host = part;
|
||||
port = 80;
|
||||
}
|
||||
if (!host || host.includes('{')) return;
|
||||
const key = host + ':' + port;
|
||||
if (!seen.has(key)) { seen.add(key); targets.push({ host, port }); }
|
||||
});
|
||||
});
|
||||
|
||||
return targets;
|
||||
}
|
||||
|
||||
function buildCaddyfileFromStructured() {
|
||||
const global = document.getElementById('global-editor').value;
|
||||
let out = '';
|
||||
if (global.trim() !== '') out += `{\n${global}\n}\n\n`;
|
||||
snippets.forEach(snippet => {
|
||||
const name = (snippet.name || '').trim();
|
||||
if (!name) return;
|
||||
out += `(${name}) {\n${snippet.body || ''}\n}\n\n`;
|
||||
});
|
||||
sites.forEach(site => {
|
||||
out += `${(site.address || '').trim()} {\n${site.body || ''}\n}\n\n`;
|
||||
});
|
||||
return out.trimEnd() + '\n';
|
||||
}
|
||||
|
||||
async function switchMode(mode) {
|
||||
if (mode === currentMode) return;
|
||||
|
||||
if (mode === 'raw') {
|
||||
collectStructured();
|
||||
if (structuredDirty) {
|
||||
document.getElementById('raw-editor').value = buildCaddyfileFromStructured();
|
||||
}
|
||||
currentMode = 'raw';
|
||||
applyModeUi();
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
setStatus('Parsing raw Caddyfile…', '');
|
||||
const r = await fetch('?action=parse_raw', {
|
||||
method: 'POST',
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
body: JSON.stringify({ raw: document.getElementById('raw-editor').value }),
|
||||
});
|
||||
const d = await r.json();
|
||||
if (!d.ok) throw new Error(d.error || 'Could not parse raw Caddyfile');
|
||||
|
||||
document.getElementById('global-editor').value = d.data.global || '';
|
||||
snippets = d.data.snippets || [];
|
||||
sites = d.data.sites || [];
|
||||
renderSnippets();
|
||||
renderSites();
|
||||
structuredDirty = false;
|
||||
currentMode = 'structured';
|
||||
applyModeUi();
|
||||
setStatus('Ready', '');
|
||||
toast('Raw Caddyfile parsed into structured view', 'warn');
|
||||
} catch (e) {
|
||||
setStatus('Raw parse failed', 'error');
|
||||
toast(e.message, 'error');
|
||||
}
|
||||
}
|
||||
|
||||
function applyModeUi() {
|
||||
const raw = currentMode === 'raw';
|
||||
document.getElementById('raw-panel').style.display = raw ? 'block' : 'none';
|
||||
document.getElementById('structured-editor').style.display = raw ? 'none' : 'block';
|
||||
document.getElementById('mode-structured').classList.toggle('active', !raw);
|
||||
document.getElementById('mode-raw').classList.toggle('active', raw);
|
||||
document.getElementById('mode-note').textContent = raw
|
||||
? 'Raw mode deploys directly through the Caddy admin API without restarting Caddy.'
|
||||
: 'Structured mode is safer; raw mode is an escape hatch for advanced Caddyfile edits.';
|
||||
}
|
||||
|
||||
// ─── Structured editor ────────────────────────────────────────────────────────
|
||||
function collectStructured() {
|
||||
collectSnippets();
|
||||
collectSites();
|
||||
}
|
||||
|
||||
function collectSnippets() {
|
||||
document.querySelectorAll('.snippet-card').forEach((card, i) => {
|
||||
snippets[i] = {
|
||||
name: card.querySelector('.snippet-name').value.trim().replace(/^\(|\)$/g, ''),
|
||||
body: card.querySelector('textarea.code').value,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function renderSnippets() {
|
||||
const container = document.getElementById('snippets-container');
|
||||
const noSnips = document.getElementById('no-snippets');
|
||||
const count = document.getElementById('snippet-count');
|
||||
container.innerHTML = '';
|
||||
count.textContent = snippets.length;
|
||||
|
||||
if (snippets.length === 0) { noSnips.style.display = 'block'; return; }
|
||||
noSnips.style.display = 'none';
|
||||
|
||||
snippets.forEach((snippet, i) => {
|
||||
const card = document.createElement('div');
|
||||
card.className = 'snippet-card';
|
||||
card.innerHTML = `
|
||||
<div class="snippet-head">
|
||||
<input class="snippet-name" type="text"
|
||||
value="${esc(snippet.name)}"
|
||||
placeholder="cors-origin">
|
||||
<button class="btn btn-sm btn-danger" onclick="removeSnippet(${i})">Remove</button>
|
||||
</div>
|
||||
<textarea class="code" rows="8"
|
||||
placeholder="header { Access-Control-Allow-Origin * }">${esc(snippet.body)}</textarea>`;
|
||||
container.appendChild(card);
|
||||
});
|
||||
|
||||
document.querySelectorAll('.snippet-card textarea.code').forEach(ta => ta.addEventListener('keydown', handleTab));
|
||||
document.querySelectorAll('.snippet-name, .snippet-card textarea.code').forEach(el => {
|
||||
el.addEventListener('input', () => {
|
||||
structuredDirty = true;
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function addSnippet() {
|
||||
collectStructured();
|
||||
snippets.push({ name: '', body: '' });
|
||||
structuredDirty = true;
|
||||
renderSnippets();
|
||||
const inputs = document.querySelectorAll('.snippet-name');
|
||||
if (inputs.length) inputs[inputs.length - 1].focus();
|
||||
}
|
||||
|
||||
function ensureCorsSnippet() {
|
||||
collectStructured();
|
||||
const existing = snippets.findIndex(s => (s.name || '').trim() === 'cors-origin');
|
||||
const body = corsSnippetBody();
|
||||
|
||||
if (existing >= 0) {
|
||||
snippets[existing].body = body;
|
||||
toast('Updated cors-origin snippet template', 'warn');
|
||||
} else {
|
||||
snippets.push({ name: 'cors-origin', body });
|
||||
toast('Added cors-origin snippet template', 'ok');
|
||||
}
|
||||
structuredDirty = true;
|
||||
renderSnippets();
|
||||
}
|
||||
|
||||
function corsSnippetBody() {
|
||||
return `@match-cors-preflight-{args[0]} {
|
||||
header Origin "{args[0]}"
|
||||
method OPTIONS
|
||||
}
|
||||
handle @match-cors-preflight-{args[0]} {
|
||||
header {
|
||||
Access-Control-Allow-Origin "{args[0]}"
|
||||
Access-Control-Allow-Methods "GET, POST, PUT, PATCH, DELETE, OPTIONS"
|
||||
Access-Control-Allow-Headers *
|
||||
Access-Control-Max-Age "3600"
|
||||
defer
|
||||
}
|
||||
respond "" 204
|
||||
}
|
||||
|
||||
@match-cors-request-{args[0]} {
|
||||
header Origin "{args[0]}"
|
||||
not method OPTIONS
|
||||
}
|
||||
handle @match-cors-request-{args[0]} {
|
||||
header {
|
||||
Access-Control-Allow-Origin "{http.request.header.origin}"
|
||||
Access-Control-Expose-Headers *
|
||||
defer
|
||||
}
|
||||
}`;
|
||||
}
|
||||
|
||||
function removeSnippet(i) {
|
||||
collectStructured();
|
||||
snippets.splice(i, 1);
|
||||
structuredDirty = true;
|
||||
renderSnippets();
|
||||
}
|
||||
|
||||
// ─── Sites ────────────────────────────────────────────────────────────────────
|
||||
function collectSites() {
|
||||
document.querySelectorAll('.site-card').forEach((card, i) => {
|
||||
@@ -763,12 +1165,13 @@ function renderSites() {
|
||||
noSites.style.display = 'none';
|
||||
|
||||
sites.forEach((site, i) => {
|
||||
const routes = summarizeRoutes(site.body || '');
|
||||
const card = document.createElement('div');
|
||||
card.className = 'site-card';
|
||||
card.dataset.idx = i;
|
||||
card.innerHTML = `
|
||||
<div class="site-card-header" onclick="toggleSite(${i})">
|
||||
<span class="chev open" id="sc-${i}">▶</span>
|
||||
<span class="chev" id="sc-${i}">▶</span>
|
||||
<input class="site-address" type="text"
|
||||
value="${esc(site.address)}"
|
||||
placeholder="example.com or :8080"
|
||||
@@ -777,28 +1180,318 @@ function renderSites() {
|
||||
<button class="btn btn-sm btn-danger"
|
||||
onclick="event.stopPropagation(); removeSite(${i})">Remove</button>
|
||||
</div>
|
||||
<div class="site-card-body" id="sb-${i}">
|
||||
<textarea class="code" rows="7"
|
||||
<div class="site-card-body hidden" id="sb-${i}">
|
||||
<div class="route-summary">${renderRouteSummary(routes)}</div>
|
||||
<div class="builder">
|
||||
<div class="builder-title">
|
||||
<strong>Add Host Route</strong>
|
||||
<button class="btn btn-sm" onclick="insertHostRoute(${i})">Insert Route</button>
|
||||
</div>
|
||||
<div class="form-grid">
|
||||
<div class="field">
|
||||
<label>Host</label>
|
||||
<input id="route-host-${i}" type="text" placeholder="pdf.example.de" oninput="suggestMatcher(${i})">
|
||||
</div>
|
||||
<div class="field">
|
||||
<label>Matcher</label>
|
||||
<input id="route-name-${i}" type="text" placeholder="pdf">
|
||||
</div>
|
||||
<div class="field">
|
||||
<label>Reverse proxy target</label>
|
||||
<input id="route-upstream-${i}" type="text" placeholder="192.168.1.7:3300">
|
||||
</div>
|
||||
<label class="check-row">
|
||||
<input id="route-gzip-${i}" type="checkbox">
|
||||
encode gzip
|
||||
</label>
|
||||
<div class="field">
|
||||
<label>CORS origin</label>
|
||||
<input id="route-cors-${i}" type="text" placeholder="https://home.example.de">
|
||||
</div>
|
||||
<div class="field">
|
||||
<label>Forward auth upstream</label>
|
||||
<input id="route-auth-${i}" type="text" placeholder="192.168.1.7:9091">
|
||||
</div>
|
||||
</div>
|
||||
<div class="help-text">Optional auth uses <code>/api/authz/forward-auth</code> and copies the Authelia-style user headers from your demo.</div>
|
||||
</div>
|
||||
<div class="quick-actions">
|
||||
<span class="quick-actions-title">Insert</span>
|
||||
<button class="btn btn-sm" onclick="insertCommonParam(${i}, 'tls-netcup')">TLS netcup</button>
|
||||
<button class="btn btn-sm" onclick="insertCommonParam(${i}, 'host-matcher')">Host matcher</button>
|
||||
<button class="btn btn-sm" onclick="insertCommonParam(${i}, 'handle')">Handle</button>
|
||||
<button class="btn btn-sm" onclick="insertCommonParam(${i}, 'gzip')">gzip</button>
|
||||
<button class="btn btn-sm" onclick="insertCommonParam(${i}, 'cors')">CORS import</button>
|
||||
<button class="btn btn-sm" onclick="insertCommonParam(${i}, 'forward-auth')">forward_auth</button>
|
||||
<button class="btn btn-sm" onclick="insertCommonParam(${i}, 'reverse-proxy')">reverse_proxy</button>
|
||||
<button class="btn btn-sm" onclick="insertCommonParam(${i}, 'fallback-abort')">Fallback abort</button>
|
||||
</div>
|
||||
<textarea class="code site-body-editor" rows="7"
|
||||
placeholder=" reverse_proxy localhost:3000">${esc(site.body)}</textarea>
|
||||
<div class="upstream-warnings" id="uw-${i}"></div>
|
||||
</div>`;
|
||||
container.appendChild(card);
|
||||
});
|
||||
|
||||
document.querySelectorAll('textarea.code').forEach(ta => ta.addEventListener('keydown', handleTab));
|
||||
document.querySelectorAll('.site-card textarea.code').forEach(ta => ta.addEventListener('keydown', handleTab));
|
||||
document.querySelectorAll('.site-address, .site-card textarea.code, .builder input').forEach(el => {
|
||||
el.addEventListener('input', () => {
|
||||
structuredDirty = true;
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function summarizeRoutes(body) {
|
||||
const hosts = {};
|
||||
let active = null;
|
||||
let depth = 0;
|
||||
|
||||
body.split('\n').forEach(line => {
|
||||
let m = line.match(/^\s*@([A-Za-z0-9_-]+)\s+host\s+([^\s]+)/);
|
||||
if (m) {
|
||||
hosts[m[1]] = { name: m[1], host: m[2], upstream: '' };
|
||||
return;
|
||||
}
|
||||
|
||||
m = line.match(/^\s*handle\s+@([A-Za-z0-9_-]+)\s*\{/);
|
||||
if (m) {
|
||||
active = m[1];
|
||||
depth = 1;
|
||||
hosts[active] = hosts[active] || { name: active, host: '', upstream: '' };
|
||||
return;
|
||||
}
|
||||
|
||||
if (!active) return;
|
||||
const proxy = line.match(/^\s*reverse_proxy\s+([^\s{]+)/);
|
||||
if (proxy) hosts[active].upstream = proxy[1];
|
||||
|
||||
depth += (line.match(/\{/g) || []).length;
|
||||
depth -= (line.match(/\}/g) || []).length;
|
||||
if (depth <= 0) active = null;
|
||||
});
|
||||
|
||||
return Object.values(hosts);
|
||||
}
|
||||
|
||||
function renderRouteSummary(routes) {
|
||||
if (!routes.length) return '<span class="route-pill">No host routes detected</span>';
|
||||
return routes.map(route => {
|
||||
const host = route.host || '@' + route.name;
|
||||
const upstream = route.upstream ? ` -> ${route.upstream}` : '';
|
||||
return `<span class="route-pill"><strong>${esc(host)}</strong>${esc(upstream)}</span>`;
|
||||
}).join('');
|
||||
}
|
||||
|
||||
function suggestMatcher(i) {
|
||||
const host = document.getElementById(`route-host-${i}`).value.trim();
|
||||
const nameInput = document.getElementById(`route-name-${i}`);
|
||||
if (nameInput.value.trim() !== '') return;
|
||||
const first = host.split('.')[0] || host;
|
||||
nameInput.value = slugify(first);
|
||||
}
|
||||
|
||||
function insertHostRoute(i) {
|
||||
const card = document.querySelector(`.site-card[data-idx="${i}"]`);
|
||||
if (!card) return;
|
||||
|
||||
const host = document.getElementById(`route-host-${i}`).value.trim();
|
||||
const upstream = document.getElementById(`route-upstream-${i}`).value.trim();
|
||||
const matcher = slugify(document.getElementById(`route-name-${i}`).value.trim() || host.split('.')[0] || 'site');
|
||||
const cors = document.getElementById(`route-cors-${i}`).value.trim();
|
||||
const auth = document.getElementById(`route-auth-${i}`).value.trim();
|
||||
const gzip = document.getElementById(`route-gzip-${i}`).checked;
|
||||
|
||||
if (!host || !upstream) {
|
||||
toast('Host and reverse proxy target are required', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
const ta = card.querySelector('textarea.code');
|
||||
const block = buildHostRouteBlock({ matcher, host, upstream, cors, auth, gzip });
|
||||
ta.value = appendBlock(ta.value, block);
|
||||
sites[i].body = ta.value;
|
||||
structuredDirty = true;
|
||||
renderSites();
|
||||
toggleSite(i);
|
||||
toast(`Added route for ${host}`, 'ok');
|
||||
}
|
||||
|
||||
function insertCommonParam(i, type) {
|
||||
const card = document.querySelector(`.site-card[data-idx="${i}"]`);
|
||||
if (!card) return;
|
||||
|
||||
const ta = card.querySelector('.site-body-editor');
|
||||
const block = commonParamBlock(type);
|
||||
if (!block) return;
|
||||
|
||||
insertAtCursor(ta, block);
|
||||
sites[i].body = ta.value;
|
||||
structuredDirty = true;
|
||||
ta.focus();
|
||||
}
|
||||
|
||||
function commonParamBlock(type) {
|
||||
if (type === 'tls-netcup') {
|
||||
return `tls {
|
||||
issuer acme {
|
||||
dns netcup {
|
||||
customer_number {env.NETCUP_CUSTOMER_NUMBER}
|
||||
api_key {env.NETCUP_API_KEY}
|
||||
api_password {env.NETCUP_API_PASSWORD}
|
||||
}
|
||||
resolvers 8.8.8.8 1.1.1.1
|
||||
propagation_timeout 30m
|
||||
propagation_delay 15m
|
||||
}
|
||||
}`;
|
||||
}
|
||||
|
||||
if (type === 'host-matcher') {
|
||||
const host = prompt('Host domain', 'pdf.example.de');
|
||||
if (!host) return '';
|
||||
const matcher = prompt('Matcher name', slugify(host.split('.')[0] || 'site'));
|
||||
if (!matcher) return '';
|
||||
return `@${slugify(matcher)} host ${host.trim()}`;
|
||||
}
|
||||
|
||||
if (type === 'handle') {
|
||||
const matcher = prompt('Matcher name', 'pdf');
|
||||
if (!matcher) return '';
|
||||
return `handle @${slugify(matcher)} {
|
||||
reverse_proxy 192.168.1.7:3300
|
||||
}`;
|
||||
}
|
||||
|
||||
if (type === 'gzip') return 'encode gzip';
|
||||
|
||||
if (type === 'cors') {
|
||||
const origin = prompt('CORS origin', 'https://home.example.de');
|
||||
if (!origin) return '';
|
||||
if (!snippets.some(s => (s.name || '').trim() === 'cors-origin')) {
|
||||
snippets.push({ name: 'cors-origin', body: corsSnippetBody() });
|
||||
renderSnippets();
|
||||
toast('Added cors-origin snippet template', 'ok');
|
||||
}
|
||||
return `import cors-origin ${origin.trim()}`;
|
||||
}
|
||||
|
||||
if (type === 'forward-auth') {
|
||||
const upstream = prompt('Forward auth upstream', '192.168.1.7:9091');
|
||||
if (!upstream) return '';
|
||||
return `forward_auth ${upstream.trim()} {
|
||||
uri /api/authz/forward-auth
|
||||
copy_headers Remote-User Remote-Groups Remote-Email Remote-Name
|
||||
}`;
|
||||
}
|
||||
|
||||
if (type === 'reverse-proxy') {
|
||||
const upstream = prompt('Reverse proxy target', '192.168.1.7:3300');
|
||||
if (!upstream) return '';
|
||||
return `reverse_proxy ${upstream.trim()}`;
|
||||
}
|
||||
|
||||
if (type === 'fallback-abort') {
|
||||
return `# Fallback for otherwise unhandled domains
|
||||
handle {
|
||||
abort
|
||||
}`;
|
||||
}
|
||||
|
||||
return '';
|
||||
}
|
||||
|
||||
function buildHostRouteBlock(route) {
|
||||
const lines = [
|
||||
`@${route.matcher} host ${route.host}`,
|
||||
`handle @${route.matcher} {`,
|
||||
];
|
||||
if (route.gzip) lines.push(' encode gzip');
|
||||
if (route.cors) lines.push(` import cors-origin ${route.cors}`);
|
||||
if (route.auth) {
|
||||
lines.push(` forward_auth ${route.auth} {`);
|
||||
lines.push(' uri /api/authz/forward-auth');
|
||||
lines.push(' copy_headers Remote-User Remote-Groups Remote-Email Remote-Name');
|
||||
lines.push(' }');
|
||||
}
|
||||
lines.push(` reverse_proxy ${route.upstream}`);
|
||||
lines.push('}');
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
function appendBlock(body, block) {
|
||||
const trimmed = body.trimEnd();
|
||||
if (trimmed === '') return block;
|
||||
const fallback = trimmed.match(/\n\s*#?\s*Fallback[\s\S]*?\n\s*handle\s*\{/i);
|
||||
if (!fallback) return trimmed + '\n\n' + block;
|
||||
const idx = fallback.index;
|
||||
return trimmed.slice(0, idx).trimEnd() + '\n\n' + block + '\n' + trimmed.slice(idx);
|
||||
}
|
||||
|
||||
function insertAtCursor(ta, block) {
|
||||
const start = ta.selectionStart ?? ta.value.length;
|
||||
const end = ta.selectionEnd ?? ta.value.length;
|
||||
const before = ta.value.slice(0, start);
|
||||
const after = ta.value.slice(end);
|
||||
const prefix = before.trimEnd() === '' ? before.trimEnd() : before.trimEnd() + '\n\n';
|
||||
const suffix = after.trimStart() === '' ? after.trimStart() : '\n\n' + after.trimStart();
|
||||
ta.value = prefix + block + suffix;
|
||||
const cursor = prefix.length + block.length;
|
||||
ta.selectionStart = ta.selectionEnd = cursor;
|
||||
}
|
||||
|
||||
function slugify(value) {
|
||||
return String(value || '')
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9_-]+/g, '-')
|
||||
.replace(/^-+|-+$/g, '') || 'site';
|
||||
}
|
||||
|
||||
function addSite() {
|
||||
collectSites();
|
||||
collectStructured();
|
||||
sites.push({ address: '', body: '' });
|
||||
structuredDirty = true;
|
||||
renderSites();
|
||||
const inputs = document.querySelectorAll('.site-address');
|
||||
if (inputs.length) inputs[inputs.length - 1].focus();
|
||||
}
|
||||
|
||||
function addWildcardSite() {
|
||||
collectStructured();
|
||||
sites.push({
|
||||
address: '*.example.de',
|
||||
body: `tls {
|
||||
issuer acme {
|
||||
dns netcup {
|
||||
customer_number {env.NETCUP_CUSTOMER_NUMBER}
|
||||
api_key {env.NETCUP_API_KEY}
|
||||
api_password {env.NETCUP_API_PASSWORD}
|
||||
}
|
||||
resolvers 8.8.8.8 1.1.1.1
|
||||
propagation_timeout 30m
|
||||
propagation_delay 15m
|
||||
}
|
||||
}
|
||||
|
||||
# Fallback for otherwise unhandled domains
|
||||
handle {
|
||||
abort
|
||||
}`,
|
||||
});
|
||||
structuredDirty = true;
|
||||
renderSites();
|
||||
const idx = sites.length - 1;
|
||||
toggleSite(idx);
|
||||
const input = document.querySelector(`.site-card[data-idx="${idx}"] .site-address`);
|
||||
if (input) {
|
||||
input.focus();
|
||||
input.select();
|
||||
}
|
||||
}
|
||||
|
||||
function removeSite(i) {
|
||||
collectSites();
|
||||
collectStructured();
|
||||
sites.splice(i, 1);
|
||||
structuredDirty = true;
|
||||
renderSites();
|
||||
}
|
||||
|
||||
@@ -880,7 +1573,9 @@ function handleTab(e) {
|
||||
}
|
||||
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
|
||||
document.getElementById('global-editor').addEventListener('input', () => {
|
||||
structuredDirty = true;
|
||||
});
|
||||
init();
|
||||
});
|
||||
</script>
|
||||
|
||||
Reference in new issue
Block a user