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
+1111
-28
No files matched your search
@@ -0,0 +1,7 @@
|
||||
.git
|
||||
.claude
|
||||
.superpowers
|
||||
docs
|
||||
caddy
|
||||
deploy.sh
|
||||
README.md
|
||||
@@ -0,0 +1,79 @@
|
||||
|
||||
(cors-origin) {
|
||||
@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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
*.example.de {
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
@jellyfin host jellyfin.example.de
|
||||
handle @jellyfin {
|
||||
encode gzip
|
||||
reverse_proxy 192.168.1.7:8098
|
||||
}
|
||||
|
||||
@auth host auth.example.de
|
||||
handle @auth {
|
||||
import cors-origin https://home.example.de
|
||||
reverse_proxy 192.168.1.7:9091
|
||||
}
|
||||
|
||||
@hassio host hassio.example.de
|
||||
handle @hassio {
|
||||
reverse_proxy 192.168.1.4:8123
|
||||
}
|
||||
|
||||
@pdf host pdf.example.de
|
||||
handle @pdf {
|
||||
forward_auth 192.168.1.7:9091 {
|
||||
uri /api/authz/forward-auth
|
||||
copy_headers Remote-User Remote-Groups Remote-Email Remote-Name
|
||||
}
|
||||
reverse_proxy 192.168.1.7:3300
|
||||
}
|
||||
|
||||
# Fallback for otherwise unhandled domains
|
||||
handle {
|
||||
abort
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -5,8 +5,8 @@ Web UI for managing an existing dockerized [Caddy](https://caddyserver.com/) ins
|
||||
## Features
|
||||
|
||||
- **Structured editor** — separate panels for global options and each site block
|
||||
- **Raw editor** — optional full Caddyfile editing escape hatch for advanced changes
|
||||
- **Admin API check** — blocks editing if Caddy's admin API is unreachable on load
|
||||
- **Admin API toggle** — one checkbox adds/removes `admin :2019` from global options
|
||||
- **Upstream reachability check** — warns before deploy if any `reverse_proxy` target is unreachable, with option to deploy anyway
|
||||
- **Atomic deploy** — posts config to Caddy's `/load` endpoint; bad configs are rejected without disrupting the running instance
|
||||
|
||||
@@ -76,9 +76,11 @@ On first load it imports your existing Caddyfile (read-only). After the first de
|
||||
| Action | Description |
|
||||
|--------|-------------|
|
||||
| **Global Options** panel | Edit top-level Caddy options (email, logging, etc.) |
|
||||
| **Enable Admin API** checkbox | Adds/removes `admin :2019` from global options |
|
||||
| **Raw Caddyfile** mode | Edit the full Caddyfile directly; deploy still uses Caddy's admin API, so no restart is required |
|
||||
| **+ Add Site** | Creates a new site block |
|
||||
| **Remove** (per site) | Deletes that site block |
|
||||
| **Deploy** | Validates and applies config via Caddy's `/load` API; shows errors inline if rejected |
|
||||
|
||||
If any `reverse_proxy` upstream is unreachable at deploy time, a warning modal lists them — you can cancel or deploy anyway.
|
||||
|
||||
Switching from raw mode back to structured mode reparses the file, so comments and exact formatting may be normalized.
|
||||
+721
-26
@@ -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,8 +903,15 @@ async function doDeploy() {
|
||||
|
||||
|
||||
try {
|
||||
const payload = {
|
||||
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', {
|
||||
@@ -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,18 +944,15 @@ 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 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;
|
||||
// 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;
|
||||
@@ -734,16 +963,189 @@ function extractUpstreams() {
|
||||
host = part;
|
||||
port = 80;
|
||||
}
|
||||
if (!host || host.includes('{')) return; // skip Caddy placeholders
|
||||
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>
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
services:
|
||||
|
||||
koncad:
|
||||
build:
|
||||
context: .
|
||||
image: git.d4nn13.de/d4nn13/koncad:latest
|
||||
restart: unless-stopped
|
||||
volumes:
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
# Remote Deploy Debug Log
|
||||
|
||||
Date: 2026-05-03
|
||||
Target: `daniel@172.30.16.10:/opt/KonCad`
|
||||
|
||||
## Summary
|
||||
|
||||
- The remote host was already running `koncad-koncad-1` on port `8080`.
|
||||
- `/opt/KonCad` only contained deployment metadata (`Dockerfile`, `docker-compose.yml`, workflow files) and did not contain `app/`.
|
||||
- The original deploy flow synced source files to `/opt/KonCad`, but `docker-compose.yml` used only the published image, so remote source changes were not applied unless the host rebuilt separately.
|
||||
|
||||
## Changes made
|
||||
|
||||
- Added `build: .` to `docker-compose.yml` so the server can build from the synced checkout.
|
||||
- Updated `deploy.sh` to run `docker compose up -d --build` on the remote host after `rsync`.
|
||||
- Added `--no-remote-restart` for cases where only file sync is wanted.
|
||||
- Added `.dockerignore` and tightened `rsync` excludes so editor metadata and docs are not part of the deployment payload.
|
||||
|
||||
## Remote checks performed
|
||||
|
||||
- Confirmed container status with `docker ps`.
|
||||
- Confirmed the live app answered on `http://127.0.0.1:8080/`.
|
||||
- Confirmed the container mounts `/opt/caddy` read-only and persists `/data` in the `koncad_koncad_data` volume.
|
||||
- Confirmed existing auth state is already present in `/data/.auth`.
|
||||
- Rebuilt the container on the host with `docker compose up -d --build`.
|
||||
- Verified `/opt/KonCad/app/index.php` and `/var/www/html/index.php` have the same SHA-256 hash after deploy.
|
||||
- Verified `php -l /var/www/html/index.php` passes inside the running container.
|
||||
- Verified KonCad can reach `http://caddy:2019/config/` from inside the container.
|
||||
- Cleaned stale `.claude`, `.superpowers`, and `docs` directories from `/opt/KonCad` on the server.
|
||||
|
||||
## Notes
|
||||
|
||||
- Local PHP tooling was not available in this workspace (`php: command not found`), so syntax/runtime verification was done on the remote host.
|
||||
- The Apache log still shows the harmless `Could not reliably determine the server's fully qualified domain name` startup warning from the base image.
|
||||
@@ -0,0 +1,264 @@
|
||||
<!-- Edited with Claude Code -->
|
||||
# KonCad UI redesign — design
|
||||
|
||||
Refresh the KonCad web UI with a "Soft Slate" visual style (GitHub / Notion-dark
|
||||
inspired), light/dark via `prefers-color-scheme`, lightweight inline syntax
|
||||
highlighting for the Caddyfile editors, and a handful of small UX wins. No
|
||||
backend changes; same single-file PHP structure.
|
||||
|
||||
## Goals
|
||||
|
||||
- A modern, calm, information-dense look that fits a homelab tool you open
|
||||
occasionally.
|
||||
- Auto-respect the OS color-scheme preference (no manual toggle).
|
||||
- Make the Caddyfile editors readable at a glance with simple syntax colors.
|
||||
- Add a small set of polish improvements that the new look invites — without
|
||||
changing what the app does or its data flow.
|
||||
|
||||
## Non-goals
|
||||
|
||||
- No changes to PHP backend logic (parser, save handler, upstream check, auth
|
||||
model).
|
||||
- No new dependencies. Stays a single-file PHP tool — no CDN, no build step.
|
||||
- No structural rework — header / global panel / list of sites stays.
|
||||
- No new features (no draft staging, no diff view, no per-directive forms,
|
||||
no bulk site operations, no manual theme toggle).
|
||||
- No editor features beyond highlighting (no line numbers, no bracket matching,
|
||||
no autocomplete).
|
||||
|
||||
## Visual system
|
||||
|
||||
CSS custom properties on `:root` for dark, overridden inside
|
||||
`@media (prefers-color-scheme: light)`. Both auth screens and the main page
|
||||
use the same token set.
|
||||
|
||||
| Token | Dark | Light | Used for |
|
||||
|---|---|---|---|
|
||||
| `--bg` | `#0d1117` | `#f6f8fa` | page background |
|
||||
| `--surface` | `#161b22` | `#ffffff` | panels, cards |
|
||||
| `--surface-2` | `#0d1117` | `#f6f8fa` | editor / nested surfaces |
|
||||
| `--border` | `#21262d` | `#d0d7de` | every divider |
|
||||
| `--text` | `#e6edf3` | `#1f2328` | primary text |
|
||||
| `--muted` | `#7d8590` | `#656d76` | labels, subtle text |
|
||||
| `--accent` | `#58a6ff` | `#0969da` | links, focus, addresses |
|
||||
| `--accent-bg` | `rgba(88,166,255,0.12)` | `rgba(9,105,218,0.1)` | accent backgrounds, focus ring |
|
||||
| `--ok` | `#3fb950` | `#1a7f37` | success status |
|
||||
| `--warn` | `#d29922` | `#9a6700` | warnings |
|
||||
| `--error` | `#f85149` | `#cf222e` | errors |
|
||||
|
||||
**Type:** Inter via system stack
|
||||
(`-apple-system, "Segoe UI", "Inter", system-ui, sans-serif`); JetBrains Mono
|
||||
for code (with monospace fallback). Sizes: 13px base, 12px secondary, 11px
|
||||
labels/badges.
|
||||
|
||||
**Geometry:** 8px radius on inputs/buttons, 10px on panels. 1px borders
|
||||
throughout — no drop shadows. Focus ring: `0 0 0 3px var(--accent-bg)` on
|
||||
inputs and buttons. Spacing on a 4px grid.
|
||||
|
||||
## Layout
|
||||
|
||||
Same three regions as today.
|
||||
|
||||
### Header (sticky)
|
||||
|
||||
- Left: a small (18×18) gradient square logo mark + "KonCad" word in 700
|
||||
weight, `-0.01em` letter-spacing.
|
||||
- Center: a status pill — `● Caddy ready` (green) on success,
|
||||
`● Caddy unreachable` (red) when the admin API is down, `● Deploying…`
|
||||
(amber, with a 1.4s pulse animation) during a deploy. Pill background uses
|
||||
a tinted version of its color.
|
||||
- Right: primary `Deploy` button (green, GitHub-style primary) and a quiet
|
||||
`Log out` ghost button when auth is enabled.
|
||||
|
||||
### Main column
|
||||
|
||||
- `max-width: 960px` centered, 1.5rem horizontal padding.
|
||||
- **Global Options panel** — surface card with a header strip
|
||||
(`Global Options` title + a small grey badge counting non-blank,
|
||||
non-comment lines, e.g. `2 directives`). Body holds the highlighted editor.
|
||||
- **Sites section** — section title `Sites` with a `+ Add site` ghost button on
|
||||
the right, then a vertical list of site cards.
|
||||
|
||||
### Site card
|
||||
|
||||
- **Collapsed**: chevron, address (mono, `--accent` color), a one-line summary
|
||||
chip (`→ host:port` if the body has a `reverse_proxy` line, else
|
||||
`N directives`), and a `Remove` ghost-danger button visible on hover.
|
||||
- **Expanded**: address bar, the highlighted editor, and any
|
||||
`upstream-warnings` rendering area (existing slot, restyled).
|
||||
|
||||
### Empty state for sites
|
||||
|
||||
A dashed-border placeholder card replacing the current grey one-liner: small
|
||||
icon (`⊕` or similar), heading `No sites yet`, and an inline primary
|
||||
`+ Add site` button.
|
||||
|
||||
### Auth screens (setup / login)
|
||||
|
||||
Same centered-card pattern, retoned to the new tokens. Logo mark + "KonCad"
|
||||
header, subtitle (`Create your login credentials` / `Sign in to continue`),
|
||||
form with one username + one password input and a primary submit button.
|
||||
Inline error message uses `--error`.
|
||||
|
||||
### Modals & toasts
|
||||
|
||||
- **Upstream warning modal**: same content, retoned. Dark-mode backdrop gets
|
||||
`backdrop-filter: blur(4px)`.
|
||||
- **Toasts**: same triggers, restyled. Slide in with
|
||||
`transform: translateY(8px) → 0`, fade. Auto-dismiss at 5s (unchanged).
|
||||
|
||||
## Highlighted editor
|
||||
|
||||
Textarea-overlay technique. Native cursor, undo, IME, copy/paste behavior is
|
||||
preserved; the highlighted layer is purely decorative.
|
||||
|
||||
### Markup per editor
|
||||
|
||||
```html
|
||||
<div class="editor-wrap">
|
||||
<pre class="editor-hl" aria-hidden="true"></pre>
|
||||
<textarea class="editor-input" spellcheck="false">…</textarea>
|
||||
</div>
|
||||
```
|
||||
|
||||
### Mechanics
|
||||
|
||||
- `<pre>` and `<textarea>` are absolutely positioned in the same box, share
|
||||
identical font, font-size, line-height, padding, border, and box-sizing.
|
||||
- Textarea has `color: transparent; caret-color: var(--text)` so the user
|
||||
sees the painted `<pre>` text and a real caret.
|
||||
- On every `input` and `scroll`: read `textarea.value`, run `tokenize()`, write
|
||||
`<pre>.innerHTML`, copy `scrollTop`/`scrollLeft` from textarea to `<pre>`.
|
||||
- A trailing newline is appended before tokenizing so the last line renders.
|
||||
|
||||
### Tokenizer
|
||||
|
||||
Pure-JS, regex-based, ~60 LOC. Tokenization runs per-line, in this priority
|
||||
order so earlier rules win:
|
||||
|
||||
1. Leading whitespace — preserved as-is.
|
||||
2. Comment — `#` to end of line.
|
||||
3. String — `"…"` and `'…'` (escape-aware: `\\` and `\"`).
|
||||
4. Placeholder — `\{[^{}\n]*\}` matching `{$VAR}`, `{http.…}`, `{args.0}`,
|
||||
etc. Bare `{` or `}` outside this pattern fall through to the brace rule.
|
||||
5. Brace — lone `{` or `}`.
|
||||
6. Number — `:\d+` (port-like) and standalone integers.
|
||||
7. Directive — first non-whitespace word of the line, only if it's in the
|
||||
known directive list.
|
||||
8. Default — any other character class falls through to plain text.
|
||||
|
||||
Known directives (initial list): `reverse_proxy`, `root`, `file_server`,
|
||||
`encode`, `tls`, `header`, `redir`, `respond`, `route`, `handle`,
|
||||
`handle_path`, `import`, `log`, `email`, `admin`, `auto_https`, `php_fastcgi`,
|
||||
`basicauth`, `try_files`, `rewrite`, `uri`, `request_body`, `templates`,
|
||||
`map`, `metrics`, `acme_dns`, `acme_ca`. Easy to extend later by appending
|
||||
to the list.
|
||||
|
||||
### Token classes & colors
|
||||
|
||||
| Class | Dark | Light |
|
||||
|---|---|---|
|
||||
| `c` comment | `#7d8590` | `#6e7781` |
|
||||
| `d` directive | `#ff7b72` | `#cf222e` |
|
||||
| `s` string | `#a5d6ff` | `#0a3069` |
|
||||
| `p` placeholder | `#d2a8ff` | `#8250df` |
|
||||
| `n` number | `#79c0ff` | `#0550ae` |
|
||||
| `b` brace | `#7d8590` | `#6e7781` |
|
||||
|
||||
These live as CSS variables (`--tok-c`, `--tok-d`, …) under both the dark and
|
||||
light blocks.
|
||||
|
||||
### Tab handling
|
||||
|
||||
Existing `handleTab()` behavior preserved (Tab inserts 4 spaces, no
|
||||
focus-jump). The overlay re-tokenizes on the resulting `input` event.
|
||||
|
||||
### Scope
|
||||
|
||||
The two existing editor types — global options + each site body. Both render
|
||||
through a single `mountEditor(textarea)` helper. No line numbers, no
|
||||
bracket matching, no autocomplete.
|
||||
|
||||
## Small UX polish
|
||||
|
||||
- **Header status pill** wired to the existing `check_admin` result and to
|
||||
deploy state.
|
||||
- **Site card summary chip** (collapsed only): scan the body for the first
|
||||
`reverse_proxy` line and show `→ host:port` (truncated to ~28 chars). If
|
||||
none, show `N directives` (non-blank, non-comment lines). Updated on
|
||||
every collapse and on `change` of the textarea.
|
||||
- **Directive count badge** on the Global Options header: count of non-blank,
|
||||
non-comment lines. Updated on `input`, debounced 200ms.
|
||||
- **Remove site → 1-step inline confirm**: first click flips the button into
|
||||
a red `Confirm remove?` for ~3 seconds; second click within that window
|
||||
deletes. Click outside / 3s timeout reverts.
|
||||
- **Deploy keyboard shortcut**: `Cmd/Ctrl+S` triggers `preDeploy()`. Listener
|
||||
`preventDefault`s only when focus is inside the app (any element under
|
||||
`<main>` or `<header>`), not globally — and only when the deploy button
|
||||
is enabled. Button gets a `title` hint.
|
||||
- **Disabled state** when admin API is unreachable: existing logic, plus a
|
||||
visual change — disabled inputs get `0.5` opacity and a subtle striped
|
||||
background (`repeating-linear-gradient`). The status pill shows the
|
||||
reason text.
|
||||
|
||||
## Files touched
|
||||
|
||||
- **`app/index.php`** — only file modified.
|
||||
|
||||
### Sections being rewritten
|
||||
|
||||
- Auth-page HTML + `<style>` (currently lines ~239–275): retoned to the new
|
||||
tokens, same form fields and POST behavior.
|
||||
- Main page `<style>` block (currently lines ~282–550): replaced.
|
||||
- Main page HTML (currently lines ~552–600): minor structural tweaks for the
|
||||
status pill, summary chip, badge, empty state.
|
||||
- `<script>` (currently lines ~602–886): adds `mountEditor()`, `tokenize()`,
|
||||
`summaryFor()`, `directiveCount()`, `armRemove()`, and a global
|
||||
keyboard-shortcut listener. Updates `renderSites()` to emit the new
|
||||
markup. All other functions unchanged.
|
||||
|
||||
### Untouched
|
||||
|
||||
- All PHP above the auth-page HTML (config, session/auth, helpers, parser,
|
||||
`caddyLoad`, `checkUpstream`, every `?action=…` handler).
|
||||
- Existing JS: `init()`, `preDeploy()`, `doDeploy()`, `extractUpstreams()`,
|
||||
`collectSites()`, `addSite()`, `removeSite()` core, `togglePanel()`,
|
||||
`toggleSite()`, `setEditable()`, `setStatus()`, `setDeployBtn()`,
|
||||
`toast()`, `esc()`, `logout()`, `handleTab()`. All keep their current
|
||||
signatures and behavior.
|
||||
|
||||
## Risks & mitigations
|
||||
|
||||
- **Overlay desync** (highlighted layer drifting from textarea on paste, IME,
|
||||
resize, or scroll): the textarea remains the source of truth; the `<pre>`
|
||||
is rebuilt from `textarea.value` on every `input` and `scroll`. Identical
|
||||
font metrics + a trailing-newline trick handle the last-line case.
|
||||
- **`removeSite` two-click** is a behavior change. Acceptable: deleting a
|
||||
configured site has a real blast radius, and a 3s armed window is friction
|
||||
light.
|
||||
- **Global `Cmd/Ctrl+S` capture** could surprise users in a textarea. Mitigated
|
||||
by only `preventDefault`ing when the deploy button is enabled and focus is
|
||||
inside the app shell.
|
||||
- **Light-mode regression**: every color must come from a token — no hex
|
||||
literals in component CSS. Manual test: flip OS theme and confirm both
|
||||
palettes render correctly on every screen (auth, main, modal, toast,
|
||||
disabled state).
|
||||
|
||||
## Manual test plan
|
||||
|
||||
1. Load with the existing Caddyfile — global + sites populate correctly,
|
||||
highlighting renders for both editors.
|
||||
2. Edit each editor — highlight tracks input, scroll syncs, Tab indents
|
||||
without focus loss, paste of multi-line content highlights correctly.
|
||||
3. Flip OS theme dark↔light — every screen (auth, main, modal, toast,
|
||||
disabled state) re-themes without a reload.
|
||||
4. Add site, remove site (verify 2-click confirm), collapse/expand cards,
|
||||
summary chip updates after edits.
|
||||
5. Deploy success → green pill + green toast. Deploy with bad config → red
|
||||
pill + error toast with Caddy's message.
|
||||
6. Stop the Caddy admin API → reload page → unreachable disabled state
|
||||
renders, deploy button disabled, status pill red with reason.
|
||||
7. `Cmd/Ctrl+S` triggers deploy when admin is reachable; does nothing when
|
||||
disabled.
|
||||
8. Setup screen (scratch container with `/data/.auth` removed) and login
|
||||
screen both look right in both color schemes.
|
||||
Reference in new issue
Block a user