[grade=A] fix(auth): preserve cross-host SSO return URLs
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled

Codex: urn:ump:endpmb3rgtqogn2u2jkbbjmsaha6ysjjcxl46fd27ayig5yosawq
This commit is contained in:
Krystie committed 2026-07-24 14:36:28 -07:00
1 parent 75f835641f
commit 003b152230
5 files changed
+154 -81

No files matched your search

+69 -69
View File
@@ -1,4 +1,4 @@
(function(l){"use strict";class n{constructor(){this.errors=[],this.maxErrors=50}logError(b,f,u={}){const v={timestamp:new Date().toISOString(),context:b,message:f instanceof Error?f.message:f,stack:f instanceof Error?f.stack:null,metadata:u};this.errors.push(v),this.errors.length>this.maxErrors&&this.errors.shift(),console.error(`[Onboarding Error] ${b}:`,f,u)}recoverFromError(b,f){switch(this.classifyError(b)){case"ELEMENT_NOT_FOUND":return this.logError("Element Not Found",b,{currentStep:f}),{action:"SKIP_STEP",nextStep:f+1,message:"Target element not found, skipping to next step"};case"STORAGE_UNAVAILABLE":return this.logError("Storage Unavailable",b),{action:"USE_MEMORY_STORAGE",message:"Local storage unavailable, using in-memory storage"};case"DRIVER_NOT_LOADED":return this.logError("Driver.js Not Loaded",b),{action:"ABORT_TOUR",message:"Driver.js library not loaded, cannot start tour"};case"INVALID_TOOLTIP":return this.logError("Invalid Tooltip Configuration",b,{currentStep:f}),{action:"SKIP_STEP",nextStep:f+1,message:"Invalid tooltip configuration, skipping"};case"THEME_DETECTION_FAILED":return this.logError("Theme Detection Failed",b),{action:"USE_DEFAULT_THEME",message:"Using default dark theme"};default:return this.logError("Unknown Error",b,{currentStep:f}),{action:"ABORT_TOUR",message:"Unexpected error occurred, aborting tour"}}}classifyError(b){const f=b.message||b.toString();return f.includes("element")&&f.includes("not found")?"ELEMENT_NOT_FOUND":f.includes("storage")||f.includes("quota")?"STORAGE_UNAVAILABLE":f.includes("driver")||f.includes("undefined")?"DRIVER_NOT_LOADED":f.includes("invalid")||f.includes("validation")?"INVALID_TOOLTIP":f.includes("theme")?"THEME_DETECTION_FAILED":"UNKNOWN"}getErrors(){return[...this.errors]}clearErrors(){this.errors=[]}getStatistics(){const b={total:this.errors.length,byContext:{},byType:{},recent:this.errors.slice(-10)};return this.errors.forEach(f=>{b.byContext[f.context]=(b.byContext[f.context]||0)+1;const u=this.classifyError({message:f.message});b.byType[u]=(b.byType[u]||0)+1}),b}handleDriverLoadFailure(){this.logError("Driver.js Load Failure","Driver.js library failed to load");const b=document.createElement("div");return b.id="onboarding-fallback",b.style.cssText=`
(function(l){"use strict";class a{constructor(){this.errors=[],this.maxErrors=50}logError(b,f,m={}){const y={timestamp:new Date().toISOString(),context:b,message:f instanceof Error?f.message:f,stack:f instanceof Error?f.stack:null,metadata:m};this.errors.push(y),this.errors.length>this.maxErrors&&this.errors.shift(),console.error(`[Onboarding Error] ${b}:`,f,m)}recoverFromError(b,f){switch(this.classifyError(b)){case"ELEMENT_NOT_FOUND":return this.logError("Element Not Found",b,{currentStep:f}),{action:"SKIP_STEP",nextStep:f+1,message:"Target element not found, skipping to next step"};case"STORAGE_UNAVAILABLE":return this.logError("Storage Unavailable",b),{action:"USE_MEMORY_STORAGE",message:"Local storage unavailable, using in-memory storage"};case"DRIVER_NOT_LOADED":return this.logError("Driver.js Not Loaded",b),{action:"ABORT_TOUR",message:"Driver.js library not loaded, cannot start tour"};case"INVALID_TOOLTIP":return this.logError("Invalid Tooltip Configuration",b,{currentStep:f}),{action:"SKIP_STEP",nextStep:f+1,message:"Invalid tooltip configuration, skipping"};case"THEME_DETECTION_FAILED":return this.logError("Theme Detection Failed",b),{action:"USE_DEFAULT_THEME",message:"Using default dark theme"};default:return this.logError("Unknown Error",b,{currentStep:f}),{action:"ABORT_TOUR",message:"Unexpected error occurred, aborting tour"}}}classifyError(b){const f=b.message||b.toString();return f.includes("element")&&f.includes("not found")?"ELEMENT_NOT_FOUND":f.includes("storage")||f.includes("quota")?"STORAGE_UNAVAILABLE":f.includes("driver")||f.includes("undefined")?"DRIVER_NOT_LOADED":f.includes("invalid")||f.includes("validation")?"INVALID_TOOLTIP":f.includes("theme")?"THEME_DETECTION_FAILED":"UNKNOWN"}getErrors(){return[...this.errors]}clearErrors(){this.errors=[]}getStatistics(){const b={total:this.errors.length,byContext:{},byType:{},recent:this.errors.slice(-10)};return this.errors.forEach(f=>{b.byContext[f.context]=(b.byContext[f.context]||0)+1;const m=this.classifyError({message:f.message});b.byType[m]=(b.byType[m]||0)+1}),b}handleDriverLoadFailure(){this.logError("Driver.js Load Failure","Driver.js library failed to load");const b=document.createElement("div");return b.id="onboarding-fallback",b.style.cssText=`
position: fixed;
bottom: 20px;
right: 20px;
@@ -16,14 +16,14 @@
The interactive tour is unavailable, but you can explore the dashboard freely.
Check the documentation for help getting started.
</p>
`,document.body.appendChild(b),setTimeout(()=>{b.parentNode&&b.parentNode.removeChild(b)},1e4),!0}handleStorageUnavailable(){this.logError("Storage Unavailable","Local storage is not available");const b={data:{},getItem(f){return this.data[f]||null},setItem(f,u){this.data[f]=u},removeItem(f){delete this.data[f]},clear(){this.data={}}};return console.warn("[ErrorHandler] Using in-memory storage - progress will not persist"),b}sendToErrorTracking(b){}}l.ErrorHandler=n,console.log("[ErrorHandler] Module loaded")})(window);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 b=await fetch("/api/v1/config");if(b.ok){const f=await b.json();if(f.tld&&(SITE.tld=f.tld.startsWith(".")?f.tld:"."+f.tld),f.dns&&(SITE.dnsIp=f.dns.ip||"",SITE.dnsPort=f.dns.port||DC.DEFAULTS.DNS_PORT),f.dnsServers&&typeof f.dnsServers=="object")for(const[v,s]of Object.entries(f.dnsServers))v!=="__proto__"&&v!=="constructor"&&v!=="prototype"&&(SITE.dnsServers[v]=s);f.configurationType&&(SITE.configurationType=f.configurationType),f.domain&&(SITE.domain=f.domain),f.defaults&&(SITE.defaults=f.defaults),f.routingMode&&(SITE.routingMode=f.routingMode),SITE.onboardingCompleted=f.onboardingCompleted===!0,localStorage.setItem("dashcaddy_site_config",JSON.stringify({tld:SITE.tld,configurationType:SITE.configurationType,domain:SITE.domain,routingMode:SITE.routingMode})),renderDnsCards();const u=document.getElementById("manage-tokens");u&&(u.style.display=Object.keys(SITE.dnsServers).length?"":"none")}}catch{}document.querySelectorAll("[data-tld]").forEach(b=>b.textContent=SITE.tld);const n=document.getElementById("edit-tld-suffix");n&&(n.textContent=SITE.tld);const g=document.getElementById("external-proxy-ip");g&&SITE.dnsIp&&(g.value=SITE.dnsIp,g.placeholder=SITE.dnsIp)})();function buildDomain(l){return l+SITE.tld}function buildServiceUrl(l){return SITE.routingMode==="subdirectory"&&SITE.domain?"https://"+SITE.domain+"/"+l:SITE.configurationType==="public"&&SITE.domain?"https://"+l+"."+SITE.domain:"https://"+buildDomain(l)}function getDnsServerAddr(l){const n=SITE.dnsServers[l];return n?`${n.ip}:${n.port}`:buildDomain(l)}function getPrimaryDnsId(){if(!SITE.dnsIp)return null;for(const[l,n]of Object.entries(SITE.dnsServers))if(n.ip===SITE.dnsIp)return l;return null}function renderDnsCards(){const l=document.querySelector(".top");if(!l)return;const n=Object.keys(SITE.dnsServers);if(!n.length)return;const g='<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>',b=l.firstElementChild;n.forEach(f=>{const u=escapeHtml(f),v=escapeHtml((SITE.dnsServers[f].name||f).toUpperCase()),s=document.createElement("div");s.className="card",s.setAttribute("data-app",f),s.setAttribute("data-status","off"),s.innerHTML=`<span id="${u}-dot" class="dot bad at-bl"></span><div class="row"><div class="logo-wrap">${g}</div><span class="name">${v}</span><span class="spacer"></span><span id="${u}-pill" class="badge off">OFF</span></div><div class="response-row"><span id="${u}-time" class="response-time">--</span></div><div class="health-row" id="health-${u}"><span id="uptime-${u}" class="uptime-chip">--</span><div class="uptime-mini-bar"><div class="fill" id="uptime-bar-${u}" style="width: 0%"></div></div></div><div class="btn-row"><button id="${u}-restart" class="restart-btn">Restart</button><button id="${u}-update" class="update-btn" title="Update DNS server">\u2B06\uFE0F</button><button id="${u}-open">Open</button><button id="${u}-logs" class="logs-btn">Logs</button><button id="${u}-settings" class="settings-btn">\u2699\uFE0F</button></div>`,l.insertBefore(s,b)})}window.renderDnsCards=renderDnsCards;let csrfToken=null;async function getCSRFToken(){if(csrfToken)return csrfToken;try{const l=await fetch("/api/v1/csrf-token");if(!l.ok)throw new Error("Failed to fetch CSRF token");return csrfToken=(await l.jsLine truncated
`,document.body.appendChild(b),setTimeout(()=>{b.parentNode&&b.parentNode.removeChild(b)},1e4),!0}handleStorageUnavailable(){this.logError("Storage Unavailable","Local storage is not available");const b={data:{},getItem(f){return this.data[f]||null},setItem(f,m){this.data[f]=m},removeItem(f){delete this.data[f]},clear(){this.data={}}};return console.warn("[ErrorHandler] Using in-memory storage - progress will not persist"),b}sendToErrorTracking(b){}}l.ErrorHandler=a,console.log("[ErrorHandler] Module loaded")})(window);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 b=await fetch("/api/v1/config");if(b.ok){const f=await b.json();if(f.tld&&(SITE.tld=f.tld.startsWith(".")?f.tld:"."+f.tld),f.dns&&(SITE.dnsIp=f.dns.ip||"",SITE.dnsPort=f.dns.port||DC.DEFAULTS.DNS_PORT),f.dnsServers&&typeof f.dnsServers=="object")for(const[y,s]of Object.entries(f.dnsServers))y!=="__proto__"&&y!=="constructor"&&y!=="prototype"&&(SITE.dnsServers[y]=s);f.configurationType&&(SITE.configurationType=f.configurationType),f.domain&&(SITE.domain=f.domain),f.defaults&&(SITE.defaults=f.defaults),f.routingMode&&(SITE.routingMode=f.routingMode),SITE.onboardingCompleted=f.onboardingCompleted===!0,localStorage.setItem("dashcaddy_site_config",JSON.stringify({tld:SITE.tld,configurationType:SITE.configurationType,domain:SITE.domain,routingMode:SITE.routingMode})),renderDnsCards();const m=document.getElementById("manage-tokens");m&&(m.style.display=Object.keys(SITE.dnsServers).length?"":"none")}}catch{}document.querySelectorAll("[data-tld]").forEach(b=>b.textContent=SITE.tld);const a=document.getElementById("edit-tld-suffix");a&&(a.textContent=SITE.tld);const g=document.getElementById("external-proxy-ip");g&&SITE.dnsIp&&(g.value=SITE.dnsIp,g.placeholder=SITE.dnsIp)})();function buildDomain(l){return l+SITE.tld}function buildServiceUrl(l){return SITE.routingMode==="subdirectory"&&SITE.domain?"https://"+SITE.domain+"/"+l:SITE.configurationType==="public"&&SITE.domain?"https://"+l+"."+SITE.domain:"https://"+buildDomain(l)}function getDnsServerAddr(l){const a=SITE.dnsServers[l];return a?`${a.ip}:${a.port}`:buildDomain(l)}function getPrimaryDnsId(){if(!SITE.dnsIp)return null;for(const[l,a]of Object.entries(SITE.dnsServers))if(a.ip===SITE.dnsIp)return l;return null}function renderDnsCards(){const l=document.querySelector(".top");if(!l)return;const a=Object.keys(SITE.dnsServers);if(!a.length)return;const g='<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>',b=l.firstElementChild;a.forEach(f=>{const m=escapeHtml(f),y=escapeHtml((SITE.dnsServers[f].name||f).toUpperCase()),s=document.createElement("div");s.className="card",s.setAttribute("data-app",f),s.setAttribute("data-status","off"),s.innerHTML=`<span id="${m}-dot" class="dot bad at-bl"></span><div class="row"><div class="logo-wrap">${g}</div><span class="name">${y}</span><span class="spacer"></span><span id="${m}-pill" class="badge off">OFF</span></div><div class="response-row"><span id="${m}-time" class="response-time">--</span></div><div class="health-row" id="health-${m}"><span id="uptime-${m}" class="uptime-chip">--</span><div class="uptime-mini-bar"><div class="fill" id="uptime-bar-${m}" style="width: 0%"></div></div></div><div class="btn-row"><button id="${m}-restart" class="restart-btn">Restart</button><button id="${m}-update" class="update-btn" title="Update DNS server">\u2B06\uFE0F</button><button id="${m}-open">Open</button><button id="${m}-logs" class="logs-btn">Logs</button><button id="${m}-settings" class="settings-btn">\u2699\uFE0F</button></div>`,l.insertBefore(s,b)})}window.renderDnsCards=renderDnsCards;let csrfToken=null;async function getCSRFToken(){if(csrfToken)return csrfToken;try{const l=await fetch("/api/v1/csrf-token");if(!l.ok)throw new Error("Failed to fetch CSRF token");return csrfToken=(await l.jsLine truncated
position: fixed; top: 20px; right: 20px;
background: ${u.bg}; color: ${u.fg};
background: ${m.bg}; color: ${m.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(v),g>0&&setTimeout(()=>v.remove(),g)}function timeAgo(l){const n=Date.now()-new Date(l).getTime();return n<6e4?"just now":n<36e5?Math.floor(n/6e4)+"m ago":n<864e5?Math.floor(n/36e5)+"h ago":Math.floor(n/864e5)+"d ago"}function safeGet(l,n=null){try{const g=localStorage.getItem(l);return g!==null?g:n}catch{return n}}function safeSet(l,n){try{localStorage.setItem(l,n)}catch{}}function safeRemove(l){try{localStorage.removeItem(l)}catch{}}function safeSessionGet(l,n=null){try{const g=sessionStorage.getItem(l);return g!==null?g:n}catch{return n}}function safeSessionSet(l,n){try{sessionStorage.setItem(l,n)}catch{}}function safeGetJSON(l,n=null){try{const g=localStorage.getItem(l);return g?JSON.parse(g):n}catch{return n}}function escapeHtml(l){return String(l??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function injectModal(l,n){document.getElementById(l)||document.body.insertAdjacentHTML("beforeend",n)}const DC_BUS={_handlers:{},on(l,n){var g;((g=this._handlers)[l]||(g[l]=[])).push(n)},off(l,n){this._handlers[l]=this._handlers[l]?.filter(g=>g!==n)},emit(l,n){this._handlers[l]?.forEach(g=>g(n))}},AppState={_apps:[],getApps(){return this._apps},setApps(l){this._apps=l,window.APPS=l,DC_BUS.emit("apps:changed",l)},findApp(l){return this._apps.find(n=>n.id===l)},addApp(l){this._apps.push(l),window.APPS=this._apps,DC_BUS.emit("apps:changed",this._apps)},removeApp(l){const n=this._apps.findIndex(g=>g.id===l);return n>-1&&(this._apps.splice(n,1),window.APPS=this._apps,DC_BUS.emit("apps:changed",this._apps)),n>-1},updateApp(l,n){const g=this._apps.find(b=>b.id===l);if(g){for(const[b,f]of Object.entries(n))b!=="__proto__"&&b!=="constructor"&&b!=="prototype"&&(g[b]=f);DC_BUS.emit("apps:changed",this._apps)}return g}};(function(){function l(){const b=document.createElement("div");return b.className="skeleton-card",b.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>',b}function n(b){const f=document.getElementById("cards");if(!(!f||f.querySelector(".card"))){b=b||6;for(let u=0;u<b;u++){const v=l();f.appendChild(v),setTimeout(function(){v.classList.add("loaded")},u*60)}}}function g(){const b=document.getElementById("cards");if(b){var f=b.querySelectorAll(".skeleton-card");f.length&&(f.forEach(function(u,v){setTimeout(function(){u.style.opacity="0",u.style.transform="translateY(-10px)"},v*25)}),setTimeout(function(){f.forEach(function(u){u.parentNode&&u.remove()})},f.length*25+300))}}window.SkeletonLoader={show:n,hide:g}})(),(function(){var l="theme",n="user-themes",g="custom-theme",b=["dark","light","blue","black","nord","dracula","solarized-dark","solarized-light","taxi","ocean"],f=b.slice(),u=["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"],v=["bg","fg","muted","card-base","card-bg","border","ok-bg","ok-fg","bad-bg","bad-fg","dot-ok","dot-bad","uptime","accent","accent-strong"],s=["fg-muted","hover","card-hover","base","success","error","warning"],y={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", Line truncated
`,document.body.appendChild(y),g>0&&setTimeout(()=>y.remove(),g)}function timeAgo(l){const a=Date.now()-new Date(l).getTime();return a<6e4?"just now":a<36e5?Math.floor(a/6e4)+"m ago":a<864e5?Math.floor(a/36e5)+"h ago":Math.floor(a/864e5)+"d ago"}function safeGet(l,a=null){try{const g=localStorage.getItem(l);return g!==null?g:a}catch{return a}}function safeSet(l,a){try{localStorage.setItem(l,a)}catch{}}function safeRemove(l){try{localStorage.removeItem(l)}catch{}}function safeSessionGet(l,a=null){try{const g=sessionStorage.getItem(l);return g!==null?g:a}catch{return a}}function safeSessionSet(l,a){try{sessionStorage.setItem(l,a)}catch{}}function safeGetJSON(l,a=null){try{const g=localStorage.getItem(l);return g?JSON.parse(g):a}catch{return a}}function escapeHtml(l){return String(l??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function injectModal(l,a){document.getElementById(l)||document.body.insertAdjacentHTML("beforeend",a)}const DC_BUS={_handlers:{},on(l,a){var g;((g=this._handlers)[l]||(g[l]=[])).push(a)},off(l,a){this._handlers[l]=this._handlers[l]?.filter(g=>g!==a)},emit(l,a){this._handlers[l]?.forEach(g=>g(a))}},AppState={_apps:[],getApps(){return this._apps},setApps(l){this._apps=l,window.APPS=l,DC_BUS.emit("apps:changed",l)},findApp(l){return this._apps.find(a=>a.id===l)},addApp(l){this._apps.push(l),window.APPS=this._apps,DC_BUS.emit("apps:changed",this._apps)},removeApp(l){const a=this._apps.findIndex(g=>g.id===l);return a>-1&&(this._apps.splice(a,1),window.APPS=this._apps,DC_BUS.emit("apps:changed",this._apps)),a>-1},updateApp(l,a){const g=this._apps.find(b=>b.id===l);if(g){for(const[b,f]of Object.entries(a))b!=="__proto__"&&b!=="constructor"&&b!=="prototype"&&(g[b]=f);DC_BUS.emit("apps:changed",this._apps)}return g}};(function(){function l(){const b=document.createElement("div");return b.className="skeleton-card",b.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>',b}function a(b){const f=document.getElementById("cards");if(!(!f||f.querySelector(".card"))){b=b||6;for(let m=0;m<b;m++){const y=l();f.appendChild(y),setTimeout(function(){y.classList.add("loaded")},m*60)}}}function g(){const b=document.getElementById("cards");if(b){var f=b.querySelectorAll(".skeleton-card");f.length&&(f.forEach(function(m,y){setTimeout(function(){m.style.opacity="0",m.style.transform="translateY(-10px)"},y*25)}),setTimeout(function(){f.forEach(function(m){m.parentNode&&m.remove()})},f.length*25+300))}}window.SkeletonLoader={show:a,hide:g}})(),(function(){var l="theme",a="user-themes",g="custom-theme",b=["dark","light","blue","black","nord","dracula","solarized-dark","solarized-light","taxi","ocean"],f=b.slice(),m=["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"],y=["bg","fg","muted","card-base","card-bg","border","ok-bg","ok-fg","bad-bg","bad-fg","dot-ok","dot-bad","uptime","accent","accent-strong"],s=["fg-muted","hover","card-hover","base","success","error","warning"],h={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", Line truncated
background:
radial-gradient(1200px 800px at 10% -10%, rgba(`+x.r+","+x.g+","+x.b+`, .08), transparent 60%),
radial-gradient(1000px 700px at 110% 10%, rgba(`+x.r+","+x.g+","+x.b+`, .05), transparent 55%),
@@ -44,20 +44,20 @@
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 r(){u.forEach(function(E){document.documentElement.style.removeProperty("--"+E)})}function h(E,B){var $=E.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"");$||($="custom"),b.indexOf($)!==-1&&($=$+"-custom");for(var C=safeGetJSON(n,{}),x=$,I=2;C[$]&&$!==B;)$=x+"-"+I++;return $}function p(E){var B=document.getElementById("user-theme-styles");B&&B.remove(),f.length=b.length,Object.keys(y).forEach(function(k){b.indexOf(k)===-1&&delete y[k]});var $=E||safeGetJSON(n,{}),C=Object.keys($);if(C=C.filter(function(k){return b.indexOf(k)===-1}),!!C.length){var x="";C.forEach(function(k){var S=$[k];f.indexOf(k)===-1&&f.push(k);var A={};u.forEach(function(O){S[O]&&(A[O]=S[O])}),A["card-bg"]=S["card-base"]||S.bg,S.lightBg&&(A.lightBg=!0);var D=e(A);s.forEach(function(O){!A[O]&&D[O]&&(A[O]=D[O])}),y[k]=A,x+=":root."+k+` {
`,u.forEach(function(O){A[O]&&(x+=" --"+O+": "+A[O]+`;
`}function t(){return window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function r(){m.forEach(function(E){document.documentElement.style.removeProperty("--"+E)})}function v(E,B){var $=E.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"");$||($="custom"),b.indexOf($)!==-1&&($=$+"-custom");for(var C=safeGetJSON(a,{}),x=$,I=2;C[$]&&$!==B;)$=x+"-"+I++;return $}function u(E){var B=document.getElementById("user-theme-styles");B&&B.remove(),f.length=b.length,Object.keys(h).forEach(function(k){b.indexOf(k)===-1&&delete h[k]});var $=E||safeGetJSON(a,{}),C=Object.keys($);if(C=C.filter(function(k){return b.indexOf(k)===-1}),!!C.length){var x="";C.forEach(function(k){var S=$[k];f.indexOf(k)===-1&&f.push(k);var A={};m.forEach(function(O){S[O]&&(A[O]=S[O])}),A["card-bg"]=S["card-base"]||S.bg,S.lightBg&&(A.lightBg=!0);var D=e(A);s.forEach(function(O){!A[O]&&D[O]&&(A[O]=D[O])}),h[k]=A,x+=":root."+k+` {
`,m.forEach(function(O){A[O]&&(x+=" --"+O+": "+A[O]+`;
`)}),x+=`}
`,x+=o(k,A),x+=d(k,A)});var I=document.createElement("style");I.id="user-theme-styles",I.textContent=x,document.head.appendChild(I)}}function w(){secureFetch("/api/v1/themes").then(function(E){return E.json()}).then(function(E){if(!(!E.success||!E.themes)){var B=E.themes,$=safeGetJSON(n,{});if(JSON.stringify(B)!==JSON.stringify($)){safeSet(n,JSON.stringify(B)),p(B);var C=safeGet(l);C&&f.indexOf(C)!==-1&&L(C)}}}).catch(function(){})}function T(){var E=safeGetJSON(g);if(E){var B=E.name||"Custom",$=h(B),C={name:B};u.forEach(function(k){E[k]&&(C[k]=E[k])});var x=safeGetJSON(n,{});x[$]=C,safeSet(n,JSON.stringify(x)),safeGet(l)==="custom"&&safeSet(l,$),safeRemove(g);var I={};u.forEach(function(k){C[k]&&(I[k]=C[k])}),fetch("/api/v1/themes/"+$,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:B,colors:I})}).catch(function(){})}}function L(E){document.documentElement.classList.add("theme-transitioning"),f.forEach(function(x){x!=="dark"&&document.documentElement.classList.remove(x)}),r(),E!=="dark"&&document.documentElement.classList.add(E),safeSet(l,E);var B=y[E],$=document.querySelector('meta[name="theme-color"]');$&&B&&$.setAttribute("content",B.bg);var C=B&&B.lightBg;!C&&B&&B.bg&&(C=i(B.bg)>.4),C?document.documentElement.classList.add("light-bg"):document.documentElement.classList.remove("light-bg"),setTimeout(function(){document.documentElement.classList.remove("theme-transitioning")},300)}T(),p();var P=safeGet(l);P==="red"&&(P="black",safeSet(l,"black")),P&&P!=="dark"&&f.indexOf(P)===-1&&(P=null),L(P||t()),w(),window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change",function(E){safeGet(l)||L(E.matches?"dark":"light")}),window.THEMES=f,window.BUILTIN_THEMES=b,window.THEME_COLORS=y,window.THEME_PROPS=u,window.BASE_PROPS=v,window.DERIVED_PROPS=s,window.USER_THEMES_KEY=n,window.applyTheme=L,window.clearCustomProperties=r,window.injectUserThemeStyles=p,window.syncThemesFromServer=w,window.slugifyThemeName=h,window.getActiveTheme=function(){return safeGet(l)||t()},window.deriveExtendedColors=e,window.hexToRgb=c,window.rgbToHex=a,window.blendColors=m})(),(function(){let l=null;async function n(){if(l)return l;try{const y=await fetch("/api/v1/auth/login/methods",{cache:"no-store"});if(!y.ok)throw new Error(`methods HTTP ${y.status}`);const c=await y.json();return l=Array.isArray(c.providers)?c.providers:[],l}catch(y){return console.warn("[auth-gate] methods fetch failed; falling back to TOTP-only",y),[]}}function g(y){const c=document.getElementById("totp-overlay");if(!c)return;const a=c.querySelector(".totp-card");if(!a)return;const m=a.innerHTML;a.dataset.originalBody||(a.dataset.originalBody=m);const i=y.map(e=>{const o=e.config&&(e.config.label||e.name)||e.name;return`<button class="provider-btn" data-provider="${e.name}"
`,x+=n(k,A),x+=d(k,A)});var I=document.createElement("style");I.id="user-theme-styles",I.textContent=x,document.head.appendChild(I)}}function w(){secureFetch("/api/v1/themes").then(function(E){return E.json()}).then(function(E){if(!(!E.success||!E.themes)){var B=E.themes,$=safeGetJSON(a,{});if(JSON.stringify(B)!==JSON.stringify($)){safeSet(a,JSON.stringify(B)),u(B);var C=safeGet(l);C&&f.indexOf(C)!==-1&&L(C)}}}).catch(function(){})}function T(){var E=safeGetJSON(g);if(E){var B=E.name||"Custom",$=v(B),C={name:B};m.forEach(function(k){E[k]&&(C[k]=E[k])});var x=safeGetJSON(a,{});x[$]=C,safeSet(a,JSON.stringify(x)),safeGet(l)==="custom"&&safeSet(l,$),safeRemove(g);var I={};m.forEach(function(k){C[k]&&(I[k]=C[k])}),fetch("/api/v1/themes/"+$,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:B,colors:I})}).catch(function(){})}}function L(E){document.documentElement.classList.add("theme-transitioning"),f.forEach(function(x){x!=="dark"&&document.documentElement.classList.remove(x)}),r(),E!=="dark"&&document.documentElement.classList.add(E),safeSet(l,E);var B=h[E],$=document.querySelector('meta[name="theme-color"]');$&&B&&$.setAttribute("content",B.bg);var C=B&&B.lightBg;!C&&B&&B.bg&&(C=i(B.bg)>.4),C?document.documentElement.classList.add("light-bg"):document.documentElement.classList.remove("light-bg"),setTimeout(function(){document.documentElement.classList.remove("theme-transitioning")},300)}T(),u();var P=safeGet(l);P==="red"&&(P="black",safeSet(l,"black")),P&&P!=="dark"&&f.indexOf(P)===-1&&(P=null),L(P||t()),w(),window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change",function(E){safeGet(l)||L(E.matches?"dark":"light")}),window.THEMES=f,window.BUILTIN_THEMES=b,window.THEME_COLORS=h,window.THEME_PROPS=m,window.BASE_PROPS=y,window.DERIVED_PROPS=s,window.USER_THEMES_KEY=a,window.applyTheme=L,window.clearCustomProperties=r,window.injectUserThemeStyles=u,window.syncThemesFromServer=w,window.slugifyThemeName=v,window.getActiveTheme=function(){return safeGet(l)||t()},window.deriveExtendedColors=e,window.hexToRgb=c,window.rgbToHex=o,window.blendColors=p})(),(function(){let l=null;async function a(){if(l)return l;try{const c=await fetch("/api/v1/auth/login/methods",{cache:"no-store"});if(!c.ok)throw new Error(`methods HTTP ${c.status}`);const o=await c.json();return l=Array.isArray(o.providers)?o.providers:[],l}catch(c){return console.warn("[auth-gate] methods fetch failed; falling back to TOTP-only",c),[]}}function g(c){const o=document.getElementById("totp-overlay");if(!o)return;const p=o.querySelector(".totp-card");if(!p)return;const i=p.innerHTML;p.dataset.originalBody||(p.dataset.originalBody=i);const e=c.map(n=>{const d=n.config&&(n.config.label||n.name)||n.name;return`<button class="provider-btn" data-provider="${n.name}"
style="margin: 6px 4px; padding: 10px 16px; background: var(--accent); color: white; border: 0; border-radius: 6px; cursor: pointer; font-size: 0.95rem;">
Sign in with ${o}
Sign in with ${d}
</button>`}).join(`
`);a.innerHTML=`
`);p.innerHTML=`
<img class="totp-logo totp-logo-dark" src="/assets/dashcaddy-logo-dark.png" alt="DashCaddy" onerror="this.style.display='none'">
<img class="totp-logo totp-logo-light" src="/assets/dashcaddy-logo-light.png" alt="DashCaddy" onerror="this.style.display='none'">
<p class="subtitle">Choose how to sign in</p>
<div id="auth-gate-providers" style="margin: 14px 0 10px;">${i}</div>
<div id="auth-gate-providers" style="margin: 14px 0 10px;">${e}</div>
<div id="auth-gate-message" style="margin-top: 8px; color: var(--muted); font-size: 0.8rem;"></div>
`,c.classList.add("show"),a.querySelectorAll(".provider-btn").forEach(e=>{e.addEventListener("click",()=>{const o=e.dataset.provider,d=y.find(t=>t.name===o);f(d)})})}function b(){const y=document.getElementById("totp-overlay");if(!y)return;const c=y.querySelector(".totp-card");!c||!c.dataset.originalBody||(c.innerHTML=c.dataset.originalBody,window.location.reload())}function f(y){const c=document.getElementById("totp-overlay");if(!c)return;const a=c.querySelector(".totp-card");if(a){if(y.name==="totp"){window.location.reload();return}if(y.name==="email"){a.innerHTML=`
`,o.classList.add("show"),p.querySelectorAll(".provider-btn").forEach(n=>{n.addEventListener("click",()=>{const d=n.dataset.provider,t=c.find(r=>r.name===d);f(t)})})}function b(){const c=document.getElementById("totp-overlay");if(!c)return;const o=c.querySelector(".totp-card");!o||!o.dataset.originalBody||(o.innerHTML=o.dataset.originalBody,window.location.reload())}function f(c){const o=document.getElementById("totp-overlay");if(!o)return;const p=o.querySelector(".totp-card");if(p){if(c.name==="totp"){window.location.reload();return}if(c.name==="email"){p.innerHTML=`
<img class="totp-logo totp-logo-dark" src="/assets/dashcaddy-logo-dark.png" alt="DashCaddy" onerror="this.style.display='none'">
<img class="totp-logo totp-logo-light" src="/assets/dashcaddy-logo-light.png" alt="DashCaddy" onerror="this.style.display='none'">
<p class="subtitle">Sign in with email</p>
@@ -75,13 +75,13 @@
<div style="margin-top: 16px;">
<a href="#" id="auth-gate-back" style="color: var(--muted); font-size: 0.8rem;">\u2190 Back</a>
</div>
`,c.classList.add("show");const m=a.querySelector("#auth-gate-email-input"),i=a.querySelector("#auth-gate-email-submit"),e=a.querySelector("#auth-gate-email-status"),o=a.querySelector("#auth-gate-back");i.addEventListener("click",async()=>{const d=(m.value||"").trim();if(!d||!d.includes("@")){e.textContent="Enter a valid email address.",e.style.color="var(--error, #d33)";return}i.disabled=!0,e.textContent="Sending\u2026",e.style.color="";try{const r=await(await fetch("/api/v1/auth/login/email/initiate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:d})})).json();if(r.success){const h=r.deliveredVia||"email",p=r.maskedEmail||d;h==="dev-console"?e.innerHTML=`
`,o.classList.add("show");const i=p.querySelector("#auth-gate-email-input"),e=p.querySelector("#auth-gate-email-submit"),n=p.querySelector("#auth-gate-email-status"),d=p.querySelector("#auth-gate-back");e.addEventListener("click",async()=>{const t=(i.value||"").trim();if(!t||!t.includes("@")){n.textContent="Enter a valid email address.",n.style.color="var(--error, #d33)";return}e.disabled=!0,n.textContent="Sending\u2026",n.style.color="";try{const v=await(await fetch("/api/v1/auth/login/email/initiate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:t})})).json();if(v.success){const u=v.deliveredVia||"email",w=v.maskedEmail||t;u==="dev-console"?n.innerHTML=`
Check the server logs for your one-time link.
(Dev mode: no SMTP configured. In production this would email <strong>${p}</strong>.)`:e.innerHTML=`Sign-in link sent to <strong>${p}</strong>.
Check your inbox (and spam folder).`,e.style.color="var(--success, #2a7)"}else e.textContent=r.error||"Could not send link.",e.style.color="var(--error, #d33)",i.disabled=!1}catch{e.textContent="Connection error. Try again.",e.style.color="var(--error, #d33)",i.disabled=!1}}),m.addEventListener("keydown",d=>{d.key==="Enter"&&i.click()}),o.addEventListener("click",d=>{d.preventDefault(),g(providers)});return}console.warn("[auth-gate] unknown provider",y.name),window.location.reload()}}async function u(){if(!document.getElementById("totp-overlay"))return;const c=await n();if(c.length===0){typeof window._showTotpOverlay=="function"&&window._showTotpOverlay();return}if(c.length===1&&c[0].name==="totp"){v(c[0]);return}g(c)}function v(y){const c=l&&l.find(e=>e.name==="email");if(!c){typeof window._showTotpOverlay=="function"&&window._showTotpOverlay();return}const a=document.getElementById("totp-overlay"),m=a.querySelector(".totp-card");if(!m)return;if(m.dataset.originalBody||(m.dataset.originalBody=m.innerHTML),!m.querySelector("#auth-gate-email-alt")){const e=document.createElement("div");e.id="auth-gate-email-alt",e.style.cssText="margin-top: 18px; padding-top: 14px; border-top: 1px solid var(--border); font-size: 0.85rem;",e.innerHTML=`<a href="#" id="auth-gate-email-alt-link"
(Dev mode: no SMTP configured. In production this would email <strong>${w}</strong>.)`:n.innerHTML=`Sign-in link sent to <strong>${w}</strong>.
Check your inbox (and spam folder).`,n.style.color="var(--success, #2a7)"}else n.textContent=v.error||"Could not send link.",n.style.color="var(--error, #d33)",e.disabled=!1}catch{n.textContent="Connection error. Try again.",n.style.color="var(--error, #d33)",e.disabled=!1}}),i.addEventListener("keydown",t=>{t.key==="Enter"&&e.click()}),d.addEventListener("click",t=>{t.preventDefault(),g(providers)});return}console.warn("[auth-gate] unknown provider",c.name),window.location.reload()}}async function m(){if(!document.getElementById("totp-overlay"))return;const o=await a();if(o.length===0){typeof window._showTotpOverlay=="function"&&window._showTotpOverlay();return}if(o.length===1&&o[0].name==="totp"){y(o[0]);return}g(o)}function y(c){const o=l&&l.find(n=>n.name==="email");if(!o){typeof window._showTotpOverlay=="function"&&window._showTotpOverlay();return}const p=document.getElementById("totp-overlay"),i=p.querySelector(".totp-card");if(!i)return;if(i.dataset.originalBody||(i.dataset.originalBody=i.innerHTML),!i.querySelector("#auth-gate-email-alt")){const n=document.createElement("div");n.id="auth-gate-email-alt",n.style.cssText="margin-top: 18px; padding-top: 14px; border-top: 1px solid var(--border); font-size: 0.85rem;",n.innerHTML=`<a href="#" id="auth-gate-email-alt-link"
style="color: var(--accent); text-decoration: none;">
Or sign in with email instead \u2192
</a>`,m.appendChild(e),e.querySelector("#auth-gate-email-alt-link").addEventListener("click",o=>{o.preventDefault(),f(c)})}a.classList.add("show")}window.__dc_049_handled=!0;const s=new URLSearchParams(window.location.search);if(s.get("auth")==="required"){const y=s.get("return");if(y)try{if(new URL(y,window.location.origin).origin===window.location.origin)try{sessionStorage.setItem("totp_redirect",y)}catch{}}catch{}window.history.replaceState({},"",window.location.pathname),setTimeout(u,0)}window._showAuthGate=u,window._authGateMethods=n})(),(function(){function l(){const v=document.querySelector(".totp-card");if(!v)return;const y=getComputedStyle(v).backgroundColor.match(/\d+/g);if(!y)return;const c=(.299*+y[0]+.587*+y[1]+.114*+y[2])/255,a=v.querySelector(".totp-logo-dark"),m=v.querySelector(".totp-logo-light");a&&(a.style.display=c>.5?"none":""),m&&(m.style.display=c>.5?"":"none")}function n(){const v=document.getElementById("totp-overlay");if(v){v.classList.add("show"),setTimeout(l,50);const s=v.querySelector(".totp-digits input");s&&setTimeout(()=>s.focus(),100)}typeof window._refreshRecoveryLink=="function"&&window._refreshRecoveryLink()}function g(){const v=document.getElementById("totp-overlay");v&&v.classList.remove("show")}const b=document.getElementById("totp-digits");if(b){const v=b.querySelectorAll("input");v.forEach((s,y)=>{s.addEventListener("input",c=>{const a=c.target.value.replace(/\D/g,"");c.target.value=a.slice(0,1),a&&y<v.length-1&&v[y+1].focus();const m=Array.from(v).map(i=>i.value).join("");m.length===6&&f(m)}),s.addEventListener("keydown",c=>{c.key==="Backspace"&&!c.target.value&&y>0&&(v[y-1].focus(),v[y-1].value="")}),s.addEventListener("paste",c=>{c.preventDefault();const a=(c.clipboardData.getData("text")||"").replace(/\D/g,"");a.length>=6&&(v.forEach((m,i)=>{m.value=a[i]||""}),v[5].focus(),f(a.slice(0,6)))})})}async function f(v){const s=document.getElementById("totp-error");s.textContent="Verifying...",s.className="totp-error verifying";try{const c=await(await secureFetch("/api/v1/totp/verify",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:v})})).json();if(c.success){s.textContent="",c.csrfToken&&(csrfToken=c.csrfToken),g();const a=safeSessionGet("totp_redirect");if(a){try{sessionStorage.removeItem("totp_redirect")}catch{}let m=a;if(c.ssoToken){const i=a.includes("?")?"&":"?";m=a+i+"dc_token="+encodeURIComponent(c.ssoToken)}window.location.href=m;return}typeof window.initializeDashboard=="function"&&window.initializeDashboard()}else{s.textContent=c.error||"Invalid code",s.className="totp-error";const a=document.querySelectorAll("#totp-digits input");a.forEach(m=>{m.value=""}),a[0]?.focus()}}catch{s.textContent="Connection error",s.className="totp-error"}}if(!!!window.__dc_049_handled&&urlParams.get("auth")==="required"){const v=urlParams.get("return");if(v)try{const s=new URL(v,window.location.origin),y=s.hostname,c=s.origin===window.location.origin,a=SITE.tld.startsWith(".")?SITE.tld:"."+SITE.tld,m=y.endsWith(a)||y===a.substring(1);(c||m)&&safeSessionSet("totp_redirect",v)}catch{}window.history.replaceState({},"",window.location.pathname)}window._showTotpOverlay=n})(),(function(){"use strict";async function l(){try{return await(await fetch("/api/v1/totp/recovery-info",{cache:"no-store"})).json()}catch{return{success:!1,status:"unknown",hint:"Could not contact server"}}}function n(v){const s=document.getElementById("totp-recovery-link");s&&(s.style.display=v?"":"none")}function g(){const v=document.getElementById("totp-recovery-panel");v&&(v.style.display="");const s=document.getElementById("totp-recovery-status"),y=document.getElementById("totp-recovery-import"),c=document.getElementById("totp-recovery-verify");y&&(y.style.display=""),c&&(c.style.display="none"),document.getElementById("totp-recovery-error").textContent="",document.getElementById("totp-recovery-confirm-error").textContent="",document.getElementById("totp-recovery-secret").value="",document.getElementById("totp-recovery-code").value="",l().then(a=>{s.textContent=a.hint||"",a.status==="healthy"?s.style.borderColor="var(--ok-fg, #7ef2ff)":a.status==="unreadable"?(s.style.borderColor="var(--bad-fg, #ff9aa3)",s.style.background="color-mix(in srgb, var(--bad-fg) 6%, transparent)"):a.status==="not_configured"?s.style.borderColor="var(--muted)":s.style.borderColor="var(--border)"}),setTimeout(()=>{document.getElementById("totp-recovery-secret")?.focus()},100)}function b(){const v=document.getElementById("totp-recovery-panel");v&&(v.style.display="none")}async function f(){const v=document.getElementById("totp-recovery-secret").value.trim(),s=document.getElementById("totp-recovery-error");if(s.textContent="",!v){s.textContent="Paste your Base32 key first";return}if(!/^[A-Za-z2-7\s]+=*$/.test(v)){s.textContent="Invalid Base32 format \u2014 should be letters A-Z and digits 2-7 only";return}try{const y=await fetch("/api/v1/totp/setup",{method:"POST",headers:{"Content-Type":"applLine truncated
</a>`,i.appendChild(n),n.querySelector("#auth-gate-email-alt-link").addEventListener("click",d=>{d.preventDefault(),f(o)})}p.classList.add("show")}window.__dc_049_handled=!0;function s(c){try{const o=new URL(c,window.location.origin);if(!["http:","https:"].includes(o.protocol))return!1;if(o.origin===window.location.origin)return!0;if(o.protocol!=="https:")return!1;const p=SITE.tld.startsWith(".")?SITE.tld:`.${SITE.tld}`;return o.hostname===p.slice(1)||o.hostname.endsWith(p)}catch{return!1}}const h=new URLSearchParams(window.location.search);if(h.get("auth")==="required"){const c=h.get("return");if(c&&s(c))try{sessionStorage.setItem("totp_redirect",c)}catch{}window.history.replaceState({},"",window.location.pathname),setTimeout(m,0)}window._showAuthGate=m,window._authGateMethods=a})(),(function(){function l(){const y=document.querySelector(".totp-card");if(!y)return;const h=getComputedStyle(y).backgroundColor.match(/\d+/g);if(!h)return;const c=(.299*+h[0]+.587*+h[1]+.114*+h[2])/255,o=y.querySelector(".totp-logo-dark"),p=y.querySelector(".totp-logo-light");o&&(o.style.display=c>.5?"none":""),p&&(p.style.display=c>.5?"":"none")}function a(){const y=document.getElementById("totp-overlay");if(y){y.classList.add("show"),setTimeout(l,50);const s=y.querySelector(".totp-digits input");s&&setTimeout(()=>s.focus(),100)}typeof window._refreshRecoveryLink=="function"&&window._refreshRecoveryLink()}function g(){const y=document.getElementById("totp-overlay");y&&y.classList.remove("show")}const b=document.getElementById("totp-digits");if(b){const y=b.querySelectorAll("input");y.forEach((s,h)=>{s.addEventListener("input",c=>{const o=c.target.value.replace(/\D/g,"");c.target.value=o.slice(0,1),o&&h<y.length-1&&y[h+1].focus();const p=Array.from(y).map(i=>i.value).join("");p.length===6&&f(p)}),s.addEventListener("keydown",c=>{c.key==="Backspace"&&!c.target.value&&h>0&&(y[h-1].focus(),y[h-1].value="")}),s.addEventListener("paste",c=>{c.preventDefault();const o=(c.clipboardData.getData("text")||"").replace(/\D/g,"");o.length>=6&&(y.forEach((p,i)=>{p.value=o[i]||""}),y[5].focus(),f(o.slice(0,6)))})})}async function f(y){const s=document.getElementById("totp-error");s.textContent="Verifying...",s.className="totp-error verifying";try{const c=await(await secureFetch("/api/v1/totp/verify",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:y})})).json();if(c.success){s.textContent="",c.csrfToken&&(csrfToken=c.csrfToken),g();const o=safeSessionGet("totp_redirect");if(o){try{sessionStorage.removeItem("totp_redirect")}catch{}let p=o;if(c.ssoToken){const i=o.includes("?")?"&":"?";p=o+i+"dc_token="+encodeURIComponent(c.ssoToken)}window.location.href=p;return}typeof window.initializeDashboard=="function"&&window.initializeDashboard()}else{s.textContent=c.error||"Invalid code",s.className="totp-error";const o=document.querySelectorAll("#totp-digits input");o.forEach(p=>{p.value=""}),o[0]?.focus()}}catch{s.textContent="Connection error",s.className="totp-error"}}if(!!!window.__dc_049_handled&&urlParams.get("auth")==="required"){const y=urlParams.get("return");if(y)try{const s=new URL(y,window.location.origin),h=s.hostname,c=s.origin===window.location.origin,o=SITE.tld.startsWith(".")?SITE.tld:"."+SITE.tld,p=h.endsWith(o)||h===o.substring(1);(c||p)&&safeSessionSet("totp_redirect",y)}catch{}window.history.replaceState({},"",window.location.pathname)}window._showTotpOverlay=a})(),(function(){"use strict";async function l(){try{return await(await fetch("/api/v1/totp/recovery-info",{cache:"no-store"})).json()}catch{return{success:!1,status:"unknown",hint:"Could not contact server"}}}function a(y){const s=document.getElementById("totp-recovery-link");s&&(s.style.display=y?"":"none")}function g(){const y=document.getElementById("totp-recovery-panel");y&&(y.style.display="");const s=document.getElementById("totp-recovery-status"),h=document.getElementById("totp-recovery-import"),c=document.getElementById("totp-recovery-verify");h&&(h.style.display=""),c&&(c.style.display="none"),document.getElementById("totp-recovery-error").textContent="",document.getElementById("totp-recovery-confirm-error").textContent="",document.getElementById("totp-recovery-secret").value="",document.getElementById("totp-recovery-code").value="",l().then(o=>{s.textContent=o.hint||"",o.status==="healthy"?s.style.borderColor="var(--ok-fg, #7ef2ff)":o.status==="unreadable"?(s.style.borderColor="var(--bad-fg, #ff9aa3)",s.style.background="color-mix(in srgb, var(--bad-fg) 6%, transparent)"):o.status==="not_configured"?s.style.borderColor="var(--muted)":s.style.borderColor="var(--border)"}),setTimeout(()=>{document.getElementById("totp-recovery-secret")?.focus()},100)}function b(){const y=document.getElementById("totp-recovery-panel");y&&(y.style.display="none")}async function f(){const y=document.getElementById("totp-recovery-secret").value.trim(),s=document.getElementById("totp-recovery-error");if(s.textContent="",!y){s.textContent="Paste yLine truncated
<div class="weather-modal-content" style="min-width: 500px; max-width: 700px; max-height: 80vh;">
<h3>\u{1F4C2} Browse for Media Folders</h3>
@@ -179,7 +179,7 @@
</button>
</div>
</div>
</div>`);const n=document.getElementById("service-creds-modal");let g=null;const b=["sonarr","radarr","prowlarr","overseerr"],f=["sonarr","radarr"];function u(a){return a.externalUrl||a.url||""}function v(a){const m=document.getElementById("svc-creds-error");m.textContent=a,m.style.display=""}function s(){const a=document.getElementById("svc-creds-error");a.textContent="",a.style.display="none"}window.openServiceCredsModal=async function(a){g=a,s();const m=document.getElementById("svc-creds-title"),i=document.getElementById("svc-creds-desc"),e=document.getElementById("svc-creds-seedhost"),o=document.getElementById("svc-creds-apikey"),d=document.getElementById("svc-creds-basic"),t=document.getElementById("svc-creds-quality");m.textContent=a.name+" Credentials";const r=!!a.isExternal,h=b.includes(a.id)||b.includes(a.appTemplate),p=f.includes(a.id)||f.includes(a.appTemplate);e.style.display=r?"":"none",o.style.display=h?"":"none",t.style.display=p?"":"none",d.style.display=r?"none":"";const w=document.getElementById("svc-quality-select");w.innerHTML='<option value="">-- Enter API key first --</option>',document.getElementById("svc-quality-status").textContent="",r?(i.textContent="Seedhost credentials auto-login past the HTTP prompt. API key bypasses the app login.",document.getElementById("svc-seedhost-pass").placeholder=`Password for ${a.name}`):h?i.textContent="API key bypasses the app login screen automatically.":i.textContent="Credentials are injected automatically when accessing this service.",await y(a),n.classList.add("show")};async function y(a){const m=document.getElementById("svc-creds-dot"),i=document.getElementById("svc-creds-status"),e=document.getElementById("svc-creds-clear");let o=!1;if(a.isExternal){try{const r=await(await fetch(`/api/v1/seedhost-creds?serviceId=${a.id}`)).json();r.success?(document.getElementById("svc-seedhost-user").value=r.username||"",r.hasCredentials&&(o=!0)):document.getElementById("svc-seedhost-user").value=""}catch{}document.getElementById("svc-seedhost-pass").value=""}try{const r=await(await fetch(`/api/v1/services/${a.id}/credentials`)).json();r.success&&(r.hasApiKey?(document.getElementById("svc-apikey-input").value="\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022",o=!0):document.getElementById("svc-apikey-input").value="",r.hasBasicAuth&&!a.isExternal?(document.getElementById("svc-basic-user").value=r.username||"",o=!0):document.getElementById("svc-basic-user").value="")}catch{}document.getElementById("svc-basic-pass")&&(document.getElementById("svc-basic-pass").value="");const d=a.id||a.appTemplate;if(f.includes(d)&&await c(a),o){m.style.background="var(--ok-fg, #74dfc4)",i.style.color="var(--ok-fg, #74dfc4)",i.textContent="Credentials stored",e.style.display="";const t=document.getElementById(`creds-btn-${a.id}`);t&&t.classList.add("has-creds")}else m.style.background="var(--muted)",i.style.color="var(--muted)",i.textContent="No credentials stored",e.style.display="none"}async function c(a){const m=document.getElementById("svc-quality-select"),i=document.getElementById("svc-quality-status"),e=a.id||a.appTemplate,o=u(a);if(!o){m.innerHTML='<option value="">-- No service URL --</option>';return}m.innerHTML='<option value="">Loading...</option>',i.textContent="";try{const d=new URLSearchParams({service:e,url:o}),r=await(await fetch(`/api/v1/arr/quality-profiles?${d}`)).json();if(!r.success||!r.profiles?.length){m.innerHTML='<option value="">-- No profiles found (enter API key and click Fetch) --</option>';return}m.innerHTML="";for(const h of r.profiles){const p=document.createElement("option");p.value=h.id,p.textContent=h.name,m.appendChild(p)}if(r.storedProfileId&&(m.value=String(r.storedProfileId)),!m.value){const h=r.profiles.find(p=>/720/i.test(p.name));h&&(m.value=String(h.id))}!m.value&&r.profiles.length&&(m.value=String(r.profiles[0].id)),i.innerHTML=`<span style="color: var(--ok-fg);">${r.profiles.length} profiles loaded</span>`}catch(d){m.innerHTML='<option value="">-- Failed to load --</option>',i.innerHTML=`<span style="color: var(--error, #c62828);">Error: ${d.message}</span>`}}document.getElementById("svc-quality-fetch")?.addEventListener("click",async()=>{if(!g)return;const a=g.id||g.appTemplate,m=u(g),e=document.getElementById("svc-apikey-input")?.value.trim(),o=document.getElementById("svc-quality-select"),d=document.getElementById("svc-quality-status");if(!m){d.innerHTML='<span style="color: var(--error, #c62828);">No service URL available</span>';return}if(!e||e==="\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022"){d.innerHTML='<span style="color: var(--error, #c62828);">Enter an API key first</span>';return}o.innerHTML='<option value="">Fetching...</option>',d.textContent="";try{const t=new URLSearchParams({service:a,url:m,apiKey:e}),h=await(await fetch(`/api/v1/arr/quality-profiles?${t}`)).json();if(!h.success){o.innerHTML='<option value="">-- Error --</option>',d.innerHTML=`<span style="color: var(--error, #c62828);">${h.error||"Failed to feLine truncated
</div>`);const a=document.getElementById("service-creds-modal");let g=null;const b=["sonarr","radarr","prowlarr","overseerr"],f=["sonarr","radarr"];function m(o){return o.externalUrl||o.url||""}function y(o){const p=document.getElementById("svc-creds-error");p.textContent=o,p.style.display=""}function s(){const o=document.getElementById("svc-creds-error");o.textContent="",o.style.display="none"}window.openServiceCredsModal=async function(o){g=o,s();const p=document.getElementById("svc-creds-title"),i=document.getElementById("svc-creds-desc"),e=document.getElementById("svc-creds-seedhost"),n=document.getElementById("svc-creds-apikey"),d=document.getElementById("svc-creds-basic"),t=document.getElementById("svc-creds-quality");p.textContent=o.name+" Credentials";const r=!!o.isExternal,v=b.includes(o.id)||b.includes(o.appTemplate),u=f.includes(o.id)||f.includes(o.appTemplate);e.style.display=r?"":"none",n.style.display=v?"":"none",t.style.display=u?"":"none",d.style.display=r?"none":"";const w=document.getElementById("svc-quality-select");w.innerHTML='<option value="">-- Enter API key first --</option>',document.getElementById("svc-quality-status").textContent="",r?(i.textContent="Seedhost credentials auto-login past the HTTP prompt. API key bypasses the app login.",document.getElementById("svc-seedhost-pass").placeholder=`Password for ${o.name}`):v?i.textContent="API key bypasses the app login screen automatically.":i.textContent="Credentials are injected automatically when accessing this service.",await h(o),a.classList.add("show")};async function h(o){const p=document.getElementById("svc-creds-dot"),i=document.getElementById("svc-creds-status"),e=document.getElementById("svc-creds-clear");let n=!1;if(o.isExternal){try{const r=await(await fetch(`/api/v1/seedhost-creds?serviceId=${o.id}`)).json();r.success?(document.getElementById("svc-seedhost-user").value=r.username||"",r.hasCredentials&&(n=!0)):document.getElementById("svc-seedhost-user").value=""}catch{}document.getElementById("svc-seedhost-pass").value=""}try{const r=await(await fetch(`/api/v1/services/${o.id}/credentials`)).json();r.success&&(r.hasApiKey?(document.getElementById("svc-apikey-input").value="\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022",n=!0):document.getElementById("svc-apikey-input").value="",r.hasBasicAuth&&!o.isExternal?(document.getElementById("svc-basic-user").value=r.username||"",n=!0):document.getElementById("svc-basic-user").value="")}catch{}document.getElementById("svc-basic-pass")&&(document.getElementById("svc-basic-pass").value="");const d=o.id||o.appTemplate;if(f.includes(d)&&await c(o),n){p.style.background="var(--ok-fg, #74dfc4)",i.style.color="var(--ok-fg, #74dfc4)",i.textContent="Credentials stored",e.style.display="";const t=document.getElementById(`creds-btn-${o.id}`);t&&t.classList.add("has-creds")}else p.style.background="var(--muted)",i.style.color="var(--muted)",i.textContent="No credentials stored",e.style.display="none"}async function c(o){const p=document.getElementById("svc-quality-select"),i=document.getElementById("svc-quality-status"),e=o.id||o.appTemplate,n=m(o);if(!n){p.innerHTML='<option value="">-- No service URL --</option>';return}p.innerHTML='<option value="">Loading...</option>',i.textContent="";try{const d=new URLSearchParams({service:e,url:n}),r=await(await fetch(`/api/v1/arr/quality-profiles?${d}`)).json();if(!r.success||!r.profiles?.length){p.innerHTML='<option value="">-- No profiles found (enter API key and click Fetch) --</option>';return}p.innerHTML="";for(const v of r.profiles){const u=document.createElement("option");u.value=v.id,u.textContent=v.name,p.appendChild(u)}if(r.storedProfileId&&(p.value=String(r.storedProfileId)),!p.value){const v=r.profiles.find(u=>/720/i.test(u.name));v&&(p.value=String(v.id))}!p.value&&r.profiles.length&&(p.value=String(r.profiles[0].id)),i.innerHTML=`<span style="color: var(--ok-fg);">${r.profiles.length} profiles loaded</span>`}catch(d){p.innerHTML='<option value="">-- Failed to load --</option>',i.innerHTML=`<span style="color: var(--error, #c62828);">Error: ${d.message}</span>`}}document.getElementById("svc-quality-fetch")?.addEventListener("click",async()=>{if(!g)return;const o=g.id||g.appTemplate,p=m(g),e=document.getElementById("svc-apikey-input")?.value.trim(),n=document.getElementById("svc-quality-select"),d=document.getElementById("svc-quality-status");if(!p){d.innerHTML='<span style="color: var(--error, #c62828);">No service URL available</span>';return}if(!e||e==="\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022"){d.innerHTML='<span style="color: var(--error, #c62828);">Enter an API key first</span>';return}n.innerHTML='<option value="">Fetching...</option>',d.textContent="";try{const t=new URLSearchParams({service:o,url:p,apiKey:e}),v=await(await fetch(`/api/v1/arr/quality-profiles?${t}`)).json();if(!v.success){n.innerHTML='<option value="">-- Error --</option>',d.innerHTML=`<span style="color: var(--error, #c62828);">${v.error||"Failed to feLine truncated
<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>
@@ -288,7 +288,7 @@
</button>
</div>
</div>
</div>`);async function n(){try{const u=await(await fetch("/api/v1/totp/config")).json();if(!u.success)return;const{enabled:v,sessionDuration:s,isSetUp:y}=u.config,c=document.getElementById("totp-status-dot"),a=document.getElementById("totp-status-text"),m=document.getElementById("totp-status-banner"),i=document.getElementById("totp-setup-section"),e=document.getElementById("totp-qr-section"),o=document.getElementById("totp-duration-section"),d=document.getElementById("totp-disable-section");if(v&&y){c.style.background="var(--ok-fg, #7ef2ff)",m.style.borderColor="var(--ok-fg, #7ef2ff)",m.style.background="color-mix(in srgb, var(--ok-fg) 8%, transparent)",a.textContent="TOTP is active",a.style.color="var(--ok-fg, #7ef2ff)",i.style.display="block";const t=document.getElementById("totp-setup-btn");t&&(t.textContent="Generate New Secret"),e.style.display="none",o.style.display="block",d.style.display="block",document.getElementById("totp-duration-select").value=s}else c.style.background="var(--muted)",m.style.borderColor="var(--border)",m.style.background="transparent",a.textContent="TOTP is not configured",a.style.color="var(--muted)",i.style.display="block",e.style.display="none",o.style.display="none",d.style.display="none";b(v&&y,s)}catch(f){console.warn("Failed to load TOTP settings:",f)}}const g={"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 b(f,u){const v=document.getElementById("auth-card"),s=document.getElementById("auth-pill"),y=document.getElementById("auth-dot"),c=document.getElementById("auth-status-text");v&&(f?(v.setAttribute("data-status","on"),s.className="badge on",s.textContent="YES",y.className="dot ok at-bl",c.textContent="Session: "+(g[u]||u)):(v.setAttribute("data-status","off"),s.className="badge off",s.textContent="NO",y.className="dot bad at-bl",c.textContent="Not configured"))}document.getElementById("totp-setup-btn")?.addEventListener("click",async()=>{try{const u=await(await secureFetch("/api/v1/totp/setup",{method:"POST"})).json();u.success&&(document.getElementById("totp-qr-image").src=u.qrCode,document.getElementById("totp-manual-key").textContent=u.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(f){l.logError("[TOTP] Setup Failed",f,{function:"setupTOTP"})}}),document.getElementById("totp-import-btn")?.addEventListener("click",async()=>{const f=document.getElementById("totp-import-key").value.trim(),u=document.getElementById("totp-import-error");if(u.textContent="",!f){u.textContent="Paste a Base32 secret key first";return}try{const s=await(await secureFetch("/api/v1/totp/setup",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({secret:f})})).json();s.success?(u.textContent="",document.getElementById("totp-qr-image").src=s.qrCode,document.getElementById("totp-manual-key").textContent=s.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()):u.textContent=s.error||s.message||"Import failed"}catch{u.textContent="Connection error \u2014 try refreshing the page"}}),document.getElementById("totp-copy-key")?.addEventListener("click",()=>{const f=document.getElementById("totp-manual-key").textContent;navigator.clipboard.writeText(f).then(()=>{const u=document.getElementById("totp-copy-key");u.textContent="\u2705",setTimeout(()=>{u.textContent="\u{1F4CB}"},2e3)})}),document.getElementById("totp-download-backup")?.addEventListener("click",()=>{const f=document.getElementById("totp-manual-key").textContent.trim();if(!f)return;const u={service:"DashCaddy",type:"totp-secret",secret:f,issuer:"DashCaddy",algorithm:"SHA1",digits:6,period:30,issued:new Date().toISOString(),recovery_url:`${window.location.origin}/ (login screen \u2192 "Lost access?")`,note:'Keep this file somewhere safe. Anyone with this secret can generate your login codes. Use it ONLY to recover TOTP access via the "Lost access?" link on the DashCaddy login screen.'},v=new Blob([JSON.stringify(u,null,2)],{type:"application/json"}),s=URL.createObjectURL(v),y=document.createElement("a");y.href=s,y.download=`dashcaddy-totp-backup-${new Date().toISOString().slice(0,10)}.json`,document.body.appendChild(y),y.click(),document.body.removeChild(y),URL.revokeObjectURL(s);const c=document.getElementById("totp-download-backup");c.textContent="\u2705 Saved",setTimeout(()=>{c.textContent="\u2B07 Download"},2e3)}),document.getElementById("totp-confirm-setup")?.addEventListener("click",async()=>{const f=doLine truncated
</div>`);async function a(){try{const m=await(await fetch("/api/v1/totp/config")).json();if(!m.success)return;const{enabled:y,sessionDuration:s,isSetUp:h}=m.config,c=document.getElementById("totp-status-dot"),o=document.getElementById("totp-status-text"),p=document.getElementById("totp-status-banner"),i=document.getElementById("totp-setup-section"),e=document.getElementById("totp-qr-section"),n=document.getElementById("totp-duration-section"),d=document.getElementById("totp-disable-section");if(y&&h){c.style.background="var(--ok-fg, #7ef2ff)",p.style.borderColor="var(--ok-fg, #7ef2ff)",p.style.background="color-mix(in srgb, var(--ok-fg) 8%, transparent)",o.textContent="TOTP is active",o.style.color="var(--ok-fg, #7ef2ff)",i.style.display="block";const t=document.getElementById("totp-setup-btn");t&&(t.textContent="Generate New Secret"),e.style.display="none",n.style.display="block",d.style.display="block",document.getElementById("totp-duration-select").value=s}else c.style.background="var(--muted)",p.style.borderColor="var(--border)",p.style.background="transparent",o.textContent="TOTP is not configured",o.style.color="var(--muted)",i.style.display="block",e.style.display="none",n.style.display="none",d.style.display="none";b(y&&h,s)}catch(f){console.warn("Failed to load TOTP settings:",f)}}const g={"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 b(f,m){const y=document.getElementById("auth-card"),s=document.getElementById("auth-pill"),h=document.getElementById("auth-dot"),c=document.getElementById("auth-status-text");y&&(f?(y.setAttribute("data-status","on"),s.className="badge on",s.textContent="YES",h.className="dot ok at-bl",c.textContent="Session: "+(g[m]||m)):(y.setAttribute("data-status","off"),s.className="badge off",s.textContent="NO",h.className="dot bad at-bl",c.textContent="Not configured"))}document.getElementById("totp-setup-btn")?.addEventListener("click",async()=>{try{const m=await(await secureFetch("/api/v1/totp/setup",{method:"POST"})).json();m.success&&(document.getElementById("totp-qr-image").src=m.qrCode,document.getElementById("totp-manual-key").textContent=m.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(f){l.logError("[TOTP] Setup Failed",f,{function:"setupTOTP"})}}),document.getElementById("totp-import-btn")?.addEventListener("click",async()=>{const f=document.getElementById("totp-import-key").value.trim(),m=document.getElementById("totp-import-error");if(m.textContent="",!f){m.textContent="Paste a Base32 secret key first";return}try{const s=await(await secureFetch("/api/v1/totp/setup",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({secret:f})})).json();s.success?(m.textContent="",document.getElementById("totp-qr-image").src=s.qrCode,document.getElementById("totp-manual-key").textContent=s.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()):m.textContent=s.error||s.message||"Import failed"}catch{m.textContent="Connection error \u2014 try refreshing the page"}}),document.getElementById("totp-copy-key")?.addEventListener("click",()=>{const f=document.getElementById("totp-manual-key").textContent;navigator.clipboard.writeText(f).then(()=>{const m=document.getElementById("totp-copy-key");m.textContent="\u2705",setTimeout(()=>{m.textContent="\u{1F4CB}"},2e3)})}),document.getElementById("totp-download-backup")?.addEventListener("click",()=>{const f=document.getElementById("totp-manual-key").textContent.trim();if(!f)return;const m={service:"DashCaddy",type:"totp-secret",secret:f,issuer:"DashCaddy",algorithm:"SHA1",digits:6,period:30,issued:new Date().toISOString(),recovery_url:`${window.location.origin}/ (login screen \u2192 "Lost access?")`,note:'Keep this file somewhere safe. Anyone with this secret can generate your login codes. Use it ONLY to recover TOTP access via the "Lost access?" link on the DashCaddy login screen.'},y=new Blob([JSON.stringify(m,null,2)],{type:"application/json"}),s=URL.createObjectURL(y),h=document.createElement("a");h.href=s,h.download=`dashcaddy-totp-backup-${new Date().toISOString().slice(0,10)}.json`,document.body.appendChild(h),h.click(),document.body.removeChild(h),URL.revokeObjectURL(s);const c=document.getElementById("totp-download-backup");c.textContent="\u2705 Saved",setTimeout(()=>{c.textContent="\u2B07 Download"},2e3)}),document.getElementById("totp-confirm-setup")?.addEventListener("click",async()=>{const f=doLine truncated
<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>
@@ -306,30 +306,30 @@
</div>
</div>
</div>
`);function l(){return Object.keys(SITE.dnsServers||{})}function n(t){return(SITE.dnsServers||{})[t]?.name||t.toUpperCase()}function g(){const t=document.getElementById("dns-cred-sections");if(!t)return;t.innerHTML="";const r=l();if(r.length===0){t.innerHTML='<p style="color: var(--muted); text-align: center; padding: 20px;">No DNS servers configured.</p>';return}for(const h of r)t.insertAdjacentHTML("beforeend",`
`);function l(){return Object.keys(SITE.dnsServers||{})}function a(t){return(SITE.dnsServers||{})[t]?.name||t.toUpperCase()}function g(){const t=document.getElementById("dns-cred-sections");if(!t)return;t.innerHTML="";const r=l();if(r.length===0){t.innerHTML='<p style="color: var(--muted); text-align: center; padding: 20px;">No DNS servers configured.</p>';return}for(const v of r)t.insertAdjacentHTML("beforeend",`
<div class="token-section">
<h4 class="token-section-title">${n(h)}</h4>
<h4 class="token-section-title">${a(v)}</h4>
<div class="token-grid">
<div class="token-field">
<label for="${h}-readonly-username">\u{1F4D6} Read-Only (Logs):</label>
<input type="text" id="${h}-readonly-username" placeholder="Username" autocomplete="off" style="margin-bottom: 4px;" />
<label for="${v}-readonly-username">\u{1F4D6} Read-Only (Logs):</label>
<input type="text" id="${v}-readonly-username" placeholder="Username" autocomplete="off" style="margin-bottom: 4px;" />
<div class="token-input-row">
<input type="password" id="${h}-readonly-token" placeholder="Password" autocomplete="off" />
<button type="button" class="token-toggle" data-target="${h}-readonly-token">\u{1F441}</button>
<input type="password" id="${v}-readonly-token" placeholder="Password" autocomplete="off" />
<button type="button" class="token-toggle" data-target="${v}-readonly-token">\u{1F441}</button>
</div>
</div>
<div class="token-field">
<label for="${h}-admin-username">\u{1F527} Admin:</label>
<input type="text" id="${h}-admin-username" placeholder="Username" autocomplete="off" style="margin-bottom: 4px;" />
<label for="${v}-admin-username">\u{1F527} Admin:</label>
<input type="text" id="${v}-admin-username" placeholder="Username" autocomplete="off" style="margin-bottom: 4px;" />
<div class="token-input-row">
<input type="password" id="${h}-admin-token" placeholder="Password" autocomplete="off" />
<button type="button" class="token-toggle" data-target="${h}-admin-token">\u{1F441}</button>
<input type="password" id="${v}-admin-token" placeholder="Password" autocomplete="off" />
<button type="button" class="token-toggle" data-target="${v}-admin-token">\u{1F441}</button>
</div>
</div>
</div>
<div class="token-status" id="${h}-token-status"></div>
<div class="token-status" id="${v}-token-status"></div>
</div>
`)}function b(){let t=safeSessionGet("dashcaddy-encryption-key");if(t)return t;const r=safeGet("dashcaddy-encryption-key");if(r)return safeSessionSet("dashcaddy-encryption-key",r),safeRemove("dashcaddy-encryption-key"),r;const h=new Uint8Array(32);return crypto.getRandomValues(h),t=Array.from(h,p=>p.toString(16).padStart(2,"0")).join(""),safeSessionSet("dashcaddy-encryption-key",t),t}const f=b();function u(t,r){if(!t)return"";const h=crypto.getRandomValues(new Uint8Array(8)),p=Array.from(h,L=>L.toString(16).padStart(2,"0")).join(""),w=new TextEncoder().encode(r+p);let T="";for(let L=0;L<t.length;L++){const P=t.charCodeAt(L)^w[L%w.length]^h[L%h.length]^L*31+17&255;T+=String.fromCharCode(P)}return p+":"+btoa(T)}function v(t,r){if(!t)return"";try{if(t.indexOf(":")===16){const T=t.substring(0,16),L=new Uint8Array(T.match(/.{2}/g).map($=>parseInt($,16))),P=atob(t.substring(17)),E=new TextEncoder().encode(r+T);let B="";for(let $=0;$<P.length;$++){const C=P.charCodeAt($)^E[$%E.length]^L[$%L.length]^$*31+17&255;B+=String.fromCharCode(C)}return B}const p=atob(t);let w="";for(let T=0;T<p.length;T++){const L=p.charCodeAt(T)^r.charCodeAt(T%r.length);w+=String.fromCharCode(L)}return w}catch{return""}}function s(t,r,h){const p=safeGet(`${t}-${r}-${h}-enc`);return v(p,f)}function y(t,r,h,p){const w=`${t}-${r}-${h}-enc`;p?safeSet(w,u(p,f)):safeRemove(w)}function c(t,r){return s(t,r,"token")}function a(t,r){return s(t,r,"username")}function m(t,r,h){y(t,r,"token",h)}function i(t,r,h){y(t,r,"username",h)}function e(){const t={};for(const r of l())t[r]={readonly:{username:a(r,"readonly"),token:c(r,"readonly")},admin:{username:a(r,"admin"),token:c(r,"admin")}};return t}function o(){l().forEach(t=>{["readonly","admin"].forEach(r=>{["token","username"].forEach(h=>{safeRemove(`${t}-${r}-${h}-enc`)})}),safeRemove(`${t}-token-enc`),safeRemove(`${t}-username-enc`)})}function d(t){const r=c(t,"readonly"),h=a(t,"readonly"),p=c(t,"admin"),w=a(t,"admin"),T=v(safeGet(`${t}-token-enc`),f),L=v(safeGet(`${t}-username-enc`),f);return{username:w||h||L,token:p||r||T,readonlyToken:r||T,readonlyUsername:h||L,adminToken:p||T,adminUsername:w||L}}document.getElementById("manage-tokens")?.addEventListener("click",()=>{g();const t=document.getElementById("token-management-modal"),r=e();l().forEach(h=>{const p=r[h];document.getElementById(`${h}-readonly-username`).value=p.readonly.username,document.getElementById(`${h}-readonly-token`).value=p.readonly.token,document.getElementById(`${h}-admin-username`).value=p.admin.username,document.getElementById(`${h}-admin-token`).value=p.admin.token,document.getElementById(`${h}-token-status`).textContent=""}),t.classList.add("show")}),document.getElementById("token-management-modal")?.addEventListener("click",t=>{const r=t.target.closest(".token-toggle");if(r){const h=r.dataset.target,p=document.getElementById(h);p.type==="password"?(p.type="text",r.textContent="\u{1F648}"):(p.type="password",r.textContent="\u{1F441}");return}t.target.id==="token-management-modal"&&t.target.classList.remove("show")}),document.getElementById("token-save")?.addEventListener("click",async()=>{const t=l();t.forEach(p=>{i(p,"readonly",document.getElementById(`${p}-readonly-username`).value.trim()),m(p,"readonly",document.getElementById(`${p}-readonly-token`).value.trim()),i(p,"admin",document.getElementById(`${p}-admin-username`).value.trim()),m(p,"admin",document.getElementById(`${p}-admin-token`).value.trim())});const r={};let h=!1;if(t.forEach(p=>{const w={},T=document.getElementById(`${p}-readonly-username`).value.trim(),L=document.getElementById(`${p}-readonly-token`).value.trim(),P=document.getElementById(`${p}-admin-username`).value.trim(),E=document.getElementById(`${p}-admin-token`).value.trim();T&&L&&(w.readonly={username:T,password:L},h=!0),P&&E&&(w.admin={username:P,password:E},h=!0),Object.keys(w).length>0&&(r[p]=w)}),h){t.forEach(p=>{r[p]&&(document.getElementById(`${p}-token-status`).textContent="Verifying...",document.getElementById(`${p}-token-status`).className="token-status")});try{const w=await(await secureFetch("/api/v1/dns/credentials",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({servers:r})})).json();w.results?t.forEach(T=>{const L=document.getElementById(`${T}-token-status`);if(!r[T]){L.textContent="";return}const P=w.results[T];P?.success?(L.textContent="\u2713 Verified & saved",L.className="token-status success"):P?.partial?(L.textContent="\u2713 "+P.partial,L.className="token-status success"):(L.textContent="\u2717 "+(P?.error||"Login failed"),L.className="token-status error")}):w.success?t.forEach(T=>{r[T]&&(document.getElementById(`${T}-token-status`).textContent="\u2713 Saved",document.getElementById(`${T}-token-status`).className="token-status success")}):t.forEach(T=>{r[T]&&(document.getElementById(`${T}-token-status`).textContent="\u2717 "+(w.error||"Failed"),document.getElementById(`${T}-token-status`).className="token-status error")})}catch(p){console.erro Line truncated
`)}function b(){let t=safeSessionGet("dashcaddy-encryption-key");if(t)return t;const r=safeGet("dashcaddy-encryption-key");if(r)return safeSessionSet("dashcaddy-encryption-key",r),safeRemove("dashcaddy-encryption-key"),r;const v=new Uint8Array(32);return crypto.getRandomValues(v),t=Array.from(v,u=>u.toString(16).padStart(2,"0")).join(""),safeSessionSet("dashcaddy-encryption-key",t),t}const f=b();function m(t,r){if(!t)return"";const v=crypto.getRandomValues(new Uint8Array(8)),u=Array.from(v,L=>L.toString(16).padStart(2,"0")).join(""),w=new TextEncoder().encode(r+u);let T="";for(let L=0;L<t.length;L++){const P=t.charCodeAt(L)^w[L%w.length]^v[L%v.length]^L*31+17&255;T+=String.fromCharCode(P)}return u+":"+btoa(T)}function y(t,r){if(!t)return"";try{if(t.indexOf(":")===16){const T=t.substring(0,16),L=new Uint8Array(T.match(/.{2}/g).map($=>parseInt($,16))),P=atob(t.substring(17)),E=new TextEncoder().encode(r+T);let B="";for(let $=0;$<P.length;$++){const C=P.charCodeAt($)^E[$%E.length]^L[$%L.length]^$*31+17&255;B+=String.fromCharCode(C)}return B}const u=atob(t);let w="";for(let T=0;T<u.length;T++){const L=u.charCodeAt(T)^r.charCodeAt(T%r.length);w+=String.fromCharCode(L)}return w}catch{return""}}function s(t,r,v){const u=safeGet(`${t}-${r}-${v}-enc`);return y(u,f)}function h(t,r,v,u){const w=`${t}-${r}-${v}-enc`;u?safeSet(w,m(u,f)):safeRemove(w)}function c(t,r){return s(t,r,"token")}function o(t,r){return s(t,r,"username")}function p(t,r,v){h(t,r,"token",v)}function i(t,r,v){h(t,r,"username",v)}function e(){const t={};for(const r of l())t[r]={readonly:{username:o(r,"readonly"),token:c(r,"readonly")},admin:{username:o(r,"admin"),token:c(r,"admin")}};return t}function n(){l().forEach(t=>{["readonly","admin"].forEach(r=>{["token","username"].forEach(v=>{safeRemove(`${t}-${r}-${v}-enc`)})}),safeRemove(`${t}-token-enc`),safeRemove(`${t}-username-enc`)})}function d(t){const r=c(t,"readonly"),v=o(t,"readonly"),u=c(t,"admin"),w=o(t,"admin"),T=y(safeGet(`${t}-token-enc`),f),L=y(safeGet(`${t}-username-enc`),f);return{username:w||v||L,token:u||r||T,readonlyToken:r||T,readonlyUsername:v||L,adminToken:u||T,adminUsername:w||L}}document.getElementById("manage-tokens")?.addEventListener("click",()=>{g();const t=document.getElementById("token-management-modal"),r=e();l().forEach(v=>{const u=r[v];document.getElementById(`${v}-readonly-username`).value=u.readonly.username,document.getElementById(`${v}-readonly-token`).value=u.readonly.token,document.getElementById(`${v}-admin-username`).value=u.admin.username,document.getElementById(`${v}-admin-token`).value=u.admin.token,document.getElementById(`${v}-token-status`).textContent=""}),t.classList.add("show")}),document.getElementById("token-management-modal")?.addEventListener("click",t=>{const r=t.target.closest(".token-toggle");if(r){const v=r.dataset.target,u=document.getElementById(v);u.type==="password"?(u.type="text",r.textContent="\u{1F648}"):(u.type="password",r.textContent="\u{1F441}");return}t.target.id==="token-management-modal"&&t.target.classList.remove("show")}),document.getElementById("token-save")?.addEventListener("click",async()=>{const t=l();t.forEach(u=>{i(u,"readonly",document.getElementById(`${u}-readonly-username`).value.trim()),p(u,"readonly",document.getElementById(`${u}-readonly-token`).value.trim()),i(u,"admin",document.getElementById(`${u}-admin-username`).value.trim()),p(u,"admin",document.getElementById(`${u}-admin-token`).value.trim())});const r={};let v=!1;if(t.forEach(u=>{const w={},T=document.getElementById(`${u}-readonly-username`).value.trim(),L=document.getElementById(`${u}-readonly-token`).value.trim(),P=document.getElementById(`${u}-admin-username`).value.trim(),E=document.getElementById(`${u}-admin-token`).value.trim();T&&L&&(w.readonly={username:T,password:L},v=!0),P&&E&&(w.admin={username:P,password:E},v=!0),Object.keys(w).length>0&&(r[u]=w)}),v){t.forEach(u=>{r[u]&&(document.getElementById(`${u}-token-status`).textContent="Verifying...",document.getElementById(`${u}-token-status`).className="token-status")});try{const w=await(await secureFetch("/api/v1/dns/credentials",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({servers:r})})).json();w.results?t.forEach(T=>{const L=document.getElementById(`${T}-token-status`);if(!r[T]){L.textContent="";return}const P=w.results[T];P?.success?(L.textContent="\u2713 Verified & saved",L.className="token-status success"):P?.partial?(L.textContent="\u2713 "+P.partial,L.className="token-status success"):(L.textContent="\u2717 "+(P?.error||"Login failed"),L.className="token-status error")}):w.success?t.forEach(T=>{r[T]&&(document.getElementById(`${T}-token-status`).textContent="\u2713 Saved",document.getElementById(`${T}-token-status`).className="token-status success")}):t.forEach(T=>{r[T]&&(document.getElementById(`${T}-token-status`).textContent="\u2717 "+(w.error||"Failed"),document.getElementById(`${T}-token-status`).className="token-status error")})}catch(u){console.erro Line truncated
Current: ${i.currentVersion}
New: ${i.updateVersion}
@@ -337,9 +337,9 @@ New: ${i.updateVersion}
`+(i.updateTitle?`${i.updateTitle}
`:"")+`The DNS server will restart during the update.
Proceed?`)){c.textContent=a,c.disabled=!1,c.title="Update DNS server";return}c.textContent="\u{1F504}",c.title="Updating...";const d=await(await secureFetch(`/api/v1/dns/update?server=${encodeURIComponent(y)}`,{method:"POST"})).json();if(!d.success)throw new Error(d.error||"Update failed");if(d.manualUpdateRequired){c.textContent="\u2B06\uFE0F",c.title=`Update available: ${d.newVersion}`;const t=d.downloadLink?`
Proceed?`)){c.textContent=o,c.disabled=!1,c.title="Update DNS server";return}c.textContent="\u{1F504}",c.title="Updating...";const d=await(await secureFetch(`/api/v1/dns/update?server=${encodeURIComponent(h)}`,{method:"POST"})).json();if(!d.success)throw new Error(d.error||"Update failed");if(d.manualUpdateRequired){c.textContent="\u2B06\uFE0F",c.title=`Update available: ${d.newVersion}`;const t=d.downloadLink?`
Download: ${d.downloadLink}`:"",r=d.instructionsLink?`
Instructions: ${d.instructionsLink}`:"";showNotification(`${s.toUpperCase()} update requires manual installation. Current: ${d.previousVersion} \u2192 ${d.newVersion}. Please update manually on the host machine.`,"warning",8e3),c.disabled=!1;return}c.textContent="\u2705",c.title="Updated successfully!",showNotification(`${s.toUpperCase()} updated successfully! ${d.previousVersion} \u2192 ${d.newVersion}. Server is restarting...`,"success"),setTimeout(()=>{c.textContent=a,c.disabled=!1,c.title="Update DNS server",window.refreshAll()},1e4)}catch(m){console.error("DNS update error:",m),c.textContent="\u274C",c.title="Update failed",showNotification(`Failed to update ${s.toUpperCase()}: ${m.message}`,"error"),setTimeout(()=>{c.textContent=a,c.disabled=!1,c.title="Update DNS server"},3e3)}}document.querySelector(".top")?.addEventListener("click",s=>{const y=s.target.closest('[id$="-update"]');if(!y)return;const c=y.id.replace("-update","");SITE.dnsServers[c]&&n(c,SITE.dnsServers[c]?.ip)}),injectModal("dns-settings-modal",`
Instructions: ${d.instructionsLink}`:"";showNotification(`${s.toUpperCase()} update requires manual installation. Current: ${d.previousVersion} \u2192 ${d.newVersion}. Please update manually on the host machine.`,"warning",8e3),c.disabled=!1;return}c.textContent="\u2705",c.title="Updated successfully!",showNotification(`${s.toUpperCase()} updated successfully! ${d.previousVersion} \u2192 ${d.newVersion}. Server is restarting...`,"success"),setTimeout(()=>{c.textContent=o,c.disabled=!1,c.title="Update DNS server",window.refreshAll()},1e4)}catch(p){console.error("DNS update error:",p),c.textContent="\u274C",c.title="Update failed",showNotification(`Failed to update ${s.toUpperCase()}: ${p.message}`,"error"),setTimeout(()=>{c.textContent=o,c.disabled=!1,c.title="Update DNS server"},3e3)}}document.querySelector(".top")?.addEventListener("click",s=>{const h=s.target.closest('[id$="-update"]');if(!h)return;const c=h.id.replace("-update","");SITE.dnsServers[c]&&a(c,SITE.dnsServers[c]?.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>
@@ -366,7 +366,7 @@ Instructions: ${d.instructionsLink}`:"";showNotification(`${s.toUpperCase()} upd
<button id="dns-settings-save" class="btn-accent">Save</button>
</div>
</div>
</div>`);let g=null;function b(s){g=s;const y=SITE.dnsServers[s]||{},c=document.getElementById("dns-settings-modal");document.getElementById("dns-settings-title").textContent=`${(y.name||s).toUpperCase()} Settings`,document.getElementById("dns-edit-ip").value=y.ip||"",document.getElementById("dns-edit-port").value=y.port||DC.DEFAULTS.DNS_PORT,document.getElementById("dns-edit-name").value=y.name||"",c.classList.add("show")}async function f(){if(!g)return;const s=document.getElementById("dns-edit-ip").value.trim(),y=document.getElementById("dns-edit-port").value.trim()||DC.DEFAULTS.DNS_PORT,c=document.getElementById("dns-edit-name").value.trim();if(!s){showNotification("Server IP is required","warning");return}const a={dnsServers:{}};a.dnsServers[g]={ip:s,port:String(y)},c&&(a.dnsServers[g].name=c);try{const i=await(await secureFetch("/api/v1/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)})).json();i.success?(SITE.dnsServers[g]=a.dnsServers[g],showNotification(`${g.toUpperCase()} settings saved`,"success"),v(),window.refreshAll()):showNotification(i.error||"Failed to save settings","error")}catch(m){showNotification("Failed to save: "+m.message,"error")}}async function u(){if(g&&confirm(`Remove ${g.toUpperCase()} from dashboard? This won't affect the actual DNS server.`))try{const y=await(await secureFetch("/api/v1/config")).json();y.dnsServers&&delete y.dnsServers[g];const a=await(await secureFetch("/api/v1/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({dnsServers:y.dnsServers||{}})})).json();if(a.success){delete SITE.dnsServers[g];const m=document.querySelector(`.top [data-app="${g}"]`);m&&m.remove(),showNotification(`${g.toUpperCase()} removed from dashboard`,"success"),v()}else showNotification(a.error||"Failed to remove","error")}catch(s){showNotification("Failed to remove: "+s.message,"error")}}function v(){closeModal("dns-settings-modal"),g=null}document.getElementById("dns-settings-cancel")?.addEventListener("click",v),document.getElementById("dns-settings-save")?.addEventListener("click",f),document.getElementById("dns-settings-delete")?.addEventListener("click",u),document.getElementById("dns-settings-modal")?.addEventListener("click",s=>{s.target.id==="dns-settings-modal"&&v()}),document.querySelector(".top")?.addEventListener("click",s=>{const y=s.target.closest('[id$="-settings"]');if(!y)return;const c=y.id.replace("-settings","");SITE.dnsServers[c]&&(s.stopPropagation(),b(c))}),document.getElementById("refresh")?.addEventListener("click",window.refreshAll)})(),(function(){injectModal("logs-modal",`
</div>`);let g=null;function b(s){g=s;const h=SITE.dnsServers[s]||{},c=document.getElementById("dns-settings-modal");document.getElementById("dns-settings-title").textContent=`${(h.name||s).toUpperCase()} Settings`,document.getElementById("dns-edit-ip").value=h.ip||"",document.getElementById("dns-edit-port").value=h.port||DC.DEFAULTS.DNS_PORT,document.getElementById("dns-edit-name").value=h.name||"",c.classList.add("show")}async function f(){if(!g)return;const s=document.getElementById("dns-edit-ip").value.trim(),h=document.getElementById("dns-edit-port").value.trim()||DC.DEFAULTS.DNS_PORT,c=document.getElementById("dns-edit-name").value.trim();if(!s){showNotification("Server IP is required","warning");return}const o={dnsServers:{}};o.dnsServers[g]={ip:s,port:String(h)},c&&(o.dnsServers[g].name=c);try{const i=await(await secureFetch("/api/v1/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)})).json();i.success?(SITE.dnsServers[g]=o.dnsServers[g],showNotification(`${g.toUpperCase()} settings saved`,"success"),y(),window.refreshAll()):showNotification(i.error||"Failed to save settings","error")}catch(p){showNotification("Failed to save: "+p.message,"error")}}async function m(){if(g&&confirm(`Remove ${g.toUpperCase()} from dashboard? This won't affect the actual DNS server.`))try{const h=await(await secureFetch("/api/v1/config")).json();h.dnsServers&&delete h.dnsServers[g];const o=await(await secureFetch("/api/v1/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({dnsServers:h.dnsServers||{}})})).json();if(o.success){delete SITE.dnsServers[g];const p=document.querySelector(`.top [data-app="${g}"]`);p&&p.remove(),showNotification(`${g.toUpperCase()} removed from dashboard`,"success"),y()}else showNotification(o.error||"Failed to remove","error")}catch(s){showNotification("Failed to remove: "+s.message,"error")}}function y(){closeModal("dns-settings-modal"),g=null}document.getElementById("dns-settings-cancel")?.addEventListener("click",y),document.getElementById("dns-settings-save")?.addEventListener("click",f),document.getElementById("dns-settings-delete")?.addEventListener("click",m),document.getElementById("dns-settings-modal")?.addEventListener("click",s=>{s.target.id==="dns-settings-modal"&&y()}),document.querySelector(".top")?.addEventListener("click",s=>{const h=s.target.closest('[id$="-settings"]');if(!h)return;const c=h.id.replace("-settings","");SITE.dnsServers[c]&&(s.stopPropagation(),b(c))}),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">
@@ -390,13 +390,13 @@ Instructions: ${d.instructionsLink}`:"";showNotification(`${s.toUpperCase()} upd
</div>
</div>
</div>
</div>`);let l=null,n=null,g=!1,b=null,f=null,u=!1,v=null,s=null,y=!1,c=null,a=!1;async function m(C,x=25){try{const I=getDnsServerAddr(C),k=await fetch(`/api/v1/dns/logs?server=${I}&limit=${x}`,{cache:"no-store",headers:{Accept:"application/json","Cache-Control":"no-cache"}});if(k.ok){const S=await k.json();return S.success&&S.logs?{logs:S.logs,count:S.count,server:S.server}:{error:S.error||"Failed to fetch logs"}}else return k.status===401?{error:"DNS auto-auth failed - check credentials in settings"}:{error:`HTTP ${k.status}`}}catch(I){return console.error("DNS logs fetch failed:",I),{error:I.message}}}function i(C){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"}[C]||"var(--fg)"}function e(C){const x=document.createElement("div");if(x.className="log-entry",x.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;",C.parsed===!1)return x.style.gridTemplateColumns="1fr",x.innerHTML=`<span style="color: var(--muted); font-family: monospace; font-size: 0.75rem;">${escapeHtml(C.raw)}</span>`,x;const I=i(C.rcode),k=C.rcode==="Refused"||C.rcode==="REFUSED";return x.innerHTML=`
</div>`);let l=null,a=null,g=!1,b=null,f=null,m=!1,y=null,s=null,h=!1,c=null,o=!1;async function p(C,x=25){try{const I=getDnsServerAddr(C),k=await fetch(`/api/v1/dns/logs?server=${I}&limit=${x}`,{cache:"no-store",headers:{Accept:"application/json","Cache-Control":"no-cache"}});if(k.ok){const S=await k.json();return S.success&&S.logs?{logs:S.logs,count:S.count,server:S.server}:{error:S.error||"Failed to fetch logs"}}else return k.status===401?{error:"DNS auto-auth failed - check credentials in settings"}:{error:`HTTP ${k.status}`}}catch(I){return console.error("DNS logs fetch failed:",I),{error:I.message}}}function i(C){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"}[C]||"var(--fg)"}function e(C){const x=document.createElement("div");if(x.className="log-entry",x.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;",C.parsed===!1)return x.style.gridTemplateColumns="1fr",x.innerHTML=`<span style="color: var(--muted); font-family: monospace; font-size: 0.75rem;">${escapeHtml(C.raw)}</span>`,x;const I=i(C.rcode),k=C.rcode==="Refused"||C.rcode==="REFUSED";return x.innerHTML=`
<span style="color: var(--muted); font-size: 0.75rem;">${escapeHtml(C.timestamp)}</span>
<span style="color: var(--accent); font-size: 0.75rem;" title="${escapeHtml(C.client)}">${escapeHtml(C.client)}</span>
<span style="font-weight: 500; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; ${k?"text-decoration: line-through; opacity: 0.6;":""}" title="${escapeHtml(C.domain)}">${escapeHtml(C.domain)}</span>
<span style="color: var(--muted); font-size: 0.75rem;">${escapeHtml(C.type)}</span>
<span style="color: ${I}; font-weight: 500; font-size: 0.75rem;">${escapeHtml(C.rcode)}</span>
`,x}async function o(){if(y){await B();return}if(u){await T();return}if(g||!l)return;const C=parseInt(document.getElementById("log-lines").value),x=document.getElementById("logs-content");try{const I=await m(l,C);if(I.error){x.innerHTML=`
`,x}async function n(){if(h){await B();return}if(m){await T();return}if(g||!l)return;const C=parseInt(document.getElementById("log-lines").value),x=document.getElementById("logs-content");try{const I=await p(l,C);if(I.error){x.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>
@@ -413,13 +413,13 @@ Instructions: ${d.instructionsLink}`:"";showNotification(`${s.toUpperCase()} upd
</div>`}catch(I){x.innerHTML=`
<div style="padding: 20px; text-align: center; color: var(--bad-fg);">
Failed to fetch logs: ${escapeHtml(I.message)}
</div>`}}function d(C){l=C,g=!1,u=!1;const x=document.getElementById("logs-modal"),I=document.getElementById("logs-title"),k=document.getElementById("logs-pause"),S=document.getElementById("logs-stream");I.textContent=`${C.toUpperCase()} DNS Logs`,k.textContent="\u23F8\uFE0F Pause",k.classList.remove("paused"),S&&(S.style.display="none"),x.classList.add("show"),o(),n=setInterval(o,DC.POLL.LOGS)}function t(){document.getElementById("logs-modal").classList.remove("show"),n&&(clearInterval(n),n=null),h(),l=null,u=!1,b=null,f=null,y=!1,v=null,s=null,g=!1}function r(C){c&&h();const x=document.getElementById("logs-stream"),I=document.getElementById("logs-pause"),k=document.getElementById("logs-content");n&&(clearInterval(n),n=null);try{c=new EventSource(`/api/v1/logs/stream/${C}`),a=!0,x.classList.add("active"),x.textContent="\u{1F534} Live",x.title="Streaming - click to stop",I.style.display="none";const S=document.getElementById("logs-title");S.textContent.includes("\u{1F534}")||(S.innerHTML=S.textContent.replace("\u{1F4CB}","\u{1F4CB} \u{1F534}")),c.onmessage=A=>{try{const D=JSON.parse(A.data);if(D.error){console.error("Stream error:",D.error),h();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",N=R?"var(--bad-fg)":"var(--fg)",_=`<span style="background: ${R?"var(--bad-bg)":"var(--ok-bg)"}; color: ${N}; 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>`}}function d(C){l=C,g=!1,m=!1;const x=document.getElementById("logs-modal"),I=document.getElementById("logs-title"),k=document.getElementById("logs-pause"),S=document.getElementById("logs-stream");I.textContent=`${C.toUpperCase()} DNS Logs`,k.textContent="\u23F8\uFE0F Pause",k.classList.remove("paused"),S&&(S.style.display="none"),x.classList.add("show"),n(),a=setInterval(n,DC.POLL.LOGS)}function t(){document.getElementById("logs-modal").classList.remove("show"),a&&(clearInterval(a),a=null),v(),l=null,m=!1,b=null,f=null,h=!1,y=null,s=null,g=!1}function r(C){c&&v();const x=document.getElementById("logs-stream"),I=document.getElementById("logs-pause"),k=document.getElementById("logs-content");a&&(clearInterval(a),a=null);try{c=new EventSource(`/api/v1/logs/stream/${C}`),o=!0,x.classList.add("active"),x.textContent="\u{1F534} Live",x.title="Streaming - click to stop",I.style.display="none";const S=document.getElementById("logs-title");S.textContent.includes("\u{1F534}")||(S.innerHTML=S.textContent.replace("\u{1F4CB}","\u{1F4CB} \u{1F534}")),c.onmessage=A=>{try{const D=JSON.parse(A.data);if(D.error){console.error("Stream error:",D.error),v();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",N=R?"var(--bad-fg)":"var(--fg)",_=`<span style="background: ${R?"var(--bad-bg)":"var(--ok-bg)"}; color: ${N}; 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;">${_}</div>
<div style="flex: 1; color: ${N}; word-break: break-all; white-space: pre-wrap;">${escapeHtml(D.text)}</div>
`,k.appendChild(O),k.scrollTop=k.scrollHeight;k.children.length>500;)k.removeChild(k.firstChild)}catch(D){console.error("Error parsing stream data:",D)}},c.onerror=A=>{console.error("EventSource error:",A),h()}}catch(S){console.error("Failed to start streaming:",S),h()}}function h(){c&&(c.close(),c=null),a=!1;const C=document.getElementById("logs-stream"),x=document.getElementById("logs-pause"),I=document.getElementById("logs-title");C&&(C.classList.remove("active"),C.textContent="\u{1F4E1} Live",C.title="Enable real-time streaming"),x&&(x.style.display=""),I&&(I.textContent=I.textContent.replace(" \u{1F534}","")),u&&b&&!n&&(n=setInterval(T,DC.POLL.LOGS))}async function p(C,x=100){try{const I=`/api/v1/logs/container/${C}?tail=${x}&timestamps=true`,k=await fetch(I,{cache:"no-store",headers:{Accept:"application/json","Cache-Control":"no-cache"}});if(k.ok){const S=await k.json();return S.success&&S.logs?{logs:S.logs,count:S.count,containerName:S.containerName,containerId:S.containerId}:{error:S.error||"Failed to fetch container logs"}}else return{error:`HTTP ${k.status}: ${k.statusText}`}}catch(I){return console.error("Container logs fetch failed:",I),{error:I.message}}}function w(C){const x=document.createElement("div");x.className="log-entry",x.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=C.stream==="stderr"?"var(--bad-fg)":"var(--fg)",k=C.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 x.innerHTML=`
`,k.appendChild(O),k.scrollTop=k.scrollHeight;k.children.length>500;)k.removeChild(k.firstChild)}catch(D){console.error("Error parsing stream data:",D)}},c.onerror=A=>{console.error("EventSource error:",A),v()}}catch(S){console.error("Failed to start streaming:",S),v()}}function v(){c&&(c.close(),c=null),o=!1;const C=document.getElementById("logs-stream"),x=document.getElementById("logs-pause"),I=document.getElementById("logs-title");C&&(C.classList.remove("active"),C.textContent="\u{1F4E1} Live",C.title="Enable real-time streaming"),x&&(x.style.display=""),I&&(I.textContent=I.textContent.replace(" \u{1F534}","")),m&&b&&!a&&(a=setInterval(T,DC.POLL.LOGS))}async function u(C,x=100){try{const I=`/api/v1/logs/container/${C}?tail=${x}&timestamps=true`,k=await fetch(I,{cache:"no-store",headers:{Accept:"application/json","Cache-Control":"no-cache"}});if(k.ok){const S=await k.json();return S.success&&S.logs?{logs:S.logs,count:S.count,containerName:S.containerName,containerId:S.containerId}:{error:S.error||"Failed to fetch container logs"}}else return{error:`HTTP ${k.status}: ${k.statusText}`}}catch(I){return console.error("Container logs fetch failed:",I),{error:I.message}}}function w(C){const x=document.createElement("div");x.className="log-entry",x.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=C.stream==="stderr"?"var(--bad-fg)":"var(--fg)",k=C.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 x.innerHTML=`
<div style="flex-shrink: 0;">${k}</div>
<div style="flex: 1; color: ${I}; word-break: break-all; white-space: pre-wrap;">${escapeHtml(C.text)}</div>
`,x}async function T(){if(g||!b||!u)return;const C=parseInt(document.getElementById("log-lines").value),x=document.getElementById("logs-content");try{const I=await p(b,C);if(I.error){x.innerHTML=`
`,x}async function T(){if(g||!b||!m)return;const C=parseInt(document.getElementById("log-lines").value),x=document.getElementById("logs-content");try{const I=await u(b,C);if(I.error){x.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>
@@ -433,10 +433,10 @@ Instructions: ${d.instructionsLink}`:"";showNotification(`${s.toUpperCase()} upd
</div>`}catch(I){x.innerHTML=`
<div style="padding: 20px; text-align: center; color: var(--bad-fg);">
Failed to fetch logs: ${escapeHtml(I.message)}
</div>`}}function L(C,x){b=C,f=x,u=!0,y=!1,g=!1,h();const I=document.getElementById("logs-modal"),k=document.getElementById("logs-title"),S=document.getElementById("logs-pause"),A=document.getElementById("logs-stream");k.textContent=`\u{1F4CB} ${x} - Container Logs`,S.textContent="\u23F8\uFE0F Pause",S.classList.remove("paused"),A&&(A.style.display=""),I.classList.add("show"),T(),n=setInterval(T,DC.POLL.LOGS)}async function P(C,x=100){try{const I=`/api/v1/logs/file?path=${encodeURIComponent(C)}&tail=${x}`,k=await fetch(I,{cache:"no-store",headers:{Accept:"application/json","Cache-Control":"no-cache"}});if(k.ok){const S=await k.json();return S.success&&S.logs?{logs:S.logs,count:S.count,logPath:S.logPath,totalLines:S.totalLines}:{error:S.error||"Failed to fetch file logs"}}else return{error:(await k.json().catch(()=>({}))).error||`HTTP ${k.status}`}}catch(I){return console.error("File logs fetch failed:",I),{error:I.message}}}function E(C){const x=document.createElement("div");x.className="log-entry",x.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=C.text;let k="INFO",S="var(--fg)";I.match(/ERROR|FATAL|CRITICAL/i)?(k="ERROR",S="var(--bad-fg)"):I.match(/WARN|WARNING/i)?(k="WARN",S="#f39c12"):I.match(/DEBUG/i)&&(k="DEBUG",S="var(--muted)");const D=`<span style="background: ${S==="var(--bad-fg)"?"var(--bad-bg)":"var(--ok-bg)"}; color: ${S}; padding: 2px 6px; border-radius: 4px; font-size: 0.7rem; font-weight: 600; min-width: 50px; text-align: center;">${k}</span>`;return x.innerHTML=`
</div>`}}function L(C,x){b=C,f=x,m=!0,h=!1,g=!1,v();const I=document.getElementById("logs-modal"),k=document.getElementById("logs-title"),S=document.getElementById("logs-pause"),A=document.getElementById("logs-stream");k.textContent=`\u{1F4CB} ${x} - Container Logs`,S.textContent="\u23F8\uFE0F Pause",S.classList.remove("paused"),A&&(A.style.display=""),I.classList.add("show"),T(),a=setInterval(T,DC.POLL.LOGS)}async function P(C,x=100){try{const I=`/api/v1/logs/file?path=${encodeURIComponent(C)}&tail=${x}`,k=await fetch(I,{cache:"no-store",headers:{Accept:"application/json","Cache-Control":"no-cache"}});if(k.ok){const S=await k.json();return S.success&&S.logs?{logs:S.logs,count:S.count,logPath:S.logPath,totalLines:S.totalLines}:{error:S.error||"Failed to fetch file logs"}}else return{error:(await k.json().catch(()=>({}))).error||`HTTP ${k.status}`}}catch(I){return console.error("File logs fetch failed:",I),{error:I.message}}}function E(C){const x=document.createElement("div");x.className="log-entry",x.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=C.text;let k="INFO",S="var(--fg)";I.match(/ERROR|FATAL|CRITICAL/i)?(k="ERROR",S="var(--bad-fg)"):I.match(/WARN|WARNING/i)?(k="WARN",S="#f39c12"):I.match(/DEBUG/i)&&(k="DEBUG",S="var(--muted)");const D=`<span style="background: ${S==="var(--bad-fg)"?"var(--bad-bg)":"var(--ok-bg)"}; color: ${S}; padding: 2px 6px; border-radius: 4px; font-size: 0.7rem; font-weight: 600; min-width: 50px; text-align: center;">${k}</span>`;return x.innerHTML=`
<div style="flex-shrink: 0;">${D}</div>
<div style="flex: 1; color: ${S}; word-break: break-all; white-space: pre-wrap;">${escapeHtml(I)}</div>
`,x}async function B(){if(g||!v||!y)return;const C=parseInt(document.getElementById("log-lines").value),x=document.getElementById("logs-content");try{const I=await P(v,C);if(I.error){x.innerHTML=`
`,x}async function B(){if(g||!y||!h)return;const C=parseInt(document.getElementById("log-lines").value),x=document.getElementById("logs-content");try{const I=await P(y,C);if(I.error){x.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>
@@ -449,7 +449,7 @@ Instructions: ${d.instructionsLink}`:"";showNotification(`${s.toUpperCase()} upd
</div>`}catch(I){x.innerHTML=`
<div style="padding: 20px; text-align: center; color: var(--bad-fg);">
Failed to fetch logs: ${escapeHtml(I.message)}
</div>`}}function $(C,x){v=C,s=x,y=!0,u=!1,g=!1;const I=document.getElementById("logs-modal"),k=document.getElementById("logs-title"),S=document.getElementById("logs-pause"),A=document.getElementById("logs-stream");k.textContent=`\u{1F4CB} ${x} - Application Logs`,S.textContent="\u23F8\uFE0F Pause",S.classList.remove("paused"),A&&(A.style.display="none"),I.classList.add("show"),B(),n=setInterval(B,DC.POLL.LOGS)}document.querySelector(".top")?.addEventListener("click",C=>{const x=C.target.closest('[id$="-logs"]');if(!x)return;const I=x.id.replace("-logs","");SITE.dnsServers[I]&&d(I)}),document.getElementById("logs-close")?.addEventListener("click",t),document.getElementById("logs-pause")?.addEventListener("click",()=>{g=!g;const C=document.getElementById("logs-pause");g?(C.textContent="\u25B6\uFE0F Resume",C.classList.add("paused")):(C.textContent="\u23F8\uFE0F Pause",C.classList.remove("paused"),o())}),document.getElementById("log-lines")?.addEventListener("change",()=>{g||o()}),document.getElementById("logs-stream")?.addEventListener("click",()=>{!u||!b||(a?h():r(b))}),document.getElementById("logs-modal")?.addEventListener("click",C=>{C.target.id==="logs-modal"&&t()}),document.addEventListener("keydown",C=>{C.key==="Escape"&&document.getElementById("logs-modal")?.classList.contains("show")&&t()}),window.openContainerLogsModal=L,window.openFileLogsModal=$,window.openLogsModal=d})(),(function(){injectModal("service-edit-modal",`
</div>`}}function $(C,x){y=C,s=x,h=!0,m=!1,g=!1;const I=document.getElementById("logs-modal"),k=document.getElementById("logs-title"),S=document.getElementById("logs-pause"),A=document.getElementById("logs-stream");k.textContent=`\u{1F4CB} ${x} - Application Logs`,S.textContent="\u23F8\uFE0F Pause",S.classList.remove("paused"),A&&(A.style.display="none"),I.classList.add("show"),B(),a=setInterval(B,DC.POLL.LOGS)}document.querySelector(".top")?.addEventListener("click",C=>{const x=C.target.closest('[id$="-logs"]');if(!x)return;const I=x.id.replace("-logs","");SITE.dnsServers[I]&&d(I)}),document.getElementById("logs-close")?.addEventListener("click",t),document.getElementById("logs-pause")?.addEventListener("click",()=>{g=!g;const C=document.getElementById("logs-pause");g?(C.textContent="\u25B6\uFE0F Resume",C.classList.add("paused")):(C.textContent="\u23F8\uFE0F Pause",C.classList.remove("paused"),n())}),document.getElementById("log-lines")?.addEventListener("change",()=>{g||n()}),document.getElementById("logs-stream")?.addEventListener("click",()=>{!m||!b||(o?v():r(b))}),document.getElementById("logs-modal")?.addEventListener("click",C=>{C.target.id==="logs-modal"&&t()}),document.addEventListener("keydown",C=>{C.key==="Escape"&&document.getElementById("logs-modal")?.classList.contains("show")&&t()}),window.openContainerLogsModal=L,window.openFileLogsModal=$,window.openLogsModal=d})(),(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>
@@ -805,44 +805,44 @@ Instructions: ${d.instructionsLink}`:"";showNotification(`${s.toUpperCase()} upd
<button id="add-service-create" class="btn-accent">Create Service</button>
</div>
</div>
</div>`)})(),(function(){async function l(u){try{const v=await fetch(`/api/v1/caddy/cas?caddyfilePath=${encodeURIComponent(u)}`);if(!v.ok)throw new Error(`Failed to load CAs: ${v.status}`);const s=await v.json();if(s.success){const y=document.getElementById("existing-ca-select");return y.innerHTML="",s.cas.length===0?y.innerHTML='<option value="">No CAs found in Caddyfile</option>':(y.innerHTML='<option value="">Select existing CA...</option>',s.cas.forEach(c=>{const a=document.createElement("option");typeof c=="object"?(a.value=c.id,a.textContent=c.displayName||c.name):(a.value=c,a.textContent=c),y.appendChild(a)})),s.data.cas}else throw new Error(s.message)}catch(v){console.error("Error loading CAs:",v);const s=document.getElementById("existing-ca-select");return s.innerHTML='<option value="">Error loading CAs</option>',[]}}function n(u){const{subdomain:v,port:s,ip:y,sslType:c,caName:a,existingCa:m,enableAuth:i,enableCors:e,customHeaders:o,upstreamPath:d,healthCheck:t,timeout:r,tailscaleOnly:h}=u;let p=`${buildDomain(v)} {
`;switch(h&&(p+=` @blocked not remote_ip 100.64.0.0/10
`,p+=` respond @blocked "Access denied. Tailscale connection required." 403
`),c){case"letsencrypt":break;case"caddy-managed":p+=` tls internal
`;break;case"existing-ca":m&&(p+=` tls {
ca ${m}
</div>`)})(),(function(){async function l(m){try{const y=await fetch(`/api/v1/caddy/cas?caddyfilePath=${encodeURIComponent(m)}`);if(!y.ok)throw new Error(`Failed to load CAs: ${y.status}`);const s=await y.json();if(s.success){const h=document.getElementById("existing-ca-select");return h.innerHTML="",s.cas.length===0?h.innerHTML='<option value="">No CAs found in Caddyfile</option>':(h.innerHTML='<option value="">Select existing CA...</option>',s.cas.forEach(c=>{const o=document.createElement("option");typeof c=="object"?(o.value=c.id,o.textContent=c.displayName||c.name):(o.value=c,o.textContent=c),h.appendChild(o)})),s.data.cas}else throw new Error(s.message)}catch(y){console.error("Error loading CAs:",y);const s=document.getElementById("existing-ca-select");return s.innerHTML='<option value="">Error loading CAs</option>',[]}}function a(m){const{subdomain:y,port:s,ip:h,sslType:c,caName:o,existingCa:p,enableAuth:i,enableCors:e,customHeaders:n,upstreamPath:d,healthCheck:t,timeout:r,tailscaleOnly:v}=m;let u=`${buildDomain(y)} {
`;switch(v&&(u+=` @blocked not remote_ip 100.64.0.0/10
`,u+=` respond @blocked "Access denied. Tailscale connection required." 403
`),c){case"letsencrypt":break;case"caddy-managed":u+=` tls internal
`;break;case"existing-ca":p&&(u+=` tls {
ca ${p}
}
`);break;case"custom-ca":a&&(p+=` tls {
ca ${a}
`);break;case"custom-ca":o&&(u+=` tls {
ca ${o}
}
`);break}if(i&&(p+=` basicauth {
`);break}if(i&&(u+=` basicauth {
admin $2a$14$hashed_password_here
}
`),e&&(p+=` header {
`,p+=` Access-Control-Allow-Origin "*"
`,p+=` Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS"
`,p+=` Access-Control-Allow-Headers "Content-Type, Authorization"
`,p+=` }
`),o)try{const w=JSON.parse(o);p+=` header {
`,Object.entries(w).forEach(([T,L])=>{p+=` ${T} "${L}"
`}),p+=` }
`}catch{console.warn("Invalid JSON in custom headers")}return t&&(p+=` health_uri ${t}
`),p+=` reverse_proxy ${y}:${s} {
`,d&&d!=="/"&&(p+=` rewrite ${d}
`),r&&r!==30&&(p+=` transport http {
`,p+=` dial_timeout ${r}s
`,p+=` response_header_timeout ${r}s
`,p+=` }
`),p+=` }
`,p+=`}
`,p}async function g(u,v,s=DC.DEFAULTS.TTL){const y=window.getToken(getPrimaryDnsId(),"admin");if(!y)throw new Error("DNS admin token not configured. Please set it in the Tokens menu.");const c=buildDomain(u),a=await secureFetch("/api/v1/dns/record",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:c,ip:v,ttl:s,token:y,server:SITE.dnsIp})});if(!a.ok){const i=await a.text();throw new Error(`DNS API Error: ${a.status} - ${i}`)}const m=await a.json();if(!m.success)throw new Error(`DNS Error: ${m.error||"Unknown error"}`);return m}async function b(u){const v={id:u.subdomain,name:u.name,logo:u.logo||`/assets/${u.subdomain}.png`};u.category&&(v.category=u.category),u.containerId&&(v.containerId=u.containerId);try{const s=await secureFetch("/api/v1/services",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(v)});if(!s.ok){const y=await s.json();throw new Error(y.error||"Failed to save service")}return await window.loadServices(),window.buildGrid(),v}catch(s){throw console.error("Failed to add service to config:",s),s}}async function f(u){const v=document.getElementById("service-subdomain-input").value.trim(),s=document.getElementById("service-ip-input").value.trim()||"localhost",y=document.getElementById("service-port-input").value.trim()||"80",c=await secureFetch("/api/v1/site",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:buildDomain(v),upstream:`${s}:${y}`,config:u})}),a=await c.json();if(!c.ok||!a.success)throw new Error(a.error||`Caddy API Error: ${c.status}`);return a}window.loadExistingCAs=l,window.generateCaddyConfig=n,window.createDnsRecord=g,window.addServiceToConfig=b,window.addToCaddyfile=f})(),(function(){let l=null;function n(s){l=s;const y=document.getElementById("service-edit-modal");document.getElementById("service-edit-title").textContent=`Edit ${s.name}`,document.getElementById("edit-service-name").value=s.name,document.getElementById("edit-service-url-display").textContent=s.url||buildServiceUrl(s.id),document.getElementById("edit-service-logo-preview").src=s.logo||`/assets/${s.id}.png`,document.getElementById("edit-subdomain").value=s.id,document.getElementById("edit-port").value=s.port||"",document.getElementById("edit-ip").value=s.ip||"localhost",document.getElementById("edit-tailscale-only").checked=s.tailscaleOnly||!1,document.getElementById("edit-logo-url").value=s.logo||"";const c=document.getElementById("edit-service-category");c&&(c.dataset.current=s.category||"",typeof window.populateCategorySelects=="function"&&window.populateCategorySelects()),y.classList.add("show")}function g(){closeModal("service-edit-modal"),l=null}async function b(){if(!l)return;const s=document.getElementById("edit-subdomain").value.trim().toLowerCase(),y=document.getElementById("edit-service-name").value.trim(),c=document.getElementById("edit-port").value.trim(),a=document.getElementById("edit-ip").value.trim()||"localhost",m=document.getElementById("edit-tailscale-only").checked,i=document.getElementById("edit-logo-url").value.trim(),e=document.getElementById("edit-service-category")?.value||"";if(!s){showNotification("Subdomain is required","warning");return}const o=l.id,d=[];if(s!==o&&d.push("subdomain"),y&&y!==l.name&&d.push("name"),c&&c!==String(l.port)&&d.push("port"),a!==l.ip&&d.push("ip"),m!==(l.tailscaleOnly||!1)&&d.push("tailscale"),i&&i!==l.logo&&d.push("logo"),e!==(l.category||"")&&d.push("category"),d.length===0){g();return}const t=document.getElementById("service-edit-save");t.textContent="Saving...",t.disabled=!0;try{const h=await(await secureFetch("/api/v1/services/update",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({oldSubdomain:o,newSubdomain:s,name:y||l.name,port:c||l.port,ip:a,tailscaleOnly:m,logo:i||void 0,category:e})})).json();if(!h.success)throw new Error(h.error||"Failed to update service");const p=window.APPS.findIndex(w=>w.id===o);p!==-1&&(window.APPS[p]={...window.APPS[p],id:s,name:y||window.APPS[p].name,port:c||window.APPS[p].port,ip:a,tailscaleOnly:m,logo:i||window.APPS[p].logo,category:e||void 0}),g(),window.buildGrid(),window.refreshAll()}catch(r){console.error("Error saving service changes:",r),showNotification(`Error saving changes: ${r.message}`,"error")}finally{t.textContent="Save Changes",t.disabled=!1}}document.getElementById("edit-logo-file")?.addEventListener("change",async s=>{const y=s.target.files[0];if(!y)return;if(!y.type.startsWith("image/")){showNotification("Please select an image file","warning");return}const c=new FileReader;c.onload=async a=>{const m=a.target.result;if(document.getElementById("edit-service-logo-preview").src=m,document.getElementById("edit-logo-url").value=m,l)try{const e=await(await secureFetch("/api/v1/assets/upload",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filename:`${l.id}.png`,data:m})})).json();e.success&&e.path&&(document.getElementById("edit-logo-url").val Line truncated
`),e&&(u+=` header {
`,u+=` Access-Control-Allow-Origin "*"
`,u+=` Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS"
`,u+=` Access-Control-Allow-Headers "Content-Type, Authorization"
`,u+=` }
`),n)try{const w=JSON.parse(n);u+=` header {
`,Object.entries(w).forEach(([T,L])=>{u+=` ${T} "${L}"
`}),u+=` }
`}catch{console.warn("Invalid JSON in custom headers")}return t&&(u+=` health_uri ${t}
`),u+=` reverse_proxy ${h}:${s} {
`,d&&d!=="/"&&(u+=` rewrite ${d}
`),r&&r!==30&&(u+=` transport http {
`,u+=` dial_timeout ${r}s
`,u+=` response_header_timeout ${r}s
`,u+=` }
`),u+=` }
`,u+=`}
`,u}async function g(m,y,s=DC.DEFAULTS.TTL){const h=window.getToken(getPrimaryDnsId(),"admin");if(!h)throw new Error("DNS admin token not configured. Please set it in the Tokens menu.");const c=buildDomain(m),o=await secureFetch("/api/v1/dns/record",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:c,ip:y,ttl:s,token:h,server:SITE.dnsIp})});if(!o.ok){const i=await o.text();throw new Error(`DNS API Error: ${o.status} - ${i}`)}const p=await o.json();if(!p.success)throw new Error(`DNS Error: ${p.error||"Unknown error"}`);return p}async function b(m){const y={id:m.subdomain,name:m.name,logo:m.logo||`/assets/${m.subdomain}.png`};m.category&&(y.category=m.category),m.containerId&&(y.containerId=m.containerId);try{const s=await secureFetch("/api/v1/services",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(y)});if(!s.ok){const h=await s.json();throw new Error(h.error||"Failed to save service")}return await window.loadServices(),window.buildGrid(),y}catch(s){throw console.error("Failed to add service to config:",s),s}}async function f(m){const y=document.getElementById("service-subdomain-input").value.trim(),s=document.getElementById("service-ip-input").value.trim()||"localhost",h=document.getElementById("service-port-input").value.trim()||"80",c=await secureFetch("/api/v1/site",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:buildDomain(y),upstream:`${s}:${h}`,config:m})}),o=await c.json();if(!c.ok||!o.success)throw new Error(o.error||`Caddy API Error: ${c.status}`);return o}window.loadExistingCAs=l,window.generateCaddyConfig=a,window.createDnsRecord=g,window.addServiceToConfig=b,window.addToCaddyfile=f})(),(function(){let l=null;function a(s){l=s;const h=document.getElementById("service-edit-modal");document.getElementById("service-edit-title").textContent=`Edit ${s.name}`,document.getElementById("edit-service-name").value=s.name,document.getElementById("edit-service-url-display").textContent=s.url||buildServiceUrl(s.id),document.getElementById("edit-service-logo-preview").src=s.logo||`/assets/${s.id}.png`,document.getElementById("edit-subdomain").value=s.id,document.getElementById("edit-port").value=s.port||"",document.getElementById("edit-ip").value=s.ip||"localhost",document.getElementById("edit-tailscale-only").checked=s.tailscaleOnly||!1,document.getElementById("edit-logo-url").value=s.logo||"";const c=document.getElementById("edit-service-category");c&&(c.dataset.current=s.category||"",typeof window.populateCategorySelects=="function"&&window.populateCategorySelects()),h.classList.add("show")}function g(){closeModal("service-edit-modal"),l=null}async function b(){if(!l)return;const s=document.getElementById("edit-subdomain").value.trim().toLowerCase(),h=document.getElementById("edit-service-name").value.trim(),c=document.getElementById("edit-port").value.trim(),o=document.getElementById("edit-ip").value.trim()||"localhost",p=document.getElementById("edit-tailscale-only").checked,i=document.getElementById("edit-logo-url").value.trim(),e=document.getElementById("edit-service-category")?.value||"";if(!s){showNotification("Subdomain is required","warning");return}const n=l.id,d=[];if(s!==n&&d.push("subdomain"),h&&h!==l.name&&d.push("name"),c&&c!==String(l.port)&&d.push("port"),o!==l.ip&&d.push("ip"),p!==(l.tailscaleOnly||!1)&&d.push("tailscale"),i&&i!==l.logo&&d.push("logo"),e!==(l.category||"")&&d.push("category"),d.length===0){g();return}const t=document.getElementById("service-edit-save");t.textContent="Saving...",t.disabled=!0;try{const v=await(await secureFetch("/api/v1/services/update",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({oldSubdomain:n,newSubdomain:s,name:h||l.name,port:c||l.port,ip:o,tailscaleOnly:p,logo:i||void 0,category:e})})).json();if(!v.success)throw new Error(v.error||"Failed to update service");const u=window.APPS.findIndex(w=>w.id===n);u!==-1&&(window.APPS[u]={...window.APPS[u],id:s,name:h||window.APPS[u].name,port:c||window.APPS[u].port,ip:o,tailscaleOnly:p,logo:i||window.APPS[u].logo,category:e||void 0}),g(),window.buildGrid(),window.refreshAll()}catch(r){console.error("Error saving service changes:",r),showNotification(`Error saving changes: ${r.message}`,"error")}finally{t.textContent="Save Changes",t.disabled=!1}}document.getElementById("edit-logo-file")?.addEventListener("change",async s=>{const h=s.target.files[0];if(!h)return;if(!h.type.startsWith("image/")){showNotification("Please select an image file","warning");return}const c=new FileReader;c.onload=async o=>{const p=o.target.result;if(document.getElementById("edit-service-logo-preview").src=p,document.getElementById("edit-logo-url").value=p,l)try{const e=await(await secureFetch("/api/v1/assets/upload",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filename:`${l.id}.png`,data:p})})).json();e.success&&e.path&&(document.getElementById("edit-logo-url").val Line truncated
This will:
1. Pull the latest image
2. Stop the container
3. Recreate with same settings
The service will be briefly unavailable.`))try{a&&(a.textContent="\u{1F504}",a.disabled=!0,a.title="Updating...");const e=await(await secureFetch(`/api/v1/containers/${s}/update`,{method:"POST"})).json();if(e.success){const o=window.APPS.find(d=>d.id===c);o&&e.newContainerId&&(o.containerId=e.newContainerId),a&&(a.textContent="\u2705",a.title="Updated successfully!",setTimeout(()=>{a.textContent=m,a.disabled=!1,a.title="Update container to latest version"},3e3)),setTimeout(()=>window.refreshAll(),2e3),showNotification(`${y} updated successfully!`,"success")}else throw new Error(e.error||"Update failed")}catch(i){console.error("Update error:",i),a&&(a.textContent="\u274C",a.title="Update failed",setTimeout(()=>{a.textContent=m,a.disabled=!1,a.title="Update container to latest version"},3e3)),showNotification(`Failed to update ${y}: ${i.message}`,"error")}}async function v(s,y){const c=window.APPS.find(p=>p.id===s),a=c?buildDomain(c.id):null,m=c?.containerId,i=await f(y||s,m,c?.containerId);if(i===null)return;let e={dashboard:!1,container:null,dns:null,caddy:null,service:null};if(i&&m)try{const p=new URLSearchParams({containerId:c.containerId,subdomain:c.id,ip:c.ip||"localhost",deleteContainer:"true"}),T=await(await secureFetch(`/api/v1/apps/${encodeURIComponent(c.id)}?${p.toString()}`,{method:"DELETE"})).json();T.success?e={...e,...T.results,dashboard:!1}:console.error("App removal failed:",T.error)}catch(p){console.error("App removal error:",p)}else if(i&&a){try{const p=c?.ip||"localhost",T=await(await secureFetch(`/api/v1/dns/record?domain=${encodeURIComponent(a)}&type=A&ipAddress=${encodeURIComponent(p)}&server=${SITE.dnsIp}`,{method:"DELETE"})).json();e.dns=T.success?"deleted":T.error||"failed"}catch(p){e.dns=p.message}try{const w=await(await secureFetch(`/api/v1/site/${encodeURIComponent(a)}`,{method:"DELETE"})).json();e.caddy=w.success||w.error&&w.error.includes("not found")?"removed":w.error||"failed"}catch(p){e.caddy=p.message}}const o=window.APPS.findIndex(p=>p.id===s);o>-1&&(window.APPS.splice(o,1),e.dashboard=!0);try{const p=safeGetJSON("custom-apps",[]),w=p.findIndex(T=>T.id===s);w>-1&&(p.splice(w,1),safeSet("custom-apps",JSON.stringify(p)))}catch{}try{const w=await(await secureFetch(`/api/v1/services/${encodeURIComponent(s)}`,{method:"DELETE"})).json();e.service=w.success?"removed":w.error||"failed"}catch(p){e.service=p.message}window.buildGrid(),window.refreshAll();let d=!1,t=[];e.dashboard||(d=!0,t.push("\u2717 Failed to remove from dashboard"));const r=["removed","already removed","not found","deleted","kept (user choice)","skipped","no such record","does not exist"],h=p=>!p||r.some(w=>p.toLowerCase().includes(w.toLowerCase()));e.container&&!h(e.container)&&(d=!0,t.push(`\u26A0 Container: ${e.container}`)),e.dns&&!h(e.dns)&&(d=!0,t.push(`\u26A0 DNS Record: ${e.dns}`)),e.caddy&&!h(e.caddy)&&(d=!0,t.push(`\u26A0 Caddy Config: ${e.caddy}`)),e.service&&!h(e.service)&&(d=!0,t.push(`\u26A0 Service File: ${e.service}`)),d&&showNotification(`Error deleting "${y||s}": ${t.join(", ")}`,"error",6e3)}window.openServiceEditModal=n,window.showDeleteModal=f,window.updateContainer=u,window.deleteService=v})(),(function(){function l(e){return e.toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"").replace(/-+/g,"-").replace(/^-|-$/g,"")}function n(){return SITE.defaults?.sslType||(SITE.configurationType==="public"?"letsencrypt":"caddy-managed")}function g(){const e=document.getElementById("service-subdomain-input").value||"subdomain",o=document.getElementById("service-ip-input").value||b.lan||"localhost",d=document.getElementById("service-port-input").value||DC.DEFAULTS.SERVICE_PORT,t=document.getElementById("ssl-type-select").value,r=document.getElementById("ca-name-input").value||"sami-ca",h=document.getElementById("existing-ca-select").value,p=document.getElementById("enable-auth").checked,w=document.getElementById("enable-cors").checked,T=document.getElementById("custom-headers-input").value,L=document.getElementById("upstream-path-input").value||"/",P=document.getElementById("health-check-input").value,E=document.getElementById("timeout-input").value||30,B=document.getElementById("dns-preview");B&&(B.textContent=`${buildDomain(e)} \u2192 ${o}`);const $=document.getElementById("url-preview");$&&($.textContent=buildServiceUrl(e));const C={subdomain:e,port:d,ip:o,sslType:t,caName:r,existingCa:h,enableAuth:p,enableCors:w,customHeaders:T,upstreamPath:L,healthCheck:P,timeout:E},x=window.generateCaddyConfig(C),I=document.getElementById("caddy-config-preview");I&&(I.value=x)}const b={localhost:"127.0.0.1",lan:"",tailscale:""};async function f(){try{const t=await fetch("/api/v1/network/ips",{signal:AbortSignal.timeout(2e3)});if(t.ok){const r=await t.json();r.lan&&(b.lan=r.lan),r.tailscale&&(b.tailscale=r.tailscale)}}catch{}const e=document.getElementById("quick-ip-lan"),o=document.getElementById("quick-ip-tailscale");e&&(b.lan?(e.dataset.ip=b.lan,e.textContent=`LAN (${b.lan})`,e.title=`LAN IP: ${b.lan}`):e Line truncated
The service will be briefly unavailable.`))try{o&&(o.textContent="\u{1F504}",o.disabled=!0,o.title="Updating...");const e=await(await secureFetch(`/api/v1/containers/${s}/update`,{method:"POST"})).json();if(e.success){const n=window.APPS.find(d=>d.id===c);n&&e.newContainerId&&(n.containerId=e.newContainerId),o&&(o.textContent="\u2705",o.title="Updated successfully!",setTimeout(()=>{o.textContent=p,o.disabled=!1,o.title="Update container to latest version"},3e3)),setTimeout(()=>window.refreshAll(),2e3),showNotification(`${h} updated successfully!`,"success")}else throw new Error(e.error||"Update failed")}catch(i){console.error("Update error:",i),o&&(o.textContent="\u274C",o.title="Update failed",setTimeout(()=>{o.textContent=p,o.disabled=!1,o.title="Update container to latest version"},3e3)),showNotification(`Failed to update ${h}: ${i.message}`,"error")}}async function y(s,h){const c=window.APPS.find(u=>u.id===s),o=c?buildDomain(c.id):null,p=c?.containerId,i=await f(h||s,p,c?.containerId);if(i===null)return;let e={dashboard:!1,container:null,dns:null,caddy:null,service:null};if(i&&p)try{const u=new URLSearchParams({containerId:c.containerId,subdomain:c.id,ip:c.ip||"localhost",deleteContainer:"true"}),T=await(await secureFetch(`/api/v1/apps/${encodeURIComponent(c.id)}?${u.toString()}`,{method:"DELETE"})).json();T.success?e={...e,...T.results,dashboard:!1}:console.error("App removal failed:",T.error)}catch(u){console.error("App removal error:",u)}else if(i&&o){try{const u=c?.ip||"localhost",T=await(await secureFetch(`/api/v1/dns/record?domain=${encodeURIComponent(o)}&type=A&ipAddress=${encodeURIComponent(u)}&server=${SITE.dnsIp}`,{method:"DELETE"})).json();e.dns=T.success?"deleted":T.error||"failed"}catch(u){e.dns=u.message}try{const w=await(await secureFetch(`/api/v1/site/${encodeURIComponent(o)}`,{method:"DELETE"})).json();e.caddy=w.success||w.error&&w.error.includes("not found")?"removed":w.error||"failed"}catch(u){e.caddy=u.message}}const n=window.APPS.findIndex(u=>u.id===s);n>-1&&(window.APPS.splice(n,1),e.dashboard=!0);try{const u=safeGetJSON("custom-apps",[]),w=u.findIndex(T=>T.id===s);w>-1&&(u.splice(w,1),safeSet("custom-apps",JSON.stringify(u)))}catch{}try{const w=await(await secureFetch(`/api/v1/services/${encodeURIComponent(s)}`,{method:"DELETE"})).json();e.service=w.success?"removed":w.error||"failed"}catch(u){e.service=u.message}window.buildGrid(),window.refreshAll();let d=!1,t=[];e.dashboard||(d=!0,t.push("\u2717 Failed to remove from dashboard"));const r=["removed","already removed","not found","deleted","kept (user choice)","skipped","no such record","does not exist"],v=u=>!u||r.some(w=>u.toLowerCase().includes(w.toLowerCase()));e.container&&!v(e.container)&&(d=!0,t.push(`\u26A0 Container: ${e.container}`)),e.dns&&!v(e.dns)&&(d=!0,t.push(`\u26A0 DNS Record: ${e.dns}`)),e.caddy&&!v(e.caddy)&&(d=!0,t.push(`\u26A0 Caddy Config: ${e.caddy}`)),e.service&&!v(e.service)&&(d=!0,t.push(`\u26A0 Service File: ${e.service}`)),d&&showNotification(`Error deleting "${h||s}": ${t.join(", ")}`,"error",6e3)}window.openServiceEditModal=a,window.showDeleteModal=f,window.updateContainer=m,window.deleteService=y})(),(function(){function l(e){return e.toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"").replace(/-+/g,"-").replace(/^-|-$/g,"")}function a(){return SITE.defaults?.sslType||(SITE.configurationType==="public"?"letsencrypt":"caddy-managed")}function g(){const e=document.getElementById("service-subdomain-input").value||"subdomain",n=document.getElementById("service-ip-input").value||b.lan||"localhost",d=document.getElementById("service-port-input").value||DC.DEFAULTS.SERVICE_PORT,t=document.getElementById("ssl-type-select").value,r=document.getElementById("ca-name-input").value||"sami-ca",v=document.getElementById("existing-ca-select").value,u=document.getElementById("enable-auth").checked,w=document.getElementById("enable-cors").checked,T=document.getElementById("custom-headers-input").value,L=document.getElementById("upstream-path-input").value||"/",P=document.getElementById("health-check-input").value,E=document.getElementById("timeout-input").value||30,B=document.getElementById("dns-preview");B&&(B.textContent=`${buildDomain(e)} \u2192 ${n}`);const $=document.getElementById("url-preview");$&&($.textContent=buildServiceUrl(e));const C={subdomain:e,port:d,ip:n,sslType:t,caName:r,existingCa:v,enableAuth:u,enableCors:w,customHeaders:T,upstreamPath:L,healthCheck:P,timeout:E},x=window.generateCaddyConfig(C),I=document.getElementById("caddy-config-preview");I&&(I.value=x)}const b={localhost:"127.0.0.1",lan:"",tailscale:""};async function f(){try{const t=await fetch("/api/v1/network/ips",{signal:AbortSignal.timeout(2e3)});if(t.ok){const r=await t.json();r.lan&&(b.lan=r.lan),r.tailscale&&(b.tailscale=r.tailscale)}}catch{}const e=document.getElementById("quick-ip-lan"),n=document.getElementById("quick-ip-tailscale");e&&(b.lan?(e.dataset.ip=b.lan,e.textContent=`LAN (${b.lan})`,e.title=`LAN IP: ${b.lan}`):e Line truncated
<span style="color: #4caf50;">\u2713 Connected</span>
<span style="color: var(--muted); margin-left: 6px;">${w.self?.hostname} (${w.self?.ip})</span>
`,h.disabled=!1):w.installed?(r.innerHTML='<span style="color: #ff9800;">\u26A0 Not connected</span>',h.disabled=!0):(r.innerHTML='<span style="color: var(--muted);">Not available</span>',h.disabled=!0)}catch{r.innerHTML='<span style="color: var(--muted);">Could not check</span>',h.disabled=!0}h.checked=!1,g()}function s(){const e=document.getElementById("service-type-local"),o=document.getElementById("service-type-external"),d=document.getElementById("local-service-config"),t=document.getElementById("external-service-config"),r=document.getElementById("tab-local"),h=document.getElementById("tab-external");function p(){e.checked?(d.style.display="grid",t.style.display="none",r&&(r.style.background="var(--accent)",r.style.color="var(--bg)"),h&&(h.style.background="transparent",h.style.color="var(--muted)")):(d.style.display="none",t.style.display="block",h&&(h.style.background="var(--accent)",h.style.color="var(--bg)"),r&&(r.style.background="transparent",r.style.color="var(--muted)"))}e?.addEventListener("change",p),o?.addEventListener("change",p)}function y(){const e=document.getElementById("service-name-input"),o=document.getElementById("service-subdomain-input"),d=document.getElementById("subdomain-preview");let t=!1;e?.addEventListener("input",()=>{const L=l(e.value);!t&&o&&(o.value=L),d&&(d.textContent=L?`\u2192 ${buildDomain(L)}`:""),g()}),o?.addEventListener("input",()=>{t=o.value!==l(e?.value||"");const L=o.value.trim()||l(e?.value||"");d&&(d.textContent=L?`\u2192 ${buildDomain(L)}`:""),g()});const r=document.getElementById("external-service-name"),h=document.getElementById("external-service-subdomain"),p=document.getElementById("external-subdomain-preview"),w=document.getElementById("external-domain-preview");let T=!1;r?.addEventListener("input",()=>{const L=l(r.value);!T&&h&&(h.value=L);const P=h?.value||L;p&&(p.textContent=P?`\u2192 ${buildDomain(P)}`:""),w&&(w.textContent=P?buildDomain(P):"")}),h?.addEventListener("input",()=>{T=h.value!==l(r?.value||"");const L=h.value.trim()||l(r?.value||"");p&&(p.textContent=L?`\u2192 ${buildDomain(L)}`:""),w&&(w.textContent=L?buildDomain(L):"")})}async function c(){const e=document.getElementById("external-service-name").value.trim(),o=document.getElementById("external-service-url").value.trim(),d=(document.getElementById("external-service-subdomain").value.trim()||l(e)).toLowerCase(),t=document.getElementById("external-service-logo").value.trim(),r=document.getElementById("external-service-icon").value.trim(),h=document.getElementById("external-create-dns").checked,p=document.getElementById("external-create-caddy").checked,w=document.getElementById("external-proxy-ip").value.trim()||SITE.dnsIp||"localhost",T=document.getElementById("external-preserve-host").checked,L=document.getElementById("external-follow-redirects").checked,P=document.getElementById("external-service-category")?.value||"";if(!e||!o){showNotification("Please fill in Name and External URL","warning");return}if(!d){showNotification("Could not derive subdomain from name. Please set one in Options.","warning");return}if(!o.startsWith("http://")&&!o.startsWith("https://")){showNotification("External URL must start with http:// or https://","warning");return}const E=buildDomain(d);try{const B={dns:null,caddy:null,dashboard:!1};if(h)if(window.getToken(getPrimaryDnsId(),"admin"))try{const A=await(await secureFetch("/api/v1/dns/record",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:E,ip:w,ttl:DC.DEFAULTS.TTL,server:SITE.dnsIp})})).json();B.dns=A.success?"created":A.error||"failed"}catch(S){B.dns=S.message}else B.dns="no admin token (configure in \u{1F511} Tokens)";if(p)try{const k={subdomain:d,externalUrl:o,preserveHost:T,followRedirects:L,sslType:"caddy-managed",caddyfilePath:DC.DEFAULTS.CADDYFILE,reloadCaddy:!0},A=await(await secureFetch("/api/v1/site/external",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(k)})).json();B.caddy=A.success?"created":A.error||"failed"}catch(k){B.caddy=k.message}const $={id:d,name:e,url:`https://${E}`,externalUrl:o,logo:t||r||"\u{1F310}",isExternal:!0,isCustom:!0};P&&($.category=P),window.APPS.push($),B.dashboard=!0;const C=["plex","router","chat","sync","torrent","radarr","sonarr","prowlarr","portainer","requests","jellyfin","emby"],x=window.APPS.filter(k=>!C.includes(k.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(k){console.warn("Failed to save to services.json:",k)}window.buildGrid(),window.refreshAll(),a();const I=[`External service "${e}" added!`];h&&I.push(`DNS: ${B.dns==="created"?"\u2713":"\u26A0 "+B.dns}`),p&&I.push(`Caddy: ${B.caddy==="created"?"\u2713":"\u26A0 "+B.caddy}`),I.push(`Access at: https://${E}`),showNotification(I.join(" | "),"success",6e3)}catch(B){console.error("Failed to create external service:",B),showNotification(`F Line truncated
`,v.disabled=!1):w.installed?(r.innerHTML='<span style="color: #ff9800;">\u26A0 Not connected</span>',v.disabled=!0):(r.innerHTML='<span style="color: var(--muted);">Not available</span>',v.disabled=!0)}catch{r.innerHTML='<span style="color: var(--muted);">Could not check</span>',v.disabled=!0}v.checked=!1,g()}function s(){const e=document.getElementById("service-type-local"),n=document.getElementById("service-type-external"),d=document.getElementById("local-service-config"),t=document.getElementById("external-service-config"),r=document.getElementById("tab-local"),v=document.getElementById("tab-external");function u(){e.checked?(d.style.display="grid",t.style.display="none",r&&(r.style.background="var(--accent)",r.style.color="var(--bg)"),v&&(v.style.background="transparent",v.style.color="var(--muted)")):(d.style.display="none",t.style.display="block",v&&(v.style.background="var(--accent)",v.style.color="var(--bg)"),r&&(r.style.background="transparent",r.style.color="var(--muted)"))}e?.addEventListener("change",u),n?.addEventListener("change",u)}function h(){const e=document.getElementById("service-name-input"),n=document.getElementById("service-subdomain-input"),d=document.getElementById("subdomain-preview");let t=!1;e?.addEventListener("input",()=>{const L=l(e.value);!t&&n&&(n.value=L),d&&(d.textContent=L?`\u2192 ${buildDomain(L)}`:""),g()}),n?.addEventListener("input",()=>{t=n.value!==l(e?.value||"");const L=n.value.trim()||l(e?.value||"");d&&(d.textContent=L?`\u2192 ${buildDomain(L)}`:""),g()});const r=document.getElementById("external-service-name"),v=document.getElementById("external-service-subdomain"),u=document.getElementById("external-subdomain-preview"),w=document.getElementById("external-domain-preview");let T=!1;r?.addEventListener("input",()=>{const L=l(r.value);!T&&v&&(v.value=L);const P=v?.value||L;u&&(u.textContent=P?`\u2192 ${buildDomain(P)}`:""),w&&(w.textContent=P?buildDomain(P):"")}),v?.addEventListener("input",()=>{T=v.value!==l(r?.value||"");const L=v.value.trim()||l(r?.value||"");u&&(u.textContent=L?`\u2192 ${buildDomain(L)}`:""),w&&(w.textContent=L?buildDomain(L):"")})}async function c(){const e=document.getElementById("external-service-name").value.trim(),n=document.getElementById("external-service-url").value.trim(),d=(document.getElementById("external-service-subdomain").value.trim()||l(e)).toLowerCase(),t=document.getElementById("external-service-logo").value.trim(),r=document.getElementById("external-service-icon").value.trim(),v=document.getElementById("external-create-dns").checked,u=document.getElementById("external-create-caddy").checked,w=document.getElementById("external-proxy-ip").value.trim()||SITE.dnsIp||"localhost",T=document.getElementById("external-preserve-host").checked,L=document.getElementById("external-follow-redirects").checked,P=document.getElementById("external-service-category")?.value||"";if(!e||!n){showNotification("Please fill in Name and External URL","warning");return}if(!d){showNotification("Could not derive subdomain from name. Please set one in Options.","warning");return}if(!n.startsWith("http://")&&!n.startsWith("https://")){showNotification("External URL must start with http:// or https://","warning");return}const E=buildDomain(d);try{const B={dns:null,caddy:null,dashboard:!1};if(v)if(window.getToken(getPrimaryDnsId(),"admin"))try{const A=await(await secureFetch("/api/v1/dns/record",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:E,ip:w,ttl:DC.DEFAULTS.TTL,server:SITE.dnsIp})})).json();B.dns=A.success?"created":A.error||"failed"}catch(S){B.dns=S.message}else B.dns="no admin token (configure in \u{1F511} Tokens)";if(u)try{const k={subdomain:d,externalUrl:n,preserveHost:T,followRedirects:L,sslType:"caddy-managed",caddyfilePath:DC.DEFAULTS.CADDYFILE,reloadCaddy:!0},A=await(await secureFetch("/api/v1/site/external",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(k)})).json();B.caddy=A.success?"created":A.error||"failed"}catch(k){B.caddy=k.message}const $={id:d,name:e,url:`https://${E}`,externalUrl:n,logo:t||r||"\u{1F310}",isExternal:!0,isCustom:!0};P&&($.category=P),window.APPS.push($),B.dashboard=!0;const C=["plex","router","chat","sync","torrent","radarr","sonarr","prowlarr","portainer","requests","jellyfin","emby"],x=window.APPS.filter(k=>!C.includes(k.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(k){console.warn("Failed to save to services.json:",k)}window.buildGrid(),window.refreshAll(),o();const I=[`External service "${e}" added!`];v&&I.push(`DNS: ${B.dns==="created"?"\u2713":"\u26A0 "+B.dns}`),u&&I.push(`Caddy: ${B.caddy==="created"?"\u2713":"\u26A0 "+B.caddy}`),I.push(`Access at: https://${E}`),showNotification(I.join(" | "),"success",6e3)}catch(B){console.error("Failed to create external service:",B),showNotification(`F Line truncated
+22 -11
View File
@@ -249,20 +249,31 @@
// back to window._showTotpOverlay() in `show()` below.
window.__dc_049_handled = true;
function isAllowedReturnUrl(returnUrl) {
try {
const parsed = new URL(returnUrl, window.location.origin);
if (!['http:', 'https:'].includes(parsed.protocol)) return false;
if (parsed.origin === window.location.origin) return true;
if (parsed.protocol !== 'https:') return false;
// globals.js is concatenated before this module in core.js, so SITE is
// available here. Permit exact hosts and subdomains under the configured
// private TLD (for example plex.sami), while rejecting lookalikes such as
// plex.sami.evil.example.
const suffix = SITE.tld.startsWith('.') ? SITE.tld : `.${SITE.tld}`;
return parsed.hostname === suffix.slice(1) || parsed.hostname.endsWith(suffix);
} catch (_) {
return false;
}
}
const urlParams = new URLSearchParams(window.location.search);
if (urlParams.get('auth') === 'required') {
// Save returnUrl the same way totp-auth.js does, so both paths share state.
// We don't have access to the SITE constant here (it lives in globals.js's
// module scope), so we use a conservative origin-only check. Caddy's
// forward_auth already validates the request origin upstream.
// Preserve the gated service destination so submitTotpCode() can append
// the one-time SSO handoff token and return the browser to that host.
const returnUrl = urlParams.get('return');
if (returnUrl) {
try {
const parsed = new URL(returnUrl, window.location.origin);
if (parsed.origin === window.location.origin) {
try { sessionStorage.setItem('totp_redirect', returnUrl); } catch (_) {}
}
} catch (_) {}
if (returnUrl && isAllowedReturnUrl(returnUrl)) {
try { sessionStorage.setItem('totp_redirect', returnUrl); } catch (_) {}
}
// Clean URL — happens after we've captured the redirect
window.history.replaceState({}, '', window.location.pathname);
+1
View File
@@ -4,6 +4,7 @@
"private": true,
"scripts": {
"build": "node build.js",
"test": "node --test tests/*.test.js",
"watch": "node build.js --watch"
},
"devDependencies": {
+1 -1
View File
@@ -1,4 +1,4 @@
const CACHE = 'dashcaddy-shell-4706f2a8fa';
const CACHE = 'dashcaddy-shell-3a6da6cb72';
const PRECACHE = [
'/',
'/index.html',
+61
View File
@@ -0,0 +1,61 @@
'use strict';
const fs = require('fs');
const path = require('path');
const vm = require('vm');
const test = require('node:test');
const assert = require('node:assert/strict');
const source = fs.readFileSync(path.join(__dirname, '..', 'js', 'auth-gate.js'), 'utf8');
function capturedRedirect(returnUrl, tld = '.sami') {
const stored = new Map();
const query = new URLSearchParams({ auth: 'required', return: returnUrl });
const location = {
origin: 'https://status.sami',
pathname: '/',
search: `?${query.toString()}`,
reload() {},
};
const context = {
URL,
URLSearchParams,
SITE: { tld },
sessionStorage: {
setItem(key, value) { stored.set(key, value); },
},
document: { getElementById() { return null; } },
setTimeout() {},
console,
window: {
location,
history: { replaceState() {} },
},
};
context.window.window = context.window;
vm.runInNewContext(source, context, { filename: 'auth-gate.js' });
return stored.get('totp_redirect');
}
test('preserves a return URL on another host under the configured private TLD', () => {
assert.equal(capturedRedirect('https://plex.sami/web/'), 'https://plex.sami/web/');
});
test('preserves a same-origin return URL', () => {
assert.equal(capturedRedirect('https://status.sami/settings'), 'https://status.sami/settings');
});
test('rejects lookalike domains, plaintext cross-host URLs, and non-web schemes', () => {
assert.equal(capturedRedirect('https://plex.sami.evil.example/'), undefined);
assert.equal(capturedRedirect('http://plex.sami/'), undefined);
assert.equal(capturedRedirect('javascript:alert(1)'), undefined);
});
test('accepts relative same-origin paths and protocol-relative HTTPS private hosts', () => {
assert.equal(capturedRedirect('/settings'), '/settings');
assert.equal(capturedRedirect('//plex.sami/web/'), '//plex.sami/web/');
});
test('normalizes a configured TLD without a leading dot', () => {
assert.equal(capturedRedirect('https://plex.sami/web/', 'sami'), 'https://plex.sami/web/');
});