Domain=.sami cookies are silently rejected by real browsers - .sami is an unregistered custom TLD, so browsers treat sami itself as the effective public suffix and refuse to set a cookie scoped to it (the same rule that stops a site from setting a supercookie for all of .com). Confirmed via curl verbose (cookie dropped, domain must not set cookies for sami) and via the Firefox console on the actual device (Cookie rejected for invalid domain) for the same cookie. The session cookie set on status.sami after TOTP verify could never reach plex.sami/jellyfin.sami/emby.sami/chat.sami no matter how the cookie itself was built - prior fixes tonight left this mechanism untouched, which is why the loop persisted. Fix: /totp/verify mints a short-lived (60s) single-use opaque token. The status.sami frontend appends it to the redirect URL when bouncing the user back to a gated service. That services login page exchanges the token via the new public GET /api/v1/auth/sso-exchange for a host-only session cookie (no Domain attribute - always accepted). isSessionValid only checks the cookies HMAC signature, never its Domain, so the host-only cookie validates identically to the cross-domain one on every existing check with zero changes to that logic.
849 lines
165 KiB
JavaScript
849 lines
165 KiB
JavaScript
(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=`
|
|
position: fixed;
|
|
bottom: 20px;
|
|
right: 20px;
|
|
background: var(--card-base, #2a2a2a);
|
|
color: var(--fg, #ffffff);
|
|
padding: 15px 20px;
|
|
border-radius: 8px;
|
|
box-shadow: 0 4px 12px rgba(0,0,0,0.3);
|
|
z-index: 9999;
|
|
max-width: 300px;
|
|
font-size: 14px;
|
|
`,b.innerHTML=`
|
|
<strong>Welcome to DashCaddy!</strong><br>
|
|
<p style="margin: 10px 0 0 0; font-size: 12px;">
|
|
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.json()).token,csrfToken}catch(l){throw errorHandler.logError("[CSRF] Get Token",l,{function:"getCSRFToken"}),l}}async function secureFetch(l,n={}){const g=(n.method||"GET").toUpperCase(),b=!["GET","HEAD","OPTIONS"].includes(g);if(b)try{const u=await getCSRFToken();n.headers={...n.headers,"X-CSRF-Token":u}}catch(u){errorHandler.logError("[CSRF] Add to Request",u,{function:"secureFetch"})}n.signal||(n={...n,signal:AbortSignal.timeout(15e3)});const f=await fetch(l,n);if(b&&f.status===403)try{const u=await f.clone().json();if(u.error&&(u.error.includes("DC-100")||u.error.includes("DC-101"))){csrfToken=null;const v=await getCSRFToken();return n.headers={...n.headers,"X-CSRF-Token":v},n.signal=AbortSignal.timeout(15e3),fetch(l,n)}}catch{}return f}async function postJSON(l,n){const g=await secureFetch(l,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)}),b=await g.json();if(!g.ok||b.success===!1)throw new Error(b.error||`Request failed (${g.status})`);return b}async function getJSON(l){const n=await secureFetch(l);if(!n.ok){let g=`Request failed (${n.status})`;try{g=(await n.json()).error||g}catch{}throw new Error(g)}return n.json()}async function deleteAPI(l){const n=await secureFetch(l,{method:"DELETE"}),g=await n.json();if(!n.ok||g.success===!1)throw new Error(g.error||`Delete failed (${n.status})`);return g}async function withButton(l,n,g,b={}){const f=l.innerHTML,{successText:u="\u2705",resetDelay:v=DC.DELAYS.BTN_RESET}=b;l.disabled=!0,l.innerHTML=n;try{const s=await g();return l.innerHTML=u,setTimeout(()=>{l.innerHTML=f,l.disabled=!1},v),s}catch(s){throw l.innerHTML=f,l.disabled=!1,s}}function openModal(l){document.getElementById(l)?.classList.add("show")}function closeModal(l){document.getElementById(l)?.classList.remove("show")}function wireModal(l,...n){l&&(l.addEventListener("click",g=>{g.target===l&&l.classList.remove("show")}),n.forEach(g=>{g&&typeof g.addEventListener=="function"&&g.addEventListener("click",()=>l.classList.remove("show"))}))}function showNotification(l,n="info",g=3e3){const b=document.querySelector(".deploy-notification");b&&b.remove();const f={info:{bg:"#2196F3",fg:"#fff"},success:{bg:"var(--ok-bg)",fg:"var(--ok-fg)"},error:{bg:"#f44336",fg:"#fff"},warning:{bg:"#ff9800",fg:"#fff"}},u=f[n]||f.info,v=document.createElement("div");v.className="deploy-notification",v.textContent=l,v.style.cssText=`
|
|
position: fixed; top: 20px; right: 20px;
|
|
background: ${u.bg}; color: ${u.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,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}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",warning:"#ffd080",accent:"#9cd4ff","accent-strong":"#6fb2ff"},black:{bg:"#0e0e0e",fg:"#f5f5f5",muted:"#999999","fg-muted":"#666666","card-base":"#1a1a1a","card-bg":"#1a1a1a",border:"#2e2e2e",hover:"#242424","card-hover":"#202020",base:"#161616","ok-bg":"#0f2a12","ok-fg":"#66ff7a","bad-bg":"#2a0f0f","bad-fg":"#ff6b6b","dot-ok":"#4caf50","dot-bad":"#ff4444",uptime:"#e0e0e0",success:"#4caf50",error:"#ff4444",warning:"#ff9800",accent:"#E63946","accent-strong":"#C62828"},nord:{bg:"#2e3440",fg:"#eceff4",muted:"#81a1c1","fg-muted":"#6882a0","card-base":"#3b4252","card-bg":"#3b4252",border:"#4c566a",hover:"#434c5e","card-hover":"#3f4858",base:"#353c4a","ok-bg":"#2d4f3e","ok-fg":"#a3be8c","bad-bg":"#4a2c2a","bad-fg":"#bf616a","dot-ok":"#a3be8c","dot-bad":"#bf616a",uptime:"#a3be8c",success:"#a3be8c",error:"#bf616a",warning:"#ebcb8b",accent:"#88c0d0","accent-strong":"#5e81ac"},dracula:{bg:"#282a36",fg:"#f8f8f2",muted:"#6272a4","fg-muted":"#515d85","card-base":"#44475a","card-bg":"#44475a",border:"#6272a4",hover:"#4e5170","card-hover":"#494c63",base:"#363848","ok-bg":"#1e3a2e","ok-fg":"#50fa7b","bad-bg":"#3d1a1a","bad-fg":"#ff5555","dot-ok":"#50fa7b","dot-bad":"#ff5555",uptime:"#50fa7b",success:"#50fa7b",error:"#ff5555",warning:"#f1fa8c",accent:"#bd93f9","accent-strong":"#8be9fd"},"solarized-dark":{bg:"#002b36",fg:"#839496",muted:"#586e75","fg-muted":"#4a5f65","card-base":"#073642","card-bg":"#073642",border:"#586e75",hover:"#0d4050","card-hover":"#0a3a48",base:"#053340","ok-bg":"#0d3d2c","ok-fg":"#859900","bad-bg":"#3d1a1a","bad-fg":"#dc322f","dot-ok":"#859900","dot-bad":"#dc322f",uptime:"#b5bd68",success:"#859900",error:"#dc322f",warning:"#b58900",accent:"#268bd2","accent-strong":"#2aa198"},"solarized-light":{bg:"#fdf6e3",fg:"#657b83",muted:"#93a1a1","fg-muted":"#adb8b8","card-base":"#eee8d5","card-bg":"#eee8d5",border:"#93a1a1",hover:"#e6dfcb","card-hover":"#eae3cf",base:"#e8e1cd","ok-bg":"#e8f5e8","ok-fg":"#859900","bad-bg":"#fdf2f2","bad-fg":"#dc322f","dot-ok":"#859900","dot-bad":"#dc322f",uptime:"#859900",success:"#859900",error:"#dc322f",warning:"#b58900",accent:"#268bd2","accent-strong":"#2aa198",lightBg:!0},taxi:{bg:"#f3d321",fg:"#0e0e00",muted:"#4a4a10","fg-muted":"#6b6b30","card-base":"#ffd700","card-bg":"#ffd700",border:"#b8a840",hover:"#ffe84d","card-hover":"#ffe033",base:"#f0d000","ok-bg":"#d4ffd9","ok-fg":"#0f2a0f","bad-bg":"#ffd4d4","bad-fg":"#2a0f0f","dot-ok":"#4caf50","dot-bad":"#ff4444",uptime:"#0e0e00",success:"#2e7d32",error:"#c62828",warning:"#e65100",accent:"#7a4a00","accent-strong":"#5c3800",lightBg:!0},ocean:{bg:"#2060b0",fg:"#faf5eb",muted:"#dcd2c0","fg-muted":"#b0a890","card-base":"#7a94ed","card-bg":"#7a94ed",border:"#deb67a",hover:"#8aa0f0","card-hover":"#8298e8",base:"#6888e0","ok-bg":"#4f5bb0","ok-fg":"#c7d7eb","bad-bg":"#f41a3a","bad-fg":"#6a1818","dot-ok":"#30a050","dot-bad":"#d04040",uptime:"#2d32f2",success:"#30a050",error:"#d04040",warning:"#e6a030",accent:"#1860a0","accent-strong":"#104080"}};function c(E){return!E||typeof E!="string"?{r:0,g:0,b:0}:(E=E.replace("#",""),E.length===3&&(E=E[0]+E[0]+E[1]+E[1]+E[2]+E[2]),{r:parseInt(E.substr(0,2),16)||0,g:parseInt(E.substr(2,2),16)||0,b:parseInt(E.substr(4,2),16)||0})}function a(E,B,$){return"#"+[E,B,$].map(function(C){var x=Math.max(0,Math.min(255,Math.round(C))).toString(16);return x.length===1?"0"+x:x}).join("")}function m(E,B,$){var C=c(E),x=c(B);return a(C.r+(x.r-C.r)*$,C.g+(x.g-C.g)*$,C.b+(x.b-C.b)*$)}function i(E){E=E.replace("#",""),E.length===3&&(E=E[0]+E[0]+E[1]+E[1]+E[2]+E[2]);var B=parseInt(E.substr(0,2),16)/255,$=parseInt(E.substr(2,2),16)/255,C=parseInt(E.substr(4,2),16)/255;return B=B<=.03928?B/12.92:Math.pow((B+.055)/1.055,2.4),$=$<=.03928?$/12.92:Math.pow(($+.055)/1.055,2.4),C=C<=.03928?C/12.92:Math.pow((C+.055)/1.055,2.4),.2126*B+.7152*$+.0722*C}function e(E){var B=E.bg||"#0b0f1a",$=E.fg||"#e8ecf5",C=E.muted||"#9aa6bf",x=E["card-base"]||E.bg||"#121826",I=E["dot-ok"]||"#4caf50",k=E["dot-bad"]||"#e74c3c",S=E.lightBg||B&&i(B)>.4,A={};return A.hover=S?m(x,B,.35):m(x,$,.08),A["card-hover"]=m(x,A.hover,.5),A.base=m(B,x,.6),A["fg-muted"]=m(C,B,.35),A.success=I,A.error=k,A.warning=S?"#d68a00":"#f39c12",A}function o(E,B){var $=B.lightBg||B.bg&&i(B.bg)>.4,C=B.accent||B["accent-strong"]||"#888888",x=c(C);return $?":root."+E+` body {
|
|
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%),
|
|
var(--bg);
|
|
}
|
|
`:":root."+E+` body {
|
|
background:
|
|
radial-gradient(1200px 900px at 8% -12%, rgba(`+x.r+","+x.g+","+x.b+`, .10), transparent 60%),
|
|
radial-gradient(1000px 700px at 110% -10%, rgba(`+x.r+","+x.g+","+x.b+`, .07), transparent 55%),
|
|
var(--bg);
|
|
}
|
|
`}function d(E,B){var $=B.lightBg||B.bg&&i(B.bg)>.4;return $?":root."+E+` button:hover {
|
|
background: color-mix(in srgb, var(--accent-strong) 12%, white 88%);
|
|
border-color: rgba(0, 0, 0, .15);
|
|
box-shadow: 0 1px 6px rgba(0, 0, 0, .08), inset 0 1px 0 rgba(255, 255, 255, .8);
|
|
}
|
|
`:":root."+E+` button:hover {
|
|
background: color-mix(in srgb, var(--accent) 18%, transparent);
|
|
border-color: color-mix(in srgb, var(--accent) 35%, var(--border));
|
|
}
|
|
`}function t(){return window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function 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]+`;
|
|
`)}),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}"
|
|
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}
|
|
</button>`}).join(`
|
|
`);a.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-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=`
|
|
<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>
|
|
<p style="margin: 6px 0 14px; font-size: 0.85rem; color: var(--muted);">
|
|
We'll email you a one-time sign-in link.
|
|
</p>
|
|
<input id="auth-gate-email-input" type="email" inputmode="email" autocomplete="email"
|
|
placeholder="you@example.com"
|
|
style="width: 100%; padding: 10px 12px; font-size: 1rem; background: var(--input-bg); color: var(--text); border: 1px solid var(--border); border-radius: 6px; box-sizing: border-box;">
|
|
<button id="auth-gate-email-submit" class="provider-btn"
|
|
style="margin-top: 14px; padding: 10px 16px; background: var(--accent); color: white; border: 0; border-radius: 6px; cursor: pointer; font-size: 0.95rem; width: 100%;">
|
|
Send sign-in link
|
|
</button>
|
|
<div id="auth-gate-email-status" style="margin-top: 12px; font-size: 0.85rem; line-height: 1.4;"></div>
|
|
<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=`
|
|
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"
|
|
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":"application/json"},body:JSON.stringify({secret:v})}),c=await y.json();if(!y.ok||!c.success){s.textContent=c.error||c.message||"Restore failed";return}document.getElementById("totp-recovery-import").style.display="none",document.getElementById("totp-recovery-verify").style.display="",setTimeout(()=>document.getElementById("totp-recovery-code")?.focus(),100)}catch{s.textContent="Network error \u2014 try again"}}async function u(){const v=document.getElementById("totp-recovery-code").value.trim(),s=document.getElementById("totp-recovery-confirm-error");if(s.textContent="",!/^\d{6}$/.test(v)){s.textContent="Enter a 6-digit code";return}try{const y=await fetch("/api/v1/totp/verify-setup",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:v})}),c=await y.json();if(!y.ok||!c.success){s.textContent=c.error||c.message||"Invalid code",document.getElementById("totp-recovery-code").value="",document.getElementById("totp-recovery-code")?.focus();return}b();const a=document.getElementById("totp-overlay");a&&a.classList.remove("show"),typeof window.initializeDashboard=="function"&&window.initializeDashboard()}catch{s.textContent="Network error \u2014 try again"}}document.getElementById("totp-show-recovery")?.addEventListener("click",v=>{v.preventDefault(),g()}),document.getElementById("totp-recovery-close")?.addEventListener("click",b),document.getElementById("totp-recovery-submit")?.addEventListener("click",f),document.getElementById("totp-recovery-confirm")?.addEventListener("click",u),document.getElementById("totp-recovery-secret")?.addEventListener("keydown",v=>{v.key==="Enter"&&(v.preventDefault(),f())}),document.getElementById("totp-recovery-code")?.addEventListener("keydown",v=>{v.key==="Enter"&&(v.preventDefault(),u())}),window._refreshRecoveryLink=async function(){const v=await l();return v&&v.success&&v.status&&v.status!=="healthy"?n(!0):n(!1),v}})(),(function(){const l=new ErrorHandler;injectModal("folder-browser-modal",`<div id="folder-browser-modal" class="weather-modal">
|
|
<div class="weather-modal-content" style="min-width: 500px; max-width: 700px; max-height: 80vh;">
|
|
<h3>\u{1F4C2} Browse for Media Folders</h3>
|
|
|
|
<div id="folder-browser-path" style="padding: 10px; background: var(--card-bg); border-radius: 6px; margin-bottom: 12px; font-family: monospace; font-size: 0.9rem; word-break: break-all;">
|
|
/
|
|
</div>
|
|
|
|
<div id="folder-browser-list" style="max-height: 400px; overflow-y: auto; border: 1px solid var(--border); border-radius: 6px;">
|
|
<div style="padding: 20px; text-align: center; color: var(--muted);">Loading...</div>
|
|
</div>
|
|
|
|
<div id="folder-browser-selected" style="margin-top: 12px; padding: 10px; background: color-mix(in srgb, var(--success) 10%, transparent); border: 1px solid var(--success); border-radius: 6px; display: none;">
|
|
<div style="font-size: 0.85rem; color: var(--success); margin-bottom: 6px;">Selected folders:</div>
|
|
<div id="folder-browser-selected-list" style="display: flex; flex-wrap: wrap; gap: 6px;"></div>
|
|
</div>
|
|
|
|
<div class="weather-modal-buttons" style="margin-top: 16px; display: flex; gap: 8px; justify-content: space-between;">
|
|
<button id="folder-browser-select-current" class="btn-accent">
|
|
+ Add Current Folder
|
|
</button>
|
|
<div class="flex-row-gap">
|
|
<button id="folder-browser-cancel">Cancel</button>
|
|
<button id="folder-browser-done" style="background: color-mix(in srgb, var(--success) 20%, transparent); border-color: var(--success); color: var(--success);">Done</button>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>`),injectModal("service-creds-modal",`<div id="service-creds-modal">
|
|
<div class="service-creds-content">
|
|
<h3 id="svc-creds-title" style="margin: 0 0 4px; font-size: 1.05rem;">Service Credentials</h3>
|
|
<p id="svc-creds-desc" style="font-size: 0.75rem; color: var(--muted); margin: 0 0 14px;">Credentials are injected automatically when accessing this service.</p>
|
|
|
|
<!-- Status indicator -->
|
|
<div style="display: flex; align-items: center; gap: 6px; margin-bottom: 12px;">
|
|
<span id="svc-creds-dot" class="status-dot"></span>
|
|
<span id="svc-creds-status" class="text-muted-sm">No credentials stored</span>
|
|
</div>
|
|
|
|
<!-- Seedhost credentials (shown for external services) -->
|
|
<div id="svc-creds-seedhost" style="display: none; margin-bottom: 14px;">
|
|
<label class="label-bold">Seedhost Login</label>
|
|
<p class="hint-micro">Username shared across all services. Password is per-service.</p>
|
|
<input type="text" id="svc-seedhost-user" placeholder="Username (shared)" autocomplete="username"
|
|
style="width: 100%; padding: 8px 10px; margin-bottom: 6px; background: var(--bg); color: var(--fg); border: 1px solid var(--border); border-radius: 6px; font-size: 0.85rem; box-sizing: border-box;" />
|
|
<input type="password" id="svc-seedhost-pass" placeholder="Password" autocomplete="current-password"
|
|
class="input-creds" />
|
|
</div>
|
|
|
|
<!-- API Key (shown for arr services or services with API key support) -->
|
|
<div id="svc-creds-apikey" style="display: none; margin-bottom: 14px;">
|
|
<label class="label-bold">API Key</label>
|
|
<p class="hint-micro">Bypasses the app's own login screen</p>
|
|
<input type="text" id="svc-apikey-input" placeholder="API key"
|
|
style="width: 100%; padding: 8px 10px; background: var(--bg); color: var(--fg); border: 1px solid var(--border); border-radius: 6px; font-size: 0.85rem; font-family: monospace; box-sizing: border-box;" />
|
|
</div>
|
|
|
|
<!-- Quality Profile (shown for radarr/sonarr only) -->
|
|
<div id="svc-creds-quality" style="display: none; margin-bottom: 14px;">
|
|
<label class="label-bold">Quality Profile</label>
|
|
<p class="hint-micro">Used when requesting via Seerr</p>
|
|
<div style="display: flex; gap: 8px; align-items: center;">
|
|
<select id="svc-quality-select"
|
|
style="flex: 1; padding: 8px 10px; background: var(--bg); color: var(--fg); border: 1px solid var(--border); border-radius: 6px; font-size: 0.85rem; box-sizing: border-box;">
|
|
<option value="">-- Enter API key first --</option>
|
|
</select>
|
|
<button id="svc-quality-fetch" type="button"
|
|
style="padding: 8px 12px; font-size: 0.75rem; cursor: pointer; white-space: nowrap;">
|
|
Fetch
|
|
</button>
|
|
</div>
|
|
<div id="svc-quality-status" style="font-size: 0.75rem; margin-top: 4px; min-height: 1em;"></div>
|
|
</div>
|
|
|
|
<!-- Per-service Basic Auth (shown for non-external services) -->
|
|
<div id="svc-creds-basic" style="display: none; margin-bottom: 14px;">
|
|
<label class="label-bold">Service Login</label>
|
|
<input type="text" id="svc-basic-user" placeholder="Username" autocomplete="username"
|
|
style="width: 100%; padding: 8px 10px; margin-top: 6px; margin-bottom: 6px; background: var(--bg); color: var(--fg); border: 1px solid var(--border); border-radius: 6px; font-size: 0.85rem; box-sizing: border-box;" />
|
|
<input type="password" id="svc-basic-pass" placeholder="Password" autocomplete="current-password"
|
|
class="input-creds" />
|
|
</div>
|
|
|
|
<!-- Error message -->
|
|
<div id="svc-creds-error" style="display: none; padding: 8px 10px; margin-bottom: 10px; background: color-mix(in srgb, var(--error, #c62828) 12%, transparent); border: 1px solid var(--error, #c62828); border-radius: 6px; font-size: 0.8rem; color: var(--error, #c62828);"></div>
|
|
|
|
<!-- Buttons -->
|
|
<div style="display: flex; gap: 8px; margin-top: 14px;">
|
|
<button id="svc-creds-save" class="btn-accent-solid" style="flex: 1; padding: 9px; border: none; border-radius: 6px; cursor: pointer; font-weight: 600; font-size: 0.85rem;">
|
|
Save
|
|
</button>
|
|
<button id="svc-creds-clear" style="padding: 9px 14px; background: transparent; color: var(--bad-fg, #ff9aa3); border: 1px solid var(--bad-fg, #ff9aa3); border-radius: 6px; cursor: pointer; font-size: 0.85rem; display: none;">
|
|
Clear
|
|
</button>
|
|
<button id="svc-creds-close" style="padding: 9px 16px; background: var(--card-base); color: var(--fg); border: 1px solid var(--border); border-radius: 6px; cursor: pointer; font-size: 0.85rem;">
|
|
Cancel
|
|
</button>
|
|
</div>
|
|
</div>
|
|
</div>`);const 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 fetch profiles"}</span>`;return}if(!h.profiles?.length){o.innerHTML='<option value="">-- No profiles found --</option>';return}o.innerHTML="";for(const w of h.profiles){const T=document.createElement("option");T.value=w.id,T.textContent=w.name,o.appendChild(T)}const p=h.profiles.find(w=>/720/i.test(w.name));p?o.value=String(p.id):h.profiles.length&&(o.value=String(h.profiles[0].id)),d.innerHTML=`<span style="color: var(--ok-fg);">${h.profiles.length} profiles loaded</span>`}catch(t){o.innerHTML='<option value="">-- Error --</option>',d.innerHTML=`<span style="color: var(--error, #c62828);">${t.message}</span>`}}),document.getElementById("svc-creds-save")?.addEventListener("click",async()=>{if(!g)return;const a=document.getElementById("svc-creds-save");a.textContent="Saving...",a.disabled=!0,s();try{const m=b.includes(g.id)||b.includes(g.appTemplate),i=g.id||g.appTemplate;if(g.isExternal){const d=document.getElementById("svc-seedhost-user").value.trim(),t=document.getElementById("svc-seedhost-pass").value;d&&await secureFetch("/api/v1/seedhost-creds",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:d,password:t||void 0,serviceId:g.id})})}const o=document.getElementById("svc-apikey-input")?.value.trim();if(o&&o!=="\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022")if(m){const d=u(g),t=document.getElementById("svc-quality-select"),r=t?.value?parseInt(t.value):void 0,h=t?.selectedOptions?.[0]?.textContent||void 0,w=await(await secureFetch("/api/v1/arr/credentials",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({service:i,apiKey:o,url:d||void 0,qualityProfileId:r||void 0,qualityProfileName:h||void 0})})).json();if(!w.success){v(w.error||"Failed to save API key"),a.textContent="Save",a.disabled=!1;return}w.connectionTest&&!w.connectionTest.success&&v(`API key saved but connection test failed: ${w.connectionTest.error}`)}else await secureFetch(`/api/v1/services/${g.id}/credentials`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:o})});else if(m&&f.includes(i)){const d=document.getElementById("svc-quality-select"),t=d?.value?parseInt(d.value):void 0,r=d?.selectedOptions?.[0]?.textContent||void 0;t&&await secureFetch("/api/v1/arr/quality-profiles",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({service:i,qualityProfileId:t,qualityProfileName:r})})}if(!g.isExternal){const d=document.getElementById("svc-basic-user").value.trim(),t=document.getElementById("svc-basic-pass").value;d&&t&&await secureFetch(`/api/v1/services/${g.id}/credentials`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:d,password:t})})}await y(g)}catch(m){l.logError("[ServiceCredentials] Save",m,{function:"saveCredentials"}),v("Failed to save: "+(m.message||"Unknown error"))}a.textContent="Save",a.disabled=!1}),document.getElementById("svc-creds-clear")?.addEventListener("click",async()=>{if(g&&confirm(`Remove stored credentials for ${g.name}?`)){s();try{const a=g.id||g.appTemplate,m=b.includes(a);g.isExternal&&await secureFetch(`/api/v1/seedhost-creds?serviceId=${g.id}`,{method:"DELETE"}),await secureFetch(`/api/v1/services/${g.id}/credentials`,{method:"DELETE"}),m&&await secureFetch(`/api/v1/arr/credentials/${a}`,{method:"DELETE"});const i=document.getElementById(`creds-btn-${g.id}`);i&&i.classList.remove("has-creds"),await y(g)}catch(a){l.logError("[ServiceCredentials] Clear",a,{function:"clearCredentials"}),v("Failed to clear: "+(a.message||"Unknown error"))}}}),document.getElementById("svc-creds-close")?.addEventListener("click",()=>{n.classList.remove("show"),g=null}),n?.addEventListener("click",a=>{a.target===n&&(n.classList.remove("show"),g=null)}),window.refreshCredsButtons=async function(){try{for(const a of window.APPS||[]){if(!a.isExternal&&!a.appTemplate&&!a.url)continue;let m=!1;if(a.isExternal)try{const o=await(await fetch(`/api/v1/seedhost-creds?serviceId=${a.id}`)).json();o.success&&o.hasCredentials&&(m=!0)}catch{}try{const o=await(await fetch(`/api/v1/services/${a.id}/credentials`)).json();o.success&&(o.hasApiKey||o.hasBasicAuth)&&(m=!0)}catch{}const i=document.getElementById(`creds-btn-${a.id}`);i&&i.classList.toggle("has-creds",m)}}catch{}}})(),(function(){const l=new ErrorHandler;injectModal("totp-settings-modal",`<div id="totp-settings-modal" class="weather-modal">
|
|
<div class="weather-modal-content" style="min-width: 420px; max-width: 520px;">
|
|
<h3 style="margin: 0 0 16px; font-size: 1.1rem;">Authentication Settings</h3>
|
|
|
|
<!-- Status Banner -->
|
|
<div id="totp-status-banner" style="margin-bottom: 16px; padding: 12px 16px; border-radius: 8px; border: 1px solid var(--border); display: flex; align-items: center; gap: 8px;">
|
|
<span id="totp-status-dot" class="status-dot"></span>
|
|
<span id="totp-status-text" style="font-size: 0.9rem;">TOTP is not configured</span>
|
|
</div>
|
|
|
|
<!-- Setup Button (not configured state) -->
|
|
<div id="totp-setup-section">
|
|
<button id="totp-setup-btn" class="btn-accent-solid" style="width: 100%; padding: 12px; border: none; border-radius: 8px; cursor: pointer; font-weight: 600; font-size: 0.95rem;">
|
|
Generate New Secret
|
|
</button>
|
|
<div style="display: flex; align-items: center; gap: 8px; margin: 10px 0 0;">
|
|
<div class="divider-line"></div>
|
|
<span class="text-tiny-muted">or</span>
|
|
<div class="divider-line"></div>
|
|
</div>
|
|
<div style="margin-top: 10px;">
|
|
<label class="text-hint">Import an existing secret key:</label>
|
|
<div style="display: flex; gap: 8px; margin-top: 6px;">
|
|
<input type="text" id="totp-import-key" placeholder="Paste your Base32 key" autocomplete="off" spellcheck="false"
|
|
style="flex: 1; padding: 10px; background: var(--bg); color: var(--fg); border: 1px solid var(--border); border-radius: 6px; font-size: 0.9rem; font-family: monospace; letter-spacing: 1px; text-transform: uppercase;" />
|
|
<button id="totp-import-btn" style="padding: 10px 16px; background: var(--card-base); color: var(--fg); border: 1px solid var(--border); border-radius: 6px; cursor: pointer; font-weight: 600; font-size: 0.85rem; white-space: nowrap;">
|
|
Import
|
|
</button>
|
|
</div>
|
|
<div id="totp-import-error" style="color: var(--bad-fg, #ff9aa3); font-size: 0.8rem; min-height: 1.2em; margin-top: 6px;"></div>
|
|
</div>
|
|
</div>
|
|
|
|
<!-- Secret Display (setup flow) -->
|
|
<div id="totp-qr-section" style="display: none;">
|
|
<!-- Manual Key (primary - for WinAuth/desktop authenticators) -->
|
|
<p style="font-size: 0.85rem; color: var(--muted); margin: 0 0 8px;">Copy this key into your authenticator app:</p>
|
|
<div style="display: flex; align-items: center; gap: 8px; margin-bottom: 8px;">
|
|
<code id="totp-manual-key" style="flex: 1; display: block; padding: 12px; background: var(--bg, #0b0f1a); border: 1px solid var(--border); border-radius: 6px; font-size: 1rem; font-family: 'Sami Grotesk', monospace; letter-spacing: 2px; word-break: break-all; user-select: all; color: var(--fg);"></code>
|
|
<button id="totp-copy-key" style="padding: 10px 14px; background: var(--card-base); border: 1px solid var(--border); border-radius: 6px; cursor: pointer; font-size: 1rem; white-space: nowrap; color: var(--fg);" title="Copy to clipboard">\u{1F4CB}</button>
|
|
</div>
|
|
|
|
<!-- Download backup file (recovery aid) -->
|
|
<div style="margin-bottom: 16px; padding: 10px 12px; background: var(--bg, #0b0f1a); border: 1px solid var(--border); border-radius: 6px;">
|
|
<div style="display: flex; align-items: center; gap: 8px;">
|
|
<span style="font-size: 0.8rem; color: var(--muted); flex: 1;">
|
|
<strong style="color: var(--fg);">Save a backup file</strong> \u2014 if you ever lose your authenticator,
|
|
this is the only way to recover without SSH access to the server.
|
|
</span>
|
|
<button id="totp-download-backup" type="button"
|
|
style="padding: 8px 14px; background: var(--card-base); color: var(--fg); border: 1px solid var(--border); border-radius: 6px; cursor: pointer; font-weight: 600; font-size: 0.85rem; white-space: nowrap;">
|
|
\u2B07 Download
|
|
</button>
|
|
</div>
|
|
</div>
|
|
|
|
<!-- QR Code (secondary - for mobile apps) -->
|
|
<details class="mb-16">
|
|
<summary style="cursor: pointer; color: var(--muted); font-size: 0.8rem;">Show QR code (for mobile authenticator apps)</summary>
|
|
<div style="text-align: center; margin-top: 8px;">
|
|
<img id="totp-qr-image" style="width: 180px; height: 180px; border-radius: 8px;" />
|
|
</div>
|
|
</details>
|
|
|
|
<!-- Verify First Code -->
|
|
<div style="border-top: 1px solid var(--border); padding-top: 16px;">
|
|
<label class="font-bold-sm">Enter code to confirm setup:</label>
|
|
<div style="display: flex; gap: 8px; margin-top: 8px;">
|
|
<input type="text" id="totp-setup-code" maxlength="6" inputmode="numeric" pattern="[0-9]{6}" placeholder="000000"
|
|
style="flex: 1; text-align: center; font-size: 1.3rem; padding: 10px; font-family: 'Sami Grotesk', monospace; letter-spacing: 4px; background: var(--bg); color: var(--fg); border: 2px solid var(--border); border-radius: 8px; outline: none;" />
|
|
<button id="totp-confirm-setup" class="btn-accent-solid" style="padding: 10px 20px; border: none; border-radius: 8px; cursor: pointer; font-weight: 600;">
|
|
Confirm
|
|
</button>
|
|
</div>
|
|
<div id="totp-setup-error" style="color: var(--bad-fg, #ff9aa3); font-size: 0.8rem; min-height: 1.2em; margin-top: 6px;"></div>
|
|
</div>
|
|
</div>
|
|
|
|
<!-- Session Duration (active state) -->
|
|
<div id="totp-duration-section" style="display: none; margin-top: 12px;">
|
|
<label class="font-bold-sm">Session Duration:</label>
|
|
<select id="totp-duration-select" style="width: 100%; padding: 10px; margin-top: 6px; background: var(--bg, #0b0f1a); color: var(--fg); border: 1px solid var(--border); border-radius: 8px; font-size: 0.9rem; cursor: pointer;">
|
|
<option value="15m">15 minutes</option>
|
|
<option value="30m">30 minutes</option>
|
|
<option value="1h">1 hour</option>
|
|
<option value="2h">2 hours</option>
|
|
<option value="4h">4 hours</option>
|
|
<option value="8h">8 hours</option>
|
|
<option value="12h">12 hours</option>
|
|
<option value="24h">24 hours</option>
|
|
<option value="never">Never (disable TOTP)</option>
|
|
</select>
|
|
<p style="font-size: 0.75rem; color: var(--muted); margin: 4px 0 0;">How long before you need to re-enter your code</p>
|
|
</div>
|
|
|
|
<!-- Disable Button (active state) -->
|
|
<div id="totp-disable-section" style="display: none; margin-top: 16px; padding-top: 16px; border-top: 1px solid var(--border);">
|
|
<button id="totp-disable-btn" style="width: 100%; padding: 10px; background: transparent; color: var(--bad-fg, #ff9aa3); border: 1px solid var(--bad-fg, #ff9aa3); border-radius: 8px; cursor: pointer; font-size: 0.9rem;">
|
|
Disable TOTP
|
|
</button>
|
|
</div>
|
|
|
|
<!-- Close -->
|
|
<div style="margin-top: 16px; text-align: right;">
|
|
<button id="totp-modal-close" style="padding: 8px 20px; background: var(--card-base); color: var(--fg); border: 1px solid var(--border); border-radius: 8px; cursor: pointer;">
|
|
Close
|
|
</button>
|
|
</div>
|
|
</div>
|
|
</div>`);async function 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=document.getElementById("totp-setup-code").value,u=document.getElementById("totp-setup-error");if(!/^\d{6}$/.test(f)){u.textContent="Enter a 6-digit code";return}try{const s=await(await secureFetch("/api/v1/totp/verify-setup",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:f})})).json();s.success?(u.textContent="",n()):u.textContent=s.error||"Invalid code"}catch{u.textContent="Connection error"}}),document.getElementById("totp-setup-code")?.addEventListener("keydown",f=>{f.key==="Enter"&&document.getElementById("totp-confirm-setup")?.click()}),document.getElementById("totp-duration-select")?.addEventListener("change",async f=>{try{await secureFetch("/api/v1/totp/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionDuration:f.target.value})}),n()}catch(u){l.logError("[TOTP] Update Session Duration",u,{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&&n()}catch(f){l.logError("[TOTP] Disable Failed",f,{function:"disableTOTP"})}}),document.getElementById("auth-settings-btn")?.addEventListener("click",()=>{n(),openModal("totp-settings-modal")}),document.getElementById("totp-modal-close")?.addEventListener("click",()=>{closeModal("totp-settings-modal")}),document.getElementById("totp-settings-modal")?.addEventListener("click",f=>{f.target.id==="totp-settings-modal"&&closeModal("totp-settings-modal")}),window._updateAuthCard=b,(async()=>{try{const u=await(await fetch("/api/v1/totp/config")).json();if(u.success){const v=u.config.enabled&&u.config.isSetUp;b(v,u.config.sessionDuration)}}catch(f){l.logError("[TOTP] AuthCard Update",f,{function:"authCardUpdate"})}})()})(),(function(){"use strict";const l={me:"/api/v1/auth/me",users:"/api/v1/auth/admin/users",allowlist:"/api/v1/auth/admin/allowlist",invites:"/api/v1/auth/admin/invites"};function n(i,e,...o){const d=document.createElement(i);if(e)for(const t of Object.keys(e)){const r=e[t];r==null||r===!1||(t==="class"?d.className=r:t==="text"?d.textContent=r:t==="html"?d.innerHTML=r:t.startsWith("on")&&typeof r=="function"?d.addEventListener(t.slice(2).toLowerCase(),r):d.setAttribute(t,r))}for(const t of o)t==null||t===!1||(typeof t=="string"?d.appendChild(document.createTextNode(t)):d.appendChild(t));return d}async function g(i,e){const o=window.SITE&&window.SITE.csrfToken||"";e=e||{},e.headers=Object.assign({"Content-Type":"application/json"},e.headers||{},o?{"X-CSRF-Token":o}:{}),e.body&&typeof e.body!="string"&&(e.body=JSON.stringify(e.body));const d=await fetch(i,e),t=await d.json().catch(()=>({}));if(!d.ok){const r=t&&(t.message||t.error)||"HTTP "+d.status,h=new Error(r);throw h.status=d.status,h}return t}function b(i){const e={admin:"background:#7c3aed;color:#fff",operator:"background:#2563eb;color:#fff",viewer:"background:#6b7280;color:#fff"};return n("span",{class:"role-badge",style:"display:inline-block;padding:2px 8px;border-radius:4px;font-size:0.75rem;font-weight:600;text-transform:uppercase;"+(e[i]||e.viewer),text:i})}function f(i,e,o){if(i.innerHTML="",!e||e.length===0){i.appendChild(n("p",{style:"color:var(--muted)",text:"No users yet."}));return}const d=n("table",{style:"width:100%;border-collapse:collapse;font-size:0.9rem"});d.appendChild(n("thead",null,n("tr",{style:"border-bottom:1px solid var(--border)"},n("th",{style:"text-align:left;padding:8px",text:"Email"}),n("th",{style:"text-align:left;padding:8px",text:"Role"}),n("th",{style:"text-align:left;padding:8px",text:"Created"}),n("th",{style:"text-align:left;padding:8px",text:"Last login"}),n("th",{style:"text-align:right;padding:8px",text:"Actions"}))));const t=n("tbody");for(const r of e){const h=n("tr",{style:"border-bottom:1px solid var(--border)"}),p=n("td",{style:"padding:8px"});p.appendChild(n("span",{text:r.email||"(no email)"})),r.displayName&&r.displayName!==(r.email||"").split("@")[0]&&(p.appendChild(n("br")),p.appendChild(n("small",{style:"color:var(--muted)",text:r.displayName}))),h.appendChild(p);const w=n("td",{style:"padding:8px"});w.appendChild(b(r.role)),h.appendChild(w),h.appendChild(n("td",{style:"padding:8px;color:var(--muted);font-size:0.85rem",text:r.createdAt?new Date(r.createdAt).toLocaleDateString():"\u2014"})),h.appendChild(n("td",{style:"padding:8px;color:var(--muted);font-size:0.85rem",text:r.lastLoginAt?new Date(r.lastLoginAt).toLocaleString():"\u2014"}));const T=n("td",{style:"padding:8px;text-align:right"}),L=n("select",{style:"padding:2px 6px;margin-right:6px",onchange:async E=>{try{await g(l.users+"/"+encodeURIComponent(r.id),{method:"PATCH",body:{role:E.target.value}}),o&&o()}catch(B){window.errorHandler&&window.errorHandler.show("Role update failed: "+B.message),E.target.value=r.role}}});for(const E of["admin","operator","viewer"]){const B=n("option",{value:E,text:E});E===r.role&&(B.selected=!0),L.appendChild(B)}T.appendChild(L);const P=n("button",{class:"btn-sm",style:"padding:2px 8px",text:"Delete",onclick:async()=>{if(confirm("Delete user "+(r.email||r.id)+"? This cannot be undone."))try{await g(l.users+"/"+encodeURIComponent(r.id),{method:"DELETE"}),o&&o()}catch(E){window.errorHandler&&window.errorHandler.show("Delete failed: "+E.message)}}});T.appendChild(P),h.appendChild(T),t.appendChild(h)}d.appendChild(t),i.appendChild(d)}function u(i,e){const o=n("form",{style:"display:flex;gap:8px;flex-wrap:wrap;align-items:end",onsubmit:async t=>{t.preventDefault();const r=new FormData(t.target),h={email:r.get("email"),role:r.get("role"),ttlHours:parseInt(r.get("ttlHours"),10)||24,sendEmail:r.get("sendEmail")==="on"};try{const p=await g(l.invites,{method:"POST",body:h});t.target.reset(),e&&e(p)}catch(p){window.errorHandler&&window.errorHandler.show("Invite failed: "+p.message)}}});o.appendChild(n("label",{style:"display:flex;flex-direction:column;gap:2px;font-size:0.85rem"},n("span",{text:"Email"}),n("input",{name:"email",type:"email",required:!0,placeholder:"user@example.com",style:"padding:6px"})));const d=n("select",{name:"role",style:"padding:6px"});for(const t of["operator","viewer","admin"])d.appendChild(n("option",{value:t,text:t}));o.appendChild(n("label",{style:"display:flex;flex-direction:column;gap:2px;font-size:0.85rem"},n("span",{text:"Role"}),d)),o.appendChild(n("label",{style:"display:flex;flex-direction:column;gap:2px;font-size:0.85rem"},n("span",{text:"TTL (hours)"}),n("input",{name:"ttlHours",type:"number",min:"1",max:"168",value:"24",style:"padding:6px;width:80px"}))),o.appendChild(n("label",{style:"display:flex;gap:4px;align-items:center;font-size:0.85rem"},n("input",{name:"sendEmail",type:"checkbox",checked:!0}),n("span",{text:"Send email"}))),o.appendChild(n("button",{type:"submit",class:"btn-sm",style:"padding:6px 12px",text:"Issue invite"})),i.appendChild(o)}function v(i,e,o){if(i.innerHTML="",!e||e.length===0){i.appendChild(n("p",{style:"color:var(--muted)",text:"No outstanding invites."}));return}const d=n("table",{style:"width:100%;border-collapse:collapse;font-size:0.9rem"});d.appendChild(n("thead",null,n("tr",{style:"border-bottom:1px solid var(--border)"},n("th",{style:"text-align:left;padding:8px",text:"Email"}),n("th",{style:"text-align:left;padding:8px",text:"Role"}),n("th",{style:"text-align:left;padding:8px",text:"Invited by"}),n("th",{style:"text-align:left;padding:8px",text:"Expires"}),n("th",{style:"text-align:right;padding:8px",text:"Actions"}))));const t=n("tbody");for(const r of e){const h=n("tr",{style:"border-bottom:1px solid var(--border)"});h.appendChild(n("td",{style:"padding:8px",text:r.email})),h.appendChild(n("td",{style:"padding:8px"},b(r.role))),h.appendChild(n("td",{style:"padding:8px;color:var(--muted)",text:r.invitedBy||"\u2014"})),h.appendChild(n("td",{style:"padding:8px;color:var(--muted);font-size:0.85rem",text:r.expiresAt?new Date(r.expiresAt).toLocaleString():"\u2014"}));const p=n("td",{style:"padding:8px;text-align:right"});p.appendChild(n("button",{class:"btn-sm",style:"padding:2px 8px",text:"Revoke",onclick:async()=>{if(confirm("Revoke invite for "+r.email+"?"))try{await g(l.invites+"/"+encodeURIComponent(r.id),{method:"DELETE"}),o&&o()}catch(w){window.errorHandler&&window.errorHandler.show("Revoke failed: "+w.message)}}})),h.appendChild(p),t.appendChild(h)}d.appendChild(t),i.appendChild(d)}function s(i,e){const o=n("div",{style:"margin-top:12px;padding:12px;border:1px solid #16a34a;border-radius:6px;background:#052e1a;color:#bbf7d0;font-size:0.85rem"});o.appendChild(n("strong",{text:"Invite issued \u2014 copy the link below. It will not be shown again."})),o.appendChild(n("br")),o.appendChild(n("code",{style:"display:block;margin-top:8px;padding:8px;background:#000;border-radius:4px;word-break:break-all;color:#d1fae5",text:i.acceptUrl}));const d=n("button",{class:"btn-sm",style:"margin-top:8px;padding:4px 10px",text:"Copy link",onclick:async()=>{try{await navigator.clipboard.writeText(i.acceptUrl),d.textContent="Copied!",setTimeout(()=>{d.textContent="Copy link"},2e3)}catch{window.errorHandler&&window.errorHandler.show("Clipboard blocked: select the link manually.")}}});o.appendChild(d),i.deliveredVia==="dev-console"?o.appendChild(n("p",{style:"margin-top:8px;color:#fbbf24;font-size:0.8rem",text:"SMTP not configured \u2014 the invite was logged to the server console (search for [DC-048-DEV-INVITE-LINK])."})):i.deliveredVia==="email"&&o.appendChild(n("p",{style:"margin-top:8px;color:#86efac;font-size:0.8rem",text:"Email sent to "+i.email+"."})),e.appendChild(o)}async function y(i){i.innerHTML="",i.appendChild(n("h2",{style:"margin:0 0 16px",text:"Admin \xB7 Users & Invites"}));const e=await g(l.me).catch(()=>({}));if(!e||!e.user||e.user.role!=="admin"){i.appendChild(n("p",{style:"color:var(--muted)",text:"Admin role required to view this panel. If multi-user mode is enabled and you should have access, check /api/v1/auth/me."}));return}const o=n("button",{class:"btn-sm",style:"float:right;padding:4px 10px",text:"Refresh",onclick:()=>y(i)});i.appendChild(o);const d=n("h3",{style:"margin:24px 0 8px;clear:both",text:"Users"});i.appendChild(d);const t=n("div",{id:"admin-users-list"});i.appendChild(t);const r=await g(l.users).catch(()=>({users:[]}));f(t,r.users,()=>y(i)),i.appendChild(n("h4",{style:"margin:24px 0 8px;font-size:0.95rem",text:"Pre-authorize email"}));const h=n("form",{style:"display:flex;gap:8px;align-items:end",onsubmit:async L=>{L.preventDefault();const P=L.target.email.value.trim();if(P)try{await g(l.users,{method:"POST",body:{email:P}}),L.target.reset(),y(i)}catch(E){window.errorHandler&&window.errorHandler.show("Add failed: "+E.message)}}});h.appendChild(n("input",{name:"email",type:"email",required:!0,placeholder:"user@example.com",style:"padding:6px"})),h.appendChild(n("button",{type:"submit",class:"btn-sm",style:"padding:6px 12px",text:"Add to allowlist"})),i.appendChild(h),i.appendChild(n("h3",{style:"margin:24px 0 8px",text:"Issue invite"}));const p=n("div");i.appendChild(p);const w=n("div",{id:"admin-invites-list",style:"margin-top:16px"});i.appendChild(w);const T=await g(l.invites).catch(()=>({invites:[]}));v(w,T.invites,()=>y(i)),u(p,L=>{s(L,p),y(i)})}async function c(){if(document.getElementById("admin-panel-root"))return;const e=n("div",{id:"admin-panel-root",style:"position:fixed;inset:0;background:rgba(0,0,0,0.5);z-index:1000;display:flex;align-items:center;justify-content:center;",onclick:t=>{t.target===e&&a()}}),o=n("div",{style:"background:var(--card-base,#1f2937);color:var(--text,#f3f4f6);border-radius:8px;padding:24px;max-width:900px;width:90%;max-height:85vh;overflow:auto;position:relative;box-shadow:0 10px 30px rgba(0,0,0,0.3)"});o.appendChild(n("button",{class:"btn-sm",style:"position:absolute;top:12px;right:12px;padding:4px 10px",text:"Close",onclick:a}));const d=n("div",{id:"admin-panel-body"});o.appendChild(d),e.appendChild(o),document.body.appendChild(e);try{await y(d)}catch(t){d.innerHTML='<p style="color:#f87171">Failed to load admin panel: '+(t.message||t)+"</p>"}}function a(){const i=document.getElementById("admin-panel-root");i&&i.remove()}async function m(i){async function e(){const o=await g(l.me).catch(()=>({})),d=document.getElementById("admin-trigger-btn");if(o&&o.user&&o.user.role==="admin"){if(d)return;const t=n("button",{id:"admin-trigger-btn",class:"btn-sm",style:"margin-left:8px;padding:6px 12px",text:"Admin",onclick:c});i?i.appendChild(t):document.body&&document.body.appendChild(t)}else d&&d.remove()}await e(),setInterval(e,6e4)}window.AdminPanel={open:c,close:a,attachTrigger:m}})(),(function(){injectModal("token-management-modal",`
|
|
<div id="token-management-modal" class="weather-modal">
|
|
<div class="weather-modal-content" style="min-width: 500px; max-width: 600px;">
|
|
<h3>\u{1F511} DNS Credentials</h3>
|
|
|
|
<p style="font-size: 0.85rem; color: var(--muted); margin: 0 0 16px;">
|
|
Enter Technitium DNS login credentials. Read-only accounts are used for logs; admin accounts for restarts, records, and updates.
|
|
</p>
|
|
|
|
<div id="dns-cred-sections"></div>
|
|
|
|
<div class="weather-modal-buttons modal-footer-bar">
|
|
<button id="token-clear-all" style="margin-right: auto; background: color-mix(in srgb, var(--bad-fg) 15%, transparent); border-color: var(--bad-fg); color: var(--bad-fg);">Clear All</button>
|
|
<button id="token-cancel">Cancel</button>
|
|
<button id="token-save" class="btn-accent">Save</button>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
`);function 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",`
|
|
<div class="token-section">
|
|
<h4 class="token-section-title">${n(h)}</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;" />
|
|
<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>
|
|
</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;" />
|
|
<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>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
<div class="token-status" id="${h}-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.error("Failed to sync DNS credentials to backend:",p),t.forEach(w=>{r[w]&&(document.getElementById(`${w}-token-status`).textContent="\u2713 Saved locally (sync failed)",document.getElementById(`${w}-token-status`).className="token-status")})}}else t.forEach(p=>{document.getElementById(`${p}-token-status`).textContent=""});setTimeout(()=>{t.every(w=>{const T=document.getElementById(`${w}-token-status`)?.textContent;return!T||T.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.")){o(),l().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=c,window.getUsername=a,window.setToken=m,window.setUsername=i,window.getAllCredentials=e,window.getCredential=s,window.setCredential=y,window.getEncryptionKey=b,window.getDnsIds=l,window.getDnsDisplayName=n})(),(function(){function l(m,i,e=null){const o=document.getElementById(m+"-dot"),d=document.getElementById(m+"-pill"),t=document.getElementById(m+"-time"),r=document.querySelector(`[data-app="${m}"]`);o&&(o.classList.toggle("ok",i),o.classList.toggle("bad",!i)),d&&(d.textContent=i?"ON":"OFF",d.classList.toggle("on",i),d.classList.toggle("off",!i)),t&&e!==null&&(t.textContent=i?`${e}ms`:"timeout",t.className=`response-time ${n(e,i)}`),r&&r.setAttribute("data-status",i?"on":"off")}function n(m,i){return i?m<200?"excellent":m<500?"good":m<1e3?"fair":"slow":"timeout"}async function g(m){const i=performance.now();try{const e=await fetch("/probe/"+m,{cache:"no-store"}),o=performance.now(),d=Math.round(o-i);return{isUp:e.status>=200&&e.status<400||e.status===401||e.status===403,responseTime:d}}catch{const e=performance.now();return{isUp:!1,responseTime:Math.round(e-i)}}}window.APPS=[];let b=null,f=!1;async function u(){try{window.SkeletonLoader&&window.SkeletonLoader.show(6);const m=await fetch("/api/v1/services",{cache:"no-store"});if(m.ok){const i=await m.json();window.APPS=i.services||[],window.SkeletonLoader&&window.SkeletonLoader.hide()}else console.error("Failed to load services:",m.status),window.SkeletonLoader&&window.SkeletonLoader.hide()}catch(m){console.error("Failed to load services:",m),window.SkeletonLoader&&window.SkeletonLoader.hide()}}function v(m){const i=window.APPS?.find(o=>o.id===m);if(i?.url)return i.url.startsWith("http")?i.url:"https://"+i.url;if(i?.isExternal&&i.externalUrl)return i.externalUrl;const e=SITE.dnsServers?.[m];return e?"http://"+e.ip+":"+(e.port||5380):buildServiceUrl(m)}function s(m,i,e){const o=document.createElement(m);return i&&(o.className=i),e&&(o.textContent=e),o}function y(){const m=document.getElementById("cards");m.innerHTML="";for(let i=0;i<window.APPS.length;i++){const e=window.APPS[i];if(e.id==="ca")continue;const o=s("div","card");o.setAttribute("data-app",e.id),o.setAttribute("data-status","off"),e.containerId&&o.setAttribute("data-container-id",e.containerId),e.category&&o.setAttribute("data-category",e.category),e.recipeId&&o.setAttribute("data-recipe-id",e.recipeId);const d=s("span","dot bad at-bl");d.id="dot-"+e.id+"-grid",o.appendChild(d);const t=s("div","row"),r=s("div","logo-wrap"),h=document.createElement("img");h.src=e.logo,h.alt=e.name,h.className="logo-img",h.onerror=function(){let k=e.id||e.appTemplate;if(!k&&e.name&&(k=e.name.toLowerCase().replace(/\s+/g,"-")),k){const S=[`https://cdn.jsdelivr.net/gh/walkxcode/dashboard-icons/png/${k}.png`,`https://cdn.jsdelivr.net/gh/walkxcode/dashboard-icons/png/${k.toLowerCase()}.png`,`https://cdn.jsdelivr.net/gh/walkxcode/dashboard-icons/png/${k.replace(/-/g,"")}.png`,`https://cdn.jsdelivr.net/gh/walkxcode/dashboard-icons/png/${e.name.toLowerCase().replace(/\s+/g,"-")}.png`],A=[...new Set(S)],O=A.indexOf(this.src)+1;O<A.length?this.src=A[O]:this.style.display="none"}else this.style.display="none"},r.appendChild(h),t.appendChild(r);const p=s("span","name",e.name);if(t.appendChild(p),e.tailscaleOnly){const k=s("span","ts-badge","\u{1F510}");k.title="Tailscale-only access",k.style.cssText="margin-left: 6px; font-size: 0.75rem; opacity: 0.8;",p.appendChild(k)}if(e.category){const S=(typeof DC<"u"&&DC.CATEGORIES||window.DC_CATEGORIES||{})[e.category]||{},A=s("span","cat-badge",`${S.icon||""} ${e.category}`.trim());A.title=`Category: ${e.category}`,A.style.cssText=`margin-left: 6px; font-size: 0.65rem; padding: 1px 6px; border-radius: 999px; background: color-mix(in srgb, ${S.color||"#7f8c8d"} 25%, transparent); color: ${S.color||"#7f8c8d"}; border: 1px solid color-mix(in srgb, ${S.color||"#7f8c8d"} 50%, transparent); white-space: nowrap; font-weight: 500;`,p.appendChild(A)}t.appendChild(s("span","spacer"));const w=s("span","badge off","OFF");w.id="badge-"+e.id,t.appendChild(w);const T=s("span","update-available-badge","UPDATE");T.id="update-badge-"+e.id,T.title="Update available",t.appendChild(T),o.appendChild(t);const L=s("div","response-row"),P=s("span","response-time","--");P.id="time-"+e.id,L.appendChild(P),o.appendChild(L);const E=s("div","health-row");E.id="health-"+e.id;const B=s("span","uptime-chip","--");B.id="uptime-"+e.id,E.appendChild(B);const $=document.createElement("div");$.className="uptime-mini-bar";const C=document.createElement("div");C.className="fill",C.id="uptime-bar-"+e.id,C.style.width="0%",$.appendChild(C),E.appendChild($),o.appendChild(E);const x=s("div","btn-row");if(e.containerId){const k=s("button","logs-btn","\u{1F4CB}");k.title="View container logs",k.onclick=D=>{D.stopPropagation(),window.openContainerLogsModal(e.containerId,e.name)},x.appendChild(k);const S=s("button","update-btn","\u2B06\uFE0F");S.title="Update container to latest version",S.id=`update-btn-${e.id}`,S.onclick=D=>{D.stopPropagation(),window.updateContainer(e.containerId,e.name,e.id)},x.appendChild(S);const A=s("button","exec-btn",">_");A.title="Open terminal",A.onclick=D=>{D.stopPropagation(),window.openExecModal&&window.openExecModal(e.containerId,e.name)},x.appendChild(A)}if(e.logPath&&!e.containerId){const k=s("button","logs-btn","\u{1F4CB}");k.title="View application logs",k.onclick=S=>{S.stopPropagation(),window.openFileLogsModal(e.logPath,e.name)},x.appendChild(k)}if(e.isExternal||e.appTemplate||e.url){const k=s("button","creds-btn","\u{1F511}");k.title="Auto-login credentials",k.id=`creds-btn-${e.id}`,k.onclick=S=>{S.stopPropagation(),window.openServiceCredsModal(e)},x.appendChild(k)}if(e.id!=="internet"){const k=s("button","options-btn","\u2699\uFE0F");k.title="Edit service settings",k.onclick=S=>{S.stopPropagation(),window.openServiceEditModal(e)},x.appendChild(k)}if(e.id!=="internet"){const k=s("button","delete-btn","\u{1F5D1}\uFE0F");k.title="Delete this service",k.onclick=S=>{S.stopPropagation(),window.deleteService(e.id,e.name)},x.appendChild(k)}const I=s("button",null,"Open");I.onclick=()=>window.open(v(e.id),"_blank","noopener"),x.appendChild(I),o.appendChild(x),o.style.transitionDelay=`${Math.min(i*45,270)}ms`,m.appendChild(o)}requestAnimationFrame(()=>{m.querySelectorAll(".card").forEach(i=>i.classList.add("loaded"))}),window.groupRecipeCards&&requestAnimationFrame(()=>window.groupRecipeCards()),window.refreshServiceFilter&&window.refreshServiceFilter()}function c(m,i,e=null){const o=document.getElementById("dot-"+m+"-grid"),d=document.getElementById("badge-"+m),t=document.getElementById("time-"+m),r=document.querySelector(`[data-app="${m}"]`);o&&(o.classList.toggle("ok",i),o.classList.toggle("bad",!i)),d&&(d.textContent=i?"ON":"OFF",d.classList.toggle("on",i),d.classList.toggle("off",!i)),t&&e!==null&&(t.textContent=i?`${e}ms`:"timeout",t.className=`response-time ${n(e,i)}`),r&&r.setAttribute("data-status",i?"on":"off")}async function a(){if(b)return f=!0,b;function m(o,d=new Date){const t=document.getElementById("stamp");t&&(t.textContent=`${o}: ${new Date(d).toLocaleTimeString()}`)}function i(o){Object.keys(SITE.dnsServers).forEach(t=>{const r=o[t];r&&l(t,r.isUp,r.responseTime)}),o.internet&&l("internet",o.internet.isUp,o.internet.responseTime),window.APPS.forEach(t=>{const r=o[t.id];r&&c(t.id,r.isUp,r.responseTime)})}async function e(){const o=Object.keys(SITE.dnsServers),d=o.map(p=>g(p));d.push(g("internet"));const t=await Promise.all(d);o.forEach((p,w)=>l(p,t[w].isUp,t[w].responseTime));const r=t[t.length-1];l("internet",r.isUp,r.responseTime),(await Promise.all(window.APPS.map(async p=>{const w=await g(p.id);return{id:p.id,...w}}))).forEach(p=>{c(p.id,p.isUp,p.responseTime)})}return b=(async()=>{try{const o=await fetch("/api/v1/services/status",{cache:"no-store"});if(!o.ok)throw new Error(`Status refresh failed (${o.status})`);const d=await o.json();i(d.statuses||{}),m("last check",d.checkedAt||new Date)}catch(o){console.warn("Batched status refresh failed, falling back to direct probes:",o);try{await e(),m("last check")}catch(d){console.error("Dashboard refresh failed:",d),m("last failed")}}finally{b=null,f&&(f=!1,setTimeout(()=>{window.refreshAll()},0))}})(),b}document.querySelector(".top")?.addEventListener("click",m=>{const i=m.target.closest('[id$="-open"]');if(!i)return;const e=i.id.replace("-open","");SITE.dnsServers[e]&&window.open(v(e),"_blank","noopener")}),document.getElementById("ca-open")?.addEventListener("click",()=>window.open(v("ca"),"_blank","noopener")),document.getElementById("creds-btn-ca")?.addEventListener("click",m=>{m.stopPropagation();const i=window.APPS.find(e=>e.id==="ca");i&&window.openServiceCredsModal&&window.openServiceCredsModal(i)}),document.getElementById("options-btn-ca")?.addEventListener("click",m=>{m.stopPropagation();const i=window.APPS.find(e=>e.id==="ca");i&&window.openServiceEditModal&&window.openServiceEditModal(i)}),document.getElementById("delete-btn-ca")?.addEventListener("click",m=>{m.stopPropagation(),window.deleteService&&window.deleteService("ca","DashCA")}),window.loadServices=u,window.buildGrid=y,window.refreshAll=a,window.setQuick=l,window.setBadge=c,window.getResponseTimeClass=n,window.checkServiceWithTiming=g,window.serviceUrl=v,window.el=s})(),(function(){async function l(s){const c=await(await secureFetch(`/api/v1/dns/restart/${s}`,{method:"POST"})).json();if(!c.success)throw new Error(c.error||"Restart failed");return c}document.querySelector(".top")?.addEventListener("click",async s=>{const y=s.target.closest('[id$="-restart"]');if(!y)return;const c=y.id.replace("-restart","");if(SITE.dnsServers[c]&&confirm(`Restart ${c.toUpperCase()} service?`))try{await withButton(y,"...",()=>l(c)),setTimeout(window.refreshAll,DC.DELAYS.RELOAD)}catch(a){showNotification("Restart failed: "+a.message,"error")}});async function n(s,y){const c=document.getElementById(`${s}-update`),a=c?.textContent||"\u2B06\uFE0F";try{c.textContent="\u{1F50D}",c.disabled=!0,c.title="Checking for updates...";const i=await(await fetch(`/api/v1/dns/check-update?server=${encodeURIComponent(y)}`)).json();if(!i.success)throw new Error(i.error||"Failed to check for updates");if(!i.updateAvailable){c.textContent="\u2705",c.title=`Already on latest version (${i.currentVersion})`,showNotification(`${s.toUpperCase()} is already up to date! Current version: ${i.currentVersion}`,"info"),setTimeout(()=>{c.textContent=a,c.disabled=!1,c.title="Update DNS server"},3e3);return}if(!confirm(`Update available for ${s.toUpperCase()}!
|
|
|
|
Current: ${i.currentVersion}
|
|
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?`
|
|
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",`
|
|
<div id="dns-settings-modal" class="weather-modal">
|
|
<div class="weather-modal-content" style="min-width: 420px; max-width: 520px;">
|
|
<h3 id="dns-settings-title">DNS Settings</h3>
|
|
|
|
<div style="display: grid; gap: 16px; margin-top: 16px;">
|
|
<div>
|
|
<label for="dns-edit-ip" class="form-label-accent-sm">Server IP</label>
|
|
<input type="text" id="dns-edit-ip" class="form-input-md" placeholder="192.168.1.1" />
|
|
</div>
|
|
<div>
|
|
<label for="dns-edit-port" class="form-label-accent-sm">Port</label>
|
|
<input type="number" id="dns-edit-port" class="form-input-md" placeholder="5380" />
|
|
</div>
|
|
<div>
|
|
<label for="dns-edit-name" class="form-label-accent-sm">Display Name (optional)</label>
|
|
<input type="text" id="dns-edit-name" class="form-input-md" placeholder="e.g. Primary DNS" />
|
|
</div>
|
|
<div class="form-hint-sm">Manage credentials via Tokens in the toolbar</div>
|
|
</div>
|
|
|
|
<div class="weather-modal-buttons" style="margin-top: 24px;">
|
|
<button id="dns-settings-cancel">Cancel</button>
|
|
<button id="dns-settings-delete" style="background: color-mix(in srgb, #e74c3c 20%, transparent); border-color: #e74c3c; color: #e74c3c;">Remove</button>
|
|
<button id="dns-settings-save" class="btn-accent">Save</button>
|
|
</div>
|
|
</div>
|
|
</div>`);let 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 id="logs-modal" class="logs-modal">
|
|
<div class="logs-modal-content" style="min-width: 800px; max-width: 1000px;">
|
|
<div class="logs-header">
|
|
<h3 id="logs-title">DNS Logs</h3>
|
|
<div class="logs-controls">
|
|
<label for="log-lines">Show:</label>
|
|
<select id="log-lines">
|
|
<option value="25" selected>25</option>
|
|
<option value="50">50</option>
|
|
<option value="100">100</option>
|
|
<option value="200">200</option>
|
|
</select>
|
|
<button id="logs-stream" class="stream-btn" title="Enable real-time streaming">\u{1F4E1} Live</button>
|
|
<button id="logs-pause" class="pause-btn">\u23F8\uFE0F Pause</button>
|
|
<button id="logs-close" class="close-btn">\u2715</button>
|
|
</div>
|
|
</div>
|
|
<div class="logs-container scroll-container">
|
|
<div id="logs-content" class="logs-content">
|
|
<div class="logs-loading">Loading logs...</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>`);let 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=`
|
|
<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=`
|
|
<div style="padding: 20px; text-align: center; color: var(--bad-fg);">
|
|
<div style="font-size: 1.2rem; margin-bottom: 8px;">\u26A0\uFE0F Error</div>
|
|
<div>${escapeHtml(I.error)}</div>
|
|
</div>`;return}x.innerHTML=`
|
|
<div style="display: grid; grid-template-columns: 140px 110px 1fr 70px 80px; gap: 8px; padding: 8px 10px; background: var(--card-base); border-bottom: 2px solid var(--border); font-size: 0.75rem; font-weight: 600; color: var(--muted); position: sticky; top: 0;">
|
|
<span>Time</span>
|
|
<span>Client</span>
|
|
<span>Domain</span>
|
|
<span>Type</span>
|
|
<span>Status</span>
|
|
</div>`,I.logs&&I.logs.length>0?I.logs.forEach(k=>{const S=e(k);x.appendChild(S)}):x.innerHTML+=`
|
|
<div style="padding: 20px; text-align: center; color: var(--muted);">
|
|
No DNS queries logged yet
|
|
</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 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}×tamps=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=`
|
|
<div style="padding: 20px; text-align: center; color: var(--bad-fg);">
|
|
<div style="font-size: 1.2rem; margin-bottom: 8px;">\u26A0\uFE0F Error</div>
|
|
<div>${escapeHtml(I.error)}</div>
|
|
</div>`;return}x.innerHTML=`
|
|
<div style="display: flex; gap: 12px; padding: 8px 10px; background: var(--card-base); border-bottom: 2px solid var(--border); font-size: 0.75rem; font-weight: 600; color: var(--muted); position: sticky; top: 0;">
|
|
<span style="flex-shrink: 0; width: 80px;">Stream</span>
|
|
<span style="flex: 1;">Log Output</span>
|
|
</div>`,I.logs&&I.logs.length>0?(I.logs.forEach(k=>{const S=w(k);x.appendChild(S)}),x.scrollTop=x.scrollHeight):x.innerHTML+=`
|
|
<div style="padding: 20px; text-align: center; color: var(--muted);">
|
|
No logs available for this container
|
|
</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 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=`
|
|
<div style="padding: 20px; text-align: center; color: var(--bad-fg);">
|
|
<div style="font-size: 1.2rem; margin-bottom: 8px;">\u26A0\uFE0F Error</div>
|
|
<div>${escapeHtml(I.error)}</div>
|
|
</div>`;return}x.innerHTML=`
|
|
<div style="display: flex; gap: 12px; padding: 8px 10px; background: var(--card-base); border-bottom: 2px solid var(--border); font-size: 0.75rem; font-weight: 600; color: var(--muted); position: sticky; top: 0;">
|
|
<span style="flex: 1;">Log Output (${I.count} of ${I.totalLines} lines)</span>
|
|
</div>`,I.logs&&I.logs.length>0?(I.logs.forEach(k=>{const S=E(k);x.appendChild(S)}),x.scrollTop=x.scrollHeight):x.innerHTML+=`
|
|
<div style="padding: 20px; text-align: center; color: var(--muted);">
|
|
No logs available in this file
|
|
</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 id="service-edit-modal" class="weather-modal">
|
|
<div class="weather-modal-content" style="min-width: 500px; max-width: 600px;">
|
|
<h3 id="service-edit-title">Edit Service</h3>
|
|
|
|
<div style="display: grid; gap: 16px; margin-top: 16px;">
|
|
<!-- Service Info -->
|
|
<div style="display: flex; align-items: center; gap: 12px; padding: 12px; background: var(--card-bg); border-radius: 8px;">
|
|
<img id="edit-service-logo-preview" src="" alt="" style="width: 48px; height: 48px; border-radius: 8px; object-fit: contain; background: var(--bg);" />
|
|
<div style="flex: 1;">
|
|
<div id="edit-service-url-display" class="text-muted-sm"></div>
|
|
</div>
|
|
</div>
|
|
|
|
<!-- Display Name -->
|
|
<div>
|
|
<label for="edit-service-name" class="form-label-accent-sm">
|
|
Display Name
|
|
</label>
|
|
<input type="text" id="edit-service-name" class="form-input-md" placeholder="Service name shown on dashboard" />
|
|
</div>
|
|
|
|
<!-- Subdomain -->
|
|
<div>
|
|
<label for="edit-subdomain" class="form-label-accent-sm">
|
|
Subdomain
|
|
</label>
|
|
<div class="flex-row-gap-center">
|
|
<input type="text" id="edit-subdomain" class="input-flex" />
|
|
<span id="edit-tld-suffix" style="color: var(--muted);">.home</span>
|
|
</div>
|
|
</div>
|
|
|
|
<!-- Port -->
|
|
<div>
|
|
<label for="edit-port" class="form-label-accent-sm">
|
|
Port
|
|
</label>
|
|
<input type="number" id="edit-port" class="form-input-md" />
|
|
<div class="form-hint-sm">
|
|
The port Caddy will proxy to (container's exposed port)
|
|
</div>
|
|
</div>
|
|
|
|
<!-- IP Address -->
|
|
<div>
|
|
<label for="edit-ip" class="form-label-accent-sm">
|
|
IP Address
|
|
</label>
|
|
<input type="text" id="edit-ip" class="form-input-md" />
|
|
</div>
|
|
|
|
<!-- Tailscale Protection -->
|
|
<div>
|
|
<label style="display: flex; align-items: center; gap: 10px; padding: 12px; background: var(--card-bg); border: 1px solid var(--border); border-radius: 6px; cursor: pointer;">
|
|
<input type="checkbox" id="edit-tailscale-only" style="width: 18px; height: 18px;" />
|
|
<div>
|
|
<div class="fw-500">Tailscale-Only Access</div>
|
|
<div class="text-hint">Restrict this service to Tailscale users only</div>
|
|
</div>
|
|
</label>
|
|
</div>
|
|
|
|
<!-- Logo -->
|
|
<div>
|
|
<label class="form-label-accent-sm">
|
|
Service Logo
|
|
</label>
|
|
<div class="flex-row-gap-center">
|
|
<input type="text" id="edit-logo-url" placeholder="/assets/service.png or https://..." class="input-flex" />
|
|
<label style="padding: 10px 16px; background: var(--card-bg); border: 1px solid var(--border); border-radius: 6px; cursor: pointer; white-space: nowrap;">
|
|
<input type="file" id="edit-logo-file" accept="image/*" style="display: none;" />
|
|
Upload
|
|
</label>
|
|
</div>
|
|
<div class="form-hint-sm">
|
|
Enter a URL or upload an image file (PNG, JPG, SVG)
|
|
</div>
|
|
</div>
|
|
|
|
<!-- Category -->
|
|
<div>
|
|
<label for="edit-service-category" class="form-label-accent-sm">
|
|
Category
|
|
</label>
|
|
<select id="edit-service-category" data-role="service-category" class="form-input-md">
|
|
<option value="">\u2014 No category \u2014</option>
|
|
</select>
|
|
</div>
|
|
</div>
|
|
|
|
<div class="weather-modal-buttons" style="margin-top: 24px;">
|
|
<button id="service-edit-cancel">Cancel</button>
|
|
<button id="service-edit-save" class="btn-accent">
|
|
Save Changes
|
|
</button>
|
|
</div>
|
|
</div>
|
|
</div>`),injectModal("delete-service-modal",`
|
|
<div id="delete-service-modal" class="weather-modal">
|
|
<div class="weather-modal-content" style="min-width: 400px; max-width: 500px;">
|
|
<h3 id="delete-modal-title" class="mb-16">Delete Service</h3>
|
|
|
|
<div id="delete-modal-message" style="margin-bottom: 20px; line-height: 1.5;">
|
|
<!-- Dynamic content -->
|
|
</div>
|
|
|
|
<div id="delete-modal-container-info" style="display: none; margin-bottom: 20px; padding: 12px; background: var(--card-bg); border-radius: 8px; border: 1px solid var(--border);">
|
|
<div style="font-weight: 500; margin-bottom: 8px;">Docker Container</div>
|
|
<div id="delete-modal-container-name" style="font-size: 0.9rem; color: var(--muted);"></div>
|
|
</div>
|
|
|
|
<div class="weather-modal-buttons" style="display: flex; gap: 8px; justify-content: flex-end;">
|
|
<button id="delete-modal-cancel" style="padding: 10px 20px;">Cancel</button>
|
|
<button id="delete-modal-remove" style="padding: 10px 20px; background: color-mix(in srgb, var(--accent) 20%, transparent); border-color: var(--accent); color: var(--accent);">
|
|
Remove
|
|
</button>
|
|
<button id="delete-modal-delete" style="display: none; padding: 10px 20px; background: color-mix(in srgb, #e74c3c 20%, transparent); border-color: #e74c3c; color: #e74c3c;">
|
|
Delete
|
|
</button>
|
|
</div>
|
|
|
|
<div id="delete-modal-help" style="display: none; margin-top: 16px; padding: 12px; background: color-mix(in srgb, var(--muted) 10%, transparent); border-radius: 8px; font-size: 0.85rem; color: var(--muted);">
|
|
<div><strong>Remove:</strong> Remove from dashboard only (container keeps running)</div>
|
|
<div style="margin-top: 6px;"><strong>Delete:</strong> Full removal - stops container, removes DNS & Caddy config</div>
|
|
</div>
|
|
</div>
|
|
</div>`),injectModal("add-service-modal",`
|
|
<div id="add-service-modal" class="weather-modal">
|
|
<div class="weather-modal-content" style="min-width: 420px; max-width: 520px;">
|
|
<h3>Add Service</h3>
|
|
|
|
<!-- Service Type Tabs -->
|
|
<div style="display: flex; gap: 2px; margin-bottom: 16px; background: var(--card-bg); border-radius: 8px; padding: 3px; border: 1px solid var(--border);">
|
|
<label id="tab-local" style="flex: 1; text-align: center; padding: 8px; border-radius: 6px; cursor: pointer; font-size: 0.85rem; font-weight: 500; background: var(--accent); color: var(--bg); transition: all 0.15s;">
|
|
<input type="radio" name="service-type" value="local" id="service-type-local" checked style="display: none;" />
|
|
Local
|
|
</label>
|
|
<label id="tab-external" style="flex: 1; text-align: center; padding: 8px; border-radius: 6px; cursor: pointer; font-size: 0.85rem; font-weight: 500; color: var(--muted); transition: all 0.15s;">
|
|
<input type="radio" name="service-type" value="external" id="service-type-external" style="display: none;" />
|
|
External
|
|
</label>
|
|
</div>
|
|
<span id="service-type-description" style="display: none;"></span>
|
|
|
|
<!-- LOCAL SERVICE -->
|
|
<div id="local-service-config" style="display: grid; gap: 12px;">
|
|
<div>
|
|
<label for="service-name-input" style="font-size: 0.8rem; color: var(--muted); margin-bottom: 4px; display: block;">Name</label>
|
|
<input type="text" id="service-name-input" placeholder="e.g., Jellyfin" style="font-size: 1rem;" />
|
|
<div id="subdomain-preview" style="font-size: 0.75rem; color: var(--accent); margin-top: 4px; min-height: 1em;"></div>
|
|
</div>
|
|
|
|
<div class="grid-2col">
|
|
<div>
|
|
<label for="service-port-input" style="font-size: 0.8rem; color: var(--muted); margin-bottom: 4px; display: block;">Port</label>
|
|
<input type="number" id="service-port-input" placeholder="e.g., 8096" style="font-size: 1rem;" />
|
|
</div>
|
|
<div>
|
|
<label for="service-ip-input" style="font-size: 0.8rem; color: var(--muted); margin-bottom: 4px; display: block;">IP Address</label>
|
|
<input type="text" id="service-ip-input" placeholder="Auto-detected" style="font-size: 1rem;" />
|
|
<div class="quick-ip-buttons" style="display: flex; gap: 4px; margin-top: 4px; flex-wrap: wrap;">
|
|
<button type="button" class="quick-ip-btn" data-ip="127.0.0.1" title="Localhost" style="font-size: 0.7rem; padding: 2px 6px;">localhost</button>
|
|
<button type="button" class="quick-ip-btn" data-ip="" id="quick-ip-lan" title="LAN IP" style="font-size: 0.7rem; padding: 2px 6px;">LAN</button>
|
|
<button type="button" class="quick-ip-btn" data-ip="" id="quick-ip-tailscale" title="Tailscale IP" style="font-size: 0.7rem; padding: 2px 6px;">Tailscale</button>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<!-- Options (collapsed by default) -->
|
|
<details id="local-advanced-options">
|
|
<summary style="cursor: pointer; color: var(--accent); font-size: 0.8rem; user-select: none;">Options</summary>
|
|
<div style="margin-top: 10px; display: grid; gap: 10px; font-size: 0.8rem;">
|
|
|
|
<div class="grid-2col">
|
|
<div>
|
|
<label for="service-subdomain-input">Subdomain:</label>
|
|
<input type="text" id="service-subdomain-input" placeholder="auto-derived from name" />
|
|
</div>
|
|
<div>
|
|
<label for="service-logo-input">Logo URL:</label>
|
|
<input type="text" id="service-logo-input" placeholder="/assets/name.png" />
|
|
</div>
|
|
</div>
|
|
|
|
<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 8px; align-items: start;">
|
|
<label style="display: flex; align-items: center; gap: 6px; cursor: pointer;">
|
|
<input type="checkbox" id="create-dns-record" checked />
|
|
Create DNS Record
|
|
</label>
|
|
<div>
|
|
<label for="ssl-type-select">SSL:</label>
|
|
<select id="ssl-type-select" style="width: 100%;">
|
|
<option value="caddy-managed">Caddy Managed (Internal)</option>
|
|
<option value="letsencrypt">Let's Encrypt</option>
|
|
<option value="existing-ca">Existing CA</option>
|
|
<option value="custom-ca">Custom CA</option>
|
|
</select>
|
|
</div>
|
|
</div>
|
|
|
|
<div id="dns-config">
|
|
<div class="grid-2col">
|
|
<div>
|
|
<label for="dns-ttl-input">DNS TTL:</label>
|
|
<input type="number" id="dns-ttl-input" value="300" />
|
|
</div>
|
|
<div>
|
|
<label for="caddyfile-path-input">Caddyfile Path:</label>
|
|
<input type="text" id="caddyfile-path-input" value="C:\\caddy\\Caddyfile" />
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<div id="existing-ca-config" style="display: none;">
|
|
<label for="existing-ca-select">Existing CA:</label>
|
|
<div class="flex-row-gap">
|
|
<select id="existing-ca-select" style="flex: 1;">
|
|
<option value="">Loading CAs...</option>
|
|
</select>
|
|
<button type="button" id="refresh-cas" style="padding: 4px 8px; font-size: 0.75rem;">\u{1F504}</button>
|
|
</div>
|
|
</div>
|
|
|
|
<div id="custom-ca-config" style="display: none;">
|
|
<label for="ca-name-input">CA Name:</label>
|
|
<input type="text" id="ca-name-input" placeholder="e.g., sami-ca" />
|
|
</div>
|
|
|
|
<div id="manual-tailscale-status" style="padding: 6px 10px; background: var(--card-bg); border-radius: 6px; font-size: 0.75rem;">
|
|
<span style="color: var(--muted);">Checking Tailscale...</span>
|
|
</div>
|
|
<label style="display: flex; align-items: center; gap: 8px; cursor: pointer;">
|
|
<input type="checkbox" id="manual-tailscale-only" />
|
|
Tailscale-Only Access
|
|
</label>
|
|
|
|
<label style="display: flex; align-items: center; gap: 6px; cursor: pointer;">
|
|
<input type="checkbox" id="reload-caddy" checked />
|
|
Reload Caddy after adding
|
|
</label>
|
|
|
|
<!-- Category -->
|
|
<div>
|
|
<label for="service-category-input" style="font-size: 0.8rem; color: var(--muted); margin-bottom: 4px; display: block;">Category</label>
|
|
<select id="service-category-input" data-role="service-category" style="width: 100%;">
|
|
<option value="">\u2014 No category \u2014</option>
|
|
</select>
|
|
<div style="font-size: 0.7rem; color: var(--muted); margin-top: 3px;">Group services on the dashboard by purpose (Media, Productivity, etc.)</div>
|
|
</div>
|
|
|
|
<hr style="border: none; border-top: 1px solid var(--border); margin: 4px 0;" />
|
|
|
|
<div class="grid-2col">
|
|
<div>
|
|
<label class="field-label-sm">
|
|
<input type="checkbox" id="enable-auth" />
|
|
Authentication
|
|
</label>
|
|
<label class="field-label-sm">
|
|
<input type="checkbox" id="enable-cors" />
|
|
CORS Headers
|
|
</label>
|
|
<label for="upstream-path-input">Upstream Path:</label>
|
|
<input type="text" id="upstream-path-input" value="/" />
|
|
</div>
|
|
<div>
|
|
<label for="health-check-input">Health Check:</label>
|
|
<input type="text" id="health-check-input" placeholder="/health" />
|
|
<label for="timeout-input">Timeout (s):</label>
|
|
<input type="number" id="timeout-input" value="30" />
|
|
<label for="custom-headers-input">Headers (JSON):</label>
|
|
<textarea id="custom-headers-input" placeholder='{"X-Custom": "value"}' rows="2" style="font-size: 0.7rem;"></textarea>
|
|
</div>
|
|
</div>
|
|
|
|
</div>
|
|
</details>
|
|
</div>
|
|
|
|
<!-- EXTERNAL SERVICE -->
|
|
<div id="external-service-config" style="display: none;">
|
|
<div style="display: grid; gap: 12px;">
|
|
<div>
|
|
<label for="external-service-name" style="font-size: 0.8rem; color: var(--muted); margin-bottom: 4px; display: block;">Name</label>
|
|
<input type="text" id="external-service-name" placeholder="e.g., Radarr (Seedhost)" style="font-size: 1rem;" />
|
|
<div id="external-subdomain-preview" style="font-size: 0.75rem; color: var(--accent); margin-top: 4px; min-height: 1em;"></div>
|
|
</div>
|
|
|
|
<div>
|
|
<label for="external-service-url" style="font-size: 0.8rem; color: var(--muted); margin-bottom: 4px; display: block;">External URL</label>
|
|
<input type="url" id="external-service-url" placeholder="https://username.seedhost.eu/radarr" style="font-size: 1rem;" />
|
|
</div>
|
|
|
|
<!-- Options (collapsed by default) -->
|
|
<details id="external-advanced-options">
|
|
<summary style="cursor: pointer; color: var(--accent); font-size: 0.8rem; user-select: none;">Options</summary>
|
|
<div style="margin-top: 10px; display: grid; gap: 10px; font-size: 0.8rem;">
|
|
|
|
<div class="grid-2col">
|
|
<div>
|
|
<label for="external-service-subdomain">Subdomain:</label>
|
|
<input type="text" id="external-service-subdomain" placeholder="auto-derived from name" />
|
|
<span id="external-domain-preview" style="font-size: 0.7rem; color: var(--accent);"></span>
|
|
</div>
|
|
<div>
|
|
<label for="external-service-logo">Logo URL:</label>
|
|
<input type="text" id="external-service-logo" placeholder="/assets/name.png" />
|
|
</div>
|
|
</div>
|
|
|
|
<div>
|
|
<label for="external-service-icon">Icon Emoji:</label>
|
|
<input type="text" id="external-service-icon" placeholder="\u{1F3AC}" maxlength="2" style="width: 60px;" />
|
|
</div>
|
|
|
|
<label style="display: flex; align-items: center; gap: 6px; cursor: pointer;">
|
|
<input type="checkbox" id="external-create-dns" checked />
|
|
Create DNS Record
|
|
</label>
|
|
<label style="display: flex; align-items: center; gap: 6px; cursor: pointer;">
|
|
<input type="checkbox" id="external-create-caddy" checked />
|
|
Create Caddy Reverse Proxy
|
|
</label>
|
|
|
|
<div>
|
|
<label for="external-proxy-ip">Proxy Server IP:</label>
|
|
<input type="text" id="external-proxy-ip" placeholder="Auto-detected" />
|
|
</div>
|
|
<label style="display: flex; align-items: center; gap: 6px; cursor: pointer;">
|
|
<input type="checkbox" id="external-preserve-host" checked />
|
|
Preserve Host Header
|
|
</label>
|
|
<label style="display: flex; align-items: center; gap: 6px; cursor: pointer;">
|
|
<input type="checkbox" id="external-follow-redirects" checked />
|
|
Follow Redirects
|
|
</label>
|
|
|
|
<!-- Category (external) -->
|
|
<div>
|
|
<label for="external-service-category" style="font-size: 0.8rem; color: var(--muted); margin-bottom: 4px; display: block;">Category</label>
|
|
<select id="external-service-category" data-role="service-category" style="width: 100%;">
|
|
<option value="">\u2014 No category \u2014</option>
|
|
</select>
|
|
</div>
|
|
|
|
</div>
|
|
</details>
|
|
</div>
|
|
</div>
|
|
|
|
<div class="weather-modal-buttons" style="margin-top: 16px; display: flex; gap: 8px; justify-content: flex-end;">
|
|
<button id="add-service-cancel">Cancel</button>
|
|
<button id="add-service-create" class="btn-accent">Create Service</button>
|
|
</div>
|
|
</div>
|
|
</div>`)})(),(function(){async function 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}
|
|
}
|
|
`);break;case"custom-ca":a&&(p+=` tls {
|
|
ca ${a}
|
|
}
|
|
`);break}if(i&&(p+=` 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").value=e.path)}catch{}},c.readAsDataURL(y)}),document.getElementById("service-edit-cancel")?.addEventListener("click",g),document.getElementById("service-edit-save")?.addEventListener("click",b),document.getElementById("service-edit-modal")?.addEventListener("click",s=>{s.target.id==="service-edit-modal"&&g()});function f(s,y,c){return new Promise(a=>{const m=document.getElementById("delete-service-modal"),i=document.getElementById("delete-modal-title"),e=document.getElementById("delete-modal-message"),o=document.getElementById("delete-modal-container-info"),d=document.getElementById("delete-modal-container-name"),t=document.getElementById("delete-modal-help"),r=document.getElementById("delete-modal-cancel"),h=document.getElementById("delete-modal-remove"),p=document.getElementById("delete-modal-delete");i.textContent=`Delete "${s}"`,y?(e.innerHTML="This service has an associated Docker container.<br>Choose how to proceed:",o.style.display="block",d.textContent=`Container ID: ${c?.slice(0,12)||"Unknown"}`,t.style.display="block",p.style.display="block"):(e.textContent="Remove this service from the dashboard?",o.style.display="none",t.style.display="none",p.style.display="none");const w=()=>{m.classList.remove("show"),r.removeEventListener("click",T),h.removeEventListener("click",L),p.removeEventListener("click",P),m.removeEventListener("click",E)},T=()=>{w(),a(null)},L=()=>{w(),a(!1)},P=()=>{w(),a(!0)},E=B=>{B.target===m&&(w(),a(null))};r.addEventListener("click",T),h.addEventListener("click",L),p.addEventListener("click",P),m.addEventListener("click",E),m.classList.add("show")})}async function u(s,y,c){const a=document.getElementById(`update-btn-${c}`),m=a?.textContent;if(confirm(`Update ${y} 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/${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.style.display="none"),o&&(b.tailscale?(o.dataset.ip=b.tailscale,o.textContent=`Tailscale (${b.tailscale})`,o.title=`Tailscale IP: ${b.tailscale}`):o.style.display="none");const d=document.getElementById("service-ip-input");d&&!d.value&&b.lan&&(d.value=b.lan)}function u(){document.querySelectorAll(".quick-ip-btn").forEach(e=>{e.addEventListener("click",()=>{const o=e.dataset.ip;o&&(document.getElementById("service-ip-input").value=o,document.querySelectorAll(".quick-ip-btn").forEach(d=>d.classList.remove("active")),e.classList.add("active"),g())})}),document.getElementById("service-ip-input")?.addEventListener("input",e=>{const o=e.target.value;document.querySelectorAll(".quick-ip-btn").forEach(d=>{d.classList.toggle("active",d.dataset.ip===o)})})}async function v(){const e=document.getElementById("add-service-modal");e.classList.add("show");const o=e.querySelector(".weather-modal-content");o&&(o.scrollTop=0),document.body.style.overflow="hidden";const d=document.getElementById("ssl-type-select");d&&(d.value=n()),await f();const t=document.getElementById("caddyfile-path-input").value||DC.DEFAULTS.CADDYFILE;await window.loadExistingCAs(t);const r=document.getElementById("manual-tailscale-status"),h=document.getElementById("manual-tailscale-only");try{const w=await(await fetch("/api/v1/tailscale/status")).json();w.success&&w.installed&&w.connected?(r.innerHTML=`
|
|
<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(`Failed to create external service: ${B.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=b.lan||"",document.getElementById("service-logo-input").value="",document.getElementById("dns-ttl-input").value=DC.DEFAULTS.TTL,document.getElementById("ssl-type-select").value=n(),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 o=document.getElementById("external-subdomain-preview");o&&(o.textContent="");const d=document.getElementById("external-service-name");d&&(d.value="");const t=document.getElementById("external-service-subdomain");t&&(t.value="");const r=document.getElementById("external-service-url");r&&(r.value="");const h=document.getElementById("external-service-logo");h&&(h.value="");const p=document.getElementById("external-service-icon");p&&(p.value="");const w=document.getElementById("local-advanced-options");w&&w.removeAttribute("open");const T=document.getElementById("external-advanced-options");T&&T.removeAttribute("open");const L=document.getElementById("service-type-local");L&&(L.checked=!0);const P=document.getElementById("local-service-config"),E=document.getElementById("external-service-config");P&&(P.style.display="grid"),E&&(E.style.display="none");const B=document.getElementById("tab-local"),$=document.getElementById("tab-external");B&&(B.style.background="var(--accent)",B.style.color="var(--bg)"),$&&($.style.background="transparent",$.style.color="var(--muted)")}async function m(){const e=document.getElementById("service-name-input").value.trim(),o=(document.getElementById("service-subdomain-input").value.trim()||l(e)).toLowerCase(),d=document.getElementById("service-port-input").value.trim(),t=document.getElementById("service-ip-input").value.trim(),r=document.getElementById("service-logo-input").value.trim(),h=document.getElementById("create-dns-record").checked,p=parseInt(document.getElementById("dns-ttl-input").value)||DC.DEFAULTS.TTL,w=document.getElementById("manual-tailscale-only")?.checked||!1,T=document.getElementById("ssl-type-select")?.value||"caddy-managed",L=document.getElementById("ca-name-input")?.value||"",P=document.getElementById("existing-ca-select")?.value||"",E=document.getElementById("enable-auth")?.checked||!1,B=document.getElementById("enable-cors")?.checked||!1,$=document.getElementById("custom-headers-input")?.value||"",C=document.getElementById("upstream-path-input")?.value||"/",x=document.getElementById("health-check-input")?.value||"",I=document.getElementById("timeout-input")?.value||30,S=(document.getElementById("service-category-input")||document.getElementById("external-service-category"))?.value||"",A=window.getToken(getPrimaryDnsId(),"admin");if(!e||!d||!t){showNotification("Please fill in Name, Port, and IP Address","warning");return}if(!o){showNotification("Could not derive subdomain from name. Please set one in Options.","warning");return}if(h&&!A){showNotification("DNS Admin token required. Configure it in the Tokens menu first.","warning");return}const D={dns:null,caddy:null,dashboard:!1};try{if(h)try{await window.createDnsRecord(o,t,p),D.dns="created"}catch(N){throw console.error("DNS creation failed:",N),D.dns=N.message,new Error(`DNS creation failed: ${N.message}`)}else D.dns="skipped";const O=window.generateCaddyConfig({subdomain:o,port:d,ip:t,sslType:T,caName:L,existingCa:P,enableAuth:E,enableCors:B,customHeaders:$,upstreamPath:C,healthCheck:x,timeout:I,tailscaleOnly:w});try{const U=await(await secureFetch("/api/v1/site",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:buildDomain(o),upstream:`${t}:${d}`,config:O})})).json();if(U.success)D.caddy="added & reloaded";else throw console.error("Caddy configuration failed:",U.error),D.caddy=U.error||"failed",new Error(`Caddy configuration failed: ${U.error}`)}catch(N){throw console.error("Caddy API error:",N),D.caddy=N.message,new Error(`Caddy API error: ${N.message}`)}const M={name:e,subdomain:o,port:d,ip:t,logo:r||`/assets/${o}.png`,tailscaleOnly:w||!1};S&&(M.category=S),await window.addServiceToConfig(M),D.dashboard=!0;const R=[`DNS: ${D.dns==="created"?"\u2713":D.dns==="skipped"?"\u25CB":"\u2717"}`,`Caddy: ${D.caddy==="added & reloaded"?"\u2713":"\u2717"}`,`Dashboard: ${D.dashboard?"\u2713":"\u2717"}`];showNotification(`Service "${e}" created! ${R.join(" | ")} \u2014 ${buildServiceUrl(o)}${w?" (Tailscale)":""}`,"success",6e3),a(),window.buildGrid(),window.refreshAll()}catch(O){console.error("Error creating service:",O),showNotification(`Error creating "${e}": ${O.message}`,"error",6e3)}}document.getElementById("add-service")?.addEventListener("click",v),document.getElementById("add-service-cancel")?.addEventListener("click",a),document.getElementById("add-service-create")?.addEventListener("click",()=>{document.querySelector('input[name="service-type"]:checked')?.value==="external"?c():m()}),s(),y(),u(),document.getElementById("ssl-type-select")?.addEventListener("change",e=>{const o=document.getElementById("existing-ca-config"),d=document.getElementById("custom-ca-config");o.style.display="none",d.style.display="none",e.target.value==="existing-ca"?o.style.display="block":e.target.value==="custom-ca"&&(d.style.display="block"),g()}),document.getElementById("refresh-cas")?.addEventListener("click",async()=>{const e=document.getElementById("refresh-cas"),o=e.textContent;e.textContent="\u231B Loading...",e.disabled=!0;try{const d=document.getElementById("caddyfile-path-input").value||DC.DEFAULTS.CADDYFILE;await window.loadExistingCAs(d),e.textContent="\u2705 Refreshed"}catch(d){e.textContent="\u274C Failed",console.error("Failed to refresh CAs:",d)}setTimeout(()=>{e.textContent=o,e.disabled=!1},2e3)}),document.getElementById("create-dns-record")?.addEventListener("change",e=>{const o=document.getElementById("dns-config");o.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 o=document.getElementById(e);o&&(o.addEventListener("input",g),o.addEventListener("change",g))});function i(){const e=safeGet("custom-services");if(e)try{JSON.parse(e).forEach(d=>{window.APPS.find(t=>t.id===d.id)||window.APPS.push(d)})}catch(o){console.warn("Failed to load custom services:",o)}}i(),window.openAddServiceModal=v,window.closeAddServiceModal=a})(),(function(){let l=null,n=1e3;const g=3e4;function b(){if(l)try{l.close()}catch{}l=new EventSource("/api/v1/events/stream"),l.addEventListener("connected",()=>{n=1e3,debug("[SSE] Connected to event stream")}),l.addEventListener("status-change",f=>{try{const u=JSON.parse(f.data);if(u.serviceId&&typeof window.setBadge=="function"){const v=u.status==="up"||u.status==="healthy";window.setBadge(u.serviceId,v,u.responseTime||null)}}catch{}}),l.addEventListener("resource-alert",f=>{try{const u=JSON.parse(f.data),v=`${u.containerName||u.containerId}: ${u.metric} at ${u.value}% (threshold: ${u.threshold}%)`;typeof showNotification=="function"&&showNotification(v,"warning")}catch{}}),l.addEventListener("auto-restart",f=>{try{const u=JSON.parse(f.data);typeof showNotification=="function"&&showNotification(`Container "${u.containerName}" was auto-restarted`,"info")}catch{}}),l.addEventListener("update-available",f=>{try{const u=JSON.parse(f.data),v=document.getElementById("updates-btn");if(v&&!v.querySelector(".sse-dot")){const s=document.createElement("span");s.className="sse-dot",s.style.cssText="display:inline-block;width:8px;height:8px;border-radius:50%;background:var(--accent);margin-left:6px;vertical-align:middle;",v.appendChild(s)}typeof showNotification=="function"&&showNotification(`Update available for ${u.containerName||u.containerId}`,"info")}catch{}}),l.addEventListener("update-complete",f=>{try{const u=JSON.parse(f.data);typeof showNotification=="function"&&showNotification(`Update completed: ${u.containerName||u.containerId}`,"success"),typeof window.refreshAll=="function"&&window.refreshAll()}catch{}}),l.addEventListener("update-failed",f=>{try{const u=JSON.parse(f.data);typeof showNotification=="function"&&showNotification(`Update failed: ${u.containerName||u.containerId} \u2014 ${u.error||"unknown error"}`,"error")}catch{}}),l.addEventListener("incident",f=>{try{const u=JSON.parse(f.data);typeof showNotification=="function"&&(u.type==="created"?showNotification(`Incident: ${u.message||u.serviceId}`,"error"):u.type==="resolved"&&showNotification(`Resolved: ${u.serviceId||"incident"}`,"success"))}catch{}}),l.onerror=()=>{l.close(),console.warn(`[SSE] Disconnected, reconnecting in ${n/1e3}s...`),setTimeout(b,n),n=Math.min(n*2,g)}}b(),window._sseReconnect=b})(),(function(){const l=document.getElementById("service-filter-search"),n=document.getElementById("service-filter-status"),g=document.getElementById("service-filter-category"),b=document.getElementById("service-filter-count");function f(){const y=new Set,c=new Set;document.querySelectorAll("#cards .card[data-category]").forEach(i=>{const e=i.dataset.category.trim();e&&c.add(e)});const a=window.DC_CATEGORIES||typeof DC<"u"&&DC.CATEGORIES||{};return Object.keys(a).concat([...c].filter(i=>!a[i])).forEach(i=>y.add(i)),{list:[...y],apiCats:a}}function u(){if(!g)return;const{list:y,apiCats:c}=f(),a=g.value;g.innerHTML='<option value="all">All Categories</option>',y.sort().forEach(m=>{const i=c[m],e=document.createElement("option");e.value=m,e.textContent=i?`${i.icon||""} ${m}`.trim():m,g.appendChild(e)}),a&&[...g.options].some(m=>m.value===a)?g.value=a:g.value="all"}function v(){u();const y=l.value.toLowerCase().trim(),c=n.value,a=g?g.value:"all",m=document.querySelectorAll("#cards .card");let i=0;if(m.forEach(e=>{const o=e.querySelector(".name")?.textContent?.toLowerCase()||"",d=e.dataset.app?.toLowerCase()||"",t=e.dataset.status||"off",r=e.dataset.category||"";(!y||o.includes(y)||d.includes(y))&&(c==="all"||t===c)&&(a==="all"||r===a)?(e.style.display="",i++):e.style.display="none"}),b){const e=m.length;b.textContent=`${i} of ${e} services`}}function s(y,c){let a;return function(...m){clearTimeout(a),a=setTimeout(()=>y.apply(this,m),c)}}l?.addEventListener("input",s(v,200)),n?.addEventListener("change",v),g?.addEventListener("change",v),document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>setTimeout(v,500)):setTimeout(v,500),window.refreshServiceFilter=v,window.refreshCategoryDropdown=u})(),(function(){const l=document.getElementById("batch-operations-btn"),n=document.getElementById("batch-action-bar"),g=document.getElementById("batch-selected-count"),b=document.getElementById("batch-start-btn"),f=document.getElementById("batch-stop-btn"),u=document.getElementById("batch-restart-btn"),v=document.getElementById("batch-cancel-btn");let s=!1,y=new Set;function c(){s=!0,y.clear(),n.style.display="",l.textContent="\u2713 Exit Batch Mode",m(),document.querySelectorAll("#cards .card[data-app]").forEach(o=>{const d=o.dataset.containerId;if(!d)return;const t=o.querySelector(".batch-checkbox");t&&t.remove();const r=document.createElement("input");r.type="checkbox",r.className="batch-checkbox",r.dataset.containerId=d,r.dataset.serviceName=o.querySelector(".name")?.textContent||d,r.style.cssText="position: absolute; top: 8px; left: 8px; z-index: 10; width: 18px; height: 18px; cursor: pointer;",r.addEventListener("change",h=>{h.stopPropagation(),r.checked?y.add(d):y.delete(d),m()}),o.style.position="relative",o.insertBefore(r,o.firstChild)})}function a(){s=!1,y.clear(),n.style.display="none",l.textContent="\u2630 Batch Operations",document.querySelectorAll(".batch-checkbox").forEach(e=>e.remove())}function m(){const e=y.size;g.textContent=`${e} selected`,b.disabled=e===0,f.disabled=e===0,u.disabled=e===0}async function i(e){if(y.size===0)return;const o=Array.from(y),d={start:"Starting",stop:"Stopping",restart:"Restarting"}[e];if(!confirm(`${d} ${o.length} container(s)? This cannot be undone.`))return;const t=[b,f,u];t.forEach(w=>{w.disabled=!0,w.textContent="..."});let r=0,h=0;const p=[];for(const w of o)try{const T=await fetch(`/api/v1/containers/${encodeURIComponent(w)}/${e}`,{method:"POST"});if(T.ok)r++;else{h++;const L=await T.json().catch(()=>({}));p.push(`${w}: ${L.error||T.statusText}`)}}catch(T){h++,p.push(`${w}: ${T.message}`)}t[0].textContent="\u25B6 Start All",t[1].textContent="\u2B1B Stop All",t[2].textContent="\u{1F504} Restart All",m(),h===0?typeof showNotification=="function"&&showNotification(`${d} completed: ${r} container(s)`,"success"):(typeof showNotification=="function"&&showNotification(`${d}: ${r} succeeded, ${h} failed`,"warning"),console.error("Batch operation errors:",p)),setTimeout(()=>{typeof refreshAll=="function"&&refreshAll()},1500)}l?.addEventListener("click",()=>{s?a():c()}),b?.addEventListener("click",()=>i("start")),f?.addEventListener("click",()=>i("stop")),u?.addEventListener("click",()=>i("restart")),v?.addEventListener("click",a)})();
|