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