- Service Filter Bar: search by name, filter by status (online/offline) - Batch Operations: multi-select containers for start/stop/restart - Container Snapshots: create and manage Docker checkpoints - Added filter bar and batch action bar to index.html - Added snapshot button to Admin tools section - New JS modules: service-filter.js, batch-operations.js, snapshot.js - Updated build.js to include new modules in bundle
756 lines
136 KiB
JavaScript
756 lines
136 KiB
JavaScript
const DC={NAME:"DashCaddy",POLL:{DASHBOARD:1e4,LOGS:3e3,STATS:5e3,WEATHER:6e5,HEALTH:1e3,DEPLOY_SSL:5e3},DELAYS:{BTN_RESET:2e3,RELOAD:5e3,MODAL_CLOSE:500,PORT_CHECK:500,DEPLOY_INIT:3e3},DEFAULTS:{DNS_PORT:"5380",SERVICE_PORT:"8080",TTL:300,CADDYFILE:"C:\\caddy\\Caddyfile"}},errorHandler=new ErrorHandler,_cachedCfg=JSON.parse(localStorage.getItem("dashcaddy_site_config")||"null"),SITE={tld:_cachedCfg&&_cachedCfg.tld||".home",dnsIp:"",dnsPort:DC.DEFAULTS.DNS_PORT,dnsServers:{},configurationType:_cachedCfg&&_cachedCfg.configurationType||"homelab",domain:_cachedCfg&&_cachedCfg.domain||"",defaults:_cachedCfg&&_cachedCfg.defaults||{},routingMode:_cachedCfg&&_cachedCfg.routingMode||"subdomain",onboardingCompleted:!1};window.__dashcaddySiteConfigLoaded=(async function(){try{const w=await fetch("/api/v1/config");if(w.ok){const v=await w.json();if(v.tld&&(SITE.tld=v.tld.startsWith(".")?v.tld:"."+v.tld),v.dns&&(SITE.dnsIp=v.dns.ip||"",SITE.dnsPort=v.dns.port||DC.DEFAULTS.DNS_PORT),v.dnsServers&&typeof v.dnsServers=="object")for(const[h,n]of Object.entries(v.dnsServers))h!=="__proto__"&&h!=="constructor"&&h!=="prototype"&&(SITE.dnsServers[h]=n);v.configurationType&&(SITE.configurationType=v.configurationType),v.domain&&(SITE.domain=v.domain),v.defaults&&(SITE.defaults=v.defaults),v.routingMode&&(SITE.routingMode=v.routingMode),SITE.onboardingCompleted=v.onboardingCompleted===!0,localStorage.setItem("dashcaddy_site_config",JSON.stringify({tld:SITE.tld,configurationType:SITE.configurationType,domain:SITE.domain,routingMode:SITE.routingMode})),renderDnsCards();const r=document.getElementById("manage-tokens");r&&(r.style.display=Object.keys(SITE.dnsServers).length?"":"none")}}catch{}document.querySelectorAll("[data-tld]").forEach(w=>w.textContent=SITE.tld);const m=document.getElementById("edit-tld-suffix");m&&(m.textContent=SITE.tld);const l=document.getElementById("external-proxy-ip");l&&SITE.dnsIp&&(l.value=SITE.dnsIp,l.placeholder=SITE.dnsIp)})();function buildDomain(o){return o+SITE.tld}function buildServiceUrl(o){return SITE.routingMode==="subdirectory"&&SITE.domain?"https://"+SITE.domain+"/"+o:SITE.configurationType==="public"&&SITE.domain?"https://"+o+"."+SITE.domain:"https://"+buildDomain(o)}function getDnsServerAddr(o){const m=SITE.dnsServers[o];return m?`${m.ip}:${m.port}`:buildDomain(o)}function getPrimaryDnsId(){if(!SITE.dnsIp)return null;for(const[o,m]of Object.entries(SITE.dnsServers))if(m.ip===SITE.dnsIp)return o;return null}function renderDnsCards(){const o=document.querySelector(".top");if(!o)return;const m=Object.keys(SITE.dnsServers);if(!m.length)return;const l='<svg viewBox="0 0 24 24" class="service-icon"><rect x="3" y="4" width="18" height="16" rx="2" fill="#34495e"/><rect x="5" y="6" width="14" height="2" rx="1" fill="#3498db"/><rect x="5" y="9" width="10" height="1" fill="#ecf0f1"/><rect x="5" y="11" width="12" height="1" fill="#ecf0f1"/><rect x="5" y="13" width="8" height="1" fill="#ecf0f1"/><rect x="5" y="15" width="14" height="1" fill="#ecf0f1"/><circle cx="17" cy="11" r="2" fill="#e74c3c"/><path d="M17 9v4M15 11h4" stroke="white" stroke-width="1"/></svg>',w=o.firstElementChild;m.forEach(v=>{const r=escapeHtml(v),h=escapeHtml((SITE.dnsServers[v].name||v).toUpperCase()),n=document.createElement("div");n.className="card",n.setAttribute("data-app",v),n.setAttribute("data-status","off"),n.innerHTML=`<span id="${r}-dot" class="dot bad at-bl"></span><div class="row"><div class="logo-wrap">${l}</div><span class="name">${h}</span><span class="spacer"></span><span id="${r}-pill" class="badge off">OFF</span></div><div class="response-row"><span id="${r}-time" class="response-time">--</span></div><div class="health-row" id="health-${r}"><span id="uptime-${r}" class="uptime-chip">--</span><div class="uptime-mini-bar"><div class="fill" id="uptime-bar-${r}" style="width: 0%"></div></div></div><div class="btn-row"><button id="${r}-restart" class="restart-btn">Restart</button><button id="${r}-update" class="update-btn" title="Update DNS server">\u2B06\uFE0F</button><button id="${r}-open">Open</button><button id="${r}-logs" class="logs-btn">Logs</button><button id="${r}-settings" class="settings-btn">\u2699\uFE0F</button></div>`,o.insertBefore(n,w)})}window.renderDnsCards=renderDnsCards;let csrfToken=null;async function getCSRFToken(){if(csrfToken)return csrfToken;try{const o=await fetch("/api/v1/csrf-token");if(!o.ok)throw new Error("Failed to fetch CSRF token");return csrfToken=(await o.json()).token,csrfToken}catch(o){throw errorHandler.logError("[CSRF] Get Token",o,{function:"getCSRFToken"}),o}}async function secureFetch(o,m={}){const l=(m.method||"GET").toUpperCase(),w=!["GET","HEAD","OPTIONS"].includes(l);if(w)try{const r=await getCSRFToken();m.headers={...m.headers,"X-CSRF-Token":r}}catch(r){errorHandler.logError("[CSRF] Add to Request",r,{function:"secureFetch"})}m.signal||(m={...m,signal:AbortSignal.timeout(15e3)});const v=await fetch(o,m);if(w&&v.status===403)try{const r=await v.clone().json();if(r.error&&(r.error.includes("DC-100")||r.error.includes("DC-101"))){csrfToken=null;const h=await getCSRFToken();return m.headers={...m.headers,"X-CSRF-Token":h},m.signal=AbortSignal.timeout(15e3),fetch(o,m)}}catch{}return v}async function postJSON(o,m){const l=await secureFetch(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(m)}),w=await l.json();if(!l.ok||w.success===!1)throw new Error(w.error||`Request failed (${l.status})`);return w}async function getJSON(o){const m=await secureFetch(o);if(!m.ok){let l=`Request failed (${m.status})`;try{l=(await m.json()).error||l}catch{}throw new Error(l)}return m.json()}async function deleteAPI(o){const m=await secureFetch(o,{method:"DELETE"}),l=await m.json();if(!m.ok||l.success===!1)throw new Error(l.error||`Delete failed (${m.status})`);return l}async function withButton(o,m,l,w={}){const v=o.innerHTML,{successText:r="\u2705",resetDelay:h=DC.DELAYS.BTN_RESET}=w;o.disabled=!0,o.innerHTML=m;try{const n=await l();return o.innerHTML=r,setTimeout(()=>{o.innerHTML=v,o.disabled=!1},h),n}catch(n){throw o.innerHTML=v,o.disabled=!1,n}}function openModal(o){document.getElementById(o)?.classList.add("show")}function closeModal(o){document.getElementById(o)?.classList.remove("show")}function wireModal(o,...m){o&&(o.addEventListener("click",l=>{l.target===o&&o.classList.remove("show")}),m.forEach(l=>l?.addEventListener("click",()=>o.classList.remove("show"))))}function showNotification(o,m="info",l=3e3){const w=document.querySelector(".deploy-notification");w&&w.remove();const v={info:{bg:"#2196F3",fg:"#fff"},success:{bg:"var(--ok-bg)",fg:"var(--ok-fg)"},error:{bg:"#f44336",fg:"#fff"},warning:{bg:"#ff9800",fg:"#fff"}},r=v[m]||v.info,h=document.createElement("div");h.className="deploy-notification",h.textContent=o,h.style.cssText=`
|
|
position: fixed; top: 20px; right: 20px;
|
|
background: ${r.bg}; color: ${r.fg};
|
|
padding: 16px 24px; border-radius: 8px;
|
|
box-shadow: 0 4px 12px rgba(0,0,0,.3);
|
|
z-index: 10000; animation: slideIn 0.3s ease-out;
|
|
max-width: 400px; white-space: pre-line; font-size: 14px;
|
|
`,document.body.appendChild(h),l>0&&setTimeout(()=>h.remove(),l)}function timeAgo(o){const m=Date.now()-new Date(o).getTime();return m<6e4?"just now":m<36e5?Math.floor(m/6e4)+"m ago":m<864e5?Math.floor(m/36e5)+"h ago":Math.floor(m/864e5)+"d ago"}function safeGet(o,m=null){try{const l=localStorage.getItem(o);return l!==null?l:m}catch{return m}}function safeSet(o,m){try{localStorage.setItem(o,m)}catch{}}function safeRemove(o){try{localStorage.removeItem(o)}catch{}}function safeSessionGet(o,m=null){try{const l=sessionStorage.getItem(o);return l!==null?l:m}catch{return m}}function safeSessionSet(o,m){try{sessionStorage.setItem(o,m)}catch{}}function safeGetJSON(o,m=null){try{const l=localStorage.getItem(o);return l?JSON.parse(l):m}catch{return m}}function escapeHtml(o){return String(o??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function injectModal(o,m){document.getElementById(o)||document.body.insertAdjacentHTML("beforeend",m)}const DC_BUS={_handlers:{},on(o,m){var l;((l=this._handlers)[o]||(l[o]=[])).push(m)},off(o,m){this._handlers[o]=this._handlers[o]?.filter(l=>l!==m)},emit(o,m){this._handlers[o]?.forEach(l=>l(m))}},AppState={_apps:[],getApps(){return this._apps},setApps(o){this._apps=o,window.APPS=o,DC_BUS.emit("apps:changed",o)},findApp(o){return this._apps.find(m=>m.id===o)},addApp(o){this._apps.push(o),window.APPS=this._apps,DC_BUS.emit("apps:changed",this._apps)},removeApp(o){const m=this._apps.findIndex(l=>l.id===o);return m>-1&&(this._apps.splice(m,1),window.APPS=this._apps,DC_BUS.emit("apps:changed",this._apps)),m>-1},updateApp(o,m){const l=this._apps.find(w=>w.id===o);if(l){for(const[w,v]of Object.entries(m))w!=="__proto__"&&w!=="constructor"&&w!=="prototype"&&(l[w]=v);DC_BUS.emit("apps:changed",this._apps)}return l}};(function(){function o(){const w=document.createElement("div");return w.className="skeleton-card",w.innerHTML='<div style="display:flex;align-items:center;gap:12px;margin-bottom:12px"><div class="skeleton-bar" style="width:48px;height:48px;border-radius:8px;flex-shrink:0"></div><div style="flex:1"><div class="skeleton-bar" style="width:60%;height:14px;margin-bottom:6px"></div><div class="skeleton-bar" style="width:35%;height:10px"></div></div><div class="skeleton-bar" style="width:42px;height:22px;border-radius:11px"></div></div><div class="skeleton-bar" style="width:45%;height:12px;margin-bottom:10px"></div><div style="display:flex;gap:8px;margin-top:auto"><div class="skeleton-bar" style="width:64px;height:28px;border-radius:8px"></div><div class="skeleton-bar" style="width:64px;height:28px;border-radius:8px"></div></div>',w}function m(w){const v=document.getElementById("cards");if(!(!v||v.querySelector(".card"))){w=w||6;for(let r=0;r<w;r++){const h=o();v.appendChild(h),setTimeout(function(){h.classList.add("loaded")},r*60)}}}function l(){const w=document.getElementById("cards");if(w){var v=w.querySelectorAll(".skeleton-card");v.length&&(v.forEach(function(r,h){setTimeout(function(){r.style.opacity="0",r.style.transform="translateY(-10px)"},h*25)}),setTimeout(function(){v.forEach(function(r){r.parentNode&&r.remove()})},v.length*25+300))}}window.SkeletonLoader={show:m,hide:l}})(),(function(){var o="theme",m="user-themes",l="custom-theme",w=["dark","light","blue","black","nord","dracula","solarized-dark","solarized-light","taxi","ocean"],v=w.slice(),r=["bg","fg","muted","fg-muted","card-base","card-bg","border","hover","card-hover","base","ok-bg","ok-fg","bad-bg","bad-fg","dot-ok","dot-bad","uptime","success","error","warning","accent","accent-strong"],h=["bg","fg","muted","card-base","card-bg","border","ok-bg","ok-fg","bad-bg","bad-fg","dot-ok","dot-bad","uptime","accent","accent-strong"],n=["fg-muted","hover","card-hover","base","success","error","warning"],b={dark:{bg:"#0b0f1a",fg:"#e8ecf5",muted:"#9aa6bf","fg-muted":"#6b7a94","card-base":"#121826","card-bg":"#121826",border:"#263552",hover:"#1a2235","card-hover":"#161e2e",base:"#151c2b","ok-bg":"#0c2430","ok-fg":"#7ef2ff","bad-bg":"#2a121a","bad-fg":"#ff9aa3","dot-ok":"#35d1ff","dot-bad":"#ff5f7a",uptime:"#35d1ff",success:"#4caf50",error:"#e74c3c",warning:"#f39c12",accent:"#8FD6FF","accent-strong":"#1F7BFF"},light:{bg:"#f6f7fb",fg:"#0f1115",muted:"#5f6b7a","fg-muted":"#8993a4","card-base":"#ffffff","card-bg":"#ffffff",border:"#e2e7ef",hover:"#eef1f6","card-hover":"#f5f6fa",base:"#ebeef3","ok-bg":"#eafff1","ok-fg":"#0a7c3a","bad-bg":"#ffefef","bad-fg":"#b00020","dot-ok":"#0fb15a","dot-bad":"#d93b3b",uptime:"#0fb15a",success:"#0a7c3a",error:"#b00020",warning:"#d68a00",accent:"#4a90d9","accent-strong":"#2563eb",lightBg:!0},blue:{bg:"#1908AC",fg:"#e8f1ff",muted:"#d6e2ff","fg-muted":"#9eafdb","card-base":"#0d1533","card-bg":"#0d1533",border:"#1c2d6a",hover:"#141f4a","card-hover":"#111a3e",base:"#0f1840","ok-bg":"#162040","ok-fg":"#edffff","bad-bg":"#0a0e24","bad-fg":"#ffb3c0","dot-ok":"#c7e5ff","dot-bad":"#ffd6dc",uptime:"#7ec8ff",success:"#7ec8ff",error:"#ffb3c0",warning:"#ffd080",accent:"#9cd4ff","accent-strong":"#6fb2ff"},black:{bg:"#0e0e0e",fg:"#f5f5f5",muted:"#999999","fg-muted":"#666666","card-base":"#1a1a1a","card-bg":"#1a1a1a",border:"#2e2e2e",hover:"#242424","card-hover":"#202020",base:"#161616","ok-bg":"#0f2a12","ok-fg":"#66ff7a","bad-bg":"#2a0f0f","bad-fg":"#ff6b6b","dot-ok":"#4caf50","dot-bad":"#ff4444",uptime:"#e0e0e0",success:"#4caf50",error:"#ff4444",warning:"#ff9800",accent:"#E63946","accent-strong":"#C62828"},nord:{bg:"#2e3440",fg:"#eceff4",muted:"#81a1c1","fg-muted":"#6882a0","card-base":"#3b4252","card-bg":"#3b4252",border:"#4c566a",hover:"#434c5e","card-hover":"#3f4858",base:"#353c4a","ok-bg":"#2d4f3e","ok-fg":"#a3be8c","bad-bg":"#4a2c2a","bad-fg":"#bf616a","dot-ok":"#a3be8c","dot-bad":"#bf616a",uptime:"#a3be8c",success:"#a3be8c",error:"#bf616a",warning:"#ebcb8b",accent:"#88c0d0","accent-strong":"#5e81ac"},dracula:{bg:"#282a36",fg:"#f8f8f2",muted:"#6272a4","fg-muted":"#515d85","card-base":"#44475a","card-bg":"#44475a",border:"#6272a4",hover:"#4e5170","card-hover":"#494c63",base:"#363848","ok-bg":"#1e3a2e","ok-fg":"#50fa7b","bad-bg":"#3d1a1a","bad-fg":"#ff5555","dot-ok":"#50fa7b","dot-bad":"#ff5555",uptime:"#50fa7b",success:"#50fa7b",error:"#ff5555",warning:"#f1fa8c",accent:"#bd93f9","accent-strong":"#8be9fd"},"solarized-dark":{bg:"#002b36",fg:"#839496",muted:"#586e75","fg-muted":"#4a5f65","card-base":"#073642","card-bg":"#073642",border:"#586e75",hover:"#0d4050","card-hover":"#0a3a48",base:"#053340","ok-bg":"#0d3d2c","ok-fg":"#859900","bad-bg":"#3d1a1a","bad-fg":"#dc322f","dot-ok":"#859900","dot-bad":"#dc322f",uptime:"#b5bd68",success:"#859900",error:"#dc322f",warning:"#b58900",accent:"#268bd2","accent-strong":"#2aa198"},"solarized-light":{bg:"#fdf6e3",fg:"#657b83",muted:"#93a1a1","fg-muted":"#adb8b8","card-base":"#eee8d5","card-bg":"#eee8d5",border:"#93a1a1",hover:"#e6dfcb","card-hover":"#eae3cf",base:"#e8e1cd","ok-bg":"#e8f5e8","ok-fg":"#859900","bad-bg":"#fdf2f2","bad-fg":"#dc322f","dot-ok":"#859900","dot-bad":"#dc322f",uptime:"#859900",success:"#859900",error:"#dc322f",warning:"#b58900",accent:"#268bd2","accent-strong":"#2aa198",lightBg:!0},taxi:{bg:"#f3d321",fg:"#0e0e00",muted:"#4a4a10","fg-muted":"#6b6b30","card-base":"#ffd700","card-bg":"#ffd700",border:"#b8a840",hover:"#ffe84d","card-hover":"#ffe033",base:"#f0d000","ok-bg":"#d4ffd9","ok-fg":"#0f2a0f","bad-bg":"#ffd4d4","bad-fg":"#2a0f0f","dot-ok":"#4caf50","dot-bad":"#ff4444",uptime:"#0e0e00",success:"#2e7d32",error:"#c62828",warning:"#e65100",accent:"#7a4a00","accent-strong":"#5c3800",lightBg:!0},ocean:{bg:"#2060b0",fg:"#faf5eb",muted:"#dcd2c0","fg-muted":"#b0a890","card-base":"#7a94ed","card-bg":"#7a94ed",border:"#deb67a",hover:"#8aa0f0","card-hover":"#8298e8",base:"#6888e0","ok-bg":"#4f5bb0","ok-fg":"#c7d7eb","bad-bg":"#f41a3a","bad-fg":"#6a1818","dot-ok":"#30a050","dot-bad":"#d04040",uptime:"#2d32f2",success:"#30a050",error:"#d04040",warning:"#e6a030",accent:"#1860a0","accent-strong":"#104080"}};function p(E){return!E||typeof E!="string"?{r:0,g:0,b:0}:(E=E.replace("#",""),E.length===3&&(E=E[0]+E[0]+E[1]+E[1]+E[2]+E[2]),{r:parseInt(E.substr(0,2),16)||0,g:parseInt(E.substr(2,2),16)||0,b:parseInt(E.substr(4,2),16)||0})}function s(E,L,$){return"#"+[E,L,$].map(function(x){var y=Math.max(0,Math.min(255,Math.round(x))).toString(16);return y.length===1?"0"+y:y}).join("")}function c(E,L,$){var x=p(E),y=p(L);return s(x.r+(y.r-x.r)*$,x.g+(y.g-x.g)*$,x.b+(y.b-x.b)*$)}function g(E){E=E.replace("#",""),E.length===3&&(E=E[0]+E[0]+E[1]+E[1]+E[2]+E[2]);var L=parseInt(E.substr(0,2),16)/255,$=parseInt(E.substr(2,2),16)/255,x=parseInt(E.substr(4,2),16)/255;return L=L<=.03928?L/12.92:Math.pow((L+.055)/1.055,2.4),$=$<=.03928?$/12.92:Math.pow(($+.055)/1.055,2.4),x=x<=.03928?x/12.92:Math.pow((x+.055)/1.055,2.4),.2126*L+.7152*$+.0722*x}function e(E){var L=E.bg||"#0b0f1a",$=E.fg||"#e8ecf5",x=E.muted||"#9aa6bf",y=E["card-base"]||E.bg||"#121826",I=E["dot-ok"]||"#4caf50",S=E["dot-bad"]||"#e74c3c",C=E.lightBg||L&&g(L)>.4,P={};return P.hover=C?c(y,L,.35):c(y,$,.08),P["card-hover"]=c(y,P.hover,.5),P.base=c(L,y,.6),P["fg-muted"]=c(x,L,.35),P.success=I,P.error=S,P.warning=C?"#d68a00":"#f39c12",P}function a(E,L){var $=L.lightBg||L.bg&&g(L.bg)>.4,x=L.accent||L["accent-strong"]||"#888888",y=p(x);return $?":root."+E+` body {
|
|
background:
|
|
radial-gradient(1200px 800px at 10% -10%, rgba(`+y.r+","+y.g+","+y.b+`, .08), transparent 60%),
|
|
radial-gradient(1000px 700px at 110% 10%, rgba(`+y.r+","+y.g+","+y.b+`, .05), transparent 55%),
|
|
var(--bg);
|
|
}
|
|
`:":root."+E+` body {
|
|
background:
|
|
radial-gradient(1200px 900px at 8% -12%, rgba(`+y.r+","+y.g+","+y.b+`, .10), transparent 60%),
|
|
radial-gradient(1000px 700px at 110% -10%, rgba(`+y.r+","+y.g+","+y.b+`, .07), transparent 55%),
|
|
var(--bg);
|
|
}
|
|
`}function u(E,L){var $=L.lightBg||L.bg&&g(L.bg)>.4;return $?":root."+E+` button:hover {
|
|
background: color-mix(in srgb, var(--accent-strong) 12%, white 88%);
|
|
border-color: rgba(0, 0, 0, .15);
|
|
box-shadow: 0 1px 6px rgba(0, 0, 0, .08), inset 0 1px 0 rgba(255, 255, 255, .8);
|
|
}
|
|
`:":root."+E+` button:hover {
|
|
background: color-mix(in srgb, var(--accent) 18%, transparent);
|
|
border-color: color-mix(in srgb, var(--accent) 35%, var(--border));
|
|
}
|
|
`}function t(){return window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function d(){r.forEach(function(E){document.documentElement.style.removeProperty("--"+E)})}function f(E,L){var $=E.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"");$||($="custom"),w.indexOf($)!==-1&&($=$+"-custom");for(var x=safeGetJSON(m,{}),y=$,I=2;x[$]&&$!==L;)$=y+"-"+I++;return $}function i(E){var L=document.getElementById("user-theme-styles");L&&L.remove(),v.length=w.length,Object.keys(b).forEach(function(S){w.indexOf(S)===-1&&delete b[S]});var $=E||safeGetJSON(m,{}),x=Object.keys($);if(x=x.filter(function(S){return w.indexOf(S)===-1}),!!x.length){var y="";x.forEach(function(S){var C=$[S];v.indexOf(S)===-1&&v.push(S);var P={};r.forEach(function(O){C[O]&&(P[O]=C[O])}),P["card-bg"]=C["card-base"]||C.bg,C.lightBg&&(P.lightBg=!0);var D=e(P);n.forEach(function(O){!P[O]&&D[O]&&(P[O]=D[O])}),b[S]=P,y+=":root."+S+` {
|
|
`,r.forEach(function(O){P[O]&&(y+=" --"+O+": "+P[O]+`;
|
|
`)}),y+=`}
|
|
`,y+=a(S,P),y+=u(S,P)});var I=document.createElement("style");I.id="user-theme-styles",I.textContent=y,document.head.appendChild(I)}}function k(){secureFetch("/api/v1/themes").then(function(E){return E.json()}).then(function(E){if(!(!E.success||!E.themes)){var L=E.themes,$=safeGetJSON(m,{});if(JSON.stringify(L)!==JSON.stringify($)){safeSet(m,JSON.stringify(L)),i(L);var x=safeGet(o);x&&v.indexOf(x)!==-1&&T(x)}}}).catch(function(){})}function B(){var E=safeGetJSON(l);if(E){var L=E.name||"Custom",$=f(L),x={name:L};r.forEach(function(S){E[S]&&(x[S]=E[S])});var y=safeGetJSON(m,{});y[$]=x,safeSet(m,JSON.stringify(y)),safeGet(o)==="custom"&&safeSet(o,$),safeRemove(l);var I={};r.forEach(function(S){x[S]&&(I[S]=x[S])}),fetch("/api/v1/themes/"+$,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:L,colors:I})}).catch(function(){})}}function T(E){document.documentElement.classList.add("theme-transitioning"),v.forEach(function(y){y!=="dark"&&document.documentElement.classList.remove(y)}),d(),E!=="dark"&&document.documentElement.classList.add(E),safeSet(o,E);var L=b[E],$=document.querySelector('meta[name="theme-color"]');$&&L&&$.setAttribute("content",L.bg);var x=L&&L.lightBg;!x&&L&&L.bg&&(x=g(L.bg)>.4),x?document.documentElement.classList.add("light-bg"):document.documentElement.classList.remove("light-bg"),setTimeout(function(){document.documentElement.classList.remove("theme-transitioning")},300)}B(),i();var A=safeGet(o);A==="red"&&(A="black",safeSet(o,"black")),A&&A!=="dark"&&v.indexOf(A)===-1&&(A=null),T(A||t()),k(),window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change",function(E){safeGet(o)||T(E.matches?"dark":"light")}),window.THEMES=v,window.BUILTIN_THEMES=w,window.THEME_COLORS=b,window.THEME_PROPS=r,window.BASE_PROPS=h,window.DERIVED_PROPS=n,window.USER_THEMES_KEY=m,window.applyTheme=T,window.clearCustomProperties=d,window.injectUserThemeStyles=i,window.syncThemesFromServer=k,window.slugifyThemeName=f,window.getActiveTheme=function(){return safeGet(o)||t()},window.deriveExtendedColors=e,window.hexToRgb=p,window.rgbToHex=s,window.blendColors=c})(),(function(){function o(){const h=document.querySelector(".totp-card");if(!h)return;const b=getComputedStyle(h).backgroundColor.match(/\d+/g);if(!b)return;const p=(.299*+b[0]+.587*+b[1]+.114*+b[2])/255,s=h.querySelector(".totp-logo-dark"),c=h.querySelector(".totp-logo-light");s&&(s.style.display=p>.5?"none":""),c&&(c.style.display=p>.5?"":"none")}function m(){const h=document.getElementById("totp-overlay");if(h){h.classList.add("show"),setTimeout(o,50);const n=h.querySelector(".totp-digits input");n&&setTimeout(()=>n.focus(),100)}}function l(){const h=document.getElementById("totp-overlay");h&&h.classList.remove("show")}const w=document.getElementById("totp-digits");if(w){const h=w.querySelectorAll("input");h.forEach((n,b)=>{n.addEventListener("input",p=>{const s=p.target.value.replace(/\D/g,"");p.target.value=s.slice(0,1),s&&b<h.length-1&&h[b+1].focus();const c=Array.from(h).map(g=>g.value).join("");c.length===6&&v(c)}),n.addEventListener("keydown",p=>{p.key==="Backspace"&&!p.target.value&&b>0&&(h[b-1].focus(),h[b-1].value="")}),n.addEventListener("paste",p=>{p.preventDefault();const s=(p.clipboardData.getData("text")||"").replace(/\D/g,"");s.length>=6&&(h.forEach((c,g)=>{c.value=s[g]||""}),h[5].focus(),v(s.slice(0,6)))})})}async function v(h){const n=document.getElementById("totp-error");n.textContent="Verifying...",n.className="totp-error verifying";try{const p=await(await secureFetch("/api/v1/totp/verify",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:h})})).json();if(p.success){n.textContent="",p.csrfToken&&(csrfToken=p.csrfToken),l();const s=safeSessionGet("totp_redirect");if(s){try{sessionStorage.removeItem("totp_redirect")}catch{}window.location.href=s;return}typeof window.initializeDashboard=="function"&&window.initializeDashboard()}else{n.textContent=p.error||"Invalid code",n.className="totp-error";const s=document.querySelectorAll("#totp-digits input");s.forEach(c=>{c.value=""}),s[0]?.focus()}}catch{n.textContent="Connection error",n.className="totp-error"}}const r=new URLSearchParams(window.location.search);if(r.get("auth")==="required"){const h=r.get("return");if(h)try{const n=new URL(h,window.location.origin),b=n.hostname,p=n.origin===window.location.origin,s=SITE.tld.startsWith(".")?SITE.tld:"."+SITE.tld,c=b.endsWith(s)||b===s.substring(1);(p||c)&&safeSessionSet("totp_redirect",h)}catch{}window.history.replaceState({},"",window.location.pathname)}window._showTotpOverlay=m})(),(function(){const o=new ErrorHandler;injectModal("folder-browser-modal",`<div id="folder-browser-modal" class="weather-modal">
|
|
<div class="weather-modal-content" style="min-width: 500px; max-width: 700px; max-height: 80vh;">
|
|
<h3>\u{1F4C2} Browse for Media Folders</h3>
|
|
|
|
<div id="folder-browser-path" style="padding: 10px; background: var(--card-bg); border-radius: 6px; margin-bottom: 12px; font-family: monospace; font-size: 0.9rem; word-break: break-all;">
|
|
/
|
|
</div>
|
|
|
|
<div id="folder-browser-list" style="max-height: 400px; overflow-y: auto; border: 1px solid var(--border); border-radius: 6px;">
|
|
<div style="padding: 20px; text-align: center; color: var(--muted);">Loading...</div>
|
|
</div>
|
|
|
|
<div id="folder-browser-selected" style="margin-top: 12px; padding: 10px; background: color-mix(in srgb, var(--success) 10%, transparent); border: 1px solid var(--success); border-radius: 6px; display: none;">
|
|
<div style="font-size: 0.85rem; color: var(--success); margin-bottom: 6px;">Selected folders:</div>
|
|
<div id="folder-browser-selected-list" style="display: flex; flex-wrap: wrap; gap: 6px;"></div>
|
|
</div>
|
|
|
|
<div class="weather-modal-buttons" style="margin-top: 16px; display: flex; gap: 8px; justify-content: space-between;">
|
|
<button id="folder-browser-select-current" class="btn-accent">
|
|
+ Add Current Folder
|
|
</button>
|
|
<div class="flex-row-gap">
|
|
<button id="folder-browser-cancel">Cancel</button>
|
|
<button id="folder-browser-done" style="background: color-mix(in srgb, var(--success) 20%, transparent); border-color: var(--success); color: var(--success);">Done</button>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>`),injectModal("service-creds-modal",`<div id="service-creds-modal">
|
|
<div class="service-creds-content">
|
|
<h3 id="svc-creds-title" style="margin: 0 0 4px; font-size: 1.05rem;">Service Credentials</h3>
|
|
<p id="svc-creds-desc" style="font-size: 0.75rem; color: var(--muted); margin: 0 0 14px;">Credentials are injected automatically when accessing this service.</p>
|
|
|
|
<!-- Status indicator -->
|
|
<div style="display: flex; align-items: center; gap: 6px; margin-bottom: 12px;">
|
|
<span id="svc-creds-dot" class="status-dot"></span>
|
|
<span id="svc-creds-status" class="text-muted-sm">No credentials stored</span>
|
|
</div>
|
|
|
|
<!-- Seedhost credentials (shown for external services) -->
|
|
<div id="svc-creds-seedhost" style="display: none; margin-bottom: 14px;">
|
|
<label class="label-bold">Seedhost Login</label>
|
|
<p class="hint-micro">Username shared across all services. Password is per-service.</p>
|
|
<input type="text" id="svc-seedhost-user" placeholder="Username (shared)" autocomplete="username"
|
|
style="width: 100%; padding: 8px 10px; margin-bottom: 6px; background: var(--bg); color: var(--fg); border: 1px solid var(--border); border-radius: 6px; font-size: 0.85rem; box-sizing: border-box;" />
|
|
<input type="password" id="svc-seedhost-pass" placeholder="Password" autocomplete="current-password"
|
|
class="input-creds" />
|
|
</div>
|
|
|
|
<!-- API Key (shown for arr services or services with API key support) -->
|
|
<div id="svc-creds-apikey" style="display: none; margin-bottom: 14px;">
|
|
<label class="label-bold">API Key</label>
|
|
<p class="hint-micro">Bypasses the app's own login screen</p>
|
|
<input type="text" id="svc-apikey-input" placeholder="API key"
|
|
style="width: 100%; padding: 8px 10px; background: var(--bg); color: var(--fg); border: 1px solid var(--border); border-radius: 6px; font-size: 0.85rem; font-family: monospace; box-sizing: border-box;" />
|
|
</div>
|
|
|
|
<!-- Quality Profile (shown for radarr/sonarr only) -->
|
|
<div id="svc-creds-quality" style="display: none; margin-bottom: 14px;">
|
|
<label class="label-bold">Quality Profile</label>
|
|
<p class="hint-micro">Used when requesting via Seerr</p>
|
|
<div style="display: flex; gap: 8px; align-items: center;">
|
|
<select id="svc-quality-select"
|
|
style="flex: 1; padding: 8px 10px; background: var(--bg); color: var(--fg); border: 1px solid var(--border); border-radius: 6px; font-size: 0.85rem; box-sizing: border-box;">
|
|
<option value="">-- Enter API key first --</option>
|
|
</select>
|
|
<button id="svc-quality-fetch" type="button"
|
|
style="padding: 8px 12px; font-size: 0.75rem; cursor: pointer; white-space: nowrap;">
|
|
Fetch
|
|
</button>
|
|
</div>
|
|
<div id="svc-quality-status" style="font-size: 0.75rem; margin-top: 4px; min-height: 1em;"></div>
|
|
</div>
|
|
|
|
<!-- Per-service Basic Auth (shown for non-external services) -->
|
|
<div id="svc-creds-basic" style="display: none; margin-bottom: 14px;">
|
|
<label class="label-bold">Service Login</label>
|
|
<input type="text" id="svc-basic-user" placeholder="Username" autocomplete="username"
|
|
style="width: 100%; padding: 8px 10px; margin-top: 6px; margin-bottom: 6px; background: var(--bg); color: var(--fg); border: 1px solid var(--border); border-radius: 6px; font-size: 0.85rem; box-sizing: border-box;" />
|
|
<input type="password" id="svc-basic-pass" placeholder="Password" autocomplete="current-password"
|
|
class="input-creds" />
|
|
</div>
|
|
|
|
<!-- Error message -->
|
|
<div id="svc-creds-error" style="display: none; padding: 8px 10px; margin-bottom: 10px; background: color-mix(in srgb, var(--error, #c62828) 12%, transparent); border: 1px solid var(--error, #c62828); border-radius: 6px; font-size: 0.8rem; color: var(--error, #c62828);"></div>
|
|
|
|
<!-- Buttons -->
|
|
<div style="display: flex; gap: 8px; margin-top: 14px;">
|
|
<button id="svc-creds-save" class="btn-accent-solid" style="flex: 1; padding: 9px; border: none; border-radius: 6px; cursor: pointer; font-weight: 600; font-size: 0.85rem;">
|
|
Save
|
|
</button>
|
|
<button id="svc-creds-clear" style="padding: 9px 14px; background: transparent; color: var(--bad-fg, #ff9aa3); border: 1px solid var(--bad-fg, #ff9aa3); border-radius: 6px; cursor: pointer; font-size: 0.85rem; display: none;">
|
|
Clear
|
|
</button>
|
|
<button id="svc-creds-close" style="padding: 9px 16px; background: var(--card-base); color: var(--fg); border: 1px solid var(--border); border-radius: 6px; cursor: pointer; font-size: 0.85rem;">
|
|
Cancel
|
|
</button>
|
|
</div>
|
|
</div>
|
|
</div>`);const m=document.getElementById("service-creds-modal");let l=null;const w=["sonarr","radarr","prowlarr","overseerr"],v=["sonarr","radarr"];function r(s){return s.externalUrl||s.url||""}function h(s){const c=document.getElementById("svc-creds-error");c.textContent=s,c.style.display=""}function n(){const s=document.getElementById("svc-creds-error");s.textContent="",s.style.display="none"}window.openServiceCredsModal=async function(s){l=s,n();const c=document.getElementById("svc-creds-title"),g=document.getElementById("svc-creds-desc"),e=document.getElementById("svc-creds-seedhost"),a=document.getElementById("svc-creds-apikey"),u=document.getElementById("svc-creds-basic"),t=document.getElementById("svc-creds-quality");c.textContent=s.name+" Credentials";const d=!!s.isExternal,f=w.includes(s.id)||w.includes(s.appTemplate),i=v.includes(s.id)||v.includes(s.appTemplate);e.style.display=d?"":"none",a.style.display=f?"":"none",t.style.display=i?"":"none",u.style.display=d?"none":"";const k=document.getElementById("svc-quality-select");k.innerHTML='<option value="">-- Enter API key first --</option>',document.getElementById("svc-quality-status").textContent="",d?(g.textContent="Seedhost credentials auto-login past the HTTP prompt. API key bypasses the app login.",document.getElementById("svc-seedhost-pass").placeholder=`Password for ${s.name}`):f?g.textContent="API key bypasses the app login screen automatically.":g.textContent="Credentials are injected automatically when accessing this service.",await b(s),m.classList.add("show")};async function b(s){const c=document.getElementById("svc-creds-dot"),g=document.getElementById("svc-creds-status"),e=document.getElementById("svc-creds-clear");let a=!1;if(s.isExternal){try{const d=await(await fetch(`/api/v1/seedhost-creds?serviceId=${s.id}`)).json();d.success?(document.getElementById("svc-seedhost-user").value=d.username||"",d.hasCredentials&&(a=!0)):document.getElementById("svc-seedhost-user").value=""}catch{}document.getElementById("svc-seedhost-pass").value=""}try{const d=await(await fetch(`/api/v1/services/${s.id}/credentials`)).json();d.success&&(d.hasApiKey?(document.getElementById("svc-apikey-input").value="\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022",a=!0):document.getElementById("svc-apikey-input").value="",d.hasBasicAuth&&!s.isExternal?(document.getElementById("svc-basic-user").value=d.username||"",a=!0):document.getElementById("svc-basic-user").value="")}catch{}document.getElementById("svc-basic-pass")&&(document.getElementById("svc-basic-pass").value="");const u=s.id||s.appTemplate;if(v.includes(u)&&await p(s),a){c.style.background="var(--ok-fg, #74dfc4)",g.style.color="var(--ok-fg, #74dfc4)",g.textContent="Credentials stored",e.style.display="";const t=document.getElementById(`creds-btn-${s.id}`);t&&t.classList.add("has-creds")}else c.style.background="var(--muted)",g.style.color="var(--muted)",g.textContent="No credentials stored",e.style.display="none"}async function p(s){const c=document.getElementById("svc-quality-select"),g=document.getElementById("svc-quality-status"),e=s.id||s.appTemplate,a=r(s);if(!a){c.innerHTML='<option value="">-- No service URL --</option>';return}c.innerHTML='<option value="">Loading...</option>',g.textContent="";try{const u=new URLSearchParams({service:e,url:a}),d=await(await fetch(`/api/v1/arr/quality-profiles?${u}`)).json();if(!d.success||!d.profiles?.length){c.innerHTML='<option value="">-- No profiles found (enter API key and click Fetch) --</option>';return}c.innerHTML="";for(const f of d.profiles){const i=document.createElement("option");i.value=f.id,i.textContent=f.name,c.appendChild(i)}if(d.storedProfileId&&(c.value=String(d.storedProfileId)),!c.value){const f=d.profiles.find(i=>/720/i.test(i.name));f&&(c.value=String(f.id))}!c.value&&d.profiles.length&&(c.value=String(d.profiles[0].id)),g.innerHTML=`<span style="color: var(--ok-fg);">${d.profiles.length} profiles loaded</span>`}catch(u){c.innerHTML='<option value="">-- Failed to load --</option>',g.innerHTML=`<span style="color: var(--error, #c62828);">Error: ${u.message}</span>`}}document.getElementById("svc-quality-fetch")?.addEventListener("click",async()=>{if(!l)return;const s=l.id||l.appTemplate,c=r(l),e=document.getElementById("svc-apikey-input")?.value.trim(),a=document.getElementById("svc-quality-select"),u=document.getElementById("svc-quality-status");if(!c){u.innerHTML='<span style="color: var(--error, #c62828);">No service URL available</span>';return}if(!e||e==="\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022"){u.innerHTML='<span style="color: var(--error, #c62828);">Enter an API key first</span>';return}a.innerHTML='<option value="">Fetching...</option>',u.textContent="";try{const t=new URLSearchParams({service:s,url:c,apiKey:e}),f=await(await fetch(`/api/v1/arr/quality-profiles?${t}`)).json();if(!f.success){a.innerHTML='<option value="">-- Error --</option>',u.innerHTML=`<span style="color: var(--error, #c62828);">${f.error||"Failed to fetch profiles"}</span>`;return}if(!f.profiles?.length){a.innerHTML='<option value="">-- No profiles found --</option>';return}a.innerHTML="";for(const k of f.profiles){const B=document.createElement("option");B.value=k.id,B.textContent=k.name,a.appendChild(B)}const i=f.profiles.find(k=>/720/i.test(k.name));i?a.value=String(i.id):f.profiles.length&&(a.value=String(f.profiles[0].id)),u.innerHTML=`<span style="color: var(--ok-fg);">${f.profiles.length} profiles loaded</span>`}catch(t){a.innerHTML='<option value="">-- Error --</option>',u.innerHTML=`<span style="color: var(--error, #c62828);">${t.message}</span>`}}),document.getElementById("svc-creds-save")?.addEventListener("click",async()=>{if(!l)return;const s=document.getElementById("svc-creds-save");s.textContent="Saving...",s.disabled=!0,n();try{const c=w.includes(l.id)||w.includes(l.appTemplate),g=l.id||l.appTemplate;if(l.isExternal){const u=document.getElementById("svc-seedhost-user").value.trim(),t=document.getElementById("svc-seedhost-pass").value;u&&await secureFetch("/api/v1/seedhost-creds",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:u,password:t||void 0,serviceId:l.id})})}const a=document.getElementById("svc-apikey-input")?.value.trim();if(a&&a!=="\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022")if(c){const u=r(l),t=document.getElementById("svc-quality-select"),d=t?.value?parseInt(t.value):void 0,f=t?.selectedOptions?.[0]?.textContent||void 0,k=await(await secureFetch("/api/v1/arr/credentials",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({service:g,apiKey:a,url:u||void 0,qualityProfileId:d||void 0,qualityProfileName:f||void 0})})).json();if(!k.success){h(k.error||"Failed to save API key"),s.textContent="Save",s.disabled=!1;return}k.connectionTest&&!k.connectionTest.success&&h(`API key saved but connection test failed: ${k.connectionTest.error}`)}else await secureFetch(`/api/v1/services/${l.id}/credentials`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:a})});else if(c&&v.includes(g)){const u=document.getElementById("svc-quality-select"),t=u?.value?parseInt(u.value):void 0,d=u?.selectedOptions?.[0]?.textContent||void 0;t&&await secureFetch("/api/v1/arr/quality-profiles",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({service:g,qualityProfileId:t,qualityProfileName:d})})}if(!l.isExternal){const u=document.getElementById("svc-basic-user").value.trim(),t=document.getElementById("svc-basic-pass").value;u&&t&&await secureFetch(`/api/v1/services/${l.id}/credentials`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:u,password:t})})}await b(l)}catch(c){o.logError("[ServiceCredentials] Save",c,{function:"saveCredentials"}),h("Failed to save: "+(c.message||"Unknown error"))}s.textContent="Save",s.disabled=!1}),document.getElementById("svc-creds-clear")?.addEventListener("click",async()=>{if(l&&confirm(`Remove stored credentials for ${l.name}?`)){n();try{const s=l.id||l.appTemplate,c=w.includes(s);l.isExternal&&await secureFetch(`/api/v1/seedhost-creds?serviceId=${l.id}`,{method:"DELETE"}),await secureFetch(`/api/v1/services/${l.id}/credentials`,{method:"DELETE"}),c&&await secureFetch(`/api/v1/arr/credentials/${s}`,{method:"DELETE"});const g=document.getElementById(`creds-btn-${l.id}`);g&&g.classList.remove("has-creds"),await b(l)}catch(s){o.logError("[ServiceCredentials] Clear",s,{function:"clearCredentials"}),h("Failed to clear: "+(s.message||"Unknown error"))}}}),document.getElementById("svc-creds-close")?.addEventListener("click",()=>{m.classList.remove("show"),l=null}),m?.addEventListener("click",s=>{s.target===m&&(m.classList.remove("show"),l=null)}),window.refreshCredsButtons=async function(){try{for(const s of window.APPS||[]){if(!s.isExternal&&!s.appTemplate&&!s.url)continue;let c=!1;if(s.isExternal)try{const a=await(await fetch(`/api/v1/seedhost-creds?serviceId=${s.id}`)).json();a.success&&a.hasCredentials&&(c=!0)}catch{}try{const a=await(await fetch(`/api/v1/services/${s.id}/credentials`)).json();a.success&&(a.hasApiKey||a.hasBasicAuth)&&(c=!0)}catch{}const g=document.getElementById(`creds-btn-${s.id}`);g&&g.classList.toggle("has-creds",c)}}catch{}}})(),(function(){const o=new ErrorHandler;injectModal("totp-settings-modal",`<div id="totp-settings-modal" class="weather-modal">
|
|
<div class="weather-modal-content" style="min-width: 420px; max-width: 520px;">
|
|
<h3 style="margin: 0 0 16px; font-size: 1.1rem;">Authentication Settings</h3>
|
|
|
|
<!-- Status Banner -->
|
|
<div id="totp-status-banner" style="margin-bottom: 16px; padding: 12px 16px; border-radius: 8px; border: 1px solid var(--border); display: flex; align-items: center; gap: 8px;">
|
|
<span id="totp-status-dot" class="status-dot"></span>
|
|
<span id="totp-status-text" style="font-size: 0.9rem;">TOTP is not configured</span>
|
|
</div>
|
|
|
|
<!-- Setup Button (not configured state) -->
|
|
<div id="totp-setup-section">
|
|
<button id="totp-setup-btn" class="btn-accent-solid" style="width: 100%; padding: 12px; border: none; border-radius: 8px; cursor: pointer; font-weight: 600; font-size: 0.95rem;">
|
|
Generate New Secret
|
|
</button>
|
|
<div style="display: flex; align-items: center; gap: 8px; margin: 10px 0 0;">
|
|
<div class="divider-line"></div>
|
|
<span class="text-tiny-muted">or</span>
|
|
<div class="divider-line"></div>
|
|
</div>
|
|
<div style="margin-top: 10px;">
|
|
<label class="text-hint">Import an existing secret key:</label>
|
|
<div style="display: flex; gap: 8px; margin-top: 6px;">
|
|
<input type="text" id="totp-import-key" placeholder="Paste your Base32 key" autocomplete="off" spellcheck="false"
|
|
style="flex: 1; padding: 10px; background: var(--bg); color: var(--fg); border: 1px solid var(--border); border-radius: 6px; font-size: 0.9rem; font-family: monospace; letter-spacing: 1px; text-transform: uppercase;" />
|
|
<button id="totp-import-btn" style="padding: 10px 16px; background: var(--card-base); color: var(--fg); border: 1px solid var(--border); border-radius: 6px; cursor: pointer; font-weight: 600; font-size: 0.85rem; white-space: nowrap;">
|
|
Import
|
|
</button>
|
|
</div>
|
|
<div id="totp-import-error" style="color: var(--bad-fg, #ff9aa3); font-size: 0.8rem; min-height: 1.2em; margin-top: 6px;"></div>
|
|
</div>
|
|
</div>
|
|
|
|
<!-- Secret Display (setup flow) -->
|
|
<div id="totp-qr-section" style="display: none;">
|
|
<!-- Manual Key (primary - for WinAuth/desktop authenticators) -->
|
|
<p style="font-size: 0.85rem; color: var(--muted); margin: 0 0 8px;">Copy this key into your authenticator app:</p>
|
|
<div style="display: flex; align-items: center; gap: 8px; margin-bottom: 16px;">
|
|
<code id="totp-manual-key" style="flex: 1; display: block; padding: 12px; background: var(--bg, #0b0f1a); border: 1px solid var(--border); border-radius: 6px; font-size: 1rem; font-family: 'Sami Grotesk', monospace; letter-spacing: 2px; word-break: break-all; user-select: all; color: var(--fg);"></code>
|
|
<button id="totp-copy-key" style="padding: 10px 14px; background: var(--card-base); border: 1px solid var(--border); border-radius: 6px; cursor: pointer; font-size: 1rem; white-space: nowrap; color: var(--fg);" title="Copy to clipboard">\u{1F4CB}</button>
|
|
</div>
|
|
|
|
<!-- QR Code (secondary - for mobile apps) -->
|
|
<details class="mb-16">
|
|
<summary style="cursor: pointer; color: var(--muted); font-size: 0.8rem;">Show QR code (for mobile authenticator apps)</summary>
|
|
<div style="text-align: center; margin-top: 8px;">
|
|
<img id="totp-qr-image" style="width: 180px; height: 180px; border-radius: 8px;" />
|
|
</div>
|
|
</details>
|
|
|
|
<!-- Verify First Code -->
|
|
<div style="border-top: 1px solid var(--border); padding-top: 16px;">
|
|
<label class="font-bold-sm">Enter code to confirm setup:</label>
|
|
<div style="display: flex; gap: 8px; margin-top: 8px;">
|
|
<input type="text" id="totp-setup-code" maxlength="6" inputmode="numeric" pattern="[0-9]{6}" placeholder="000000"
|
|
style="flex: 1; text-align: center; font-size: 1.3rem; padding: 10px; font-family: 'Sami Grotesk', monospace; letter-spacing: 4px; background: var(--bg); color: var(--fg); border: 2px solid var(--border); border-radius: 8px; outline: none;" />
|
|
<button id="totp-confirm-setup" class="btn-accent-solid" style="padding: 10px 20px; border: none; border-radius: 8px; cursor: pointer; font-weight: 600;">
|
|
Confirm
|
|
</button>
|
|
</div>
|
|
<div id="totp-setup-error" style="color: var(--bad-fg, #ff9aa3); font-size: 0.8rem; min-height: 1.2em; margin-top: 6px;"></div>
|
|
</div>
|
|
</div>
|
|
|
|
<!-- Session Duration (active state) -->
|
|
<div id="totp-duration-section" style="display: none; margin-top: 12px;">
|
|
<label class="font-bold-sm">Session Duration:</label>
|
|
<select id="totp-duration-select" style="width: 100%; padding: 10px; margin-top: 6px; background: var(--bg, #0b0f1a); color: var(--fg); border: 1px solid var(--border); border-radius: 8px; font-size: 0.9rem; cursor: pointer;">
|
|
<option value="15m">15 minutes</option>
|
|
<option value="30m">30 minutes</option>
|
|
<option value="1h">1 hour</option>
|
|
<option value="2h">2 hours</option>
|
|
<option value="4h">4 hours</option>
|
|
<option value="8h">8 hours</option>
|
|
<option value="12h">12 hours</option>
|
|
<option value="24h">24 hours</option>
|
|
<option value="never">Never (disable TOTP)</option>
|
|
</select>
|
|
<p style="font-size: 0.75rem; color: var(--muted); margin: 4px 0 0;">How long before you need to re-enter your code</p>
|
|
</div>
|
|
|
|
<!-- Disable Button (active state) -->
|
|
<div id="totp-disable-section" style="display: none; margin-top: 16px; padding-top: 16px; border-top: 1px solid var(--border);">
|
|
<button id="totp-disable-btn" style="width: 100%; padding: 10px; background: transparent; color: var(--bad-fg, #ff9aa3); border: 1px solid var(--bad-fg, #ff9aa3); border-radius: 8px; cursor: pointer; font-size: 0.9rem;">
|
|
Disable TOTP
|
|
</button>
|
|
</div>
|
|
|
|
<!-- Close -->
|
|
<div style="margin-top: 16px; text-align: right;">
|
|
<button id="totp-modal-close" style="padding: 8px 20px; background: var(--card-base); color: var(--fg); border: 1px solid var(--border); border-radius: 8px; cursor: pointer;">
|
|
Close
|
|
</button>
|
|
</div>
|
|
</div>
|
|
</div>`);async function m(){try{const r=await(await fetch("/api/v1/totp/config")).json();if(!r.success)return;const{enabled:h,sessionDuration:n,isSetUp:b}=r.config,p=document.getElementById("totp-status-dot"),s=document.getElementById("totp-status-text"),c=document.getElementById("totp-status-banner"),g=document.getElementById("totp-setup-section"),e=document.getElementById("totp-qr-section"),a=document.getElementById("totp-duration-section"),u=document.getElementById("totp-disable-section");h&&b?(p.style.background="var(--ok-fg, #7ef2ff)",c.style.borderColor="var(--ok-fg, #7ef2ff)",c.style.background="color-mix(in srgb, var(--ok-fg) 8%, transparent)",s.textContent="TOTP is active",s.style.color="var(--ok-fg, #7ef2ff)",g.style.display="none",e.style.display="none",a.style.display="block",u.style.display="block",document.getElementById("totp-duration-select").value=n):(p.style.background="var(--muted)",c.style.borderColor="var(--border)",c.style.background="transparent",s.textContent="TOTP is not configured",s.style.color="var(--muted)",g.style.display="block",e.style.display="none",a.style.display="none",u.style.display="none"),w(h&&b,n)}catch(v){console.warn("Failed to load TOTP settings:",v)}}const l={"15m":"15 min","30m":"30 min","1h":"1 hour","2h":"2 hours","4h":"4 hours","8h":"8 hours","12h":"12 hours","24h":"24 hours",never:"Disabled"};function w(v,r){const h=document.getElementById("auth-card"),n=document.getElementById("auth-pill"),b=document.getElementById("auth-dot"),p=document.getElementById("auth-status-text");h&&(v?(h.setAttribute("data-status","on"),n.className="badge on",n.textContent="YES",b.className="dot ok at-bl",p.textContent="Session: "+(l[r]||r)):(h.setAttribute("data-status","off"),n.className="badge off",n.textContent="NO",b.className="dot bad at-bl",p.textContent="Not configured"))}document.getElementById("totp-setup-btn")?.addEventListener("click",async()=>{try{const r=await(await secureFetch("/api/v1/totp/setup",{method:"POST"})).json();r.success&&(document.getElementById("totp-qr-image").src=r.qrCode,document.getElementById("totp-manual-key").textContent=r.manualKey,document.getElementById("totp-setup-section").style.display="none",document.getElementById("totp-qr-section").style.display="block",document.getElementById("totp-setup-code").value="",document.getElementById("totp-setup-error").textContent="",document.getElementById("totp-setup-code").focus())}catch(v){o.logError("[TOTP] Setup Failed",v,{function:"setupTOTP"})}}),document.getElementById("totp-import-btn")?.addEventListener("click",async()=>{const v=document.getElementById("totp-import-key").value.trim(),r=document.getElementById("totp-import-error");if(r.textContent="",!v){r.textContent="Paste a Base32 secret key first";return}try{const n=await(await secureFetch("/api/v1/totp/setup",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({secret:v})})).json();n.success?(r.textContent="",document.getElementById("totp-qr-image").src=n.qrCode,document.getElementById("totp-manual-key").textContent=n.manualKey,document.getElementById("totp-setup-section").style.display="none",document.getElementById("totp-qr-section").style.display="block",document.getElementById("totp-setup-code").value="",document.getElementById("totp-setup-error").textContent="",document.getElementById("totp-setup-code").focus()):r.textContent=n.error||n.message||"Import failed"}catch{r.textContent="Connection error \u2014 try refreshing the page"}}),document.getElementById("totp-copy-key")?.addEventListener("click",()=>{const v=document.getElementById("totp-manual-key").textContent;navigator.clipboard.writeText(v).then(()=>{const r=document.getElementById("totp-copy-key");r.textContent="\u2705",setTimeout(()=>{r.textContent="\u{1F4CB}"},2e3)})}),document.getElementById("totp-confirm-setup")?.addEventListener("click",async()=>{const v=document.getElementById("totp-setup-code").value,r=document.getElementById("totp-setup-error");if(!/^\d{6}$/.test(v)){r.textContent="Enter a 6-digit code";return}try{const n=await(await secureFetch("/api/v1/totp/verify-setup",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:v})})).json();n.success?(r.textContent="",m()):r.textContent=n.error||"Invalid code"}catch{r.textContent="Connection error"}}),document.getElementById("totp-setup-code")?.addEventListener("keydown",v=>{v.key==="Enter"&&document.getElementById("totp-confirm-setup")?.click()}),document.getElementById("totp-duration-select")?.addEventListener("change",async v=>{try{await secureFetch("/api/v1/totp/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionDuration:v.target.value})}),m()}catch(r){o.logError("[TOTP] Update Session Duration",r,{function:"updateSessionDuration"})}}),document.getElementById("totp-disable-btn")?.addEventListener("click",async()=>{if(confirm("Disable TOTP authentication? All services will be accessible without a code."))try{(await(await secureFetch("/api/v1/totp/disable",{method:"POST",headers:{"Content-Type":"application/json"},body:"{}"})).json()).success&&m()}catch(v){o.logError("[TOTP] Disable Failed",v,{function:"disableTOTP"})}}),document.getElementById("auth-settings-btn")?.addEventListener("click",()=>{m(),openModal("totp-settings-modal")}),document.getElementById("totp-modal-close")?.addEventListener("click",()=>{closeModal("totp-settings-modal")}),document.getElementById("totp-settings-modal")?.addEventListener("click",v=>{v.target.id==="totp-settings-modal"&&closeModal("totp-settings-modal")}),window._updateAuthCard=w,(async()=>{try{const r=await(await fetch("/api/v1/totp/config")).json();if(r.success){const h=r.config.enabled&&r.config.isSetUp;w(h,r.config.sessionDuration)}}catch(v){o.logError("[TOTP] AuthCard Update",v,{function:"authCardUpdate"})}})()})(),(function(){injectModal("token-management-modal",`
|
|
<div id="token-management-modal" class="weather-modal">
|
|
<div class="weather-modal-content" style="min-width: 500px; max-width: 600px;">
|
|
<h3>\u{1F511} DNS Credentials</h3>
|
|
|
|
<p style="font-size: 0.85rem; color: var(--muted); margin: 0 0 16px;">
|
|
Enter Technitium DNS login credentials. Read-only accounts are used for logs; admin accounts for restarts, records, and updates.
|
|
</p>
|
|
|
|
<div id="dns-cred-sections"></div>
|
|
|
|
<div class="weather-modal-buttons modal-footer-bar">
|
|
<button id="token-clear-all" style="margin-right: auto; background: color-mix(in srgb, var(--bad-fg) 15%, transparent); border-color: var(--bad-fg); color: var(--bad-fg);">Clear All</button>
|
|
<button id="token-cancel">Cancel</button>
|
|
<button id="token-save" class="btn-accent">Save</button>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
`);function o(){return Object.keys(SITE.dnsServers||{})}function m(t){return(SITE.dnsServers||{})[t]?.name||t.toUpperCase()}function l(){const t=document.getElementById("dns-cred-sections");if(!t)return;t.innerHTML="";const d=o();if(d.length===0){t.innerHTML='<p style="color: var(--muted); text-align: center; padding: 20px;">No DNS servers configured.</p>';return}for(const f of d)t.insertAdjacentHTML("beforeend",`
|
|
<div class="token-section">
|
|
<h4 class="token-section-title">${m(f)}</h4>
|
|
<div class="token-grid">
|
|
<div class="token-field">
|
|
<label for="${f}-readonly-username">\u{1F4D6} Read-Only (Logs):</label>
|
|
<input type="text" id="${f}-readonly-username" placeholder="Username" autocomplete="off" style="margin-bottom: 4px;" />
|
|
<div class="token-input-row">
|
|
<input type="password" id="${f}-readonly-token" placeholder="Password" autocomplete="off" />
|
|
<button type="button" class="token-toggle" data-target="${f}-readonly-token">\u{1F441}</button>
|
|
</div>
|
|
</div>
|
|
<div class="token-field">
|
|
<label for="${f}-admin-username">\u{1F527} Admin:</label>
|
|
<input type="text" id="${f}-admin-username" placeholder="Username" autocomplete="off" style="margin-bottom: 4px;" />
|
|
<div class="token-input-row">
|
|
<input type="password" id="${f}-admin-token" placeholder="Password" autocomplete="off" />
|
|
<button type="button" class="token-toggle" data-target="${f}-admin-token">\u{1F441}</button>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
<div class="token-status" id="${f}-token-status"></div>
|
|
</div>
|
|
`)}function w(){let t=safeSessionGet("dashcaddy-encryption-key");if(t)return t;const d=safeGet("dashcaddy-encryption-key");if(d)return safeSessionSet("dashcaddy-encryption-key",d),safeRemove("dashcaddy-encryption-key"),d;const f=new Uint8Array(32);return crypto.getRandomValues(f),t=Array.from(f,i=>i.toString(16).padStart(2,"0")).join(""),safeSessionSet("dashcaddy-encryption-key",t),t}const v=w();function r(t,d){if(!t)return"";const f=crypto.getRandomValues(new Uint8Array(8)),i=Array.from(f,T=>T.toString(16).padStart(2,"0")).join(""),k=new TextEncoder().encode(d+i);let B="";for(let T=0;T<t.length;T++){const A=t.charCodeAt(T)^k[T%k.length]^f[T%f.length]^T*31+17&255;B+=String.fromCharCode(A)}return i+":"+btoa(B)}function h(t,d){if(!t)return"";try{if(t.indexOf(":")===16){const B=t.substring(0,16),T=new Uint8Array(B.match(/.{2}/g).map($=>parseInt($,16))),A=atob(t.substring(17)),E=new TextEncoder().encode(d+B);let L="";for(let $=0;$<A.length;$++){const x=A.charCodeAt($)^E[$%E.length]^T[$%T.length]^$*31+17&255;L+=String.fromCharCode(x)}return L}const i=atob(t);let k="";for(let B=0;B<i.length;B++){const T=i.charCodeAt(B)^d.charCodeAt(B%d.length);k+=String.fromCharCode(T)}return k}catch{return""}}function n(t,d,f){const i=safeGet(`${t}-${d}-${f}-enc`);return h(i,v)}function b(t,d,f,i){const k=`${t}-${d}-${f}-enc`;i?safeSet(k,r(i,v)):safeRemove(k)}function p(t,d){return n(t,d,"token")}function s(t,d){return n(t,d,"username")}function c(t,d,f){b(t,d,"token",f)}function g(t,d,f){b(t,d,"username",f)}function e(){const t={};for(const d of o())t[d]={readonly:{username:s(d,"readonly"),token:p(d,"readonly")},admin:{username:s(d,"admin"),token:p(d,"admin")}};return t}function a(){o().forEach(t=>{["readonly","admin"].forEach(d=>{["token","username"].forEach(f=>{safeRemove(`${t}-${d}-${f}-enc`)})}),safeRemove(`${t}-token-enc`),safeRemove(`${t}-username-enc`)})}function u(t){const d=p(t,"readonly"),f=s(t,"readonly"),i=p(t,"admin"),k=s(t,"admin"),B=h(safeGet(`${t}-token-enc`),v),T=h(safeGet(`${t}-username-enc`),v);return{username:k||f||T,token:i||d||B,readonlyToken:d||B,readonlyUsername:f||T,adminToken:i||B,adminUsername:k||T}}document.getElementById("manage-tokens")?.addEventListener("click",()=>{l();const t=document.getElementById("token-management-modal"),d=e();o().forEach(f=>{const i=d[f];document.getElementById(`${f}-readonly-username`).value=i.readonly.username,document.getElementById(`${f}-readonly-token`).value=i.readonly.token,document.getElementById(`${f}-admin-username`).value=i.admin.username,document.getElementById(`${f}-admin-token`).value=i.admin.token,document.getElementById(`${f}-token-status`).textContent=""}),t.classList.add("show")}),document.getElementById("token-management-modal")?.addEventListener("click",t=>{const d=t.target.closest(".token-toggle");if(d){const f=d.dataset.target,i=document.getElementById(f);i.type==="password"?(i.type="text",d.textContent="\u{1F648}"):(i.type="password",d.textContent="\u{1F441}");return}t.target.id==="token-management-modal"&&t.target.classList.remove("show")}),document.getElementById("token-save")?.addEventListener("click",async()=>{const t=o();t.forEach(i=>{g(i,"readonly",document.getElementById(`${i}-readonly-username`).value.trim()),c(i,"readonly",document.getElementById(`${i}-readonly-token`).value.trim()),g(i,"admin",document.getElementById(`${i}-admin-username`).value.trim()),c(i,"admin",document.getElementById(`${i}-admin-token`).value.trim())});const d={};let f=!1;if(t.forEach(i=>{const k={},B=document.getElementById(`${i}-readonly-username`).value.trim(),T=document.getElementById(`${i}-readonly-token`).value.trim(),A=document.getElementById(`${i}-admin-username`).value.trim(),E=document.getElementById(`${i}-admin-token`).value.trim();B&&T&&(k.readonly={username:B,password:T},f=!0),A&&E&&(k.admin={username:A,password:E},f=!0),Object.keys(k).length>0&&(d[i]=k)}),f){t.forEach(i=>{d[i]&&(document.getElementById(`${i}-token-status`).textContent="Verifying...",document.getElementById(`${i}-token-status`).className="token-status")});try{const k=await(await secureFetch("/api/v1/dns/credentials",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({servers:d})})).json();k.results?t.forEach(B=>{const T=document.getElementById(`${B}-token-status`);if(!d[B]){T.textContent="";return}const A=k.results[B];A?.success?(T.textContent="\u2713 Verified & saved",T.className="token-status success"):A?.partial?(T.textContent="\u2713 "+A.partial,T.className="token-status success"):(T.textContent="\u2717 "+(A?.error||"Login failed"),T.className="token-status error")}):k.success?t.forEach(B=>{d[B]&&(document.getElementById(`${B}-token-status`).textContent="\u2713 Saved",document.getElementById(`${B}-token-status`).className="token-status success")}):t.forEach(B=>{d[B]&&(document.getElementById(`${B}-token-status`).textContent="\u2717 "+(k.error||"Failed"),document.getElementById(`${B}-token-status`).className="token-status error")})}catch(i){console.error("Failed to sync DNS credentials to backend:",i),t.forEach(k=>{d[k]&&(document.getElementById(`${k}-token-status`).textContent="\u2713 Saved locally (sync failed)",document.getElementById(`${k}-token-status`).className="token-status")})}}else t.forEach(i=>{document.getElementById(`${i}-token-status`).textContent=""});setTimeout(()=>{t.every(k=>{const B=document.getElementById(`${k}-token-status`)?.textContent;return!B||B.includes("\u2713")})&&closeModal("token-management-modal")},1500)}),document.getElementById("token-cancel")?.addEventListener("click",()=>{closeModal("token-management-modal")}),document.getElementById("token-clear-all")?.addEventListener("click",async()=>{if(confirm("Clear all stored DNS credentials? This cannot be undone.")){a(),o().forEach(t=>{document.getElementById(`${t}-readonly-username`).value="",document.getElementById(`${t}-readonly-token`).value="",document.getElementById(`${t}-admin-username`).value="",document.getElementById(`${t}-admin-token`).value="",document.getElementById(`${t}-token-status`).textContent="\u2713 Cleared",document.getElementById(`${t}-token-status`).className="token-status success"});try{await secureFetch("/api/v1/dns/credentials",{method:"DELETE"})}catch{}}}),window.getToken=p,window.getUsername=s,window.setToken=c,window.setUsername=g,window.getAllCredentials=e,window.getCredential=n,window.setCredential=b,window.getEncryptionKey=w,window.getDnsIds=o,window.getDnsDisplayName=m})(),(function(){function o(c,g,e=null){const a=document.getElementById(c+"-dot"),u=document.getElementById(c+"-pill"),t=document.getElementById(c+"-time"),d=document.querySelector(`[data-app="${c}"]`);a&&(a.classList.toggle("ok",g),a.classList.toggle("bad",!g)),u&&(u.textContent=g?"ON":"OFF",u.classList.toggle("on",g),u.classList.toggle("off",!g)),t&&e!==null&&(t.textContent=g?`${e}ms`:"timeout",t.className=`response-time ${m(e,g)}`),d&&d.setAttribute("data-status",g?"on":"off")}function m(c,g){return g?c<200?"excellent":c<500?"good":c<1e3?"fair":"slow":"timeout"}async function l(c){const g=performance.now();try{const e=await fetch("/probe/"+c,{cache:"no-store"}),a=performance.now(),u=Math.round(a-g);return{isUp:e.status>=200&&e.status<400||e.status===401||e.status===403,responseTime:u}}catch{const e=performance.now();return{isUp:!1,responseTime:Math.round(e-g)}}}window.APPS=[];let w=null,v=!1;async function r(){try{window.SkeletonLoader&&window.SkeletonLoader.show(6);const c=await fetch("/api/v1/services",{cache:"no-store"});c.ok?(window.APPS=await c.json(),window.SkeletonLoader&&window.SkeletonLoader.hide()):(console.error("Failed to load services:",c.status),window.SkeletonLoader&&window.SkeletonLoader.hide())}catch(c){console.error("Failed to load services:",c),window.SkeletonLoader&&window.SkeletonLoader.hide()}}function h(c){const g=window.APPS?.find(a=>a.id===c);if(g?.url)return g.url.startsWith("http")?g.url:"https://"+g.url;if(g?.isExternal&&g.externalUrl)return g.externalUrl;const e=SITE.dnsServers?.[c];return e?"http://"+e.ip+":"+(e.port||5380):buildServiceUrl(c)}function n(c,g,e){const a=document.createElement(c);return g&&(a.className=g),e&&(a.textContent=e),a}function b(){const c=document.getElementById("cards");c.innerHTML="";for(let g=0;g<window.APPS.length;g++){const e=window.APPS[g];if(e.id==="ca")continue;const a=n("div","card");a.setAttribute("data-app",e.id),a.setAttribute("data-status","off"),e.recipeId&&a.setAttribute("data-recipe-id",e.recipeId);const u=n("span","dot bad at-bl");u.id="dot-"+e.id+"-grid",a.appendChild(u);const t=n("div","row"),d=n("div","logo-wrap"),f=document.createElement("img");f.src=e.logo,f.alt=e.name,f.className="logo-img",f.onerror=function(){let S=e.id||e.appTemplate;if(!S&&e.name&&(S=e.name.toLowerCase().replace(/\s+/g,"-")),S){const C=[`https://cdn.jsdelivr.net/gh/walkxcode/dashboard-icons/png/${S}.png`,`https://cdn.jsdelivr.net/gh/walkxcode/dashboard-icons/png/${S.toLowerCase()}.png`,`https://cdn.jsdelivr.net/gh/walkxcode/dashboard-icons/png/${S.replace(/-/g,"")}.png`,`https://cdn.jsdelivr.net/gh/walkxcode/dashboard-icons/png/${e.name.toLowerCase().replace(/\s+/g,"-")}.png`],P=[...new Set(C)],O=P.indexOf(this.src)+1;O<P.length?this.src=P[O]:this.style.display="none"}else this.style.display="none"},d.appendChild(f),t.appendChild(d);const i=n("span","name",e.name);if(t.appendChild(i),e.tailscaleOnly){const S=n("span","ts-badge","\u{1F510}");S.title="Tailscale-only access",S.style.cssText="margin-left: 6px; font-size: 0.75rem; opacity: 0.8;",i.appendChild(S)}t.appendChild(n("span","spacer"));const k=n("span","badge off","OFF");k.id="badge-"+e.id,t.appendChild(k);const B=n("span","update-available-badge","UPDATE");B.id="update-badge-"+e.id,B.title="Update available",t.appendChild(B),a.appendChild(t);const T=n("div","response-row"),A=n("span","response-time","--");A.id="time-"+e.id,T.appendChild(A),a.appendChild(T);const E=n("div","health-row");E.id="health-"+e.id;const L=n("span","uptime-chip","--");L.id="uptime-"+e.id,E.appendChild(L);const $=document.createElement("div");$.className="uptime-mini-bar";const x=document.createElement("div");x.className="fill",x.id="uptime-bar-"+e.id,x.style.width="0%",$.appendChild(x),E.appendChild($),a.appendChild(E);const y=n("div","btn-row");if(e.containerId){const S=n("button","logs-btn","\u{1F4CB}");S.title="View container logs",S.onclick=D=>{D.stopPropagation(),window.openContainerLogsModal(e.containerId,e.name)},y.appendChild(S);const C=n("button","update-btn","\u2B06\uFE0F");C.title="Update container to latest version",C.id=`update-btn-${e.id}`,C.onclick=D=>{D.stopPropagation(),window.updateContainer(e.containerId,e.name,e.id)},y.appendChild(C);const P=n("button","exec-btn",">_");P.title="Open terminal",P.onclick=D=>{D.stopPropagation(),window.openExecModal&&window.openExecModal(e.containerId,e.name)},y.appendChild(P)}if(e.logPath&&!e.containerId){const S=n("button","logs-btn","\u{1F4CB}");S.title="View application logs",S.onclick=C=>{C.stopPropagation(),window.openFileLogsModal(e.logPath,e.name)},y.appendChild(S)}if(e.isExternal||e.appTemplate||e.url){const S=n("button","creds-btn","\u{1F511}");S.title="Auto-login credentials",S.id=`creds-btn-${e.id}`,S.onclick=C=>{C.stopPropagation(),window.openServiceCredsModal(e)},y.appendChild(S)}if(e.id!=="internet"){const S=n("button","options-btn","\u2699\uFE0F");S.title="Edit service settings",S.onclick=C=>{C.stopPropagation(),window.openServiceEditModal(e)},y.appendChild(S)}if(e.id!=="internet"){const S=n("button","delete-btn","\u{1F5D1}\uFE0F");S.title="Delete this service",S.onclick=C=>{C.stopPropagation(),window.deleteService(e.id,e.name)},y.appendChild(S)}const I=n("button",null,"Open");I.onclick=()=>window.open(h(e.id),"_blank","noopener"),y.appendChild(I),a.appendChild(y),a.style.transitionDelay=`${Math.min(g*45,270)}ms`,c.appendChild(a)}requestAnimationFrame(()=>{c.querySelectorAll(".card").forEach(g=>g.classList.add("loaded"))}),window.groupRecipeCards&&requestAnimationFrame(()=>window.groupRecipeCards())}function p(c,g,e=null){const a=document.getElementById("dot-"+c+"-grid"),u=document.getElementById("badge-"+c),t=document.getElementById("time-"+c),d=document.querySelector(`[data-app="${c}"]`);a&&(a.classList.toggle("ok",g),a.classList.toggle("bad",!g)),u&&(u.textContent=g?"ON":"OFF",u.classList.toggle("on",g),u.classList.toggle("off",!g)),t&&e!==null&&(t.textContent=g?`${e}ms`:"timeout",t.className=`response-time ${m(e,g)}`),d&&d.setAttribute("data-status",g?"on":"off")}async function s(){if(w)return v=!0,w;function c(a,u=new Date){const t=document.getElementById("stamp");t&&(t.textContent=`${a}: ${new Date(u).toLocaleTimeString()}`)}function g(a){Object.keys(SITE.dnsServers).forEach(t=>{const d=a[t];d&&o(t,d.isUp,d.responseTime)}),a.internet&&o("internet",a.internet.isUp,a.internet.responseTime),window.APPS.forEach(t=>{const d=a[t.id];d&&p(t.id,d.isUp,d.responseTime)})}async function e(){const a=Object.keys(SITE.dnsServers),u=a.map(i=>l(i));u.push(l("internet"));const t=await Promise.all(u);a.forEach((i,k)=>o(i,t[k].isUp,t[k].responseTime));const d=t[t.length-1];o("internet",d.isUp,d.responseTime),(await Promise.all(window.APPS.map(async i=>{const k=await l(i.id);return{id:i.id,...k}}))).forEach(i=>{p(i.id,i.isUp,i.responseTime)})}return w=(async()=>{try{const a=await fetch("/api/v1/services/status",{cache:"no-store"});if(!a.ok)throw new Error(`Status refresh failed (${a.status})`);const u=await a.json();g(u.statuses||{}),c("last check",u.checkedAt||new Date)}catch(a){console.warn("Batched status refresh failed, falling back to direct probes:",a);try{await e(),c("last check")}catch(u){console.error("Dashboard refresh failed:",u),c("last failed")}}finally{w=null,v&&(v=!1,setTimeout(()=>{window.refreshAll()},0))}})(),w}document.querySelector(".top")?.addEventListener("click",c=>{const g=c.target.closest('[id$="-open"]');if(!g)return;const e=g.id.replace("-open","");SITE.dnsServers[e]&&window.open(h(e),"_blank","noopener")}),document.getElementById("ca-open")?.addEventListener("click",()=>window.open(h("ca"),"_blank","noopener")),document.getElementById("creds-btn-ca")?.addEventListener("click",c=>{c.stopPropagation();const g=window.APPS.find(e=>e.id==="ca");g&&window.openServiceCredsModal&&window.openServiceCredsModal(g)}),document.getElementById("options-btn-ca")?.addEventListener("click",c=>{c.stopPropagation();const g=window.APPS.find(e=>e.id==="ca");g&&window.openServiceEditModal&&window.openServiceEditModal(g)}),document.getElementById("delete-btn-ca")?.addEventListener("click",c=>{c.stopPropagation(),window.deleteService&&window.deleteService("ca","DashCA")}),window.loadServices=r,window.buildGrid=b,window.refreshAll=s,window.setQuick=o,window.setBadge=p,window.getResponseTimeClass=m,window.checkServiceWithTiming=l,window.serviceUrl=h,window.el=n})(),(function(){async function o(n){const p=await(await secureFetch(`/api/v1/dns/restart/${n}`,{method:"POST"})).json();if(!p.success)throw new Error(p.error||"Restart failed");return p}document.querySelector(".top")?.addEventListener("click",async n=>{const b=n.target.closest('[id$="-restart"]');if(!b)return;const p=b.id.replace("-restart","");if(SITE.dnsServers[p]&&confirm(`Restart ${p.toUpperCase()} service?`))try{await withButton(b,"...",()=>o(p)),setTimeout(window.refreshAll,DC.DELAYS.RELOAD)}catch(s){showNotification("Restart failed: "+s.message,"error")}});async function m(n,b){const p=document.getElementById(`${n}-update`),s=p?.textContent||"\u2B06\uFE0F";try{p.textContent="\u{1F50D}",p.disabled=!0,p.title="Checking for updates...";const g=await(await fetch(`/api/v1/dns/check-update?server=${encodeURIComponent(b)}`)).json();if(!g.success)throw new Error(g.error||"Failed to check for updates");if(!g.updateAvailable){p.textContent="\u2705",p.title=`Already on latest version (${g.currentVersion})`,showNotification(`${n.toUpperCase()} is already up to date! Current version: ${g.currentVersion}`,"info"),setTimeout(()=>{p.textContent=s,p.disabled=!1,p.title="Update DNS server"},3e3);return}if(!confirm(`Update available for ${n.toUpperCase()}!
|
|
|
|
Current: ${g.currentVersion}
|
|
New: ${g.updateVersion}
|
|
|
|
`+(g.updateTitle?`${g.updateTitle}
|
|
|
|
`:"")+`The DNS server will restart during the update.
|
|
Proceed?`)){p.textContent=s,p.disabled=!1,p.title="Update DNS server";return}p.textContent="\u{1F504}",p.title="Updating...";const u=await(await secureFetch(`/api/v1/dns/update?server=${encodeURIComponent(b)}`,{method:"POST"})).json();if(!u.success)throw new Error(u.error||"Update failed");if(u.manualUpdateRequired){p.textContent="\u2B06\uFE0F",p.title=`Update available: ${u.newVersion}`;const t=u.downloadLink?`
|
|
Download: ${u.downloadLink}`:"",d=u.instructionsLink?`
|
|
Instructions: ${u.instructionsLink}`:"";showNotification(`${n.toUpperCase()} update requires manual installation. Current: ${u.previousVersion} \u2192 ${u.newVersion}. Please update manually on the host machine.`,"warning",8e3),p.disabled=!1;return}p.textContent="\u2705",p.title="Updated successfully!",showNotification(`${n.toUpperCase()} updated successfully! ${u.previousVersion} \u2192 ${u.newVersion}. Server is restarting...`,"success"),setTimeout(()=>{p.textContent=s,p.disabled=!1,p.title="Update DNS server",window.refreshAll()},1e4)}catch(c){console.error("DNS update error:",c),p.textContent="\u274C",p.title="Update failed",showNotification(`Failed to update ${n.toUpperCase()}: ${c.message}`,"error"),setTimeout(()=>{p.textContent=s,p.disabled=!1,p.title="Update DNS server"},3e3)}}document.querySelector(".top")?.addEventListener("click",n=>{const b=n.target.closest('[id$="-update"]');if(!b)return;const p=b.id.replace("-update","");SITE.dnsServers[p]&&m(p,SITE.dnsServers[p]?.ip)}),injectModal("dns-settings-modal",`
|
|
<div id="dns-settings-modal" class="weather-modal">
|
|
<div class="weather-modal-content" style="min-width: 420px; max-width: 520px;">
|
|
<h3 id="dns-settings-title">DNS Settings</h3>
|
|
|
|
<div style="display: grid; gap: 16px; margin-top: 16px;">
|
|
<div>
|
|
<label for="dns-edit-ip" class="form-label-accent-sm">Server IP</label>
|
|
<input type="text" id="dns-edit-ip" class="form-input-md" placeholder="192.168.1.1" />
|
|
</div>
|
|
<div>
|
|
<label for="dns-edit-port" class="form-label-accent-sm">Port</label>
|
|
<input type="number" id="dns-edit-port" class="form-input-md" placeholder="5380" />
|
|
</div>
|
|
<div>
|
|
<label for="dns-edit-name" class="form-label-accent-sm">Display Name (optional)</label>
|
|
<input type="text" id="dns-edit-name" class="form-input-md" placeholder="e.g. Primary DNS" />
|
|
</div>
|
|
<div class="form-hint-sm">Manage credentials via Tokens in the toolbar</div>
|
|
</div>
|
|
|
|
<div class="weather-modal-buttons" style="margin-top: 24px;">
|
|
<button id="dns-settings-cancel">Cancel</button>
|
|
<button id="dns-settings-delete" style="background: color-mix(in srgb, #e74c3c 20%, transparent); border-color: #e74c3c; color: #e74c3c;">Remove</button>
|
|
<button id="dns-settings-save" class="btn-accent">Save</button>
|
|
</div>
|
|
</div>
|
|
</div>`);let l=null;function w(n){l=n;const b=SITE.dnsServers[n]||{},p=document.getElementById("dns-settings-modal");document.getElementById("dns-settings-title").textContent=`${(b.name||n).toUpperCase()} Settings`,document.getElementById("dns-edit-ip").value=b.ip||"",document.getElementById("dns-edit-port").value=b.port||DC.DEFAULTS.DNS_PORT,document.getElementById("dns-edit-name").value=b.name||"",p.classList.add("show")}async function v(){if(!l)return;const n=document.getElementById("dns-edit-ip").value.trim(),b=document.getElementById("dns-edit-port").value.trim()||DC.DEFAULTS.DNS_PORT,p=document.getElementById("dns-edit-name").value.trim();if(!n){showNotification("Server IP is required","warning");return}const s={dnsServers:{}};s.dnsServers[l]={ip:n,port:String(b)},p&&(s.dnsServers[l].name=p);try{const g=await(await secureFetch("/api/v1/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)})).json();g.success?(SITE.dnsServers[l]=s.dnsServers[l],showNotification(`${l.toUpperCase()} settings saved`,"success"),h(),window.refreshAll()):showNotification(g.error||"Failed to save settings","error")}catch(c){showNotification("Failed to save: "+c.message,"error")}}async function r(){if(l&&confirm(`Remove ${l.toUpperCase()} from dashboard? This won't affect the actual DNS server.`))try{const b=await(await secureFetch("/api/v1/config")).json();b.dnsServers&&delete b.dnsServers[l];const s=await(await secureFetch("/api/v1/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({dnsServers:b.dnsServers||{}})})).json();if(s.success){delete SITE.dnsServers[l];const c=document.querySelector(`.top [data-app="${l}"]`);c&&c.remove(),showNotification(`${l.toUpperCase()} removed from dashboard`,"success"),h()}else showNotification(s.error||"Failed to remove","error")}catch(n){showNotification("Failed to remove: "+n.message,"error")}}function h(){closeModal("dns-settings-modal"),l=null}document.getElementById("dns-settings-cancel")?.addEventListener("click",h),document.getElementById("dns-settings-save")?.addEventListener("click",v),document.getElementById("dns-settings-delete")?.addEventListener("click",r),document.getElementById("dns-settings-modal")?.addEventListener("click",n=>{n.target.id==="dns-settings-modal"&&h()}),document.querySelector(".top")?.addEventListener("click",n=>{const b=n.target.closest('[id$="-settings"]');if(!b)return;const p=b.id.replace("-settings","");SITE.dnsServers[p]&&(n.stopPropagation(),w(p))}),document.getElementById("refresh")?.addEventListener("click",window.refreshAll)})(),(function(){injectModal("logs-modal",`
|
|
<div id="logs-modal" class="logs-modal">
|
|
<div class="logs-modal-content" style="min-width: 800px; max-width: 1000px;">
|
|
<div class="logs-header">
|
|
<h3 id="logs-title">DNS Logs</h3>
|
|
<div class="logs-controls">
|
|
<label for="log-lines">Show:</label>
|
|
<select id="log-lines">
|
|
<option value="25" selected>25</option>
|
|
<option value="50">50</option>
|
|
<option value="100">100</option>
|
|
<option value="200">200</option>
|
|
</select>
|
|
<button id="logs-stream" class="stream-btn" title="Enable real-time streaming">\u{1F4E1} Live</button>
|
|
<button id="logs-pause" class="pause-btn">\u23F8\uFE0F Pause</button>
|
|
<button id="logs-close" class="close-btn">\u2715</button>
|
|
</div>
|
|
</div>
|
|
<div class="logs-container scroll-container">
|
|
<div id="logs-content" class="logs-content">
|
|
<div class="logs-loading">Loading logs...</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>`);let o=null,m=null,l=!1,w=null,v=null,r=!1,h=null,n=null,b=!1,p=null,s=!1;async function c(x,y=25){try{const I=getDnsServerAddr(x),S=await fetch(`/api/v1/dns/logs?server=${I}&limit=${y}`,{cache:"no-store",headers:{Accept:"application/json","Cache-Control":"no-cache"}});if(S.ok){const C=await S.json();return C.success&&C.logs?{logs:C.logs,count:C.count,server:C.server}:{error:C.error||"Failed to fetch logs"}}else return S.status===401?{error:"DNS auto-auth failed - check credentials in settings"}:{error:`HTTP ${S.status}`}}catch(I){return console.error("DNS logs fetch failed:",I),{error:I.message}}}function g(x){return{NoError:"var(--ok-fg)",NOERROR:"var(--ok-fg)",NxDomain:"var(--muted)",NXDOMAIN:"var(--muted)",Refused:"var(--bad-fg)",REFUSED:"var(--bad-fg)",ServerFailure:"#f39c12",SERVFAIL:"#f39c12"}[x]||"var(--fg)"}function e(x){const y=document.createElement("div");if(y.className="log-entry",y.style.cssText="display: grid; grid-template-columns: 140px 110px 1fr 70px 80px; gap: 8px; padding: 6px 10px; border-bottom: 1px solid var(--border); font-size: 0.8rem; align-items: center;",x.parsed===!1)return y.style.gridTemplateColumns="1fr",y.innerHTML=`<span style="color: var(--muted); font-family: monospace; font-size: 0.75rem;">${escapeHtml(x.raw)}</span>`,y;const I=g(x.rcode),S=x.rcode==="Refused"||x.rcode==="REFUSED";return y.innerHTML=`
|
|
<span style="color: var(--muted); font-size: 0.75rem;">${escapeHtml(x.timestamp)}</span>
|
|
<span style="color: var(--accent); font-size: 0.75rem;" title="${escapeHtml(x.client)}">${escapeHtml(x.client)}</span>
|
|
<span style="font-weight: 500; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; ${S?"text-decoration: line-through; opacity: 0.6;":""}" title="${escapeHtml(x.domain)}">${escapeHtml(x.domain)}</span>
|
|
<span style="color: var(--muted); font-size: 0.75rem;">${escapeHtml(x.type)}</span>
|
|
<span style="color: ${I}; font-weight: 500; font-size: 0.75rem;">${escapeHtml(x.rcode)}</span>
|
|
`,y}async function a(){if(b){await L();return}if(r){await B();return}if(l||!o)return;const x=parseInt(document.getElementById("log-lines").value),y=document.getElementById("logs-content");try{const I=await c(o,x);if(I.error){y.innerHTML=`
|
|
<div style="padding: 20px; text-align: center; color: var(--bad-fg);">
|
|
<div style="font-size: 1.2rem; margin-bottom: 8px;">\u26A0\uFE0F Error</div>
|
|
<div>${escapeHtml(I.error)}</div>
|
|
</div>`;return}y.innerHTML=`
|
|
<div style="display: grid; grid-template-columns: 140px 110px 1fr 70px 80px; gap: 8px; padding: 8px 10px; background: var(--card-base); border-bottom: 2px solid var(--border); font-size: 0.75rem; font-weight: 600; color: var(--muted); position: sticky; top: 0;">
|
|
<span>Time</span>
|
|
<span>Client</span>
|
|
<span>Domain</span>
|
|
<span>Type</span>
|
|
<span>Status</span>
|
|
</div>`,I.logs&&I.logs.length>0?I.logs.forEach(S=>{const C=e(S);y.appendChild(C)}):y.innerHTML+=`
|
|
<div style="padding: 20px; text-align: center; color: var(--muted);">
|
|
No DNS queries logged yet
|
|
</div>`}catch(I){y.innerHTML=`
|
|
<div style="padding: 20px; text-align: center; color: var(--bad-fg);">
|
|
Failed to fetch logs: ${escapeHtml(I.message)}
|
|
</div>`}}function u(x){o=x,l=!1,r=!1;const y=document.getElementById("logs-modal"),I=document.getElementById("logs-title"),S=document.getElementById("logs-pause"),C=document.getElementById("logs-stream");I.textContent=`${x.toUpperCase()} DNS Logs`,S.textContent="\u23F8\uFE0F Pause",S.classList.remove("paused"),C&&(C.style.display="none"),y.classList.add("show"),a(),m=setInterval(a,DC.POLL.LOGS)}function t(){document.getElementById("logs-modal").classList.remove("show"),m&&(clearInterval(m),m=null),f(),o=null,r=!1,w=null,v=null,b=!1,h=null,n=null,l=!1}function d(x){p&&f();const y=document.getElementById("logs-stream"),I=document.getElementById("logs-pause"),S=document.getElementById("logs-content");m&&(clearInterval(m),m=null);try{p=new EventSource(`/api/v1/logs/stream/${x}`),s=!0,y.classList.add("active"),y.textContent="\u{1F534} Live",y.title="Streaming - click to stop",I.style.display="none";const C=document.getElementById("logs-title");C.textContent.includes("\u{1F534}")||(C.innerHTML=C.textContent.replace("\u{1F4CB}","\u{1F4CB} \u{1F534}")),p.onmessage=P=>{try{const D=JSON.parse(P.data);if(D.error){console.error("Stream error:",D.error),f();return}const O=document.createElement("div");O.className="log-entry",O.style.cssText="display: flex; gap: 12px; padding: 6px 10px; border-bottom: 1px solid var(--border); font-size: 0.8rem; align-items: flex-start; font-family: monospace;";const R=(D.stream||"stdout")==="stderr",U=R?"var(--bad-fg)":"var(--fg)",M=`<span style="background: ${R?"var(--bad-bg)":"var(--ok-bg)"}; color: ${U}; padding: 2px 6px; border-radius: 4px; font-size: 0.7rem; font-weight: 600; min-width: 50px; text-align: center;">${R?"STDERR":"STDOUT"}</span>`;for(O.innerHTML=`
|
|
<div style="flex-shrink: 0;">${M}</div>
|
|
<div style="flex: 1; color: ${U}; word-break: break-all; white-space: pre-wrap;">${escapeHtml(D.text)}</div>
|
|
`,S.appendChild(O),S.scrollTop=S.scrollHeight;S.children.length>500;)S.removeChild(S.firstChild)}catch(D){console.error("Error parsing stream data:",D)}},p.onerror=P=>{console.error("EventSource error:",P),f()}}catch(C){console.error("Failed to start streaming:",C),f()}}function f(){p&&(p.close(),p=null),s=!1;const x=document.getElementById("logs-stream"),y=document.getElementById("logs-pause"),I=document.getElementById("logs-title");x&&(x.classList.remove("active"),x.textContent="\u{1F4E1} Live",x.title="Enable real-time streaming"),y&&(y.style.display=""),I&&(I.textContent=I.textContent.replace(" \u{1F534}","")),r&&w&&!m&&(m=setInterval(B,DC.POLL.LOGS))}async function i(x,y=100){try{const I=`/api/v1/logs/container/${x}?tail=${y}×tamps=true`,S=await fetch(I,{cache:"no-store",headers:{Accept:"application/json","Cache-Control":"no-cache"}});if(S.ok){const C=await S.json();return C.success&&C.logs?{logs:C.logs,count:C.count,containerName:C.containerName,containerId:C.containerId}:{error:C.error||"Failed to fetch container logs"}}else return{error:`HTTP ${S.status}: ${S.statusText}`}}catch(I){return console.error("Container logs fetch failed:",I),{error:I.message}}}function k(x){const y=document.createElement("div");y.className="log-entry",y.style.cssText="display: flex; gap: 12px; padding: 6px 10px; border-bottom: 1px solid var(--border); font-size: 0.8rem; align-items: flex-start; font-family: monospace;";const I=x.stream==="stderr"?"var(--bad-fg)":"var(--fg)",S=x.stream==="stderr"?'<span style="background: var(--bad-bg); color: var(--bad-fg); padding: 2px 6px; border-radius: 4px; font-size: 0.7rem; font-weight: 600;">STDERR</span>':'<span style="background: var(--ok-bg); color: var(--ok-fg); padding: 2px 6px; border-radius: 4px; font-size: 0.7rem; font-weight: 600;">STDOUT</span>';return y.innerHTML=`
|
|
<div style="flex-shrink: 0;">${S}</div>
|
|
<div style="flex: 1; color: ${I}; word-break: break-all; white-space: pre-wrap;">${escapeHtml(x.text)}</div>
|
|
`,y}async function B(){if(l||!w||!r)return;const x=parseInt(document.getElementById("log-lines").value),y=document.getElementById("logs-content");try{const I=await i(w,x);if(I.error){y.innerHTML=`
|
|
<div style="padding: 20px; text-align: center; color: var(--bad-fg);">
|
|
<div style="font-size: 1.2rem; margin-bottom: 8px;">\u26A0\uFE0F Error</div>
|
|
<div>${escapeHtml(I.error)}</div>
|
|
</div>`;return}y.innerHTML=`
|
|
<div style="display: flex; gap: 12px; padding: 8px 10px; background: var(--card-base); border-bottom: 2px solid var(--border); font-size: 0.75rem; font-weight: 600; color: var(--muted); position: sticky; top: 0;">
|
|
<span style="flex-shrink: 0; width: 80px;">Stream</span>
|
|
<span style="flex: 1;">Log Output</span>
|
|
</div>`,I.logs&&I.logs.length>0?(I.logs.forEach(S=>{const C=k(S);y.appendChild(C)}),y.scrollTop=y.scrollHeight):y.innerHTML+=`
|
|
<div style="padding: 20px; text-align: center; color: var(--muted);">
|
|
No logs available for this container
|
|
</div>`}catch(I){y.innerHTML=`
|
|
<div style="padding: 20px; text-align: center; color: var(--bad-fg);">
|
|
Failed to fetch logs: ${escapeHtml(I.message)}
|
|
</div>`}}function T(x,y){w=x,v=y,r=!0,b=!1,l=!1,f();const I=document.getElementById("logs-modal"),S=document.getElementById("logs-title"),C=document.getElementById("logs-pause"),P=document.getElementById("logs-stream");S.textContent=`\u{1F4CB} ${y} - Container Logs`,C.textContent="\u23F8\uFE0F Pause",C.classList.remove("paused"),P&&(P.style.display=""),I.classList.add("show"),B(),m=setInterval(B,DC.POLL.LOGS)}async function A(x,y=100){try{const I=`/api/v1/logs/file?path=${encodeURIComponent(x)}&tail=${y}`,S=await fetch(I,{cache:"no-store",headers:{Accept:"application/json","Cache-Control":"no-cache"}});if(S.ok){const C=await S.json();return C.success&&C.logs?{logs:C.logs,count:C.count,logPath:C.logPath,totalLines:C.totalLines}:{error:C.error||"Failed to fetch file logs"}}else return{error:(await S.json().catch(()=>({}))).error||`HTTP ${S.status}`}}catch(I){return console.error("File logs fetch failed:",I),{error:I.message}}}function E(x){const y=document.createElement("div");y.className="log-entry",y.style.cssText="display: flex; gap: 12px; padding: 6px 10px; border-bottom: 1px solid var(--border); font-size: 0.8rem; align-items: flex-start; font-family: monospace;";const I=x.text;let S="INFO",C="var(--fg)";I.match(/ERROR|FATAL|CRITICAL/i)?(S="ERROR",C="var(--bad-fg)"):I.match(/WARN|WARNING/i)?(S="WARN",C="#f39c12"):I.match(/DEBUG/i)&&(S="DEBUG",C="var(--muted)");const D=`<span style="background: ${C==="var(--bad-fg)"?"var(--bad-bg)":"var(--ok-bg)"}; color: ${C}; padding: 2px 6px; border-radius: 4px; font-size: 0.7rem; font-weight: 600; min-width: 50px; text-align: center;">${S}</span>`;return y.innerHTML=`
|
|
<div style="flex-shrink: 0;">${D}</div>
|
|
<div style="flex: 1; color: ${C}; word-break: break-all; white-space: pre-wrap;">${escapeHtml(I)}</div>
|
|
`,y}async function L(){if(l||!h||!b)return;const x=parseInt(document.getElementById("log-lines").value),y=document.getElementById("logs-content");try{const I=await A(h,x);if(I.error){y.innerHTML=`
|
|
<div style="padding: 20px; text-align: center; color: var(--bad-fg);">
|
|
<div style="font-size: 1.2rem; margin-bottom: 8px;">\u26A0\uFE0F Error</div>
|
|
<div>${escapeHtml(I.error)}</div>
|
|
</div>`;return}y.innerHTML=`
|
|
<div style="display: flex; gap: 12px; padding: 8px 10px; background: var(--card-base); border-bottom: 2px solid var(--border); font-size: 0.75rem; font-weight: 600; color: var(--muted); position: sticky; top: 0;">
|
|
<span style="flex: 1;">Log Output (${I.count} of ${I.totalLines} lines)</span>
|
|
</div>`,I.logs&&I.logs.length>0?(I.logs.forEach(S=>{const C=E(S);y.appendChild(C)}),y.scrollTop=y.scrollHeight):y.innerHTML+=`
|
|
<div style="padding: 20px; text-align: center; color: var(--muted);">
|
|
No logs available in this file
|
|
</div>`}catch(I){y.innerHTML=`
|
|
<div style="padding: 20px; text-align: center; color: var(--bad-fg);">
|
|
Failed to fetch logs: ${escapeHtml(I.message)}
|
|
</div>`}}function $(x,y){h=x,n=y,b=!0,r=!1,l=!1;const I=document.getElementById("logs-modal"),S=document.getElementById("logs-title"),C=document.getElementById("logs-pause"),P=document.getElementById("logs-stream");S.textContent=`\u{1F4CB} ${y} - Application Logs`,C.textContent="\u23F8\uFE0F Pause",C.classList.remove("paused"),P&&(P.style.display="none"),I.classList.add("show"),L(),m=setInterval(L,DC.POLL.LOGS)}document.querySelector(".top")?.addEventListener("click",x=>{const y=x.target.closest('[id$="-logs"]');if(!y)return;const I=y.id.replace("-logs","");SITE.dnsServers[I]&&u(I)}),document.getElementById("logs-close")?.addEventListener("click",t),document.getElementById("logs-pause")?.addEventListener("click",()=>{l=!l;const x=document.getElementById("logs-pause");l?(x.textContent="\u25B6\uFE0F Resume",x.classList.add("paused")):(x.textContent="\u23F8\uFE0F Pause",x.classList.remove("paused"),a())}),document.getElementById("log-lines")?.addEventListener("change",()=>{l||a()}),document.getElementById("logs-stream")?.addEventListener("click",()=>{!r||!w||(s?f():d(w))}),document.getElementById("logs-modal")?.addEventListener("click",x=>{x.target.id==="logs-modal"&&t()}),document.addEventListener("keydown",x=>{x.key==="Escape"&&document.getElementById("logs-modal")?.classList.contains("show")&&t()}),window.openContainerLogsModal=T,window.openFileLogsModal=$,window.openLogsModal=u})(),(function(){injectModal("service-edit-modal",`
|
|
<div id="service-edit-modal" class="weather-modal">
|
|
<div class="weather-modal-content" style="min-width: 500px; max-width: 600px;">
|
|
<h3 id="service-edit-title">Edit Service</h3>
|
|
|
|
<div style="display: grid; gap: 16px; margin-top: 16px;">
|
|
<!-- Service Info -->
|
|
<div style="display: flex; align-items: center; gap: 12px; padding: 12px; background: var(--card-bg); border-radius: 8px;">
|
|
<img id="edit-service-logo-preview" src="" alt="" style="width: 48px; height: 48px; border-radius: 8px; object-fit: contain; background: var(--bg);" />
|
|
<div style="flex: 1;">
|
|
<div id="edit-service-url-display" class="text-muted-sm"></div>
|
|
</div>
|
|
</div>
|
|
|
|
<!-- Display Name -->
|
|
<div>
|
|
<label for="edit-service-name" class="form-label-accent-sm">
|
|
Display Name
|
|
</label>
|
|
<input type="text" id="edit-service-name" class="form-input-md" placeholder="Service name shown on dashboard" />
|
|
</div>
|
|
|
|
<!-- Subdomain -->
|
|
<div>
|
|
<label for="edit-subdomain" class="form-label-accent-sm">
|
|
Subdomain
|
|
</label>
|
|
<div class="flex-row-gap-center">
|
|
<input type="text" id="edit-subdomain" class="input-flex" />
|
|
<span id="edit-tld-suffix" style="color: var(--muted);">.home</span>
|
|
</div>
|
|
</div>
|
|
|
|
<!-- Port -->
|
|
<div>
|
|
<label for="edit-port" class="form-label-accent-sm">
|
|
Port
|
|
</label>
|
|
<input type="number" id="edit-port" class="form-input-md" />
|
|
<div class="form-hint-sm">
|
|
The port Caddy will proxy to (container's exposed port)
|
|
</div>
|
|
</div>
|
|
|
|
<!-- IP Address -->
|
|
<div>
|
|
<label for="edit-ip" class="form-label-accent-sm">
|
|
IP Address
|
|
</label>
|
|
<input type="text" id="edit-ip" class="form-input-md" />
|
|
</div>
|
|
|
|
<!-- Tailscale Protection -->
|
|
<div>
|
|
<label style="display: flex; align-items: center; gap: 10px; padding: 12px; background: var(--card-bg); border: 1px solid var(--border); border-radius: 6px; cursor: pointer;">
|
|
<input type="checkbox" id="edit-tailscale-only" style="width: 18px; height: 18px;" />
|
|
<div>
|
|
<div class="fw-500">Tailscale-Only Access</div>
|
|
<div class="text-hint">Restrict this service to Tailscale users only</div>
|
|
</div>
|
|
</label>
|
|
</div>
|
|
|
|
<!-- Logo -->
|
|
<div>
|
|
<label class="form-label-accent-sm">
|
|
Service Logo
|
|
</label>
|
|
<div class="flex-row-gap-center">
|
|
<input type="text" id="edit-logo-url" placeholder="/assets/service.png or https://..." class="input-flex" />
|
|
<label style="padding: 10px 16px; background: var(--card-bg); border: 1px solid var(--border); border-radius: 6px; cursor: pointer; white-space: nowrap;">
|
|
<input type="file" id="edit-logo-file" accept="image/*" style="display: none;" />
|
|
Upload
|
|
</label>
|
|
</div>
|
|
<div class="form-hint-sm">
|
|
Enter a URL or upload an image file (PNG, JPG, SVG)
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<div class="weather-modal-buttons" style="margin-top: 24px;">
|
|
<button id="service-edit-cancel">Cancel</button>
|
|
<button id="service-edit-save" class="btn-accent">
|
|
Save Changes
|
|
</button>
|
|
</div>
|
|
</div>
|
|
</div>`),injectModal("delete-service-modal",`
|
|
<div id="delete-service-modal" class="weather-modal">
|
|
<div class="weather-modal-content" style="min-width: 400px; max-width: 500px;">
|
|
<h3 id="delete-modal-title" class="mb-16">Delete Service</h3>
|
|
|
|
<div id="delete-modal-message" style="margin-bottom: 20px; line-height: 1.5;">
|
|
<!-- Dynamic content -->
|
|
</div>
|
|
|
|
<div id="delete-modal-container-info" style="display: none; margin-bottom: 20px; padding: 12px; background: var(--card-bg); border-radius: 8px; border: 1px solid var(--border);">
|
|
<div style="font-weight: 500; margin-bottom: 8px;">Docker Container</div>
|
|
<div id="delete-modal-container-name" style="font-size: 0.9rem; color: var(--muted);"></div>
|
|
</div>
|
|
|
|
<div class="weather-modal-buttons" style="display: flex; gap: 8px; justify-content: flex-end;">
|
|
<button id="delete-modal-cancel" style="padding: 10px 20px;">Cancel</button>
|
|
<button id="delete-modal-remove" style="padding: 10px 20px; background: color-mix(in srgb, var(--accent) 20%, transparent); border-color: var(--accent); color: var(--accent);">
|
|
Remove
|
|
</button>
|
|
<button id="delete-modal-delete" style="display: none; padding: 10px 20px; background: color-mix(in srgb, #e74c3c 20%, transparent); border-color: #e74c3c; color: #e74c3c;">
|
|
Delete
|
|
</button>
|
|
</div>
|
|
|
|
<div id="delete-modal-help" style="display: none; margin-top: 16px; padding: 12px; background: color-mix(in srgb, var(--muted) 10%, transparent); border-radius: 8px; font-size: 0.85rem; color: var(--muted);">
|
|
<div><strong>Remove:</strong> Remove from dashboard only (container keeps running)</div>
|
|
<div style="margin-top: 6px;"><strong>Delete:</strong> Full removal - stops container, removes DNS & Caddy config</div>
|
|
</div>
|
|
</div>
|
|
</div>`),injectModal("add-service-modal",`
|
|
<div id="add-service-modal" class="weather-modal">
|
|
<div class="weather-modal-content" style="min-width: 420px; max-width: 520px;">
|
|
<h3>Add Service</h3>
|
|
|
|
<!-- Service Type Tabs -->
|
|
<div style="display: flex; gap: 2px; margin-bottom: 16px; background: var(--card-bg); border-radius: 8px; padding: 3px; border: 1px solid var(--border);">
|
|
<label id="tab-local" style="flex: 1; text-align: center; padding: 8px; border-radius: 6px; cursor: pointer; font-size: 0.85rem; font-weight: 500; background: var(--accent); color: var(--bg); transition: all 0.15s;">
|
|
<input type="radio" name="service-type" value="local" id="service-type-local" checked style="display: none;" />
|
|
Local
|
|
</label>
|
|
<label id="tab-external" style="flex: 1; text-align: center; padding: 8px; border-radius: 6px; cursor: pointer; font-size: 0.85rem; font-weight: 500; color: var(--muted); transition: all 0.15s;">
|
|
<input type="radio" name="service-type" value="external" id="service-type-external" style="display: none;" />
|
|
External
|
|
</label>
|
|
</div>
|
|
<span id="service-type-description" style="display: none;"></span>
|
|
|
|
<!-- LOCAL SERVICE -->
|
|
<div id="local-service-config" style="display: grid; gap: 12px;">
|
|
<div>
|
|
<label for="service-name-input" style="font-size: 0.8rem; color: var(--muted); margin-bottom: 4px; display: block;">Name</label>
|
|
<input type="text" id="service-name-input" placeholder="e.g., Jellyfin" style="font-size: 1rem;" />
|
|
<div id="subdomain-preview" style="font-size: 0.75rem; color: var(--accent); margin-top: 4px; min-height: 1em;"></div>
|
|
</div>
|
|
|
|
<div class="grid-2col">
|
|
<div>
|
|
<label for="service-port-input" style="font-size: 0.8rem; color: var(--muted); margin-bottom: 4px; display: block;">Port</label>
|
|
<input type="number" id="service-port-input" placeholder="e.g., 8096" style="font-size: 1rem;" />
|
|
</div>
|
|
<div>
|
|
<label for="service-ip-input" style="font-size: 0.8rem; color: var(--muted); margin-bottom: 4px; display: block;">IP Address</label>
|
|
<input type="text" id="service-ip-input" placeholder="Auto-detected" style="font-size: 1rem;" />
|
|
<div class="quick-ip-buttons" style="display: flex; gap: 4px; margin-top: 4px; flex-wrap: wrap;">
|
|
<button type="button" class="quick-ip-btn" data-ip="127.0.0.1" title="Localhost" style="font-size: 0.7rem; padding: 2px 6px;">localhost</button>
|
|
<button type="button" class="quick-ip-btn" data-ip="" id="quick-ip-lan" title="LAN IP" style="font-size: 0.7rem; padding: 2px 6px;">LAN</button>
|
|
<button type="button" class="quick-ip-btn" data-ip="" id="quick-ip-tailscale" title="Tailscale IP" style="font-size: 0.7rem; padding: 2px 6px;">Tailscale</button>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<!-- Options (collapsed by default) -->
|
|
<details id="local-advanced-options">
|
|
<summary style="cursor: pointer; color: var(--accent); font-size: 0.8rem; user-select: none;">Options</summary>
|
|
<div style="margin-top: 10px; display: grid; gap: 10px; font-size: 0.8rem;">
|
|
|
|
<div class="grid-2col">
|
|
<div>
|
|
<label for="service-subdomain-input">Subdomain:</label>
|
|
<input type="text" id="service-subdomain-input" placeholder="auto-derived from name" />
|
|
</div>
|
|
<div>
|
|
<label for="service-logo-input">Logo URL:</label>
|
|
<input type="text" id="service-logo-input" placeholder="/assets/name.png" />
|
|
</div>
|
|
</div>
|
|
|
|
<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 8px; align-items: start;">
|
|
<label style="display: flex; align-items: center; gap: 6px; cursor: pointer;">
|
|
<input type="checkbox" id="create-dns-record" checked />
|
|
Create DNS Record
|
|
</label>
|
|
<div>
|
|
<label for="ssl-type-select">SSL:</label>
|
|
<select id="ssl-type-select" style="width: 100%;">
|
|
<option value="caddy-managed">Caddy Managed (Internal)</option>
|
|
<option value="letsencrypt">Let's Encrypt</option>
|
|
<option value="existing-ca">Existing CA</option>
|
|
<option value="custom-ca">Custom CA</option>
|
|
</select>
|
|
</div>
|
|
</div>
|
|
|
|
<div id="dns-config">
|
|
<div class="grid-2col">
|
|
<div>
|
|
<label for="dns-ttl-input">DNS TTL:</label>
|
|
<input type="number" id="dns-ttl-input" value="300" />
|
|
</div>
|
|
<div>
|
|
<label for="caddyfile-path-input">Caddyfile Path:</label>
|
|
<input type="text" id="caddyfile-path-input" value="C:\\caddy\\Caddyfile" />
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<div id="existing-ca-config" style="display: none;">
|
|
<label for="existing-ca-select">Existing CA:</label>
|
|
<div class="flex-row-gap">
|
|
<select id="existing-ca-select" style="flex: 1;">
|
|
<option value="">Loading CAs...</option>
|
|
</select>
|
|
<button type="button" id="refresh-cas" style="padding: 4px 8px; font-size: 0.75rem;">\u{1F504}</button>
|
|
</div>
|
|
</div>
|
|
|
|
<div id="custom-ca-config" style="display: none;">
|
|
<label for="ca-name-input">CA Name:</label>
|
|
<input type="text" id="ca-name-input" placeholder="e.g., sami-ca" />
|
|
</div>
|
|
|
|
<div id="manual-tailscale-status" style="padding: 6px 10px; background: var(--card-bg); border-radius: 6px; font-size: 0.75rem;">
|
|
<span style="color: var(--muted);">Checking Tailscale...</span>
|
|
</div>
|
|
<label style="display: flex; align-items: center; gap: 8px; cursor: pointer;">
|
|
<input type="checkbox" id="manual-tailscale-only" />
|
|
Tailscale-Only Access
|
|
</label>
|
|
|
|
<label style="display: flex; align-items: center; gap: 6px; cursor: pointer;">
|
|
<input type="checkbox" id="reload-caddy" checked />
|
|
Reload Caddy after adding
|
|
</label>
|
|
|
|
<hr style="border: none; border-top: 1px solid var(--border); margin: 4px 0;" />
|
|
|
|
<div class="grid-2col">
|
|
<div>
|
|
<label class="field-label-sm">
|
|
<input type="checkbox" id="enable-auth" />
|
|
Authentication
|
|
</label>
|
|
<label class="field-label-sm">
|
|
<input type="checkbox" id="enable-cors" />
|
|
CORS Headers
|
|
</label>
|
|
<label for="upstream-path-input">Upstream Path:</label>
|
|
<input type="text" id="upstream-path-input" value="/" />
|
|
</div>
|
|
<div>
|
|
<label for="health-check-input">Health Check:</label>
|
|
<input type="text" id="health-check-input" placeholder="/health" />
|
|
<label for="timeout-input">Timeout (s):</label>
|
|
<input type="number" id="timeout-input" value="30" />
|
|
<label for="custom-headers-input">Headers (JSON):</label>
|
|
<textarea id="custom-headers-input" placeholder='{"X-Custom": "value"}' rows="2" style="font-size: 0.7rem;"></textarea>
|
|
</div>
|
|
</div>
|
|
|
|
</div>
|
|
</details>
|
|
</div>
|
|
|
|
<!-- EXTERNAL SERVICE -->
|
|
<div id="external-service-config" style="display: none;">
|
|
<div style="display: grid; gap: 12px;">
|
|
<div>
|
|
<label for="external-service-name" style="font-size: 0.8rem; color: var(--muted); margin-bottom: 4px; display: block;">Name</label>
|
|
<input type="text" id="external-service-name" placeholder="e.g., Radarr (Seedhost)" style="font-size: 1rem;" />
|
|
<div id="external-subdomain-preview" style="font-size: 0.75rem; color: var(--accent); margin-top: 4px; min-height: 1em;"></div>
|
|
</div>
|
|
|
|
<div>
|
|
<label for="external-service-url" style="font-size: 0.8rem; color: var(--muted); margin-bottom: 4px; display: block;">External URL</label>
|
|
<input type="url" id="external-service-url" placeholder="https://username.seedhost.eu/radarr" style="font-size: 1rem;" />
|
|
</div>
|
|
|
|
<!-- Options (collapsed by default) -->
|
|
<details id="external-advanced-options">
|
|
<summary style="cursor: pointer; color: var(--accent); font-size: 0.8rem; user-select: none;">Options</summary>
|
|
<div style="margin-top: 10px; display: grid; gap: 10px; font-size: 0.8rem;">
|
|
|
|
<div class="grid-2col">
|
|
<div>
|
|
<label for="external-service-subdomain">Subdomain:</label>
|
|
<input type="text" id="external-service-subdomain" placeholder="auto-derived from name" />
|
|
<span id="external-domain-preview" style="font-size: 0.7rem; color: var(--accent);"></span>
|
|
</div>
|
|
<div>
|
|
<label for="external-service-logo">Logo URL:</label>
|
|
<input type="text" id="external-service-logo" placeholder="/assets/name.png" />
|
|
</div>
|
|
</div>
|
|
|
|
<div>
|
|
<label for="external-service-icon">Icon Emoji:</label>
|
|
<input type="text" id="external-service-icon" placeholder="\u{1F3AC}" maxlength="2" style="width: 60px;" />
|
|
</div>
|
|
|
|
<label style="display: flex; align-items: center; gap: 6px; cursor: pointer;">
|
|
<input type="checkbox" id="external-create-dns" checked />
|
|
Create DNS Record
|
|
</label>
|
|
<label style="display: flex; align-items: center; gap: 6px; cursor: pointer;">
|
|
<input type="checkbox" id="external-create-caddy" checked />
|
|
Create Caddy Reverse Proxy
|
|
</label>
|
|
|
|
<div>
|
|
<label for="external-proxy-ip">Proxy Server IP:</label>
|
|
<input type="text" id="external-proxy-ip" placeholder="Auto-detected" />
|
|
</div>
|
|
<label style="display: flex; align-items: center; gap: 6px; cursor: pointer;">
|
|
<input type="checkbox" id="external-preserve-host" checked />
|
|
Preserve Host Header
|
|
</label>
|
|
<label style="display: flex; align-items: center; gap: 6px; cursor: pointer;">
|
|
<input type="checkbox" id="external-follow-redirects" checked />
|
|
Follow Redirects
|
|
</label>
|
|
|
|
</div>
|
|
</details>
|
|
</div>
|
|
</div>
|
|
|
|
<div class="weather-modal-buttons" style="margin-top: 16px; display: flex; gap: 8px; justify-content: flex-end;">
|
|
<button id="add-service-cancel">Cancel</button>
|
|
<button id="add-service-create" class="btn-accent">Create Service</button>
|
|
</div>
|
|
</div>
|
|
</div>`)})(),(function(){async function o(r){try{const h=await fetch(`/api/v1/caddy/cas?caddyfilePath=${encodeURIComponent(r)}`);if(!h.ok)throw new Error(`Failed to load CAs: ${h.status}`);const n=await h.json();if(n.status==="success"){const b=document.getElementById("existing-ca-select");return b.innerHTML="",n.data.cas.length===0?b.innerHTML='<option value="">No CAs found in Caddyfile</option>':(b.innerHTML='<option value="">Select existing CA...</option>',n.data.cas.forEach(p=>{const s=document.createElement("option");typeof p=="object"?(s.value=p.id,s.textContent=p.displayName||p.name):(s.value=p,s.textContent=p),b.appendChild(s)})),n.data.cas}else throw new Error(n.message)}catch(h){console.error("Error loading CAs:",h);const n=document.getElementById("existing-ca-select");return n.innerHTML='<option value="">Error loading CAs</option>',[]}}function m(r){const{subdomain:h,port:n,ip:b,sslType:p,caName:s,existingCa:c,enableAuth:g,enableCors:e,customHeaders:a,upstreamPath:u,healthCheck:t,timeout:d,tailscaleOnly:f}=r;let i=`${buildDomain(h)} {
|
|
`;switch(f&&(i+=` @blocked not remote_ip 100.64.0.0/10
|
|
`,i+=` respond @blocked "Access denied. Tailscale connection required." 403
|
|
`),p){case"letsencrypt":break;case"caddy-managed":i+=` tls internal
|
|
`;break;case"existing-ca":c&&(i+=` tls {
|
|
ca ${c}
|
|
}
|
|
`);break;case"custom-ca":s&&(i+=` tls {
|
|
ca ${s}
|
|
}
|
|
`);break}if(g&&(i+=` basicauth {
|
|
admin $2a$14$hashed_password_here
|
|
}
|
|
`),e&&(i+=` header {
|
|
`,i+=` Access-Control-Allow-Origin "*"
|
|
`,i+=` Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS"
|
|
`,i+=` Access-Control-Allow-Headers "Content-Type, Authorization"
|
|
`,i+=` }
|
|
`),a)try{const k=JSON.parse(a);i+=` header {
|
|
`,Object.entries(k).forEach(([B,T])=>{i+=` ${B} "${T}"
|
|
`}),i+=` }
|
|
`}catch{console.warn("Invalid JSON in custom headers")}return t&&(i+=` health_uri ${t}
|
|
`),i+=` reverse_proxy ${b}:${n} {
|
|
`,u&&u!=="/"&&(i+=` rewrite ${u}
|
|
`),d&&d!==30&&(i+=` transport http {
|
|
`,i+=` dial_timeout ${d}s
|
|
`,i+=` response_header_timeout ${d}s
|
|
`,i+=` }
|
|
`),i+=` }
|
|
`,i+=`}
|
|
`,i}async function l(r,h,n=DC.DEFAULTS.TTL){const b=window.getToken(getPrimaryDnsId(),"admin");if(!b)throw new Error("DNS admin token not configured. Please set it in the Tokens menu.");const p=buildDomain(r),s=await secureFetch("/api/v1/dns/record",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:p,ip:h,ttl:n,token:b,server:SITE.dnsIp})});if(!s.ok){const g=await s.text();throw new Error(`DNS API Error: ${s.status} - ${g}`)}const c=await s.json();if(!c.success)throw new Error(`DNS Error: ${c.error||"Unknown error"}`);return c}async function w(r){const h={id:r.subdomain,name:r.name,logo:r.logo||`/assets/${r.subdomain}.png`};try{const n=await secureFetch("/api/v1/services",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(h)});if(!n.ok){const b=await n.json();throw new Error(b.error||"Failed to save service")}return await window.loadServices(),window.buildGrid(),h}catch(n){throw console.error("Failed to add service to config:",n),n}}async function v(r){const h=document.getElementById("service-subdomain-input").value.trim(),n=document.getElementById("service-ip-input").value.trim()||"localhost",b=document.getElementById("service-port-input").value.trim()||"80",p=await secureFetch("/api/v1/site",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:buildDomain(h),upstream:`${n}:${b}`,config:r})}),s=await p.json();if(!p.ok||!s.success)throw new Error(s.error||`Caddy API Error: ${p.status}`);return s}window.loadExistingCAs=o,window.generateCaddyConfig=m,window.createDnsRecord=l,window.addServiceToConfig=w,window.addToCaddyfile=v})(),(function(){let o=null;function m(n){o=n;const b=document.getElementById("service-edit-modal");document.getElementById("service-edit-title").textContent=`Edit ${n.name}`,document.getElementById("edit-service-name").value=n.name,document.getElementById("edit-service-url-display").textContent=n.url||buildServiceUrl(n.id),document.getElementById("edit-service-logo-preview").src=n.logo||`/assets/${n.id}.png`,document.getElementById("edit-subdomain").value=n.id,document.getElementById("edit-port").value=n.port||"",document.getElementById("edit-ip").value=n.ip||"localhost",document.getElementById("edit-tailscale-only").checked=n.tailscaleOnly||!1,document.getElementById("edit-logo-url").value=n.logo||"",b.classList.add("show")}function l(){closeModal("service-edit-modal"),o=null}async function w(){if(!o)return;const n=document.getElementById("edit-subdomain").value.trim().toLowerCase(),b=document.getElementById("edit-service-name").value.trim(),p=document.getElementById("edit-port").value.trim(),s=document.getElementById("edit-ip").value.trim()||"localhost",c=document.getElementById("edit-tailscale-only").checked,g=document.getElementById("edit-logo-url").value.trim();if(!n){showNotification("Subdomain is required","warning");return}const e=o.id,a=[];if(n!==e&&a.push("subdomain"),b&&b!==o.name&&a.push("name"),p&&p!==String(o.port)&&a.push("port"),s!==o.ip&&a.push("ip"),c!==(o.tailscaleOnly||!1)&&a.push("tailscale"),g&&g!==o.logo&&a.push("logo"),a.length===0){l();return}const u=document.getElementById("service-edit-save");u.textContent="Saving...",u.disabled=!0;try{const d=await(await secureFetch("/api/v1/services/update",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({oldSubdomain:e,newSubdomain:n,name:b||o.name,port:p||o.port,ip:s,tailscaleOnly:c,logo:g||void 0})})).json();if(!d.success)throw new Error(d.error||"Failed to update service");const f=window.APPS.findIndex(i=>i.id===e);f!==-1&&(window.APPS[f]={...window.APPS[f],id:n,name:b||window.APPS[f].name,port:p||window.APPS[f].port,ip:s,tailscaleOnly:c,logo:g||window.APPS[f].logo}),l(),window.buildGrid(),window.refreshAll()}catch(t){console.error("Error saving service changes:",t),showNotification(`Error saving changes: ${t.message}`,"error")}finally{u.textContent="Save Changes",u.disabled=!1}}document.getElementById("edit-logo-file")?.addEventListener("change",async n=>{const b=n.target.files[0];if(!b)return;if(!b.type.startsWith("image/")){showNotification("Please select an image file","warning");return}const p=new FileReader;p.onload=async s=>{const c=s.target.result;if(document.getElementById("edit-service-logo-preview").src=c,document.getElementById("edit-logo-url").value=c,o)try{const e=await(await secureFetch("/api/v1/assets/upload",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filename:`${o.id}.png`,data:c})})).json();e.success&&e.path&&(document.getElementById("edit-logo-url").value=e.path)}catch{}},p.readAsDataURL(b)}),document.getElementById("service-edit-cancel")?.addEventListener("click",l),document.getElementById("service-edit-save")?.addEventListener("click",w),document.getElementById("service-edit-modal")?.addEventListener("click",n=>{n.target.id==="service-edit-modal"&&l()});function v(n,b,p){return new Promise(s=>{const c=document.getElementById("delete-service-modal"),g=document.getElementById("delete-modal-title"),e=document.getElementById("delete-modal-message"),a=document.getElementById("delete-modal-container-info"),u=document.getElementById("delete-modal-container-name"),t=document.getElementById("delete-modal-help"),d=document.getElementById("delete-modal-cancel"),f=document.getElementById("delete-modal-remove"),i=document.getElementById("delete-modal-delete");g.textContent=`Delete "${n}"`,b?(e.innerHTML="This service has an associated Docker container.<br>Choose how to proceed:",a.style.display="block",u.textContent=`Container ID: ${p?.slice(0,12)||"Unknown"}`,t.style.display="block",i.style.display="block"):(e.textContent="Remove this service from the dashboard?",a.style.display="none",t.style.display="none",i.style.display="none");const k=()=>{c.classList.remove("show"),d.removeEventListener("click",B),f.removeEventListener("click",T),i.removeEventListener("click",A),c.removeEventListener("click",E)},B=()=>{k(),s(null)},T=()=>{k(),s(!1)},A=()=>{k(),s(!0)},E=L=>{L.target===c&&(k(),s(null))};d.addEventListener("click",B),f.addEventListener("click",T),i.addEventListener("click",A),c.addEventListener("click",E),c.classList.add("show")})}async function r(n,b,p){const s=document.getElementById(`update-btn-${p}`),c=s?.textContent;if(confirm(`Update ${b} to the latest version?
|
|
|
|
This will:
|
|
1. Pull the latest image
|
|
2. Stop the container
|
|
3. Recreate with same settings
|
|
|
|
The service will be briefly unavailable.`))try{s&&(s.textContent="\u{1F504}",s.disabled=!0,s.title="Updating...");const e=await(await secureFetch(`/api/v1/containers/${n}/update`,{method:"POST"})).json();if(e.success){const a=window.APPS.find(u=>u.id===p);a&&e.newContainerId&&(a.containerId=e.newContainerId),s&&(s.textContent="\u2705",s.title="Updated successfully!",setTimeout(()=>{s.textContent=c,s.disabled=!1,s.title="Update container to latest version"},3e3)),setTimeout(()=>window.refreshAll(),2e3),showNotification(`${b} updated successfully!`,"success")}else throw new Error(e.error||"Update failed")}catch(g){console.error("Update error:",g),s&&(s.textContent="\u274C",s.title="Update failed",setTimeout(()=>{s.textContent=c,s.disabled=!1,s.title="Update container to latest version"},3e3)),showNotification(`Failed to update ${b}: ${g.message}`,"error")}}async function h(n,b){const p=window.APPS.find(i=>i.id===n),s=p?buildDomain(p.id):null,c=p?.containerId,g=await v(b||n,c,p?.containerId);if(g===null)return;let e={dashboard:!1,container:null,dns:null,caddy:null,service:null};if(g&&c)try{const i=new URLSearchParams({containerId:p.containerId,subdomain:p.id,ip:p.ip||"localhost",deleteContainer:"true"}),B=await(await secureFetch(`/api/v1/apps/${encodeURIComponent(p.id)}?${i.toString()}`,{method:"DELETE"})).json();B.success?e={...e,...B.results,dashboard:!1}:console.error("App removal failed:",B.error)}catch(i){console.error("App removal error:",i)}else if(g&&s){try{const i=p?.ip||"localhost",B=await(await secureFetch(`/api/v1/dns/record?domain=${encodeURIComponent(s)}&type=A&ipAddress=${encodeURIComponent(i)}&server=${SITE.dnsIp}`,{method:"DELETE"})).json();e.dns=B.success?"deleted":B.error||"failed"}catch(i){e.dns=i.message}try{const k=await(await secureFetch(`/api/v1/site/${encodeURIComponent(s)}`,{method:"DELETE"})).json();e.caddy=k.success||k.error&&k.error.includes("not found")?"removed":k.error||"failed"}catch(i){e.caddy=i.message}}const a=window.APPS.findIndex(i=>i.id===n);a>-1&&(window.APPS.splice(a,1),e.dashboard=!0);try{const i=safeGetJSON("custom-apps",[]),k=i.findIndex(B=>B.id===n);k>-1&&(i.splice(k,1),safeSet("custom-apps",JSON.stringify(i)))}catch{}try{const k=await(await secureFetch(`/api/v1/services/${encodeURIComponent(n)}`,{method:"DELETE"})).json();e.service=k.success?"removed":k.error||"failed"}catch(i){e.service=i.message}window.buildGrid(),window.refreshAll();let u=!1,t=[];e.dashboard||(u=!0,t.push("\u2717 Failed to remove from dashboard"));const d=["removed","already removed","not found","deleted","kept (user choice)","skipped","no such record","does not exist"],f=i=>!i||d.some(k=>i.toLowerCase().includes(k.toLowerCase()));e.container&&!f(e.container)&&(u=!0,t.push(`\u26A0 Container: ${e.container}`)),e.dns&&!f(e.dns)&&(u=!0,t.push(`\u26A0 DNS Record: ${e.dns}`)),e.caddy&&!f(e.caddy)&&(u=!0,t.push(`\u26A0 Caddy Config: ${e.caddy}`)),e.service&&!f(e.service)&&(u=!0,t.push(`\u26A0 Service File: ${e.service}`)),u&&showNotification(`Error deleting "${b||n}": ${t.join(", ")}`,"error",6e3)}window.openServiceEditModal=m,window.showDeleteModal=v,window.updateContainer=r,window.deleteService=h})(),(function(){function o(e){return e.toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"").replace(/-+/g,"-").replace(/^-|-$/g,"")}function m(){return SITE.defaults?.sslType||(SITE.configurationType==="public"?"letsencrypt":"caddy-managed")}function l(){const e=document.getElementById("service-subdomain-input").value||"subdomain",a=document.getElementById("service-ip-input").value||w.lan||"localhost",u=document.getElementById("service-port-input").value||DC.DEFAULTS.SERVICE_PORT,t=document.getElementById("ssl-type-select").value,d=document.getElementById("ca-name-input").value||"sami-ca",f=document.getElementById("existing-ca-select").value,i=document.getElementById("enable-auth").checked,k=document.getElementById("enable-cors").checked,B=document.getElementById("custom-headers-input").value,T=document.getElementById("upstream-path-input").value||"/",A=document.getElementById("health-check-input").value,E=document.getElementById("timeout-input").value||30,L=document.getElementById("dns-preview");L&&(L.textContent=`${buildDomain(e)} \u2192 ${a}`);const $=document.getElementById("url-preview");$&&($.textContent=buildServiceUrl(e));const x={subdomain:e,port:u,ip:a,sslType:t,caName:d,existingCa:f,enableAuth:i,enableCors:k,customHeaders:B,upstreamPath:T,healthCheck:A,timeout:E},y=window.generateCaddyConfig(x),I=document.getElementById("caddy-config-preview");I&&(I.value=y)}const w={localhost:"127.0.0.1",lan:"",tailscale:""};async function v(){try{const t=await fetch("/api/v1/network/ips",{signal:AbortSignal.timeout(2e3)});if(t.ok){const d=await t.json();d.lan&&(w.lan=d.lan),d.tailscale&&(w.tailscale=d.tailscale)}}catch{}const e=document.getElementById("quick-ip-lan"),a=document.getElementById("quick-ip-tailscale");e&&(w.lan?(e.dataset.ip=w.lan,e.textContent=`LAN (${w.lan})`,e.title=`LAN IP: ${w.lan}`):e.style.display="none"),a&&(w.tailscale?(a.dataset.ip=w.tailscale,a.textContent=`Tailscale (${w.tailscale})`,a.title=`Tailscale IP: ${w.tailscale}`):a.style.display="none");const u=document.getElementById("service-ip-input");u&&!u.value&&w.lan&&(u.value=w.lan)}function r(){document.querySelectorAll(".quick-ip-btn").forEach(e=>{e.addEventListener("click",()=>{const a=e.dataset.ip;a&&(document.getElementById("service-ip-input").value=a,document.querySelectorAll(".quick-ip-btn").forEach(u=>u.classList.remove("active")),e.classList.add("active"),l())})}),document.getElementById("service-ip-input")?.addEventListener("input",e=>{const a=e.target.value;document.querySelectorAll(".quick-ip-btn").forEach(u=>{u.classList.toggle("active",u.dataset.ip===a)})})}async function h(){const e=document.getElementById("add-service-modal");e.classList.add("show");const a=e.querySelector(".weather-modal-content");a&&(a.scrollTop=0),document.body.style.overflow="hidden";const u=document.getElementById("ssl-type-select");u&&(u.value=m()),await v();const t=document.getElementById("caddyfile-path-input").value||DC.DEFAULTS.CADDYFILE;await window.loadExistingCAs(t);const d=document.getElementById("manual-tailscale-status"),f=document.getElementById("manual-tailscale-only");try{const k=await(await fetch("/api/v1/tailscale/status")).json();k.success&&k.installed&&k.connected?(d.innerHTML=`
|
|
<span style="color: #4caf50;">\u2713 Connected</span>
|
|
<span style="color: var(--muted); margin-left: 6px;">${k.self?.hostname} (${k.self?.ip})</span>
|
|
`,f.disabled=!1):k.installed?(d.innerHTML='<span style="color: #ff9800;">\u26A0 Not connected</span>',f.disabled=!0):(d.innerHTML='<span style="color: var(--muted);">Not available</span>',f.disabled=!0)}catch{d.innerHTML='<span style="color: var(--muted);">Could not check</span>',f.disabled=!0}f.checked=!1,l()}function n(){const e=document.getElementById("service-type-local"),a=document.getElementById("service-type-external"),u=document.getElementById("local-service-config"),t=document.getElementById("external-service-config"),d=document.getElementById("tab-local"),f=document.getElementById("tab-external");function i(){e.checked?(u.style.display="grid",t.style.display="none",d&&(d.style.background="var(--accent)",d.style.color="var(--bg)"),f&&(f.style.background="transparent",f.style.color="var(--muted)")):(u.style.display="none",t.style.display="block",f&&(f.style.background="var(--accent)",f.style.color="var(--bg)"),d&&(d.style.background="transparent",d.style.color="var(--muted)"))}e?.addEventListener("change",i),a?.addEventListener("change",i)}function b(){const e=document.getElementById("service-name-input"),a=document.getElementById("service-subdomain-input"),u=document.getElementById("subdomain-preview");let t=!1;e?.addEventListener("input",()=>{const T=o(e.value);!t&&a&&(a.value=T),u&&(u.textContent=T?`\u2192 ${buildDomain(T)}`:""),l()}),a?.addEventListener("input",()=>{t=a.value!==o(e?.value||"");const T=a.value.trim()||o(e?.value||"");u&&(u.textContent=T?`\u2192 ${buildDomain(T)}`:""),l()});const d=document.getElementById("external-service-name"),f=document.getElementById("external-service-subdomain"),i=document.getElementById("external-subdomain-preview"),k=document.getElementById("external-domain-preview");let B=!1;d?.addEventListener("input",()=>{const T=o(d.value);!B&&f&&(f.value=T);const A=f?.value||T;i&&(i.textContent=A?`\u2192 ${buildDomain(A)}`:""),k&&(k.textContent=A?buildDomain(A):"")}),f?.addEventListener("input",()=>{B=f.value!==o(d?.value||"");const T=f.value.trim()||o(d?.value||"");i&&(i.textContent=T?`\u2192 ${buildDomain(T)}`:""),k&&(k.textContent=T?buildDomain(T):"")})}async function p(){const e=document.getElementById("external-service-name").value.trim(),a=document.getElementById("external-service-url").value.trim(),u=(document.getElementById("external-service-subdomain").value.trim()||o(e)).toLowerCase(),t=document.getElementById("external-service-logo").value.trim(),d=document.getElementById("external-service-icon").value.trim(),f=document.getElementById("external-create-dns").checked,i=document.getElementById("external-create-caddy").checked,k=document.getElementById("external-proxy-ip").value.trim()||SITE.dnsIp||"localhost",B=document.getElementById("external-preserve-host").checked,T=document.getElementById("external-follow-redirects").checked;if(!e||!a){showNotification("Please fill in Name and External URL","warning");return}if(!u){showNotification("Could not derive subdomain from name. Please set one in Options.","warning");return}if(!a.startsWith("http://")&&!a.startsWith("https://")){showNotification("External URL must start with http:// or https://","warning");return}const A=buildDomain(u);try{const E={dns:null,caddy:null,dashboard:!1};if(f)if(window.getToken(getPrimaryDnsId(),"admin"))try{const C=await(await secureFetch("/api/v1/dns/record",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:A,ip:k,ttl:DC.DEFAULTS.TTL,server:SITE.dnsIp})})).json();E.dns=C.success?"created":C.error||"failed"}catch(S){E.dns=S.message}else E.dns="no admin token (configure in \u{1F511} Tokens)";if(i)try{const I={subdomain:u,externalUrl:a,preserveHost:B,followRedirects:T,sslType:"caddy-managed",caddyfilePath:DC.DEFAULTS.CADDYFILE,reloadCaddy:!0},C=await(await secureFetch("/api/v1/site/external",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(I)})).json();E.caddy=C.success?"created":C.error||"failed"}catch(I){E.caddy=I.message}const L={id:u,name:e,url:`https://${A}`,externalUrl:a,logo:t||d||"\u{1F310}",isExternal:!0,isCustom:!0};window.APPS.push(L),E.dashboard=!0;const $=["plex","router","chat","sync","torrent","radarr","sonarr","prowlarr","portainer","requests","jellyfin","emby"],x=window.APPS.filter(I=>!$.includes(I.id));safeSet("custom-services",JSON.stringify(x));try{await secureFetch("/api/v1/services",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(window.APPS)})}catch(I){console.warn("Failed to save to services.json:",I)}window.buildGrid(),window.refreshAll(),s();const y=[`External service "${e}" added!`];f&&y.push(`DNS: ${E.dns==="created"?"\u2713":"\u26A0 "+E.dns}`),i&&y.push(`Caddy: ${E.caddy==="created"?"\u2713":"\u26A0 "+E.caddy}`),y.push(`Access at: https://${A}`),showNotification(y.join(" | "),"success",6e3)}catch(E){console.error("Failed to create external service:",E),showNotification(`Failed to create external service: ${E.message}`,"error")}}function s(){closeModal("add-service-modal"),document.body.style.overflow="",document.getElementById("service-name-input").value="",document.getElementById("service-subdomain-input").value="",document.getElementById("service-port-input").value="",document.getElementById("service-ip-input").value=w.lan||"",document.getElementById("service-logo-input").value="",document.getElementById("dns-ttl-input").value=DC.DEFAULTS.TTL,document.getElementById("ssl-type-select").value=m(),document.getElementById("ca-name-input").value="",document.getElementById("enable-auth").checked=!1,document.getElementById("enable-cors").checked=!1,document.getElementById("custom-headers-input").value="",document.getElementById("upstream-path-input").value="/",document.getElementById("health-check-input").value="",document.getElementById("timeout-input").value="30";const e=document.getElementById("subdomain-preview");e&&(e.textContent="");const a=document.getElementById("external-subdomain-preview");a&&(a.textContent="");const u=document.getElementById("external-service-name");u&&(u.value="");const t=document.getElementById("external-service-subdomain");t&&(t.value="");const d=document.getElementById("external-service-url");d&&(d.value="");const f=document.getElementById("external-service-logo");f&&(f.value="");const i=document.getElementById("external-service-icon");i&&(i.value="");const k=document.getElementById("local-advanced-options");k&&k.removeAttribute("open");const B=document.getElementById("external-advanced-options");B&&B.removeAttribute("open");const T=document.getElementById("service-type-local");T&&(T.checked=!0);const A=document.getElementById("local-service-config"),E=document.getElementById("external-service-config");A&&(A.style.display="grid"),E&&(E.style.display="none");const L=document.getElementById("tab-local"),$=document.getElementById("tab-external");L&&(L.style.background="var(--accent)",L.style.color="var(--bg)"),$&&($.style.background="transparent",$.style.color="var(--muted)")}async function c(){const e=document.getElementById("service-name-input").value.trim(),a=(document.getElementById("service-subdomain-input").value.trim()||o(e)).toLowerCase(),u=document.getElementById("service-port-input").value.trim(),t=document.getElementById("service-ip-input").value.trim(),d=document.getElementById("service-logo-input").value.trim(),f=document.getElementById("create-dns-record").checked,i=parseInt(document.getElementById("dns-ttl-input").value)||DC.DEFAULTS.TTL,k=document.getElementById("manual-tailscale-only")?.checked||!1,B=document.getElementById("ssl-type-select")?.value||"caddy-managed",T=document.getElementById("ca-name-input")?.value||"",A=document.getElementById("existing-ca-select")?.value||"",E=document.getElementById("enable-auth")?.checked||!1,L=document.getElementById("enable-cors")?.checked||!1,$=document.getElementById("custom-headers-input")?.value||"",x=document.getElementById("upstream-path-input")?.value||"/",y=document.getElementById("health-check-input")?.value||"",I=document.getElementById("timeout-input")?.value||30,S=window.getToken(getPrimaryDnsId(),"admin");if(!e||!u||!t){showNotification("Please fill in Name, Port, and IP Address","warning");return}if(!a){showNotification("Could not derive subdomain from name. Please set one in Options.","warning");return}if(f&&!S){showNotification("DNS Admin token required. Configure it in the Tokens menu first.","warning");return}const C={dns:null,caddy:null,dashboard:!1};try{if(f)try{await window.createDnsRecord(a,t,i),C.dns="created"}catch(N){throw console.error("DNS creation failed:",N),C.dns=N.message,new Error(`DNS creation failed: ${N.message}`)}else C.dns="skipped";const P=window.generateCaddyConfig({subdomain:a,port:u,ip:t,sslType:B,caName:T,existingCa:A,enableAuth:E,enableCors:L,customHeaders:$,upstreamPath:x,healthCheck:y,timeout:I,tailscaleOnly:k});try{const R=await(await secureFetch("/api/v1/site",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:buildDomain(a),upstream:`${t}:${u}`,config:P})})).json();if(R.success)C.caddy="added & reloaded";else throw console.error("Caddy configuration failed:",R.error),C.caddy=R.error||"failed",new Error(`Caddy configuration failed: ${R.error}`)}catch(N){throw console.error("Caddy API error:",N),C.caddy=N.message,new Error(`Caddy API error: ${N.message}`)}const D={name:e,subdomain:a,port:u,ip:t,logo:d||`/assets/${a}.png`,tailscaleOnly:k||!1};await window.addServiceToConfig(D),C.dashboard=!0;const O=[`DNS: ${C.dns==="created"?"\u2713":C.dns==="skipped"?"\u25CB":"\u2717"}`,`Caddy: ${C.caddy==="added & reloaded"?"\u2713":"\u2717"}`,`Dashboard: ${C.dashboard?"\u2713":"\u2717"}`];showNotification(`Service "${e}" created! ${O.join(" | ")} \u2014 ${buildServiceUrl(a)}${k?" (Tailscale)":""}`,"success",6e3),s(),window.buildGrid(),window.refreshAll()}catch(P){console.error("Error creating service:",P),showNotification(`Error creating "${e}": ${P.message}`,"error",6e3)}}document.getElementById("add-service")?.addEventListener("click",h),document.getElementById("add-service-cancel")?.addEventListener("click",s),document.getElementById("add-service-create")?.addEventListener("click",()=>{document.querySelector('input[name="service-type"]:checked')?.value==="external"?p():c()}),n(),b(),r(),document.getElementById("ssl-type-select")?.addEventListener("change",e=>{const a=document.getElementById("existing-ca-config"),u=document.getElementById("custom-ca-config");a.style.display="none",u.style.display="none",e.target.value==="existing-ca"?a.style.display="block":e.target.value==="custom-ca"&&(u.style.display="block"),l()}),document.getElementById("refresh-cas")?.addEventListener("click",async()=>{const e=document.getElementById("refresh-cas"),a=e.textContent;e.textContent="\u231B Loading...",e.disabled=!0;try{const u=document.getElementById("caddyfile-path-input").value||DC.DEFAULTS.CADDYFILE;await window.loadExistingCAs(u),e.textContent="\u2705 Refreshed"}catch(u){e.textContent="\u274C Failed",console.error("Failed to refresh CAs:",u)}setTimeout(()=>{e.textContent=a,e.disabled=!1},2e3)}),document.getElementById("create-dns-record")?.addEventListener("change",e=>{const a=document.getElementById("dns-config");a.style.display=e.target.checked?"block":"none"}),["service-subdomain-input","service-ip-input","service-port-input","ca-name-input","existing-ca-select","enable-auth","enable-cors","custom-headers-input","upstream-path-input","health-check-input","timeout-input"].forEach(e=>{const a=document.getElementById(e);a&&(a.addEventListener("input",l),a.addEventListener("change",l))});function g(){const e=safeGet("custom-services");if(e)try{JSON.parse(e).forEach(u=>{window.APPS.find(t=>t.id===u.id)||window.APPS.push(u)})}catch(a){console.warn("Failed to load custom services:",a)}}g(),window.openAddServiceModal=h,window.closeAddServiceModal=s})(),(function(){let o=null,m=1e3;const l=3e4;function w(){if(o)try{o.close()}catch{}o=new EventSource("/api/v1/events/stream"),o.addEventListener("connected",()=>{m=1e3,debug("[SSE] Connected to event stream")}),o.addEventListener("status-change",v=>{try{const r=JSON.parse(v.data);if(r.serviceId&&typeof window.setBadge=="function"){const h=r.status==="up"||r.status==="healthy";window.setBadge(r.serviceId,h,r.responseTime||null)}}catch{}}),o.addEventListener("resource-alert",v=>{try{const r=JSON.parse(v.data),h=`${r.containerName||r.containerId}: ${r.metric} at ${r.value}% (threshold: ${r.threshold}%)`;typeof showNotification=="function"&&showNotification(h,"warning")}catch{}}),o.addEventListener("auto-restart",v=>{try{const r=JSON.parse(v.data);typeof showNotification=="function"&&showNotification(`Container "${r.containerName}" was auto-restarted`,"info")}catch{}}),o.addEventListener("update-available",v=>{try{const r=JSON.parse(v.data),h=document.getElementById("updates-btn");if(h&&!h.querySelector(".sse-dot")){const n=document.createElement("span");n.className="sse-dot",n.style.cssText="display:inline-block;width:8px;height:8px;border-radius:50%;background:var(--accent);margin-left:6px;vertical-align:middle;",h.appendChild(n)}typeof showNotification=="function"&&showNotification(`Update available for ${r.containerName||r.containerId}`,"info")}catch{}}),o.addEventListener("update-complete",v=>{try{const r=JSON.parse(v.data);typeof showNotification=="function"&&showNotification(`Update completed: ${r.containerName||r.containerId}`,"success"),typeof window.refreshAll=="function"&&window.refreshAll()}catch{}}),o.addEventListener("update-failed",v=>{try{const r=JSON.parse(v.data);typeof showNotification=="function"&&showNotification(`Update failed: ${r.containerName||r.containerId} \u2014 ${r.error||"unknown error"}`,"error")}catch{}}),o.addEventListener("incident",v=>{try{const r=JSON.parse(v.data);typeof showNotification=="function"&&(r.type==="created"?showNotification(`Incident: ${r.message||r.serviceId}`,"error"):r.type==="resolved"&&showNotification(`Resolved: ${r.serviceId||"incident"}`,"success"))}catch{}}),o.onerror=()=>{o.close(),console.warn(`[SSE] Disconnected, reconnecting in ${m/1e3}s...`),setTimeout(w,m),m=Math.min(m*2,l)}}w(),window._sseReconnect=w})(),(function(){const o=document.getElementById("service-filter-search"),m=document.getElementById("service-filter-status"),l=document.getElementById("service-filter-count");function w(){const r=o.value.toLowerCase().trim(),h=m.value,n=document.querySelectorAll("#cards .card");let b=0;if(n.forEach(p=>{const s=p.querySelector(".name")?.textContent?.toLowerCase()||"",c=p.dataset.app?.toLowerCase()||"",g=p.dataset.status||"off";(!r||s.includes(r)||c.includes(r))&&(h==="all"||g===h)?(p.style.display="",b++):p.style.display="none"}),l){const p=n.length;l.textContent=`${b} of ${p} services`}}function v(r,h){let n;return function(...b){clearTimeout(n),n=setTimeout(()=>r.apply(this,b),h)}}o?.addEventListener("input",v(w,200)),m?.addEventListener("change",w),document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>setTimeout(w,500)):setTimeout(w,500),window.refreshServiceFilter=w})(),(function(){const o=document.getElementById("batch-operations-btn"),m=document.getElementById("batch-action-bar"),l=document.getElementById("batch-selected-count"),w=document.getElementById("batch-start-btn"),v=document.getElementById("batch-stop-btn"),r=document.getElementById("batch-restart-btn"),h=document.getElementById("batch-cancel-btn");let n=!1,b=new Set;function p(){n=!0,b.clear(),m.style.display="",o.textContent="\u2713 Exit Batch Mode",c(),document.querySelectorAll("#cards .card[data-app]").forEach(a=>{const u=a.dataset.containerId;if(!u)return;const t=a.querySelector(".batch-checkbox");t&&t.remove();const d=document.createElement("input");d.type="checkbox",d.className="batch-checkbox",d.dataset.containerId=u,d.dataset.serviceName=a.querySelector(".name")?.textContent||u,d.style.cssText="position: absolute; top: 8px; left: 8px; z-index: 10; width: 18px; height: 18px; cursor: pointer;",d.addEventListener("change",f=>{f.stopPropagation(),d.checked?b.add(u):b.delete(u),c()}),a.style.position="relative",a.insertBefore(d,a.firstChild)})}function s(){n=!1,b.clear(),m.style.display="none",o.textContent="\u2630 Batch Operations",document.querySelectorAll(".batch-checkbox").forEach(e=>e.remove())}function c(){const e=b.size;l.textContent=`${e} selected`,w.disabled=e===0,v.disabled=e===0,r.disabled=e===0}async function g(e){if(b.size===0)return;const a=Array.from(b),u={start:"Starting",stop:"Stopping",restart:"Restarting"}[e];if(!confirm(`${u} ${a.length} container(s)? This cannot be undone.`))return;const t=[w,v,r];t.forEach(k=>{k.disabled=!0,k.textContent="..."});let d=0,f=0;const i=[];for(const k of a)try{const B=await fetch(`/api/v1/containers/${encodeURIComponent(k)}/${e}`,{method:"POST"});if(B.ok)d++;else{f++;const T=await B.json().catch(()=>({}));i.push(`${k}: ${T.error||B.statusText}`)}}catch(B){f++,i.push(`${k}: ${B.message}`)}t[0].textContent="\u25B6 Start All",t[1].textContent="\u2B1B Stop All",t[2].textContent="\u{1F504} Restart All",c(),f===0?typeof showNotification=="function"&&showNotification(`${u} completed: ${d} container(s)`,"success"):(typeof showNotification=="function"&&showNotification(`${u}: ${d} succeeded, ${f} failed`,"warning"),console.error("Batch operation errors:",i)),setTimeout(()=>{typeof refreshAll=="function"&&refreshAll()},1500)}o?.addEventListener("click",()=>{n?s():p()}),w?.addEventListener("click",()=>g("start")),v?.addEventListener("click",()=>g("stop")),r?.addEventListener("click",()=>g("restart")),h?.addEventListener("click",s)})();
|