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 k=await fetch("/api/v1/config");if(k.ok){const v=await k.json();if(v.tld&&(SITE.tld=v.tld.startsWith(".")?v.tld:"."+v.tld),v.dns&&(SITE.dnsIp=v.dns.ip||"",SITE.dnsPort=v.dns.port||DC.DEFAULTS.DNS_PORT),v.dnsServers&&typeof v.dnsServers=="object")for(const[h,n]of Object.entries(v.dnsServers))h!=="__proto__"&&h!=="constructor"&&h!=="prototype"&&(SITE.dnsServers[h]=n);v.configurationType&&(SITE.configurationType=v.configurationType),v.domain&&(SITE.domain=v.domain),v.defaults&&(SITE.defaults=v.defaults),v.routingMode&&(SITE.routingMode=v.routingMode),SITE.onboardingCompleted=v.onboardingCompleted===!0,localStorage.setItem("dashcaddy_site_config",JSON.stringify({tld:SITE.tld,configurationType:SITE.configurationType,domain:SITE.domain,routingMode:SITE.routingMode})),renderDnsCards();const i=document.getElementById("manage-tokens");i&&(i.style.display=Object.keys(SITE.dnsServers).length?"":"none")}}catch{}document.querySelectorAll("[data-tld]").forEach(k=>k.textContent=SITE.tld);const m=document.getElementById("edit-tld-suffix");m&&(m.textContent=SITE.tld);const l=document.getElementById("external-proxy-ip");l&&SITE.dnsIp&&(l.value=SITE.dnsIp,l.placeholder=SITE.dnsIp)})();function buildDomain(o){return o+SITE.tld}function buildServiceUrl(o){return SITE.routingMode==="subdirectory"&&SITE.domain?"https://"+SITE.domain+"/"+o:SITE.configurationType==="public"&&SITE.domain?"https://"+o+"."+SITE.domain:"https://"+buildDomain(o)}function getDnsServerAddr(o){const m=SITE.dnsServers[o];return m?`${m.ip}:${m.port}`:buildDomain(o)}function getPrimaryDnsId(){if(!SITE.dnsIp)return null;for(const[o,m]of Object.entries(SITE.dnsServers))if(m.ip===SITE.dnsIp)return o;return null}function renderDnsCards(){const o=document.querySelector(".top");if(!o)return;const m=Object.keys(SITE.dnsServers);if(!m.length)return;const l=' ',k=o.firstElementChild;m.forEach(v=>{const i=escapeHtml(v),h=escapeHtml((SITE.dnsServers[v].name||v).toUpperCase()),n=document.createElement("div");n.className="card",n.setAttribute("data-app",v),n.setAttribute("data-status","off"),n.innerHTML=`
--
Restart \u2B06\uFE0F Open Logs \u2699\uFE0F
`,o.insertBefore(n,k)})}window.renderDnsCards=renderDnsCards;let csrfToken=null;async function getCSRFToken(){if(csrfToken)return csrfToken;try{const o=await fetch("/api/v1/csrf-token");if(!o.ok)throw new Error("Failed to fetch CSRF token");return csrfToken=(await o.json()).token,csrfToken}catch(o){throw errorHandler.logError("[CSRF] Get Token",o,{function:"getCSRFToken"}),o}}async function secureFetch(o,m={}){const l=(m.method||"GET").toUpperCase(),k=!["GET","HEAD","OPTIONS"].includes(l);if(k)try{const i=await getCSRFToken();m.headers={...m.headers,"X-CSRF-Token":i}}catch(i){errorHandler.logError("[CSRF] Add to Request",i,{function:"secureFetch"})}m.signal||(m={...m,signal:AbortSignal.timeout(15e3)});const v=await fetch(o,m);if(k&&v.status===403)try{const i=await v.clone().json();if(i.error&&(i.error.includes("DC-100")||i.error.includes("DC-101"))){csrfToken=null;const h=await getCSRFToken();return m.headers={...m.headers,"X-CSRF-Token":h},m.signal=AbortSignal.timeout(15e3),fetch(o,m)}}catch{}return v}async function postJSON(o,m){const l=await secureFetch(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(m)}),k=await l.json();if(!l.ok||k.success===!1)throw new Error(k.error||`Request failed (${l.status})`);return k}async function getJSON(o){const m=await secureFetch(o);if(!m.ok){let l=`Request failed (${m.status})`;try{l=(await m.json()).error||l}catch{}throw new Error(l)}return m.json()}async function deleteAPI(o){const m=await secureFetch(o,{method:"DELETE"}),l=await m.json();if(!m.ok||l.success===!1)throw new Error(l.error||`Delete failed (${m.status})`);return l}async function withButton(o,m,l,k={}){const v=o.innerHTML,{successText:i="\u2705",resetDelay:h=DC.DELAYS.BTN_RESET}=k;o.disabled=!0,o.innerHTML=m;try{const n=await l();return o.innerHTML=i,setTimeout(()=>{o.innerHTML=v,o.disabled=!1},h),n}catch(n){throw o.innerHTML=v,o.disabled=!1,n}}function openModal(o){document.getElementById(o)?.classList.add("show")}function closeModal(o){document.getElementById(o)?.classList.remove("show")}function wireModal(o,...m){o&&(o.addEventListener("click",l=>{l.target===o&&o.classList.remove("show")}),m.forEach(l=>l?.addEventListener("click",()=>o.classList.remove("show"))))}function showNotification(o,m="info",l=3e3){const k=document.querySelector(".deploy-notification");k&&k.remove();const v={info:{bg:"#2196F3",fg:"#fff"},success:{bg:"var(--ok-bg)",fg:"var(--ok-fg)"},error:{bg:"#f44336",fg:"#fff"},warning:{bg:"#ff9800",fg:"#fff"}},i=v[m]||v.info,h=document.createElement("div");h.className="deploy-notification",h.textContent=o,h.style.cssText=`
position: fixed; top: 20px; right: 20px;
background: ${i.bg}; color: ${i.fg};
padding: 16px 24px; border-radius: 8px;
box-shadow: 0 4px 12px rgba(0,0,0,.3);
z-index: 10000; animation: slideIn 0.3s ease-out;
max-width: 400px; white-space: pre-line; font-size: 14px;
`,document.body.appendChild(h),l>0&&setTimeout(()=>h.remove(),l)}function timeAgo(o){const m=Date.now()-new Date(o).getTime();return m<6e4?"just now":m<36e5?Math.floor(m/6e4)+"m ago":m<864e5?Math.floor(m/36e5)+"h ago":Math.floor(m/864e5)+"d ago"}function safeGet(o,m=null){try{const l=localStorage.getItem(o);return l!==null?l:m}catch{return m}}function safeSet(o,m){try{localStorage.setItem(o,m)}catch{}}function safeRemove(o){try{localStorage.removeItem(o)}catch{}}function safeSessionGet(o,m=null){try{const l=sessionStorage.getItem(o);return l!==null?l:m}catch{return m}}function safeSessionSet(o,m){try{sessionStorage.setItem(o,m)}catch{}}function safeGetJSON(o,m=null){try{const l=localStorage.getItem(o);return l?JSON.parse(l):m}catch{return m}}function escapeHtml(o){return String(o??"").replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'")}function injectModal(o,m){document.getElementById(o)||document.body.insertAdjacentHTML("beforeend",m)}const DC_BUS={_handlers:{},on(o,m){var l;((l=this._handlers)[o]||(l[o]=[])).push(m)},off(o,m){this._handlers[o]=this._handlers[o]?.filter(l=>l!==m)},emit(o,m){this._handlers[o]?.forEach(l=>l(m))}},AppState={_apps:[],getApps(){return this._apps},setApps(o){this._apps=o,window.APPS=o,DC_BUS.emit("apps:changed",o)},findApp(o){return this._apps.find(m=>m.id===o)},addApp(o){this._apps.push(o),window.APPS=this._apps,DC_BUS.emit("apps:changed",this._apps)},removeApp(o){const m=this._apps.findIndex(l=>l.id===o);return m>-1&&(this._apps.splice(m,1),window.APPS=this._apps,DC_BUS.emit("apps:changed",this._apps)),m>-1},updateApp(o,m){const l=this._apps.find(k=>k.id===o);if(l){for(const[k,v]of Object.entries(m))k!=="__proto__"&&k!=="constructor"&&k!=="prototype"&&(l[k]=v);DC_BUS.emit("apps:changed",this._apps)}return l}};(function(){function o(){const k=document.createElement("div");return k.className="skeleton-card",k.innerHTML='
',k}function m(k){const v=document.getElementById("cards");if(!(!v||v.querySelector(".card"))){k=k||6;for(let i=0;i.4,P={};return P.hover=C?c(y,T,.35):c(y,$,.08),P["card-hover"]=c(y,P.hover,.5),P.base=c(T,y,.6),P["fg-muted"]=c(b,T,.35),P.success=I,P.error=E,P.warning=C?"#d68a00":"#f39c12",P}function s(w,T){var $=T.lightBg||T.bg&&g(T.bg)>.4,b=T.accent||T["accent-strong"]||"#888888",y=p(b);return $?":root."+w+` body {
background:
radial-gradient(1200px 800px at 10% -10%, rgba(`+y.r+","+y.g+","+y.b+`, .08), transparent 60%),
radial-gradient(1000px 700px at 110% 10%, rgba(`+y.r+","+y.g+","+y.b+`, .05), transparent 55%),
var(--bg);
}
`:":root."+w+` body {
background:
radial-gradient(1200px 900px at 8% -12%, rgba(`+y.r+","+y.g+","+y.b+`, .10), transparent 60%),
radial-gradient(1000px 700px at 110% -10%, rgba(`+y.r+","+y.g+","+y.b+`, .07), transparent 55%),
var(--bg);
}
`}function u(w,T){var $=T.lightBg||T.bg&&g(T.bg)>.4;return $?":root."+w+` button:hover {
background: color-mix(in srgb, var(--accent-strong) 12%, white 88%);
border-color: rgba(0, 0, 0, .15);
box-shadow: 0 1px 6px rgba(0, 0, 0, .08), inset 0 1px 0 rgba(255, 255, 255, .8);
}
`:":root."+w+` button:hover {
background: color-mix(in srgb, var(--accent) 18%, transparent);
border-color: color-mix(in srgb, var(--accent) 35%, var(--border));
}
`}function t(){return window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function d(){i.forEach(function(w){document.documentElement.style.removeProperty("--"+w)})}function f(w,T){var $=w.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"");$||($="custom"),k.indexOf($)!==-1&&($=$+"-custom");for(var b=safeGetJSON(m,{}),y=$,I=2;b[$]&&$!==T;)$=y+"-"+I++;return $}function r(w){var T=document.getElementById("user-theme-styles");T&&T.remove(),v.length=k.length,Object.keys(x).forEach(function(E){k.indexOf(E)===-1&&delete x[E]});var $=w||safeGetJSON(m,{}),b=Object.keys($);if(b=b.filter(function(E){return k.indexOf(E)===-1}),!!b.length){var y="";b.forEach(function(E){var C=$[E];v.indexOf(E)===-1&&v.push(E);var P={};i.forEach(function(O){C[O]&&(P[O]=C[O])}),P["card-bg"]=C["card-base"]||C.bg,C.lightBg&&(P.lightBg=!0);var D=e(P);n.forEach(function(O){!P[O]&&D[O]&&(P[O]=D[O])}),x[E]=P,y+=":root."+E+` {
`,i.forEach(function(O){P[O]&&(y+=" --"+O+": "+P[O]+`;
`)}),y+=`}
`,y+=s(E,P),y+=u(E,P)});var I=document.createElement("style");I.id="user-theme-styles",I.textContent=y,document.head.appendChild(I)}}function S(){secureFetch("/api/v1/themes").then(function(w){return w.json()}).then(function(w){if(!(!w.success||!w.themes)){var T=w.themes,$=safeGetJSON(m,{});if(JSON.stringify(T)!==JSON.stringify($)){safeSet(m,JSON.stringify(T)),r(T);var b=safeGet(o);b&&v.indexOf(b)!==-1&&L(b)}}}).catch(function(){})}function B(){var w=safeGetJSON(l);if(w){var T=w.name||"Custom",$=f(T),b={name:T};i.forEach(function(E){w[E]&&(b[E]=w[E])});var y=safeGetJSON(m,{});y[$]=b,safeSet(m,JSON.stringify(y)),safeGet(o)==="custom"&&safeSet(o,$),safeRemove(l);var I={};i.forEach(function(E){b[E]&&(I[E]=b[E])}),fetch("/api/v1/themes/"+$,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:T,colors:I})}).catch(function(){})}}function L(w){document.documentElement.classList.add("theme-transitioning"),v.forEach(function(y){y!=="dark"&&document.documentElement.classList.remove(y)}),d(),w!=="dark"&&document.documentElement.classList.add(w),safeSet(o,w);var T=x[w],$=document.querySelector('meta[name="theme-color"]');$&&T&&$.setAttribute("content",T.bg);var b=T&&T.lightBg;!b&&T&&T.bg&&(b=g(T.bg)>.4),b?document.documentElement.classList.add("light-bg"):document.documentElement.classList.remove("light-bg"),setTimeout(function(){document.documentElement.classList.remove("theme-transitioning")},300)}B(),r();var A=safeGet(o);A==="red"&&(A="black",safeSet(o,"black")),A&&A!=="dark"&&v.indexOf(A)===-1&&(A=null),L(A||t()),S(),window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change",function(w){safeGet(o)||L(w.matches?"dark":"light")}),window.THEMES=v,window.BUILTIN_THEMES=k,window.THEME_COLORS=x,window.THEME_PROPS=i,window.BASE_PROPS=h,window.DERIVED_PROPS=n,window.USER_THEMES_KEY=m,window.applyTheme=L,window.clearCustomProperties=d,window.injectUserThemeStyles=r,window.syncThemesFromServer=S,window.slugifyThemeName=f,window.getActiveTheme=function(){return safeGet(o)||t()},window.deriveExtendedColors=e,window.hexToRgb=p,window.rgbToHex=a,window.blendColors=c})(),(function(){function o(){const h=document.querySelector(".totp-card");if(!h)return;const x=getComputedStyle(h).backgroundColor.match(/\d+/g);if(!x)return;const p=(.299*+x[0]+.587*+x[1]+.114*+x[2])/255,a=h.querySelector(".totp-logo-dark"),c=h.querySelector(".totp-logo-light");a&&(a.style.display=p>.5?"none":""),c&&(c.style.display=p>.5?"":"none")}function m(){const h=document.getElementById("totp-overlay");if(h){h.classList.add("show"),setTimeout(o,50);const n=h.querySelector(".totp-digits input");n&&setTimeout(()=>n.focus(),100)}}function l(){const h=document.getElementById("totp-overlay");h&&h.classList.remove("show")}const k=document.getElementById("totp-digits");if(k){const h=k.querySelectorAll("input");h.forEach((n,x)=>{n.addEventListener("input",p=>{const a=p.target.value.replace(/\D/g,"");p.target.value=a.slice(0,1),a&&xg.value).join("");c.length===6&&v(c)}),n.addEventListener("keydown",p=>{p.key==="Backspace"&&!p.target.value&&x>0&&(h[x-1].focus(),h[x-1].value="")}),n.addEventListener("paste",p=>{p.preventDefault();const a=(p.clipboardData.getData("text")||"").replace(/\D/g,"");a.length>=6&&(h.forEach((c,g)=>{c.value=a[g]||""}),h[5].focus(),v(a.slice(0,6)))})})}async function v(h){const n=document.getElementById("totp-error");n.textContent="Verifying...",n.className="totp-error verifying";try{const p=await(await secureFetch("/api/v1/totp/verify",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:h})})).json();if(p.success){n.textContent="",p.csrfToken&&(csrfToken=p.csrfToken),l();const a=safeSessionGet("totp_redirect");if(a){try{sessionStorage.removeItem("totp_redirect")}catch{}window.location.href=a;return}typeof window.initializeDashboard=="function"&&window.initializeDashboard()}else{n.textContent=p.error||"Invalid code",n.className="totp-error";const a=document.querySelectorAll("#totp-digits input");a.forEach(c=>{c.value=""}),a[0]?.focus()}}catch{n.textContent="Connection error",n.className="totp-error"}}const i=new URLSearchParams(window.location.search);if(i.get("auth")==="required"){const h=i.get("return");if(h)try{const n=new URL(h,window.location.origin),x=n.hostname,p=n.origin===window.location.origin,a=SITE.tld.startsWith(".")?SITE.tld:"."+SITE.tld,c=x.endsWith(a)||x===a.substring(1);(p||c)&&safeSessionSet("totp_redirect",h)}catch{}window.history.replaceState({},"",window.location.pathname)}window._showTotpOverlay=m})(),(function(){const o=new ErrorHandler;injectModal("folder-browser-modal",`
\u{1F4C2} Browse for Media Folders
/
`),injectModal("service-creds-modal",`
Service Credentials
Credentials are injected automatically when accessing this service.
No credentials stored
Quality Profile
Used when requesting via Seerr
-- Enter API key first --
Fetch
Service Login
Save
Clear
Cancel
`);const m=document.getElementById("service-creds-modal");let l=null;const k=["sonarr","radarr","prowlarr","overseerr"],v=["sonarr","radarr"];function i(a){return a.externalUrl||a.url||""}function h(a){const c=document.getElementById("svc-creds-error");c.textContent=a,c.style.display=""}function n(){const a=document.getElementById("svc-creds-error");a.textContent="",a.style.display="none"}window.openServiceCredsModal=async function(a){l=a,n();const c=document.getElementById("svc-creds-title"),g=document.getElementById("svc-creds-desc"),e=document.getElementById("svc-creds-seedhost"),s=document.getElementById("svc-creds-apikey"),u=document.getElementById("svc-creds-basic"),t=document.getElementById("svc-creds-quality");c.textContent=a.name+" Credentials";const d=!!a.isExternal,f=k.includes(a.id)||k.includes(a.appTemplate),r=v.includes(a.id)||v.includes(a.appTemplate);e.style.display=d?"":"none",s.style.display=f?"":"none",t.style.display=r?"":"none",u.style.display=d?"none":"";const S=document.getElementById("svc-quality-select");S.innerHTML='-- Enter API key first -- ',document.getElementById("svc-quality-status").textContent="",d?(g.textContent="Seedhost credentials auto-login past the HTTP prompt. API key bypasses the app login.",document.getElementById("svc-seedhost-pass").placeholder=`Password for ${a.name}`):f?g.textContent="API key bypasses the app login screen automatically.":g.textContent="Credentials are injected automatically when accessing this service.",await x(a),m.classList.add("show")};async function x(a){const c=document.getElementById("svc-creds-dot"),g=document.getElementById("svc-creds-status"),e=document.getElementById("svc-creds-clear");let s=!1;if(a.isExternal){try{const d=await(await fetch(`/api/v1/seedhost-creds?serviceId=${a.id}`)).json();d.success?(document.getElementById("svc-seedhost-user").value=d.username||"",d.hasCredentials&&(s=!0)):document.getElementById("svc-seedhost-user").value=""}catch{}document.getElementById("svc-seedhost-pass").value=""}try{const d=await(await fetch(`/api/v1/services/${a.id}/credentials`)).json();d.success&&(d.hasApiKey?(document.getElementById("svc-apikey-input").value="\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022",s=!0):document.getElementById("svc-apikey-input").value="",d.hasBasicAuth&&!a.isExternal?(document.getElementById("svc-basic-user").value=d.username||"",s=!0):document.getElementById("svc-basic-user").value="")}catch{}document.getElementById("svc-basic-pass")&&(document.getElementById("svc-basic-pass").value="");const u=a.id||a.appTemplate;if(v.includes(u)&&await p(a),s){c.style.background="var(--ok-fg, #74dfc4)",g.style.color="var(--ok-fg, #74dfc4)",g.textContent="Credentials stored",e.style.display="";const t=document.getElementById(`creds-btn-${a.id}`);t&&t.classList.add("has-creds")}else c.style.background="var(--muted)",g.style.color="var(--muted)",g.textContent="No credentials stored",e.style.display="none"}async function p(a){const c=document.getElementById("svc-quality-select"),g=document.getElementById("svc-quality-status"),e=a.id||a.appTemplate,s=i(a);if(!s){c.innerHTML='-- No service URL -- ';return}c.innerHTML='Loading... ',g.textContent="";try{const u=new URLSearchParams({service:e,url:s}),d=await(await fetch(`/api/v1/arr/quality-profiles?${u}`)).json();if(!d.success||!d.profiles?.length){c.innerHTML='-- No profiles found (enter API key and click Fetch) -- ';return}c.innerHTML="";for(const f of d.profiles){const r=document.createElement("option");r.value=f.id,r.textContent=f.name,c.appendChild(r)}if(d.storedProfileId&&(c.value=String(d.storedProfileId)),!c.value){const f=d.profiles.find(r=>/720/i.test(r.name));f&&(c.value=String(f.id))}!c.value&&d.profiles.length&&(c.value=String(d.profiles[0].id)),g.innerHTML=`${d.profiles.length} profiles loaded `}catch(u){c.innerHTML='-- Failed to load -- ',g.innerHTML=`Error: ${u.message} `}}document.getElementById("svc-quality-fetch")?.addEventListener("click",async()=>{if(!l)return;const a=l.id||l.appTemplate,c=i(l),e=document.getElementById("svc-apikey-input")?.value.trim(),s=document.getElementById("svc-quality-select"),u=document.getElementById("svc-quality-status");if(!c){u.innerHTML='No service URL available ';return}if(!e||e==="\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022"){u.innerHTML='Enter an API key first ';return}s.innerHTML='Fetching... ',u.textContent="";try{const t=new URLSearchParams({service:a,url:c,apiKey:e}),f=await(await fetch(`/api/v1/arr/quality-profiles?${t}`)).json();if(!f.success){s.innerHTML='-- Error -- ',u.innerHTML=`${f.error||"Failed to fetch profiles"} `;return}if(!f.profiles?.length){s.innerHTML='-- No profiles found -- ';return}s.innerHTML="";for(const S of f.profiles){const B=document.createElement("option");B.value=S.id,B.textContent=S.name,s.appendChild(B)}const r=f.profiles.find(S=>/720/i.test(S.name));r?s.value=String(r.id):f.profiles.length&&(s.value=String(f.profiles[0].id)),u.innerHTML=`${f.profiles.length} profiles loaded `}catch(t){s.innerHTML='-- Error -- ',u.innerHTML=`${t.message} `}}),document.getElementById("svc-creds-save")?.addEventListener("click",async()=>{if(!l)return;const a=document.getElementById("svc-creds-save");a.textContent="Saving...",a.disabled=!0,n();try{const c=k.includes(l.id)||k.includes(l.appTemplate),g=l.id||l.appTemplate;if(l.isExternal){const u=document.getElementById("svc-seedhost-user").value.trim(),t=document.getElementById("svc-seedhost-pass").value;u&&await secureFetch("/api/v1/seedhost-creds",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:u,password:t||void 0,serviceId:l.id})})}const s=document.getElementById("svc-apikey-input")?.value.trim();if(s&&s!=="\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022")if(c){const u=i(l),t=document.getElementById("svc-quality-select"),d=t?.value?parseInt(t.value):void 0,f=t?.selectedOptions?.[0]?.textContent||void 0,S=await(await secureFetch("/api/v1/arr/credentials",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({service:g,apiKey:s,url:u||void 0,qualityProfileId:d||void 0,qualityProfileName:f||void 0})})).json();if(!S.success){h(S.error||"Failed to save API key"),a.textContent="Save",a.disabled=!1;return}S.connectionTest&&!S.connectionTest.success&&h(`API key saved but connection test failed: ${S.connectionTest.error}`)}else await secureFetch(`/api/v1/services/${l.id}/credentials`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:s})});else if(c&&v.includes(g)){const u=document.getElementById("svc-quality-select"),t=u?.value?parseInt(u.value):void 0,d=u?.selectedOptions?.[0]?.textContent||void 0;t&&await secureFetch("/api/v1/arr/quality-profiles",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({service:g,qualityProfileId:t,qualityProfileName:d})})}if(!l.isExternal){const u=document.getElementById("svc-basic-user").value.trim(),t=document.getElementById("svc-basic-pass").value;u&&t&&await secureFetch(`/api/v1/services/${l.id}/credentials`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:u,password:t})})}await x(l)}catch(c){o.logError("[ServiceCredentials] Save",c,{function:"saveCredentials"}),h("Failed to save: "+(c.message||"Unknown error"))}a.textContent="Save",a.disabled=!1}),document.getElementById("svc-creds-clear")?.addEventListener("click",async()=>{if(l&&confirm(`Remove stored credentials for ${l.name}?`)){n();try{const a=l.id||l.appTemplate,c=k.includes(a);l.isExternal&&await secureFetch(`/api/v1/seedhost-creds?serviceId=${l.id}`,{method:"DELETE"}),await secureFetch(`/api/v1/services/${l.id}/credentials`,{method:"DELETE"}),c&&await secureFetch(`/api/v1/arr/credentials/${a}`,{method:"DELETE"});const g=document.getElementById(`creds-btn-${l.id}`);g&&g.classList.remove("has-creds"),await x(l)}catch(a){o.logError("[ServiceCredentials] Clear",a,{function:"clearCredentials"}),h("Failed to clear: "+(a.message||"Unknown error"))}}}),document.getElementById("svc-creds-close")?.addEventListener("click",()=>{m.classList.remove("show"),l=null}),m?.addEventListener("click",a=>{a.target===m&&(m.classList.remove("show"),l=null)}),window.refreshCredsButtons=async function(){try{for(const a of window.APPS||[]){if(!a.isExternal&&!a.appTemplate&&!a.url)continue;let c=!1;if(a.isExternal)try{const s=await(await fetch(`/api/v1/seedhost-creds?serviceId=${a.id}`)).json();s.success&&s.hasCredentials&&(c=!0)}catch{}try{const s=await(await fetch(`/api/v1/services/${a.id}/credentials`)).json();s.success&&(s.hasApiKey||s.hasBasicAuth)&&(c=!0)}catch{}const g=document.getElementById(`creds-btn-${a.id}`);g&&g.classList.toggle("has-creds",c)}}catch{}}})(),(function(){const o=new ErrorHandler;injectModal("totp-settings-modal",`
Authentication Settings
TOTP is not configured
Copy this key into your authenticator app:
\u{1F4CB}
Show QR code (for mobile authenticator apps)
Session Duration:
15 minutes
30 minutes
1 hour
2 hours
4 hours
8 hours
12 hours
24 hours
Never (disable TOTP)
How long before you need to re-enter your code
Disable TOTP
Close
`);async function m(){try{const i=await(await fetch("/api/v1/totp/config")).json();if(!i.success)return;const{enabled:h,sessionDuration:n,isSetUp:x}=i.config,p=document.getElementById("totp-status-dot"),a=document.getElementById("totp-status-text"),c=document.getElementById("totp-status-banner"),g=document.getElementById("totp-setup-section"),e=document.getElementById("totp-qr-section"),s=document.getElementById("totp-duration-section"),u=document.getElementById("totp-disable-section");h&&x?(p.style.background="var(--ok-fg, #7ef2ff)",c.style.borderColor="var(--ok-fg, #7ef2ff)",c.style.background="color-mix(in srgb, var(--ok-fg) 8%, transparent)",a.textContent="TOTP is active",a.style.color="var(--ok-fg, #7ef2ff)",g.style.display="none",e.style.display="none",s.style.display="block",u.style.display="block",document.getElementById("totp-duration-select").value=n):(p.style.background="var(--muted)",c.style.borderColor="var(--border)",c.style.background="transparent",a.textContent="TOTP is not configured",a.style.color="var(--muted)",g.style.display="block",e.style.display="none",s.style.display="none",u.style.display="none"),k(h&&x,n)}catch(v){console.warn("Failed to load TOTP settings:",v)}}const l={"15m":"15 min","30m":"30 min","1h":"1 hour","2h":"2 hours","4h":"4 hours","8h":"8 hours","12h":"12 hours","24h":"24 hours",never:"Disabled"};function k(v,i){const h=document.getElementById("auth-card"),n=document.getElementById("auth-pill"),x=document.getElementById("auth-dot"),p=document.getElementById("auth-status-text");h&&(v?(h.setAttribute("data-status","on"),n.className="badge on",n.textContent="YES",x.className="dot ok at-bl",p.textContent="Session: "+(l[i]||i)):(h.setAttribute("data-status","off"),n.className="badge off",n.textContent="NO",x.className="dot bad at-bl",p.textContent="Not configured"))}document.getElementById("totp-setup-btn")?.addEventListener("click",async()=>{try{const i=await(await secureFetch("/api/v1/totp/setup",{method:"POST"})).json();i.success&&(document.getElementById("totp-qr-image").src=i.qrCode,document.getElementById("totp-manual-key").textContent=i.manualKey,document.getElementById("totp-setup-section").style.display="none",document.getElementById("totp-qr-section").style.display="block",document.getElementById("totp-setup-code").value="",document.getElementById("totp-setup-error").textContent="",document.getElementById("totp-setup-code").focus())}catch(v){o.logError("[TOTP] Setup Failed",v,{function:"setupTOTP"})}}),document.getElementById("totp-import-btn")?.addEventListener("click",async()=>{const v=document.getElementById("totp-import-key").value.trim(),i=document.getElementById("totp-import-error");if(i.textContent="",!v){i.textContent="Paste a Base32 secret key first";return}try{const n=await(await secureFetch("/api/v1/totp/setup",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({secret:v})})).json();n.success?(i.textContent="",document.getElementById("totp-qr-image").src=n.qrCode,document.getElementById("totp-manual-key").textContent=n.manualKey,document.getElementById("totp-setup-section").style.display="none",document.getElementById("totp-qr-section").style.display="block",document.getElementById("totp-setup-code").value="",document.getElementById("totp-setup-error").textContent="",document.getElementById("totp-setup-code").focus()):i.textContent=n.error||n.message||"Import failed"}catch{i.textContent="Connection error \u2014 try refreshing the page"}}),document.getElementById("totp-copy-key")?.addEventListener("click",()=>{const v=document.getElementById("totp-manual-key").textContent;navigator.clipboard.writeText(v).then(()=>{const i=document.getElementById("totp-copy-key");i.textContent="\u2705",setTimeout(()=>{i.textContent="\u{1F4CB}"},2e3)})}),document.getElementById("totp-confirm-setup")?.addEventListener("click",async()=>{const v=document.getElementById("totp-setup-code").value,i=document.getElementById("totp-setup-error");if(!/^\d{6}$/.test(v)){i.textContent="Enter a 6-digit code";return}try{const n=await(await secureFetch("/api/v1/totp/verify-setup",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:v})})).json();n.success?(i.textContent="",m()):i.textContent=n.error||"Invalid code"}catch{i.textContent="Connection error"}}),document.getElementById("totp-setup-code")?.addEventListener("keydown",v=>{v.key==="Enter"&&document.getElementById("totp-confirm-setup")?.click()}),document.getElementById("totp-duration-select")?.addEventListener("change",async v=>{try{await secureFetch("/api/v1/totp/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionDuration:v.target.value})}),m()}catch(i){o.logError("[TOTP] Update Session Duration",i,{function:"updateSessionDuration"})}}),document.getElementById("totp-disable-btn")?.addEventListener("click",async()=>{if(confirm("Disable TOTP authentication? All services will be accessible without a code."))try{(await(await secureFetch("/api/v1/totp/disable",{method:"POST",headers:{"Content-Type":"application/json"},body:"{}"})).json()).success&&m()}catch(v){o.logError("[TOTP] Disable Failed",v,{function:"disableTOTP"})}}),document.getElementById("auth-settings-btn")?.addEventListener("click",()=>{m(),openModal("totp-settings-modal")}),document.getElementById("totp-modal-close")?.addEventListener("click",()=>{closeModal("totp-settings-modal")}),document.getElementById("totp-settings-modal")?.addEventListener("click",v=>{v.target.id==="totp-settings-modal"&&closeModal("totp-settings-modal")}),window._updateAuthCard=k,(async()=>{try{const i=await(await fetch("/api/v1/totp/config")).json();if(i.success){const h=i.config.enabled&&i.config.isSetUp;k(h,i.config.sessionDuration)}}catch(v){o.logError("[TOTP] AuthCard Update",v,{function:"authCardUpdate"})}})()})(),(function(){injectModal("token-management-modal",`
\u{1F511} DNS Credentials
Enter Technitium DNS login credentials. Read-only accounts are used for logs; admin accounts for restarts, records, and updates.
`);function o(){return Object.keys(SITE.dnsServers||{})}function m(t){return(SITE.dnsServers||{})[t]?.name||t.toUpperCase()}function l(){const t=document.getElementById("dns-cred-sections");if(!t)return;t.innerHTML="";const d=o();if(d.length===0){t.innerHTML='No DNS servers configured.
';return}for(const f of d)t.insertAdjacentHTML("beforeend",`
`)}function k(){let t=safeSessionGet("dashcaddy-encryption-key");if(t)return t;const d=safeGet("dashcaddy-encryption-key");if(d)return safeSessionSet("dashcaddy-encryption-key",d),safeRemove("dashcaddy-encryption-key"),d;const f=new Uint8Array(32);return crypto.getRandomValues(f),t=Array.from(f,r=>r.toString(16).padStart(2,"0")).join(""),safeSessionSet("dashcaddy-encryption-key",t),t}const v=k();function i(t,d){if(!t)return"";const f=crypto.getRandomValues(new Uint8Array(8)),r=Array.from(f,L=>L.toString(16).padStart(2,"0")).join(""),S=new TextEncoder().encode(d+r);let B="";for(let L=0;LparseInt($,16))),A=atob(t.substring(17)),w=new TextEncoder().encode(d+B);let T="";for(let $=0;${["readonly","admin"].forEach(d=>{["token","username"].forEach(f=>{safeRemove(`${t}-${d}-${f}-enc`)})}),safeRemove(`${t}-token-enc`),safeRemove(`${t}-username-enc`)})}function u(t){const d=p(t,"readonly"),f=a(t,"readonly"),r=p(t,"admin"),S=a(t,"admin"),B=h(safeGet(`${t}-token-enc`),v),L=h(safeGet(`${t}-username-enc`),v);return{username:S||f||L,token:r||d||B,readonlyToken:d||B,readonlyUsername:f||L,adminToken:r||B,adminUsername:S||L}}document.getElementById("manage-tokens")?.addEventListener("click",()=>{l();const t=document.getElementById("token-management-modal"),d=e();o().forEach(f=>{const r=d[f];document.getElementById(`${f}-readonly-username`).value=r.readonly.username,document.getElementById(`${f}-readonly-token`).value=r.readonly.token,document.getElementById(`${f}-admin-username`).value=r.admin.username,document.getElementById(`${f}-admin-token`).value=r.admin.token,document.getElementById(`${f}-token-status`).textContent=""}),t.classList.add("show")}),document.getElementById("token-management-modal")?.addEventListener("click",t=>{const d=t.target.closest(".token-toggle");if(d){const f=d.dataset.target,r=document.getElementById(f);r.type==="password"?(r.type="text",d.textContent="\u{1F648}"):(r.type="password",d.textContent="\u{1F441}");return}t.target.id==="token-management-modal"&&t.target.classList.remove("show")}),document.getElementById("token-save")?.addEventListener("click",async()=>{const t=o();t.forEach(r=>{g(r,"readonly",document.getElementById(`${r}-readonly-username`).value.trim()),c(r,"readonly",document.getElementById(`${r}-readonly-token`).value.trim()),g(r,"admin",document.getElementById(`${r}-admin-username`).value.trim()),c(r,"admin",document.getElementById(`${r}-admin-token`).value.trim())});const d={};let f=!1;if(t.forEach(r=>{const S={},B=document.getElementById(`${r}-readonly-username`).value.trim(),L=document.getElementById(`${r}-readonly-token`).value.trim(),A=document.getElementById(`${r}-admin-username`).value.trim(),w=document.getElementById(`${r}-admin-token`).value.trim();B&&L&&(S.readonly={username:B,password:L},f=!0),A&&w&&(S.admin={username:A,password:w},f=!0),Object.keys(S).length>0&&(d[r]=S)}),f){t.forEach(r=>{d[r]&&(document.getElementById(`${r}-token-status`).textContent="Verifying...",document.getElementById(`${r}-token-status`).className="token-status")});try{const S=await(await secureFetch("/api/v1/dns/credentials",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({servers:d})})).json();S.results?t.forEach(B=>{const L=document.getElementById(`${B}-token-status`);if(!d[B]){L.textContent="";return}const A=S.results[B];A?.success?(L.textContent="\u2713 Verified & saved",L.className="token-status success"):A?.partial?(L.textContent="\u2713 "+A.partial,L.className="token-status success"):(L.textContent="\u2717 "+(A?.error||"Login failed"),L.className="token-status error")}):S.success?t.forEach(B=>{d[B]&&(document.getElementById(`${B}-token-status`).textContent="\u2713 Saved",document.getElementById(`${B}-token-status`).className="token-status success")}):t.forEach(B=>{d[B]&&(document.getElementById(`${B}-token-status`).textContent="\u2717 "+(S.error||"Failed"),document.getElementById(`${B}-token-status`).className="token-status error")})}catch(r){console.error("Failed to sync DNS credentials to backend:",r),t.forEach(S=>{d[S]&&(document.getElementById(`${S}-token-status`).textContent="\u2713 Saved locally (sync failed)",document.getElementById(`${S}-token-status`).className="token-status")})}}else t.forEach(r=>{document.getElementById(`${r}-token-status`).textContent=""});setTimeout(()=>{t.every(S=>{const B=document.getElementById(`${S}-token-status`)?.textContent;return!B||B.includes("\u2713")})&&closeModal("token-management-modal")},1500)}),document.getElementById("token-cancel")?.addEventListener("click",()=>{closeModal("token-management-modal")}),document.getElementById("token-clear-all")?.addEventListener("click",async()=>{if(confirm("Clear all stored DNS credentials? This cannot be undone.")){s(),o().forEach(t=>{document.getElementById(`${t}-readonly-username`).value="",document.getElementById(`${t}-readonly-token`).value="",document.getElementById(`${t}-admin-username`).value="",document.getElementById(`${t}-admin-token`).value="",document.getElementById(`${t}-token-status`).textContent="\u2713 Cleared",document.getElementById(`${t}-token-status`).className="token-status success"});try{await secureFetch("/api/v1/dns/credentials",{method:"DELETE"})}catch{}}}),window.getToken=p,window.getUsername=a,window.setToken=c,window.setUsername=g,window.getAllCredentials=e,window.getCredential=n,window.setCredential=x,window.getEncryptionKey=k,window.getDnsIds=o,window.getDnsDisplayName=m})(),(function(){function o(c,g,e=null){const s=document.getElementById(c+"-dot"),u=document.getElementById(c+"-pill"),t=document.getElementById(c+"-time"),d=document.querySelector(`[data-app="${c}"]`);s&&(s.classList.toggle("ok",g),s.classList.toggle("bad",!g)),u&&(u.textContent=g?"ON":"OFF",u.classList.toggle("on",g),u.classList.toggle("off",!g)),t&&e!==null&&(t.textContent=g?`${e}ms`:"timeout",t.className=`response-time ${m(e,g)}`),d&&d.setAttribute("data-status",g?"on":"off")}function m(c,g){return g?c<200?"excellent":c<500?"good":c<1e3?"fair":"slow":"timeout"}async function l(c){const g=performance.now();try{const e=await fetch("/probe/"+c,{cache:"no-store"}),s=performance.now(),u=Math.round(s-g);return{isUp:e.status>=200&&e.status<400||e.status===401||e.status===403,responseTime:u}}catch{const e=performance.now();return{isUp:!1,responseTime:Math.round(e-g)}}}window.APPS=[];let k=null,v=!1;async function i(){try{window.SkeletonLoader&&window.SkeletonLoader.show(6);const c=await fetch("/api/v1/services",{cache:"no-store"});c.ok?(window.APPS=await c.json(),window.SkeletonLoader&&window.SkeletonLoader.hide()):(console.error("Failed to load services:",c.status),window.SkeletonLoader&&window.SkeletonLoader.hide())}catch(c){console.error("Failed to load services:",c),window.SkeletonLoader&&window.SkeletonLoader.hide()}}function h(c){const g=window.APPS?.find(s=>s.id===c);if(g?.url)return g.url.startsWith("http")?g.url:"https://"+g.url;if(g?.isExternal&&g.externalUrl)return g.externalUrl;const e=SITE.dnsServers?.[c];return e?"http://"+e.ip+":"+(e.port||5380):buildServiceUrl(c)}function n(c,g,e){const s=document.createElement(c);return g&&(s.className=g),e&&(s.textContent=e),s}function x(){const c=document.getElementById("cards");c.innerHTML="";for(let g=0;g{D.stopPropagation(),window.openContainerLogsModal(e.containerId,e.name)},y.appendChild(E);const C=n("button","update-btn","\u2B06\uFE0F");C.title="Update container to latest version",C.id=`update-btn-${e.id}`,C.onclick=D=>{D.stopPropagation(),window.updateContainer(e.containerId,e.name,e.id)},y.appendChild(C);const P=n("button","exec-btn",">_");P.title="Open terminal",P.onclick=D=>{D.stopPropagation(),window.openExecModal&&window.openExecModal(e.containerId,e.name)},y.appendChild(P)}if(e.logPath&&!e.containerId){const E=n("button","logs-btn","\u{1F4CB}");E.title="View application logs",E.onclick=C=>{C.stopPropagation(),window.openFileLogsModal(e.logPath,e.name)},y.appendChild(E)}if(e.isExternal||e.appTemplate||e.url){const E=n("button","creds-btn","\u{1F511}");E.title="Auto-login credentials",E.id=`creds-btn-${e.id}`,E.onclick=C=>{C.stopPropagation(),window.openServiceCredsModal(e)},y.appendChild(E)}if(e.id!=="internet"){const E=n("button","options-btn","\u2699\uFE0F");E.title="Edit service settings",E.onclick=C=>{C.stopPropagation(),window.openServiceEditModal(e)},y.appendChild(E)}if(e.id!=="internet"){const E=n("button","delete-btn","\u{1F5D1}\uFE0F");E.title="Delete this service",E.onclick=C=>{C.stopPropagation(),window.deleteService(e.id,e.name)},y.appendChild(E)}const I=n("button",null,"Open");I.onclick=()=>window.open(h(e.id),"_blank","noopener"),y.appendChild(I),s.appendChild(y),s.style.transitionDelay=`${Math.min(g*45,270)}ms`,c.appendChild(s)}requestAnimationFrame(()=>{c.querySelectorAll(".card").forEach(g=>g.classList.add("loaded"))}),window.groupRecipeCards&&requestAnimationFrame(()=>window.groupRecipeCards())}function p(c,g,e=null){const s=document.getElementById("dot-"+c+"-grid"),u=document.getElementById("badge-"+c),t=document.getElementById("time-"+c),d=document.querySelector(`[data-app="${c}"]`);s&&(s.classList.toggle("ok",g),s.classList.toggle("bad",!g)),u&&(u.textContent=g?"ON":"OFF",u.classList.toggle("on",g),u.classList.toggle("off",!g)),t&&e!==null&&(t.textContent=g?`${e}ms`:"timeout",t.className=`response-time ${m(e,g)}`),d&&d.setAttribute("data-status",g?"on":"off")}async function a(){if(k)return v=!0,k;function c(s,u=new Date){const t=document.getElementById("stamp");t&&(t.textContent=`${s}: ${new Date(u).toLocaleTimeString()}`)}function g(s){Object.keys(SITE.dnsServers).forEach(t=>{const d=s[t];d&&o(t,d.isUp,d.responseTime)}),s.internet&&o("internet",s.internet.isUp,s.internet.responseTime),window.APPS.forEach(t=>{const d=s[t.id];d&&p(t.id,d.isUp,d.responseTime)})}async function e(){const s=Object.keys(SITE.dnsServers),u=s.map(r=>l(r));u.push(l("internet"));const t=await Promise.all(u);s.forEach((r,S)=>o(r,t[S].isUp,t[S].responseTime));const d=t[t.length-1];o("internet",d.isUp,d.responseTime),(await Promise.all(window.APPS.map(async r=>{const S=await l(r.id);return{id:r.id,...S}}))).forEach(r=>{p(r.id,r.isUp,r.responseTime)})}return k=(async()=>{try{const s=await fetch("/api/v1/services/status",{cache:"no-store"});if(!s.ok)throw new Error(`Status refresh failed (${s.status})`);const u=await s.json();g(u.statuses||{}),c("last check",u.checkedAt||new Date)}catch(s){console.warn("Batched status refresh failed, falling back to direct probes:",s);try{await e(),c("last check")}catch(u){console.error("Dashboard refresh failed:",u),c("last failed")}}finally{k=null,v&&(v=!1,setTimeout(()=>{window.refreshAll()},0))}})(),k}document.querySelector(".top")?.addEventListener("click",c=>{const g=c.target.closest('[id$="-open"]');if(!g)return;const e=g.id.replace("-open","");SITE.dnsServers[e]&&window.open(h(e),"_blank","noopener")}),document.getElementById("ca-open")?.addEventListener("click",()=>window.open(h("ca"),"_blank","noopener")),document.getElementById("creds-btn-ca")?.addEventListener("click",c=>{c.stopPropagation();const g=window.APPS.find(e=>e.id==="ca");g&&window.openServiceCredsModal&&window.openServiceCredsModal(g)}),document.getElementById("options-btn-ca")?.addEventListener("click",c=>{c.stopPropagation();const g=window.APPS.find(e=>e.id==="ca");g&&window.openServiceEditModal&&window.openServiceEditModal(g)}),document.getElementById("delete-btn-ca")?.addEventListener("click",c=>{c.stopPropagation(),window.deleteService&&window.deleteService("ca","DashCA")}),window.loadServices=i,window.buildGrid=x,window.refreshAll=a,window.setQuick=o,window.setBadge=p,window.getResponseTimeClass=m,window.checkServiceWithTiming=l,window.serviceUrl=h,window.el=n})(),(function(){async function o(n){const p=await(await secureFetch(`/api/v1/dns/restart/${n}`,{method:"POST"})).json();if(!p.success)throw new Error(p.error||"Restart failed");return p}document.querySelector(".top")?.addEventListener("click",async n=>{const x=n.target.closest('[id$="-restart"]');if(!x)return;const p=x.id.replace("-restart","");if(SITE.dnsServers[p]&&confirm(`Restart ${p.toUpperCase()} service?`))try{await withButton(x,"...",()=>o(p)),setTimeout(window.refreshAll,DC.DELAYS.RELOAD)}catch(a){showNotification("Restart failed: "+a.message,"error")}});async function m(n,x){const p=document.getElementById(`${n}-update`),a=p?.textContent||"\u2B06\uFE0F";try{p.textContent="\u{1F50D}",p.disabled=!0,p.title="Checking for updates...";const g=await(await fetch(`/api/v1/dns/check-update?server=${encodeURIComponent(x)}`)).json();if(!g.success)throw new Error(g.error||"Failed to check for updates");if(!g.updateAvailable){p.textContent="\u2705",p.title=`Already on latest version (${g.currentVersion})`,showNotification(`${n.toUpperCase()} is already up to date! Current version: ${g.currentVersion}`,"info"),setTimeout(()=>{p.textContent=a,p.disabled=!1,p.title="Update DNS server"},3e3);return}if(!confirm(`Update available for ${n.toUpperCase()}!
Current: ${g.currentVersion}
New: ${g.updateVersion}
`+(g.updateTitle?`${g.updateTitle}
`:"")+`The DNS server will restart during the update.
Proceed?`)){p.textContent=a,p.disabled=!1,p.title="Update DNS server";return}p.textContent="\u{1F504}",p.title="Updating...";const u=await(await secureFetch(`/api/v1/dns/update?server=${encodeURIComponent(x)}`,{method:"POST"})).json();if(!u.success)throw new Error(u.error||"Update failed");if(u.manualUpdateRequired){p.textContent="\u2B06\uFE0F",p.title=`Update available: ${u.newVersion}`;const t=u.downloadLink?`
Download: ${u.downloadLink}`:"",d=u.instructionsLink?`
Instructions: ${u.instructionsLink}`:"";showNotification(`${n.toUpperCase()} update requires manual installation. Current: ${u.previousVersion} \u2192 ${u.newVersion}. Please update manually on the host machine.`,"warning",8e3),p.disabled=!1;return}p.textContent="\u2705",p.title="Updated successfully!",showNotification(`${n.toUpperCase()} updated successfully! ${u.previousVersion} \u2192 ${u.newVersion}. Server is restarting...`,"success"),setTimeout(()=>{p.textContent=a,p.disabled=!1,p.title="Update DNS server",window.refreshAll()},1e4)}catch(c){console.error("DNS update error:",c),p.textContent="\u274C",p.title="Update failed",showNotification(`Failed to update ${n.toUpperCase()}: ${c.message}`,"error"),setTimeout(()=>{p.textContent=a,p.disabled=!1,p.title="Update DNS server"},3e3)}}document.querySelector(".top")?.addEventListener("click",n=>{const x=n.target.closest('[id$="-update"]');if(!x)return;const p=x.id.replace("-update","");SITE.dnsServers[p]&&m(p,SITE.dnsServers[p]?.ip)}),injectModal("dns-settings-modal",`
DNS Settings
Cancel
Remove
Save
`);let l=null;function k(n){l=n;const x=SITE.dnsServers[n]||{},p=document.getElementById("dns-settings-modal");document.getElementById("dns-settings-title").textContent=`${(x.name||n).toUpperCase()} Settings`,document.getElementById("dns-edit-ip").value=x.ip||"",document.getElementById("dns-edit-port").value=x.port||DC.DEFAULTS.DNS_PORT,document.getElementById("dns-edit-name").value=x.name||"",p.classList.add("show")}async function v(){if(!l)return;const n=document.getElementById("dns-edit-ip").value.trim(),x=document.getElementById("dns-edit-port").value.trim()||DC.DEFAULTS.DNS_PORT,p=document.getElementById("dns-edit-name").value.trim();if(!n){showNotification("Server IP is required","warning");return}const a={dnsServers:{}};a.dnsServers[l]={ip:n,port:String(x)},p&&(a.dnsServers[l].name=p);try{const g=await(await secureFetch("/api/v1/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)})).json();g.success?(SITE.dnsServers[l]=a.dnsServers[l],showNotification(`${l.toUpperCase()} settings saved`,"success"),h(),window.refreshAll()):showNotification(g.error||"Failed to save settings","error")}catch(c){showNotification("Failed to save: "+c.message,"error")}}async function i(){if(l&&confirm(`Remove ${l.toUpperCase()} from dashboard? This won't affect the actual DNS server.`))try{const x=await(await secureFetch("/api/v1/config")).json();x.dnsServers&&delete x.dnsServers[l];const a=await(await secureFetch("/api/v1/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({dnsServers:x.dnsServers||{}})})).json();if(a.success){delete SITE.dnsServers[l];const c=document.querySelector(`.top [data-app="${l}"]`);c&&c.remove(),showNotification(`${l.toUpperCase()} removed from dashboard`,"success"),h()}else showNotification(a.error||"Failed to remove","error")}catch(n){showNotification("Failed to remove: "+n.message,"error")}}function h(){closeModal("dns-settings-modal"),l=null}document.getElementById("dns-settings-cancel")?.addEventListener("click",h),document.getElementById("dns-settings-save")?.addEventListener("click",v),document.getElementById("dns-settings-delete")?.addEventListener("click",i),document.getElementById("dns-settings-modal")?.addEventListener("click",n=>{n.target.id==="dns-settings-modal"&&h()}),document.querySelector(".top")?.addEventListener("click",n=>{const x=n.target.closest('[id$="-settings"]');if(!x)return;const p=x.id.replace("-settings","");SITE.dnsServers[p]&&(n.stopPropagation(),k(p))}),document.getElementById("refresh")?.addEventListener("click",window.refreshAll)})(),(function(){injectModal("logs-modal",`
`);let o=null,m=null,l=!1,k=null,v=null,i=!1,h=null,n=null,x=!1,p=null,a=!1;async function c(b,y=25){try{const I=getDnsServerAddr(b),E=await fetch(`/api/v1/dns/logs?server=${I}&limit=${y}`,{cache:"no-store",headers:{Accept:"application/json","Cache-Control":"no-cache"}});if(E.ok){const C=await E.json();return C.success&&C.logs?{logs:C.logs,count:C.count,server:C.server}:{error:C.error||"Failed to fetch logs"}}else return E.status===401?{error:"DNS auto-auth failed - check credentials in settings"}:{error:`HTTP ${E.status}`}}catch(I){return console.error("DNS logs fetch failed:",I),{error:I.message}}}function g(b){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"}[b]||"var(--fg)"}function e(b){const y=document.createElement("div");if(y.className="log-entry",y.style.cssText="display: grid; grid-template-columns: 140px 110px 1fr 70px 80px; gap: 8px; padding: 6px 10px; border-bottom: 1px solid var(--border); font-size: 0.8rem; align-items: center;",b.parsed===!1)return y.style.gridTemplateColumns="1fr",y.innerHTML=`${escapeHtml(b.raw)} `,y;const I=g(b.rcode),E=b.rcode==="Refused"||b.rcode==="REFUSED";return y.innerHTML=`
${escapeHtml(b.timestamp)}
${escapeHtml(b.client)}
${escapeHtml(b.domain)}
${escapeHtml(b.type)}
${escapeHtml(b.rcode)}
`,y}async function s(){if(x){await T();return}if(i){await B();return}if(l||!o)return;const b=parseInt(document.getElementById("log-lines").value),y=document.getElementById("logs-content");try{const I=await c(o,b);if(I.error){y.innerHTML=`
\u26A0\uFE0F Error
${escapeHtml(I.error)}
`;return}y.innerHTML=`
Time
Client
Domain
Type
Status
`,I.logs&&I.logs.length>0?I.logs.forEach(E=>{const C=e(E);y.appendChild(C)}):y.innerHTML+=`
No DNS queries logged yet
`}catch(I){y.innerHTML=`
Failed to fetch logs: ${escapeHtml(I.message)}
`}}function u(b){o=b,l=!1,i=!1;const y=document.getElementById("logs-modal"),I=document.getElementById("logs-title"),E=document.getElementById("logs-pause"),C=document.getElementById("logs-stream");I.textContent=`${b.toUpperCase()} DNS Logs`,E.textContent="\u23F8\uFE0F Pause",E.classList.remove("paused"),C&&(C.style.display="none"),y.classList.add("show"),s(),m=setInterval(s,DC.POLL.LOGS)}function t(){document.getElementById("logs-modal").classList.remove("show"),m&&(clearInterval(m),m=null),f(),o=null,i=!1,k=null,v=null,x=!1,h=null,n=null,l=!1}function d(b){p&&f();const y=document.getElementById("logs-stream"),I=document.getElementById("logs-pause"),E=document.getElementById("logs-content");m&&(clearInterval(m),m=null);try{p=new EventSource(`/api/v1/logs/stream/${b}`),a=!0,y.classList.add("active"),y.textContent="\u{1F534} Live",y.title="Streaming - click to stop",I.style.display="none";const C=document.getElementById("logs-title");C.textContent.includes("\u{1F534}")||(C.innerHTML=C.textContent.replace("\u{1F4CB}","\u{1F4CB} \u{1F534}")),p.onmessage=P=>{try{const D=JSON.parse(P.data);if(D.error){console.error("Stream error:",D.error),f();return}const O=document.createElement("div");O.className="log-entry",O.style.cssText="display: flex; gap: 12px; padding: 6px 10px; border-bottom: 1px solid var(--border); font-size: 0.8rem; align-items: flex-start; font-family: monospace;";const R=(D.stream||"stdout")==="stderr",U=R?"var(--bad-fg)":"var(--fg)",M=`${R?"STDERR":"STDOUT"} `;for(O.innerHTML=`
${M}
${escapeHtml(D.text)}
`,E.appendChild(O),E.scrollTop=E.scrollHeight;E.children.length>500;)E.removeChild(E.firstChild)}catch(D){console.error("Error parsing stream data:",D)}},p.onerror=P=>{console.error("EventSource error:",P),f()}}catch(C){console.error("Failed to start streaming:",C),f()}}function f(){p&&(p.close(),p=null),a=!1;const b=document.getElementById("logs-stream"),y=document.getElementById("logs-pause"),I=document.getElementById("logs-title");b&&(b.classList.remove("active"),b.textContent="\u{1F4E1} Live",b.title="Enable real-time streaming"),y&&(y.style.display=""),I&&(I.textContent=I.textContent.replace(" \u{1F534}","")),i&&k&&!m&&(m=setInterval(B,DC.POLL.LOGS))}async function r(b,y=100){try{const I=`/api/v1/logs/container/${b}?tail=${y}×tamps=true`,E=await fetch(I,{cache:"no-store",headers:{Accept:"application/json","Cache-Control":"no-cache"}});if(E.ok){const C=await E.json();return C.success&&C.logs?{logs:C.logs,count:C.count,containerName:C.containerName,containerId:C.containerId}:{error:C.error||"Failed to fetch container logs"}}else return{error:`HTTP ${E.status}: ${E.statusText}`}}catch(I){return console.error("Container logs fetch failed:",I),{error:I.message}}}function S(b){const y=document.createElement("div");y.className="log-entry",y.style.cssText="display: flex; gap: 12px; padding: 6px 10px; border-bottom: 1px solid var(--border); font-size: 0.8rem; align-items: flex-start; font-family: monospace;";const I=b.stream==="stderr"?"var(--bad-fg)":"var(--fg)",E=b.stream==="stderr"?'STDERR ':'STDOUT ';return y.innerHTML=`
${E}
${escapeHtml(b.text)}
`,y}async function B(){if(l||!k||!i)return;const b=parseInt(document.getElementById("log-lines").value),y=document.getElementById("logs-content");try{const I=await r(k,b);if(I.error){y.innerHTML=`
\u26A0\uFE0F Error
${escapeHtml(I.error)}
`;return}y.innerHTML=`
Stream
Log Output
`,I.logs&&I.logs.length>0?(I.logs.forEach(E=>{const C=S(E);y.appendChild(C)}),y.scrollTop=y.scrollHeight):y.innerHTML+=`
No logs available for this container
`}catch(I){y.innerHTML=`
Failed to fetch logs: ${escapeHtml(I.message)}
`}}function L(b,y){k=b,v=y,i=!0,x=!1,l=!1,f();const I=document.getElementById("logs-modal"),E=document.getElementById("logs-title"),C=document.getElementById("logs-pause"),P=document.getElementById("logs-stream");E.textContent=`\u{1F4CB} ${y} - Container Logs`,C.textContent="\u23F8\uFE0F Pause",C.classList.remove("paused"),P&&(P.style.display=""),I.classList.add("show"),B(),m=setInterval(B,DC.POLL.LOGS)}async function A(b,y=100){try{const I=`/api/v1/logs/file?path=${encodeURIComponent(b)}&tail=${y}`,E=await fetch(I,{cache:"no-store",headers:{Accept:"application/json","Cache-Control":"no-cache"}});if(E.ok){const C=await E.json();return C.success&&C.logs?{logs:C.logs,count:C.count,logPath:C.logPath,totalLines:C.totalLines}:{error:C.error||"Failed to fetch file logs"}}else return{error:(await E.json().catch(()=>({}))).error||`HTTP ${E.status}`}}catch(I){return console.error("File logs fetch failed:",I),{error:I.message}}}function w(b){const y=document.createElement("div");y.className="log-entry",y.style.cssText="display: flex; gap: 12px; padding: 6px 10px; border-bottom: 1px solid var(--border); font-size: 0.8rem; align-items: flex-start; font-family: monospace;";const I=b.text;let E="INFO",C="var(--fg)";I.match(/ERROR|FATAL|CRITICAL/i)?(E="ERROR",C="var(--bad-fg)"):I.match(/WARN|WARNING/i)?(E="WARN",C="#f39c12"):I.match(/DEBUG/i)&&(E="DEBUG",C="var(--muted)");const D=`${E} `;return y.innerHTML=`
${D}
${escapeHtml(I)}
`,y}async function T(){if(l||!h||!x)return;const b=parseInt(document.getElementById("log-lines").value),y=document.getElementById("logs-content");try{const I=await A(h,b);if(I.error){y.innerHTML=`
\u26A0\uFE0F Error
${escapeHtml(I.error)}
`;return}y.innerHTML=`
Log Output (${I.count} of ${I.totalLines} lines)
`,I.logs&&I.logs.length>0?(I.logs.forEach(E=>{const C=w(E);y.appendChild(C)}),y.scrollTop=y.scrollHeight):y.innerHTML+=`
No logs available in this file
`}catch(I){y.innerHTML=`
Failed to fetch logs: ${escapeHtml(I.message)}
`}}function $(b,y){h=b,n=y,x=!0,i=!1,l=!1;const I=document.getElementById("logs-modal"),E=document.getElementById("logs-title"),C=document.getElementById("logs-pause"),P=document.getElementById("logs-stream");E.textContent=`\u{1F4CB} ${y} - Application Logs`,C.textContent="\u23F8\uFE0F Pause",C.classList.remove("paused"),P&&(P.style.display="none"),I.classList.add("show"),T(),m=setInterval(T,DC.POLL.LOGS)}document.querySelector(".top")?.addEventListener("click",b=>{const y=b.target.closest('[id$="-logs"]');if(!y)return;const I=y.id.replace("-logs","");SITE.dnsServers[I]&&u(I)}),document.getElementById("logs-close")?.addEventListener("click",t),document.getElementById("logs-pause")?.addEventListener("click",()=>{l=!l;const b=document.getElementById("logs-pause");l?(b.textContent="\u25B6\uFE0F Resume",b.classList.add("paused")):(b.textContent="\u23F8\uFE0F Pause",b.classList.remove("paused"),s())}),document.getElementById("log-lines")?.addEventListener("change",()=>{l||s()}),document.getElementById("logs-stream")?.addEventListener("click",()=>{!i||!k||(a?f():d(k))}),document.getElementById("logs-modal")?.addEventListener("click",b=>{b.target.id==="logs-modal"&&t()}),document.addEventListener("keydown",b=>{b.key==="Escape"&&document.getElementById("logs-modal")?.classList.contains("show")&&t()}),window.openContainerLogsModal=L,window.openFileLogsModal=$,window.openLogsModal=u})(),(function(){injectModal("service-edit-modal",`
Edit Service
Cancel
Save Changes
`),injectModal("delete-service-modal",`
Delete Service
Cancel
Remove
Delete
Remove: Remove from dashboard only (container keeps running)
Delete: Full removal - stops container, removes DNS & Caddy config
`),injectModal("add-service-modal",`
`)})(),(function(){async function o(i){try{const h=await fetch(`/api/v1/caddy/cas?caddyfilePath=${encodeURIComponent(i)}`);if(!h.ok)throw new Error(`Failed to load CAs: ${h.status}`);const n=await h.json();if(n.status==="success"){const x=document.getElementById("existing-ca-select");return x.innerHTML="",n.data.cas.length===0?x.innerHTML='No CAs found in Caddyfile ':(x.innerHTML='Select existing CA... ',n.data.cas.forEach(p=>{const a=document.createElement("option");typeof p=="object"?(a.value=p.id,a.textContent=p.displayName||p.name):(a.value=p,a.textContent=p),x.appendChild(a)})),n.data.cas}else throw new Error(n.message)}catch(h){console.error("Error loading CAs:",h);const n=document.getElementById("existing-ca-select");return n.innerHTML='Error loading CAs ',[]}}function m(i){const{subdomain:h,port:n,ip:x,sslType:p,caName:a,existingCa:c,enableAuth:g,enableCors:e,customHeaders:s,upstreamPath:u,healthCheck:t,timeout:d,tailscaleOnly:f}=i;let r=`${buildDomain(h)} {
`;switch(f&&(r+=` @blocked not remote_ip 100.64.0.0/10
`,r+=` respond @blocked "Access denied. Tailscale connection required." 403
`),p){case"letsencrypt":break;case"caddy-managed":r+=` tls internal
`;break;case"existing-ca":c&&(r+=` tls {
ca ${c}
}
`);break;case"custom-ca":a&&(r+=` tls {
ca ${a}
}
`);break}if(g&&(r+=` basicauth {
admin $2a$14$hashed_password_here
}
`),e&&(r+=` header {
`,r+=` Access-Control-Allow-Origin "*"
`,r+=` Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS"
`,r+=` Access-Control-Allow-Headers "Content-Type, Authorization"
`,r+=` }
`),s)try{const S=JSON.parse(s);r+=` header {
`,Object.entries(S).forEach(([B,L])=>{r+=` ${B} "${L}"
`}),r+=` }
`}catch{console.warn("Invalid JSON in custom headers")}return t&&(r+=` health_uri ${t}
`),r+=` reverse_proxy ${x}:${n} {
`,u&&u!=="/"&&(r+=` rewrite ${u}
`),d&&d!==30&&(r+=` transport http {
`,r+=` dial_timeout ${d}s
`,r+=` response_header_timeout ${d}s
`,r+=` }
`),r+=` }
`,r+=`}
`,r}async function l(i,h,n=DC.DEFAULTS.TTL){const x=window.getToken(getPrimaryDnsId(),"admin");if(!x)throw new Error("DNS admin token not configured. Please set it in the Tokens menu.");const p=buildDomain(i),a=await secureFetch("/api/v1/dns/record",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:p,ip:h,ttl:n,token:x,server:SITE.dnsIp})});if(!a.ok){const g=await a.text();throw new Error(`DNS API Error: ${a.status} - ${g}`)}const c=await a.json();if(!c.success)throw new Error(`DNS Error: ${c.error||"Unknown error"}`);return c}async function k(i){const h={id:i.subdomain,name:i.name,logo:i.logo||`/assets/${i.subdomain}.png`};try{const n=await secureFetch("/api/v1/services",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(h)});if(!n.ok){const x=await n.json();throw new Error(x.error||"Failed to save service")}return await window.loadServices(),window.buildGrid(),h}catch(n){throw console.error("Failed to add service to config:",n),n}}async function v(i){const h=document.getElementById("service-subdomain-input").value.trim(),n=document.getElementById("service-ip-input").value.trim()||"localhost",x=document.getElementById("service-port-input").value.trim()||"80",p=await secureFetch("/api/v1/site",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:buildDomain(h),upstream:`${n}:${x}`,config:i})}),a=await p.json();if(!p.ok||!a.success)throw new Error(a.error||`Caddy API Error: ${p.status}`);return a}window.loadExistingCAs=o,window.generateCaddyConfig=m,window.createDnsRecord=l,window.addServiceToConfig=k,window.addToCaddyfile=v})(),(function(){let o=null;function m(n){o=n;const x=document.getElementById("service-edit-modal");document.getElementById("service-edit-title").textContent=`Edit ${n.name}`,document.getElementById("edit-service-name").value=n.name,document.getElementById("edit-service-url-display").textContent=n.url||buildServiceUrl(n.id),document.getElementById("edit-service-logo-preview").src=n.logo||`/assets/${n.id}.png`,document.getElementById("edit-subdomain").value=n.id,document.getElementById("edit-port").value=n.port||"",document.getElementById("edit-ip").value=n.ip||"localhost",document.getElementById("edit-tailscale-only").checked=n.tailscaleOnly||!1,document.getElementById("edit-logo-url").value=n.logo||"",x.classList.add("show")}function l(){closeModal("service-edit-modal"),o=null}async function k(){if(!o)return;const n=document.getElementById("edit-subdomain").value.trim().toLowerCase(),x=document.getElementById("edit-service-name").value.trim(),p=document.getElementById("edit-port").value.trim(),a=document.getElementById("edit-ip").value.trim()||"localhost",c=document.getElementById("edit-tailscale-only").checked,g=document.getElementById("edit-logo-url").value.trim();if(!n){showNotification("Subdomain is required","warning");return}const e=o.id,s=[];if(n!==e&&s.push("subdomain"),x&&x!==o.name&&s.push("name"),p&&p!==String(o.port)&&s.push("port"),a!==o.ip&&s.push("ip"),c!==(o.tailscaleOnly||!1)&&s.push("tailscale"),g&&g!==o.logo&&s.push("logo"),s.length===0){l();return}const u=document.getElementById("service-edit-save");u.textContent="Saving...",u.disabled=!0;try{const d=await(await secureFetch("/api/v1/services/update",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({oldSubdomain:e,newSubdomain:n,name:x||o.name,port:p||o.port,ip:a,tailscaleOnly:c,logo:g||void 0})})).json();if(!d.success)throw new Error(d.error||"Failed to update service");const f=window.APPS.findIndex(r=>r.id===e);f!==-1&&(window.APPS[f]={...window.APPS[f],id:n,name:x||window.APPS[f].name,port:p||window.APPS[f].port,ip:a,tailscaleOnly:c,logo:g||window.APPS[f].logo}),l(),window.buildGrid(),window.refreshAll()}catch(t){console.error("Error saving service changes:",t),showNotification(`Error saving changes: ${t.message}`,"error")}finally{u.textContent="Save Changes",u.disabled=!1}}document.getElementById("edit-logo-file")?.addEventListener("change",async n=>{const x=n.target.files[0];if(!x)return;if(!x.type.startsWith("image/")){showNotification("Please select an image file","warning");return}const p=new FileReader;p.onload=async a=>{const c=a.target.result;if(document.getElementById("edit-service-logo-preview").src=c,document.getElementById("edit-logo-url").value=c,o)try{const e=await(await secureFetch("/api/v1/assets/upload",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filename:`${o.id}.png`,data:c})})).json();e.success&&e.path&&(document.getElementById("edit-logo-url").value=e.path)}catch{}},p.readAsDataURL(x)}),document.getElementById("service-edit-cancel")?.addEventListener("click",l),document.getElementById("service-edit-save")?.addEventListener("click",k),document.getElementById("service-edit-modal")?.addEventListener("click",n=>{n.target.id==="service-edit-modal"&&l()});function v(n,x,p){return new Promise(a=>{const c=document.getElementById("delete-service-modal"),g=document.getElementById("delete-modal-title"),e=document.getElementById("delete-modal-message"),s=document.getElementById("delete-modal-container-info"),u=document.getElementById("delete-modal-container-name"),t=document.getElementById("delete-modal-help"),d=document.getElementById("delete-modal-cancel"),f=document.getElementById("delete-modal-remove"),r=document.getElementById("delete-modal-delete");g.textContent=`Delete "${n}"`,x?(e.innerHTML="This service has an associated Docker container. Choose how to proceed:",s.style.display="block",u.textContent=`Container ID: ${p?.slice(0,12)||"Unknown"}`,t.style.display="block",r.style.display="block"):(e.textContent="Remove this service from the dashboard?",s.style.display="none",t.style.display="none",r.style.display="none");const S=()=>{c.classList.remove("show"),d.removeEventListener("click",B),f.removeEventListener("click",L),r.removeEventListener("click",A),c.removeEventListener("click",w)},B=()=>{S(),a(null)},L=()=>{S(),a(!1)},A=()=>{S(),a(!0)},w=T=>{T.target===c&&(S(),a(null))};d.addEventListener("click",B),f.addEventListener("click",L),r.addEventListener("click",A),c.addEventListener("click",w),c.classList.add("show")})}async function i(n,x,p){const a=document.getElementById(`update-btn-${p}`),c=a?.textContent;if(confirm(`Update ${x} to the latest version?
This will:
1. Pull the latest image
2. Stop the container
3. Recreate with same settings
The service will be briefly unavailable.`))try{a&&(a.textContent="\u{1F504}",a.disabled=!0,a.title="Updating...");const e=await(await secureFetch(`/api/v1/containers/${n}/update`,{method:"POST"})).json();if(e.success){const s=window.APPS.find(u=>u.id===p);s&&e.newContainerId&&(s.containerId=e.newContainerId),a&&(a.textContent="\u2705",a.title="Updated successfully!",setTimeout(()=>{a.textContent=c,a.disabled=!1,a.title="Update container to latest version"},3e3)),setTimeout(()=>window.refreshAll(),2e3),showNotification(`${x} updated successfully!`,"success")}else throw new Error(e.error||"Update failed")}catch(g){console.error("Update error:",g),a&&(a.textContent="\u274C",a.title="Update failed",setTimeout(()=>{a.textContent=c,a.disabled=!1,a.title="Update container to latest version"},3e3)),showNotification(`Failed to update ${x}: ${g.message}`,"error")}}async function h(n,x){const p=window.APPS.find(r=>r.id===n),a=p?buildDomain(p.id):null,c=p?.containerId,g=await v(x||n,c,p?.containerId);if(g===null)return;let e={dashboard:!1,container:null,dns:null,caddy:null,service:null};if(g&&c)try{const r=new URLSearchParams({containerId:p.containerId,subdomain:p.id,ip:p.ip||"localhost",deleteContainer:"true"}),B=await(await secureFetch(`/api/v1/apps/${encodeURIComponent(p.id)}?${r.toString()}`,{method:"DELETE"})).json();B.success?e={...e,...B.results,dashboard:!1}:console.error("App removal failed:",B.error)}catch(r){console.error("App removal error:",r)}else if(g&&a){try{const r=p?.ip||"localhost",B=await(await secureFetch(`/api/v1/dns/record?domain=${encodeURIComponent(a)}&type=A&ipAddress=${encodeURIComponent(r)}&server=${SITE.dnsIp}`,{method:"DELETE"})).json();e.dns=B.success?"deleted":B.error||"failed"}catch(r){e.dns=r.message}try{const S=await(await secureFetch(`/api/v1/site/${encodeURIComponent(a)}`,{method:"DELETE"})).json();e.caddy=S.success||S.error&&S.error.includes("not found")?"removed":S.error||"failed"}catch(r){e.caddy=r.message}}const s=window.APPS.findIndex(r=>r.id===n);s>-1&&(window.APPS.splice(s,1),e.dashboard=!0);try{const r=safeGetJSON("custom-apps",[]),S=r.findIndex(B=>B.id===n);S>-1&&(r.splice(S,1),safeSet("custom-apps",JSON.stringify(r)))}catch{}try{const S=await(await secureFetch(`/api/v1/services/${encodeURIComponent(n)}`,{method:"DELETE"})).json();e.service=S.success?"removed":S.error||"failed"}catch(r){e.service=r.message}window.buildGrid(),window.refreshAll();let u=!1,t=[];e.dashboard||(u=!0,t.push("\u2717 Failed to remove from dashboard"));const d=["removed","already removed","not found","deleted","kept (user choice)","skipped","no such record","does not exist"],f=r=>!r||d.some(S=>r.toLowerCase().includes(S.toLowerCase()));e.container&&!f(e.container)&&(u=!0,t.push(`\u26A0 Container: ${e.container}`)),e.dns&&!f(e.dns)&&(u=!0,t.push(`\u26A0 DNS Record: ${e.dns}`)),e.caddy&&!f(e.caddy)&&(u=!0,t.push(`\u26A0 Caddy Config: ${e.caddy}`)),e.service&&!f(e.service)&&(u=!0,t.push(`\u26A0 Service File: ${e.service}`)),u&&showNotification(`Error deleting "${x||n}": ${t.join(", ")}`,"error",6e3)}window.openServiceEditModal=m,window.showDeleteModal=v,window.updateContainer=i,window.deleteService=h})(),(function(){function o(e){return e.toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"").replace(/-+/g,"-").replace(/^-|-$/g,"")}function m(){return SITE.defaults?.sslType||(SITE.configurationType==="public"?"letsencrypt":"caddy-managed")}function l(){const e=document.getElementById("service-subdomain-input").value||"subdomain",s=document.getElementById("service-ip-input").value||k.lan||"localhost",u=document.getElementById("service-port-input").value||DC.DEFAULTS.SERVICE_PORT,t=document.getElementById("ssl-type-select").value,d=document.getElementById("ca-name-input").value||"sami-ca",f=document.getElementById("existing-ca-select").value,r=document.getElementById("enable-auth").checked,S=document.getElementById("enable-cors").checked,B=document.getElementById("custom-headers-input").value,L=document.getElementById("upstream-path-input").value||"/",A=document.getElementById("health-check-input").value,w=document.getElementById("timeout-input").value||30,T=document.getElementById("dns-preview");T&&(T.textContent=`${buildDomain(e)} \u2192 ${s}`);const $=document.getElementById("url-preview");$&&($.textContent=buildServiceUrl(e));const b={subdomain:e,port:u,ip:s,sslType:t,caName:d,existingCa:f,enableAuth:r,enableCors:S,customHeaders:B,upstreamPath:L,healthCheck:A,timeout:w},y=window.generateCaddyConfig(b),I=document.getElementById("caddy-config-preview");I&&(I.value=y)}const k={localhost:"127.0.0.1",lan:"",tailscale:""};async function v(){try{const t=await fetch("/api/v1/network/ips",{signal:AbortSignal.timeout(2e3)});if(t.ok){const d=await t.json();d.lan&&(k.lan=d.lan),d.tailscale&&(k.tailscale=d.tailscale)}}catch{}const e=document.getElementById("quick-ip-lan"),s=document.getElementById("quick-ip-tailscale");e&&(k.lan?(e.dataset.ip=k.lan,e.textContent=`LAN (${k.lan})`,e.title=`LAN IP: ${k.lan}`):e.style.display="none"),s&&(k.tailscale?(s.dataset.ip=k.tailscale,s.textContent=`Tailscale (${k.tailscale})`,s.title=`Tailscale IP: ${k.tailscale}`):s.style.display="none");const u=document.getElementById("service-ip-input");u&&!u.value&&k.lan&&(u.value=k.lan)}function i(){document.querySelectorAll(".quick-ip-btn").forEach(e=>{e.addEventListener("click",()=>{const s=e.dataset.ip;s&&(document.getElementById("service-ip-input").value=s,document.querySelectorAll(".quick-ip-btn").forEach(u=>u.classList.remove("active")),e.classList.add("active"),l())})}),document.getElementById("service-ip-input")?.addEventListener("input",e=>{const s=e.target.value;document.querySelectorAll(".quick-ip-btn").forEach(u=>{u.classList.toggle("active",u.dataset.ip===s)})})}async function h(){const e=document.getElementById("add-service-modal");e.classList.add("show");const s=e.querySelector(".weather-modal-content");s&&(s.scrollTop=0),document.body.style.overflow="hidden";const u=document.getElementById("ssl-type-select");u&&(u.value=m()),await v();const t=document.getElementById("caddyfile-path-input").value||DC.DEFAULTS.CADDYFILE;await window.loadExistingCAs(t);const d=document.getElementById("manual-tailscale-status"),f=document.getElementById("manual-tailscale-only");try{const S=await(await fetch("/api/v1/tailscale/status")).json();S.success&&S.installed&&S.connected?(d.innerHTML=`
\u2713 Connected
${S.self?.hostname} (${S.self?.ip})
`,f.disabled=!1):S.installed?(d.innerHTML='\u26A0 Not connected ',f.disabled=!0):(d.innerHTML='Not available ',f.disabled=!0)}catch{d.innerHTML='Could not check ',f.disabled=!0}f.checked=!1,l()}function n(){const e=document.getElementById("service-type-local"),s=document.getElementById("service-type-external"),u=document.getElementById("local-service-config"),t=document.getElementById("external-service-config"),d=document.getElementById("tab-local"),f=document.getElementById("tab-external");function r(){e.checked?(u.style.display="grid",t.style.display="none",d&&(d.style.background="var(--accent)",d.style.color="var(--bg)"),f&&(f.style.background="transparent",f.style.color="var(--muted)")):(u.style.display="none",t.style.display="block",f&&(f.style.background="var(--accent)",f.style.color="var(--bg)"),d&&(d.style.background="transparent",d.style.color="var(--muted)"))}e?.addEventListener("change",r),s?.addEventListener("change",r)}function x(){const e=document.getElementById("service-name-input"),s=document.getElementById("service-subdomain-input"),u=document.getElementById("subdomain-preview");let t=!1;e?.addEventListener("input",()=>{const L=o(e.value);!t&&s&&(s.value=L),u&&(u.textContent=L?`\u2192 ${buildDomain(L)}`:""),l()}),s?.addEventListener("input",()=>{t=s.value!==o(e?.value||"");const L=s.value.trim()||o(e?.value||"");u&&(u.textContent=L?`\u2192 ${buildDomain(L)}`:""),l()});const d=document.getElementById("external-service-name"),f=document.getElementById("external-service-subdomain"),r=document.getElementById("external-subdomain-preview"),S=document.getElementById("external-domain-preview");let B=!1;d?.addEventListener("input",()=>{const L=o(d.value);!B&&f&&(f.value=L);const A=f?.value||L;r&&(r.textContent=A?`\u2192 ${buildDomain(A)}`:""),S&&(S.textContent=A?buildDomain(A):"")}),f?.addEventListener("input",()=>{B=f.value!==o(d?.value||"");const L=f.value.trim()||o(d?.value||"");r&&(r.textContent=L?`\u2192 ${buildDomain(L)}`:""),S&&(S.textContent=L?buildDomain(L):"")})}async function p(){const e=document.getElementById("external-service-name").value.trim(),s=document.getElementById("external-service-url").value.trim(),u=(document.getElementById("external-service-subdomain").value.trim()||o(e)).toLowerCase(),t=document.getElementById("external-service-logo").value.trim(),d=document.getElementById("external-service-icon").value.trim(),f=document.getElementById("external-create-dns").checked,r=document.getElementById("external-create-caddy").checked,S=document.getElementById("external-proxy-ip").value.trim()||SITE.dnsIp||"localhost",B=document.getElementById("external-preserve-host").checked,L=document.getElementById("external-follow-redirects").checked;if(!e||!s){showNotification("Please fill in Name and External URL","warning");return}if(!u){showNotification("Could not derive subdomain from name. Please set one in Options.","warning");return}if(!s.startsWith("http://")&&!s.startsWith("https://")){showNotification("External URL must start with http:// or https://","warning");return}const A=buildDomain(u);try{const w={dns:null,caddy:null,dashboard:!1};if(f)if(window.getToken(getPrimaryDnsId(),"admin"))try{const C=await(await secureFetch("/api/v1/dns/record",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:A,ip:S,ttl:DC.DEFAULTS.TTL,server:SITE.dnsIp})})).json();w.dns=C.success?"created":C.error||"failed"}catch(E){w.dns=E.message}else w.dns="no admin token (configure in \u{1F511} Tokens)";if(r)try{const I={subdomain:u,externalUrl:s,preserveHost:B,followRedirects:L,sslType:"caddy-managed",caddyfilePath:DC.DEFAULTS.CADDYFILE,reloadCaddy:!0},C=await(await secureFetch("/api/v1/site/external",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(I)})).json();w.caddy=C.success?"created":C.error||"failed"}catch(I){w.caddy=I.message}const T={id:u,name:e,url:`https://${A}`,externalUrl:s,logo:t||d||"\u{1F310}",isExternal:!0,isCustom:!0};window.APPS.push(T),w.dashboard=!0;const $=["plex","router","chat","sync","torrent","radarr","sonarr","prowlarr","portainer","requests","jellyfin","emby"],b=window.APPS.filter(I=>!$.includes(I.id));safeSet("custom-services",JSON.stringify(b));try{await secureFetch("/api/v1/services",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(window.APPS)})}catch(I){console.warn("Failed to save to services.json:",I)}window.buildGrid(),window.refreshAll(),a();const y=[`External service "${e}" added!`];f&&y.push(`DNS: ${w.dns==="created"?"\u2713":"\u26A0 "+w.dns}`),r&&y.push(`Caddy: ${w.caddy==="created"?"\u2713":"\u26A0 "+w.caddy}`),y.push(`Access at: https://${A}`),showNotification(y.join(" | "),"success",6e3)}catch(w){console.error("Failed to create external service:",w),showNotification(`Failed to create external service: ${w.message}`,"error")}}function a(){closeModal("add-service-modal"),document.body.style.overflow="",document.getElementById("service-name-input").value="",document.getElementById("service-subdomain-input").value="",document.getElementById("service-port-input").value="",document.getElementById("service-ip-input").value=k.lan||"",document.getElementById("service-logo-input").value="",document.getElementById("dns-ttl-input").value=DC.DEFAULTS.TTL,document.getElementById("ssl-type-select").value=m(),document.getElementById("ca-name-input").value="",document.getElementById("enable-auth").checked=!1,document.getElementById("enable-cors").checked=!1,document.getElementById("custom-headers-input").value="",document.getElementById("upstream-path-input").value="/",document.getElementById("health-check-input").value="",document.getElementById("timeout-input").value="30";const e=document.getElementById("subdomain-preview");e&&(e.textContent="");const s=document.getElementById("external-subdomain-preview");s&&(s.textContent="");const u=document.getElementById("external-service-name");u&&(u.value="");const t=document.getElementById("external-service-subdomain");t&&(t.value="");const d=document.getElementById("external-service-url");d&&(d.value="");const f=document.getElementById("external-service-logo");f&&(f.value="");const r=document.getElementById("external-service-icon");r&&(r.value="");const S=document.getElementById("local-advanced-options");S&&S.removeAttribute("open");const B=document.getElementById("external-advanced-options");B&&B.removeAttribute("open");const L=document.getElementById("service-type-local");L&&(L.checked=!0);const A=document.getElementById("local-service-config"),w=document.getElementById("external-service-config");A&&(A.style.display="grid"),w&&(w.style.display="none");const T=document.getElementById("tab-local"),$=document.getElementById("tab-external");T&&(T.style.background="var(--accent)",T.style.color="var(--bg)"),$&&($.style.background="transparent",$.style.color="var(--muted)")}async function c(){const e=document.getElementById("service-name-input").value.trim(),s=(document.getElementById("service-subdomain-input").value.trim()||o(e)).toLowerCase(),u=document.getElementById("service-port-input").value.trim(),t=document.getElementById("service-ip-input").value.trim(),d=document.getElementById("service-logo-input").value.trim(),f=document.getElementById("create-dns-record").checked,r=parseInt(document.getElementById("dns-ttl-input").value)||DC.DEFAULTS.TTL,S=document.getElementById("manual-tailscale-only")?.checked||!1,B=document.getElementById("ssl-type-select")?.value||"caddy-managed",L=document.getElementById("ca-name-input")?.value||"",A=document.getElementById("existing-ca-select")?.value||"",w=document.getElementById("enable-auth")?.checked||!1,T=document.getElementById("enable-cors")?.checked||!1,$=document.getElementById("custom-headers-input")?.value||"",b=document.getElementById("upstream-path-input")?.value||"/",y=document.getElementById("health-check-input")?.value||"",I=document.getElementById("timeout-input")?.value||30,E=window.getToken(getPrimaryDnsId(),"admin");if(!e||!u||!t){showNotification("Please fill in Name, Port, and IP Address","warning");return}if(!s){showNotification("Could not derive subdomain from name. Please set one in Options.","warning");return}if(f&&!E){showNotification("DNS Admin token required. Configure it in the Tokens menu first.","warning");return}const C={dns:null,caddy:null,dashboard:!1};try{if(f)try{await window.createDnsRecord(s,t,r),C.dns="created"}catch(N){throw console.error("DNS creation failed:",N),C.dns=N.message,new Error(`DNS creation failed: ${N.message}`)}else C.dns="skipped";const P=window.generateCaddyConfig({subdomain:s,port:u,ip:t,sslType:B,caName:L,existingCa:A,enableAuth:w,enableCors:T,customHeaders:$,upstreamPath:b,healthCheck:y,timeout:I,tailscaleOnly:S});try{const R=await(await secureFetch("/api/v1/site",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:buildDomain(s),upstream:`${t}:${u}`,config:P})})).json();if(R.success)C.caddy="added & reloaded";else throw console.error("Caddy configuration failed:",R.error),C.caddy=R.error||"failed",new Error(`Caddy configuration failed: ${R.error}`)}catch(N){throw console.error("Caddy API error:",N),C.caddy=N.message,new Error(`Caddy API error: ${N.message}`)}const D={name:e,subdomain:s,port:u,ip:t,logo:d||`/assets/${s}.png`,tailscaleOnly:S||!1};await window.addServiceToConfig(D),C.dashboard=!0;const O=[`DNS: ${C.dns==="created"?"\u2713":C.dns==="skipped"?"\u25CB":"\u2717"}`,`Caddy: ${C.caddy==="added & reloaded"?"\u2713":"\u2717"}`,`Dashboard: ${C.dashboard?"\u2713":"\u2717"}`];showNotification(`Service "${e}" created! ${O.join(" | ")} \u2014 ${buildServiceUrl(s)}${S?" (Tailscale)":""}`,"success",6e3),a(),window.buildGrid(),window.refreshAll()}catch(P){console.error("Error creating service:",P),showNotification(`Error creating "${e}": ${P.message}`,"error",6e3)}}document.getElementById("add-service")?.addEventListener("click",h),document.getElementById("add-service-cancel")?.addEventListener("click",a),document.getElementById("add-service-create")?.addEventListener("click",()=>{document.querySelector('input[name="service-type"]:checked')?.value==="external"?p():c()}),n(),x(),i(),document.getElementById("ssl-type-select")?.addEventListener("change",e=>{const s=document.getElementById("existing-ca-config"),u=document.getElementById("custom-ca-config");s.style.display="none",u.style.display="none",e.target.value==="existing-ca"?s.style.display="block":e.target.value==="custom-ca"&&(u.style.display="block"),l()}),document.getElementById("refresh-cas")?.addEventListener("click",async()=>{const e=document.getElementById("refresh-cas"),s=e.textContent;e.textContent="\u231B Loading...",e.disabled=!0;try{const u=document.getElementById("caddyfile-path-input").value||DC.DEFAULTS.CADDYFILE;await window.loadExistingCAs(u),e.textContent="\u2705 Refreshed"}catch(u){e.textContent="\u274C Failed",console.error("Failed to refresh CAs:",u)}setTimeout(()=>{e.textContent=s,e.disabled=!1},2e3)}),document.getElementById("create-dns-record")?.addEventListener("change",e=>{const s=document.getElementById("dns-config");s.style.display=e.target.checked?"block":"none"}),["service-subdomain-input","service-ip-input","service-port-input","ca-name-input","existing-ca-select","enable-auth","enable-cors","custom-headers-input","upstream-path-input","health-check-input","timeout-input"].forEach(e=>{const s=document.getElementById(e);s&&(s.addEventListener("input",l),s.addEventListener("change",l))});function g(){const e=safeGet("custom-services");if(e)try{JSON.parse(e).forEach(u=>{window.APPS.find(t=>t.id===u.id)||window.APPS.push(u)})}catch(s){console.warn("Failed to load custom services:",s)}}g(),window.openAddServiceModal=h,window.closeAddServiceModal=a})(),(function(){let o=null,m=1e3;const l=3e4;function k(){if(o)try{o.close()}catch{}o=new EventSource("/api/v1/events/stream"),o.addEventListener("connected",()=>{m=1e3,debug("[SSE] Connected to event stream")}),o.addEventListener("status-change",v=>{try{const i=JSON.parse(v.data);if(i.serviceId&&typeof window.setBadge=="function"){const h=i.status==="up"||i.status==="healthy";window.setBadge(i.serviceId,h,i.responseTime||null)}}catch{}}),o.addEventListener("resource-alert",v=>{try{const i=JSON.parse(v.data),h=`${i.containerName||i.containerId}: ${i.metric} at ${i.value}% (threshold: ${i.threshold}%)`;typeof showNotification=="function"&&showNotification(h,"warning")}catch{}}),o.addEventListener("auto-restart",v=>{try{const i=JSON.parse(v.data);typeof showNotification=="function"&&showNotification(`Container "${i.containerName}" was auto-restarted`,"info")}catch{}}),o.addEventListener("update-available",v=>{try{const i=JSON.parse(v.data),h=document.getElementById("updates-btn");if(h&&!h.querySelector(".sse-dot")){const n=document.createElement("span");n.className="sse-dot",n.style.cssText="display:inline-block;width:8px;height:8px;border-radius:50%;background:var(--accent);margin-left:6px;vertical-align:middle;",h.appendChild(n)}typeof showNotification=="function"&&showNotification(`Update available for ${i.containerName||i.containerId}`,"info")}catch{}}),o.addEventListener("update-complete",v=>{try{const i=JSON.parse(v.data);typeof showNotification=="function"&&showNotification(`Update completed: ${i.containerName||i.containerId}`,"success"),typeof window.refreshAll=="function"&&window.refreshAll()}catch{}}),o.addEventListener("update-failed",v=>{try{const i=JSON.parse(v.data);typeof showNotification=="function"&&showNotification(`Update failed: ${i.containerName||i.containerId} \u2014 ${i.error||"unknown error"}`,"error")}catch{}}),o.addEventListener("incident",v=>{try{const i=JSON.parse(v.data);typeof showNotification=="function"&&(i.type==="created"?showNotification(`Incident: ${i.message||i.serviceId}`,"error"):i.type==="resolved"&&showNotification(`Resolved: ${i.serviceId||"incident"}`,"success"))}catch{}}),o.onerror=()=>{o.close(),console.warn(`[SSE] Disconnected, reconnecting in ${m/1e3}s...`),setTimeout(k,m),m=Math.min(m*2,l)}}k(),window._sseReconnect=k})();