(() => { const basePath = String(document.body.dataset.basePath || '').replace(/\/$/, ''); const appUrl = path => { const value = String(path || '/'); if (!value.startsWith('/') || value.startsWith('//')) return value; return `${basePath}${value}` || '/'; }; const nativeFetch = window.fetch.bind(window); window.fetch = (input, init) => { if (typeof input === 'string' && input.startsWith('/') && !input.startsWith('//')) input = appUrl(input); return nativeFetch(input, init); }; const page = document.body.dataset.page; const refreshSeconds = Number(document.body.dataset.refresh || '10'); const threshold = Number(document.body.dataset.onlineThreshold || '180'); let snapshot = null; let interfacesData = {interfaces:[], suggested:null}; let timer = null; let historyTimer = null; let dashboardDiagnosticsTimer = null; let serverDiagnosticsTimer = null; let tooltipTimer = null; let tooltipOwner = null; const $ = id => document.getElementById(id); const t = (key, fallback) => window.WGToolsI18n?.t(key, fallback) || fallback || key; const esc = value => String(value ?? '').replace(/[&<>'"]/g, c => ({'&':'&','<':'<','>':'>',"'":''','"':'"'}[c])); function fmtBytes(bytes) { const n = Number(bytes || 0); if (!n) return '0 B'; const u = ['B','KB','MB','GB','TB']; let i = Math.floor(Math.log(n)/Math.log(1024)); i=Math.min(i,u.length-1); return `${(n/Math.pow(1024,i)).toFixed(i ? 1 : 0)} ${u[i]}`; } function fmtRate(bytes){ return `${fmtBytes(bytes)}/s`; } function fmtUptime(seconds){ let s=Math.max(0,Number(seconds||0)); const d=Math.floor(s/86400); s%=86400; const h=Math.floor(s/3600); s%=3600; const m=Math.floor(s/60); if(d)return `${d}d ${h}h`; if(h)return `${h}h ${m}m`; return `${m}m`; } function ago(ts) { const n = Number(ts || 0); if (!n) return t('common.never','Never'); const s = Math.max(0, Math.floor(Date.now()/1000 - n)); if (s < 60) return `${s}s ${t('common.ago','ago')}`; if (s < 3600) return `${Math.floor(s/60)}m ${t('common.ago','ago')}`; if (s < 86400) return `${Math.floor(s/3600)}h ${t('common.ago','ago')}`; return `${Math.floor(s/86400)}d ${t('common.ago','ago')}`; } function online(peer){ if(peer?.expired_disabled||peer?.schedule_disabled)return false; const ts=Number(peer.latest_handshake||0); return ts>0 && Date.now()/1000-ts <= threshold; } function statusHtml(peer){ if(peer?.expired_disabled)return `${esc(t('clients.expired_disabled_status','Expired'))}`; if(peer?.schedule_disabled)return `${esc(t('clients.schedule_blocked_status','Blocked by schedule'))}`; const is=online(peer); // Offline status is never animated. The table renderer reuses this DOM node // during normal polling, so the online CSS animation never restarts. return `${esc(is?t('common.online','Online'):t('common.offline','Offline'))}`; } // Update only changed cells. Keeping the existing status cell when its state // is unchanged preserves the CSS animation clock, even at 2-second polling. // Peer keys and row order must match; otherwise safely rebuild the table. function renderPeerTable(body, html, statusColumn){ if(!body)return; const staged=document.createElement('tbody'); staged.innerHTML=html; const incoming=Array.from(staged.rows), current=Array.from(body.rows); const reusable=incoming.length===current.length && incoming.every((row,i)=> Boolean(row.dataset.peerKey) && current[i].dataset.peerKey===row.dataset.peerKey && row.cells.length===current[i].cells.length); if(!reusable){body.replaceChildren(...incoming);return;} for(let i=0;iel.classList.remove('show'),duration); } function healthClass(ok){ return ok ? 'health-ok' : 'health-bad'; } function setHidden(id, hidden){ const el=$(id); if(el) el.hidden=hidden; } function operationStatus(id, text, kind='info'){ const el=$(id); if(!el)return; // Keep structural classes such as vps-operation-status and migration-status. // Replacing className here used to silently remove those classes as soon as // a status message was shown, which also discarded their layout rules. el.classList.remove('working','success','error','info'); if(!text){ el.hidden=true; el.textContent=''; return; } el.hidden=false; el.textContent=text; if(kind) el.classList.add(kind); } function activeInterfaceItem(){ const name=snapshot?.interface||document.body.dataset.interface||''; return (interfacesData.interfaces||[]).find(item=>item.name===name)||null; } function interfaceDisplay(item){ if(!item)return ''; const alias=String(item.display_name||'').trim(); return alias&&alias!==item.name?`${item.name} · ${alias}`:item.name; } function setInterfaceCookie(name){ document.cookie=`wgtools_interface=${encodeURIComponent(name)}; Path=/; Max-Age=31536000; SameSite=Lax`; } function selectInterface(name){ if(!name||name===(snapshot?.interface||document.body.dataset.interface))return; setInterfaceCookie(name); location.reload(); } function renderInterfaceSwitcher(){ const menu=$('interface-switcher-menu'); if(!menu)return; const items=interfacesData.interfaces||[]; if(!items.length){menu.innerHTML=`
${esc(t('interfaces.none','No WireGuard interfaces found'))}
`;return;} menu.innerHTML=`
${esc(t('interfaces.switch_title','WireGuard interfaces'))}
`+items.map(item=>{ const state=item.configured?(item.running?t('common.running','Running'):t('common.stopped','Stopped')):t('common.not_configured','Not configured'); const stateClass=item.configured?(item.running?'online':'offline'):'unknown'; const alias=item.display_name&&item.display_name!==item.name?`${esc(item.display_name)}`:''; const meta=[item.address,item.listen_port?`:${item.listen_port}`:'',`${Number(item.peer_count||0)} ${t('interfaces.peers_short','peers')}`].filter(Boolean).join(' · '); return ``; }).join(''); } function renderInterfaceManager(){ const list=$('interface-manager-list'); if(!list)return; const items=(interfacesData.interfaces||[]).filter(item=>item.configured); if(!items.length){list.innerHTML=`
${esc(t('interfaces.none_configured','No configured WireGuard interfaces yet.'))}
`;return;} list.innerHTML=items.map(item=>{ const state=item.running?t('common.running','Running'):t('common.stopped','Stopped'); const alias=item.display_name&&item.display_name!==item.name?`${esc(item.display_name)}`:''; const canDelete=items.length>1; const deleteButton=``; return `
${esc(item.name)}${alias}
${esc(state)} · ${Number(item.peer_count||0)} ${esc(t('interfaces.peers_short','peers'))}
${esc(t('server.address','Address'))}${esc(item.address||'—')}
${esc(t('server.listen_port','Listen port'))}${item.listen_port?esc(item.listen_port):'—'}
${esc(t('server.policy_table','Policy table'))}${item.policy_table?esc(item.policy_table):'—'}
${deleteButton}
`; }).join(''); } async function fetchInterfaces(render=true){ try{ const r=await fetch('/api/interfaces',{cache:'no-store'}); const d=await r.json(); if(!r.ok)throw new Error(d.error||'Interface list failed'); interfacesData=d||{interfaces:[],suggested:null}; if(render){renderInterfaceSwitcher();renderInterfaceManager();} return d; }catch(e){ if(render){const menu=$('interface-switcher-menu');if(menu)menu.innerHTML=`
${esc(e.message)}
`;} return null; } } async function toggleInterfaceMenu(){ const button=$('interface-switcher-button'), menu=$('interface-switcher-menu');if(!button||!menu)return; const opening=menu.hidden; if(opening)await fetchInterfaces(true); menu.hidden=!opening;button.setAttribute('aria-expanded',opening?'true':'false'); } function closeInterfaceMenu(){const button=$('interface-switcher-button'),menu=$('interface-switcher-menu');if(menu)menu.hidden=true;if(button)button.setAttribute('aria-expanded','false');} function bindInterfaceSwitcher(){ $('interface-switcher-button')?.addEventListener('click',e=>{e.stopPropagation();toggleInterfaceMenu();}); $('interface-switcher-menu')?.addEventListener('click',e=>{const target=e.target.closest('[data-interface-select]');if(!target)return;selectInterface(target.dataset.interfaceSelect);}); document.addEventListener('click',e=>{if(!e.target.closest('.interface-switcher-wrap'))closeInterfaceMenu();}); $('interface-manager-list')?.addEventListener('click',e=>{ const deleteTarget=e.target.closest('[data-interface-delete]'); if(deleteTarget){e.stopPropagation();deleteInterface(deleteTarget.dataset.interfaceDelete);return;} const target=e.target.closest('[data-interface-select]');if(!target)return;selectInterface(target.dataset.interfaceSelect); }); } function tooltipTextFor(el){ if(!el)return ''; const explicit=el.dataset?.tooltip||el.getAttribute('aria-label')||el.getAttribute('title')||''; if(explicit.trim())return explicit.trim(); if(el.matches('button,.btn,.nav-item'))return String(el.textContent||'').replace(/\s+/g,' ').trim(); return ''; } function hideTooltip(){ if(tooltipTimer){clearTimeout(tooltipTimer);tooltipTimer=null;} tooltipOwner=null; const tip=$('wg-delayed-tooltip'); if(tip)tip.classList.remove('show'); } function showTooltipFor(el){ const text=tooltipTextFor(el); if(!text)return; let tip=$('wg-delayed-tooltip'); if(!tip){tip=document.createElement('div');tip.id='wg-delayed-tooltip';tip.className='wg-tooltip';document.body.appendChild(tip);} tip.textContent=text; tip.classList.remove('show'); tip.style.left='0px';tip.style.top='0px'; const rect=el.getBoundingClientRect(); const width=Math.min(280,Math.max(80,tip.offsetWidth||180)); let left=rect.left+(rect.width-width)/2; left=Math.max(8,Math.min(window.innerWidth-width-8,left)); let top=rect.bottom+8; const height=tip.offsetHeight||32; if(top+height>window.innerHeight-8)top=Math.max(8,rect.top-height-8); tip.style.left=`${Math.round(left)}px`;tip.style.top=`${Math.round(top)}px`;requestAnimationFrame(()=>tip.classList.add('show')); } function bindDelayedTooltips(){ document.querySelectorAll('[title]').forEach(el=>{if(!el.dataset.tooltip)el.dataset.tooltip=el.getAttribute('title')||'';el.removeAttribute('title');}); document.addEventListener('mouseover',e=>{ const el=e.target.closest('[data-tooltip],button,.btn,.nav-item'); if(!el||el===tooltipOwner)return; hideTooltip(); const text=tooltipTextFor(el); if(!text)return; tooltipOwner=el; tooltipTimer=setTimeout(()=>{if(tooltipOwner===el)showTooltipFor(el);},700); }); document.addEventListener('mouseout',e=>{const el=e.target.closest('[data-tooltip],button,.btn,.nav-item');if(el&&tooltipOwner===el&&!el.contains(e.relatedTarget))hideTooltip();}); document.addEventListener('mousedown',hideTooltip); document.addEventListener('scroll',hideTooltip,true); window.addEventListener('resize',hideTooltip); } function serverStateText(data){ const state=data?.wireguard?.state; if(state==='not_installed') return t('common.not_installed','Not installed'); if(state==='not_configured') return t('common.not_configured','Not configured'); if(data?.running) return t('common.running','Running'); return t('common.stopped','Stopped'); } function snapshotView(){ return page==='dashboard'?'dashboard':page==='clients'?'clients':page==='server'?'server':'full'; } async function fetchSnapshot(showToast=false){ try{ const r=await fetch(`/api/snapshot?view=${encodeURIComponent(snapshotView())}`,{cache:'no-store'}); const data=await r.json(); if(!r.ok) throw new Error(data.error||'Server error'); snapshot=data; renderHeader(data); renderCurrent(); if(page==='server'&&activeServerTab==='nodes')loadNodes(false); if(showToast) toast(t('common.updated','Updated')); }catch(e){ renderHeader({running:false,error:e.message}); if(showToast) toast(e.message); } } function renderHeader(data){ const dot=$('header-dot'), status=$('header-status'); if(!dot||!status)return; const active=Boolean(data.running); dot.className=`status-dot ${active?'online':'offline'}`; const item=(interfacesData.interfaces||[]).find(x=>x.name===(data.interface||'')); const name=item?interfaceDisplay(item):(data.interface||'wg0'); status.textContent=`${name} · ${serverStateText(data)}`; if(item){item.running=Boolean(data.running);item.configured=Boolean(data.wireguard?.config_exists);renderInterfaceSwitcher();renderInterfaceManager();} } function renderCurrent(){ if(!snapshot)return; if(page==='dashboard') renderDashboard(snapshot); if(page==='server') renderServer(snapshot); if(page==='clients') renderClients(snapshot); if(page==='settings') renderSettings(snapshot); } function renderDashboard(d){ const peers=d.peers||[]; const on=peers.filter(online); const s2s=peers.filter(p=>(p.remote_networks||[]).length); $('wg-state').textContent=serverStateText(d); $('wg-state-dot').className=`status-dot ${d.running?'online':'offline'}`; $('wg-interface').textContent=`${t('server.interface','Interface')}: ${d.interface||'—'}`; $('wg-address').textContent=`${t('server.address','Address')}: ${d.config?.interface?.address||'—'}`; $('wg-port').textContent=`${t('server.listen_port','Listen port')}: ${d.listen_port||d.config?.interface?.listen_port||'—'}`; $('peer-online').textContent=on.length; $('peer-total').textContent=peers.length; $('peer-s2s').textContent=s2s.length; const traffic=d.traffic_totals||{}; $('rx-total').textContent=fmtBytes(traffic.rx_bytes ?? peers.reduce((a,p)=>a+Number(p.rx_bytes||0),0)); $('tx-total').textContent=fmtBytes(traffic.tx_bytes ?? peers.reduce((a,p)=>a+Number(p.tx_bytes||0),0)); $('forwarding-icon').textContent=d.system?.ip_forwarding?'✓':'✕'; $('forwarding-icon').className=healthClass(d.system?.ip_forwarding); $('nat-icon').textContent=d.config?.detected?.nat_enabled?'✓':'✕'; $('nat-icon').className=healthClass(d.config?.detected?.nat_enabled); $('table-icon').textContent=d.config?.detected?.policy_table?'✓':'○'; $('table-icon').className=d.config?.detected?.policy_table?'health-ok':'health-warn'; $('policy-table').textContent=d.config?.detected?.policy_table||'—'; const cpu=d.metrics?.cpu||{}, mem=d.metrics?.memory||{}, net=d.metrics?.network||{}; if($('cpu-percent')) $('cpu-percent').textContent=cpu.percent==null?'—':Number(cpu.percent).toFixed(1); if($('cpu-detail')) $('cpu-detail').textContent=`${cpu.cores||'—'} ${t('dashboard.cores','cores')} · Load ${cpu.load1??'—'}`; if($('cpu-bar')) $('cpu-bar').style.width=`${Math.max(0,Math.min(100,Number(cpu.percent||0)))}%`; if($('memory-percent')) $('memory-percent').textContent=Number(mem.percent||0).toFixed(1); if($('memory-detail')) $('memory-detail').textContent=`${fmtBytes(mem.used_bytes)} / ${fmtBytes(mem.total_bytes)}`; if($('memory-bar')) $('memory-bar').style.width=`${Math.max(0,Math.min(100,Number(mem.percent||0)))}%`; if($('network-rx-rate')) $('network-rx-rate').textContent=fmtRate(net.rx_bytes_per_second); if($('network-tx-rate')) $('network-tx-rate').textContent=fmtRate(net.tx_bytes_per_second); if($('network-interface')) $('network-interface').textContent=net.interface||'—'; if($('server-uptime')) $('server-uptime').textContent=`${t('dashboard.uptime','Uptime')}: ${fmtUptime(d.metrics?.uptime_seconds)}`; updateWireGuardControls(d); const body=$('dashboard-peer-body'); const search=String($('dashboard-peer-search')?.value||'').trim().toLocaleLowerCase(); const visiblePeers=search?peers.filter(p=>{ const status=p?.expired_disabled?t('clients.expired_disabled_status','Expired'):p?.schedule_disabled?t('clients.schedule_blocked_status','Blocked by schedule'):online(p)?t('common.online','Online'):t('common.offline','Offline'); const haystack=[p?.name,p?.vpn_address,typeOf(p),p?.endpoint,status].map(v=>String(v||'').toLocaleLowerCase()).join(' '); return haystack.includes(search); }):peers; if(!peers.length){body.innerHTML=`${esc(t('clients.no_peers','No peers found'))}`;} else if(!visiblePeers.length){body.innerHTML=`${esc(t('dashboard.quick_search_empty','No peers match the search'))}`;} else renderPeerTable(body,visiblePeers.map(p=>`
${esc(p.name||'Unnamed')}
${online(p)&&p.endpoint?`
Endpoint: ${esc(p.endpoint)}
`:''}${esc(p.vpn_address||'—')}${esc(typeOf(p))}${statusHtml(p)}${esc(ago(p.latest_handshake))}${fmtBytes(p.rx_bytes)}${fmtBytes(p.tx_bytes)}`).join(''),3); $('last-update').textContent=new Date().toLocaleTimeString(); if(Array.isArray(d.diagnostics)) renderDashboardDiagnostics(d.diagnostics); } function renderDashboardDiagnostics(checks){ const strip=$('diagnostic-strip');if(!strip)return; strip.innerHTML=(checks||[]).slice(0,6).map(c=>`
${c.ok?'✓':'✕'}${esc(c.label)}
`).join(''); } async function loadDashboardDiagnostics(){ if(page!=='dashboard')return; try{const r=await fetch('/api/diagnostics',{cache:'no-store'});const d=await r.json();if(r.ok)renderDashboardDiagnostics(d.diagnostics||[]);}catch(_){} } async function loadServerDiagnostics(){ if(page!=='server'||!$('diagnostics-list'))return; try{const r=await fetch('/api/diagnostics',{cache:'no-store'});const d=await r.json();if(r.ok)renderDiagnostics(d.diagnostics||[]);}catch(_){} } async function resetTraffic(){ const button=$('traffic-reset-button'); if(!confirm(t('dashboard.traffic_reset_confirm','Reset accumulated WireGuard traffic counters for this interface? Client counters will also restart from zero.')))return; if(button)button.disabled=true; try{ const r=await fetch('/api/traffic/reset',{method:'POST',headers:{'Content-Type':'application/json'}}); const d=await r.json(); if(!r.ok)throw new Error(d.error||t('dashboard.traffic_reset_failed','Could not reset traffic counters')); await fetchSnapshot(false); toast(t('dashboard.traffic_reset_done','Traffic counters reset')); }catch(e){toast(e.message,5000);} finally{if(button)button.disabled=false;} } function metricHistoryPath(history,key,{min=0,max=null}={}){ const points=(history||[]).filter(p=>Number.isFinite(Number(p?.timestamp))&&Number.isFinite(Number(p?.[key]))); if(!points.length)return ''; const now=Date.now()/1000, start=now-24*60*60, width=320, height=64; const values=points.map(p=>Number(p[key])); const top=max==null?Math.max(1,...values):max; const bottom=min; const span=Math.max(.0001,top-bottom); const coords=points.map(p=>{const x=Math.max(0,Math.min(width,(Number(p.timestamp)-start)/(24*60*60)*width));const v=Math.max(bottom,Math.min(top,Number(p[key])));const y=height-(v-bottom)/span*height;return [x,y];}); if(coords.length===1){const [x,y]=coords[0];return `M${x.toFixed(2)} ${y.toFixed(2)}L${Math.min(width,x+.2).toFixed(2)} ${y.toFixed(2)}`;} return coords.map(([x,y],i)=>`${i?'L':'M'}${x.toFixed(2)} ${y.toFixed(2)}`).join(''); } function metricHistoryStats(history,key){ const values=(history||[]).map(p=>Number(p?.[key])).filter(Number.isFinite); if(!values.length)return null; const sum=values.reduce((acc,value)=>acc+value,0); return {min:Math.min(...values),avg:sum/values.length,max:Math.max(...values)}; } function renderHistoryStats(prefix,stats,formatter){ for(const name of ['min','avg','max']){ const el=$(`${prefix}-${name}`); if(el)el.textContent=stats?formatter(stats[name]):'—'; } } function renderMetricsHistory(data){ const history=(data?.history||[]).filter(p=>Number(p.timestamp)>=Date.now()/1000-24*60*60); const cpu=$('cpu-history-line'), mem=$('memory-history-line'), rx=$('network-rx-history-line'), tx=$('network-tx-history-line'); if(cpu)cpu.setAttribute('d',metricHistoryPath(history,'cpu',{min:0,max:100})); if(mem)mem.setAttribute('d',metricHistoryPath(history,'memory',{min:0,max:100})); const networkMax=Math.max(1,...history.flatMap(p=>[Number(p.rx||0),Number(p.tx||0)])); if(rx)rx.setAttribute('d',metricHistoryPath(history,'rx',{min:0,max:networkMax})); if(tx)tx.setAttribute('d',metricHistoryPath(history,'tx',{min:0,max:networkMax})); renderHistoryStats('cpu-history',metricHistoryStats(history,'cpu'),value=>`${value.toFixed(1)}%`); renderHistoryStats('memory-history',metricHistoryStats(history,'memory'),value=>`${value.toFixed(1)}%`); renderHistoryStats('network-rx-history',metricHistoryStats(history,'rx'),fmtRate); renderHistoryStats('network-tx-history',metricHistoryStats(history,'tx'),fmtRate); document.querySelectorAll('.history-chart').forEach(svg=>svg.classList.toggle('is-empty',history.length<2)); } async function loadMetricsHistory(){ if(page!=='dashboard')return; try{const r=await fetch('/api/metrics/history',{cache:'no-store'});const d=await r.json();if(r.ok)renderMetricsHistory(d);}catch(_){} } function updateWireGuardControls(d){ const configured=Boolean(d?.wireguard?.config_exists), running=Boolean(d?.running); const start=$('wg-start-button'), restart=$('wg-restart-button'), stop=$('wg-stop-button'); if(start) start.disabled=!configured||running; if(restart) restart.disabled=!configured||!running; if(stop) stop.disabled=!configured||!running; } async function wireGuardControl(action){ const labels={start:t('dashboard.start','Start'),stop:t('dashboard.stop','Stop'),restart:t('dashboard.restart','Restart')}; if(action==='stop'&&!confirm(t('dashboard.stop_confirm','Stop WireGuard? Active VPN clients will be disconnected.')))return; if(action==='restart'&&!confirm(t('dashboard.restart_confirm','Restart WireGuard? Active VPN clients will reconnect automatically.')))return; const buttons=['wg-start-button','wg-restart-button','wg-stop-button'].map($).filter(Boolean); buttons.forEach(b=>b.disabled=true); try{ const r=await fetch(`/api/server/${action}`,{method:'POST'}); const d=await r.json(); if(!r.ok)throw new Error(d.error||`${labels[action]} failed`); toast(t(`dashboard.${action}_ok`,`${labels[action]} completed`)); await fetchSnapshot(); }catch(e){toast(e.message); await fetchSnapshot();} } function bindWireGuardControls(){ $('wg-start-button')?.addEventListener('click',()=>wireGuardControl('start')); $('wg-restart-button')?.addEventListener('click',()=>wireGuardControl('restart')); $('wg-stop-button')?.addEventListener('click',()=>wireGuardControl('stop')); } let activeServerTab = 'interface'; let vpsPreflight = null; function updateServerTabActions(){ if(page!=='server')return; const configured=Boolean(snapshot?.wireguard?.config_exists); const installed=Boolean(snapshot?.wireguard?.installed); const configuredInterfaces=(interfacesData.interfaces||[]).filter(item=>item.configured); const interfaceTab=activeServerTab==='interface'; setHidden('edit-server-button', !interfaceTab || !configured); setHidden('add-interface-button', !interfaceTab || !installed || configuredInterfaces.length===0); } function activateServerTab(name){ if(page!=='server')return; const allowed=['interface','routing','nodes','vps','trace','config']; activeServerTab=allowed.includes(name)?name:'interface'; document.querySelectorAll('[data-server-tab]').forEach(button=>{ const active=button.dataset.serverTab===activeServerTab; button.classList.toggle('active',active); button.setAttribute('aria-selected',active?'true':'false'); button.tabIndex=active?0:-1; }); document.querySelectorAll('[data-server-tab-panel]').forEach(panel=>{panel.hidden=panel.dataset.serverTabPanel!==activeServerTab;}); try{sessionStorage.setItem('wgtools.server.tab',activeServerTab);}catch(_){} updateServerTabActions(); if(activeServerTab==='vps')loadVpsList(); if(activeServerTab==='nodes')loadNodes(); if(activeServerTab==='trace')window.requestAnimationFrame(()=>renderTraceSlippyMap()); } function bindServerTabs(){ if(page!=='server')return; document.querySelectorAll('[data-server-tab]').forEach(button=>{ button.addEventListener('click',()=>activateServerTab(button.dataset.serverTab)); button.addEventListener('keydown',event=>{ if(!['ArrowLeft','ArrowRight'].includes(event.key))return; const buttons=[...document.querySelectorAll('[data-server-tab]')].filter(x=>!x.hidden&&!x.disabled); const index=buttons.indexOf(button);if(index<0||!buttons.length)return; event.preventDefault();const next=buttons[(index+(event.key==='ArrowRight'?1:-1)+buttons.length)%buttons.length]; activateServerTab(next.dataset.serverTab);next.focus(); }); }); let remembered='interface';try{remembered=sessionStorage.getItem('wgtools.server.tab')||'interface';}catch(_){} activateServerTab(remembered); } let nodesData = null; function currentPanelUrl(){ const path=basePath?`${basePath}/`:'/'; return `${location.origin}${path}`; } function nodeNetworks(node){ return (node?.exports||[]).map(x=>typeof x==='string'?x:x?.network).filter(Boolean); } function availableNodeNetworks(){ return (nodesData?.available_networks||[]).map(x=>typeof x==='string'?x:x?.network).filter(Boolean); } function detectedNodeNetworks(){ return (nodesData?.detected_networks||[]).map(x=>typeof x==='string'?x:x?.network).filter(Boolean); } function nodeNetworkChangeMessage(changes){ if(!changes?.changed)return ''; const added=(changes.added||[]).join(', ')||'—'; const removed=(changes.removed||[]).join(', ')||'—'; return t('nodes.networks_changed','Detected local networks changed after the published list was last saved. New: {added}. No longer detected: {removed}. Review the published networks.') .replace('{added}',added).replace('{removed}',removed); } function nodeVpnPoolMismatchMessage(mismatch){ if(!mismatch?.changed)return ''; const oldPools=(mismatch.published_old||[]).join(', ')||'—'; const currentPools=(mismatch.current_vpn||[]).join(', ')||'—'; return t('nodes.vpn_pool_mismatch','VPN pool changed: Nodes still publishes {old}, while the current WireGuard VPN pool is {current}. Open Node settings and update the published networks.') .replace('{old}',oldPools).replace('{current}',currentPools); } function nodeReviewMessage(data){ const vpn=nodeVpnPoolMismatchMessage(data?.vpn_pool_mismatch); if(vpn)return vpn; return nodeNetworkChangeMessage(data?.network_changes); } function nodeApiErrorMessage(data,fallback){ if(data?.error_code==='network_conflict'){ const conflicts=(data.conflicts||[]).map(item=>{ const left=item?.network||'—', right=item?.owner_network||'—'; const owner=item?.owner_type==='transport'?t('nodes.transport_network','Node transport network'):(item?.owner_name||'WGTools'); return `${left} ↔ ${right} (${owner})`; }).filter(Boolean).join('; '); return t('nodes.network_conflict_error','Published networks conflict with another Node or the Nodes transport network: {conflicts}. Remove or change the conflicting network.') .replace('{conflicts}',conflicts||data.error||'—'); } return data?.error||fallback; } function nodeModeText(mode){ if(mode==='hub')return t('nodes.mode_hub','HUB'); if(mode==='spoke')return t('nodes.mode_spoke','Connected to HUB'); return t('nodes.mode_none','Not configured'); } function renderNodes(data){ nodesData=data||{mode:'none',nodes:[]}; const mode=nodesData.mode||'none'; const configured=mode==='hub'||mode==='spoke'; setHidden('nodes-enable-hub-button',configured); setHidden('nodes-connect-button',configured); setHidden('nodes-settings-button',!configured); setHidden('nodes-disable-button',!configured); setHidden('nodes-sync-button',mode!=='spoke'); setHidden('nodes-join-card',mode!=='hub'); setHidden('nodes-list-card',!configured); const status=$('nodes-status'); if(status){ if(!configured){ status.innerHTML=`
${esc(t('nodes.not_configured','WGTools Nodes is not configured'))}

${esc(t('nodes.not_configured_help','Enable HUB on this panel or connect it to an existing WGTools HUB.'))}

`; }else{ const local=nodesData.local||{}, hub=nodesData.hub||{}; const exports=nodeNetworks(local); const service=nodesData.service_active; const role=mode==='hub'?t('nodes.mode_hub','HUB'):t('nodes.mode_spoke','Spoke'); const endpoint=mode==='hub'?`TCP/UDP :${hub.endpoint_port||'—'}`:(hub.endpoint_host?`${hub.endpoint_host}:${hub.endpoint_port||'—'}`:'—'); const sync=mode==='spoke'?(nodesData.last_sync?ago(nodesData.last_sync):t('common.never','Never')):'—'; const nodeError=nodesData.last_error||nodesData.control_error||''; const error=nodeError?`
${esc(nodeError)}
`:''; const networkChange=nodeReviewMessage(nodesData); const networkReview=networkChange?` ${esc(t('nodes.review_networks','Review networks'))}`:''; const networkWarning=networkChange?`
${esc(networkChange)}
`:''; status.classList.toggle('nodes-network-drift',Boolean(networkChange)); status.innerHTML=`
${esc(t('nodes.role','Role'))}
${esc(role)}
${esc(t('nodes.tunnel','Node tunnel'))}
${service?esc(t('common.running','Running')):esc(t('common.stopped','Stopped'))} · ${esc(nodesData.interface||'wgnode0')}
${esc(t('nodes.node_name','Node name'))}
${esc(local.name||'—')}
${esc(t('nodes.node_ip','Node IP'))}
${esc(local.transport_ip||nodesData.hub?.transport_ip||'—')}
${esc(t('nodes.endpoint','HUB endpoint'))}
${esc(endpoint)}
${esc(t('nodes.published_networks','Published networks'))}${networkReview}
${esc(exports.join(', ')||'—')}
${mode==='spoke'?`
${esc(t('nodes.last_sync','Last sync'))}
${esc(sync)}
`:''}
${networkWarning}${error}`; } } const list=$('nodes-list'); if(list&&configured){ const nodes=nodesData.nodes||[]; if(!nodes.length){list.innerHTML=`
${esc(mode==='hub'?t('nodes.no_nodes_hub','No nodes are connected yet. Create a connection code and use it on another WGTools panel.'):t('nodes.no_nodes_spoke','No remote node information has been received yet.'))}
`;return;} list.innerHTML=nodes.map(node=>{ const networks=nodeNetworks(node); const conflicts=node.conflicts||[]; const status=node.online?t('common.online','Online'):t('common.offline','Offline'); const panel=node.panel_url?``:''; const remove=mode==='hub'?``:''; const conflictBadge=conflicts.length?`${esc(t('nodes.route_conflict','Route conflict'))}`:''; return `
${esc(node.name||'WGTools')}${esc(status)}${conflictBadge}
${esc(node.transport_ip||'—')}WGTools v${esc(node.version||'—')}${esc(t('nodes.clients_short','Clients'))}: ${esc(node.online_clients||0)}/${esc(node.client_count||0)}${esc(networks.join(', ')||t('nodes.no_published_networks','No published networks'))}
${panel}${remove}
`; }).join(''); } } async function loadNodes(showToast=false){ if(page!=='server'||!$('nodes-status'))return; try{ const r=await fetch('/api/nodes',{cache:'no-store'});const d=await r.json();if(!r.ok)throw new Error(d.error||t('nodes.load_failed','Could not load WGTools Nodes')); renderNodes(d);if(showToast)toast(t('common.updated','Updated')); }catch(e){operationStatus('nodes-operation-status',e.message,'error');} } function openNodeHubModal(){ $('node-hub-name').value=nodesData?.local?.name||location.hostname||'WGTools HUB'; $('node-hub-port').value='51950';$('node-hub-network').value='10.254.240.0/24'; $('node-hub-extra').value=availableNodeNetworks().join('\n');operationStatus('node-hub-status','');modalShow('node-hub-modal',true); } async function enableNodeHub(event){ event.preventDefault();const button=$('node-hub-save');if(!button)return; const payload={node_name:$('node-hub-name').value.trim(),listen_port:Number($('node-hub-port').value||51950),transport_network:$('node-hub-network').value.trim(),published_networks:splitList($('node-hub-extra').value)}; if(!confirm(t('nodes.enable_hub_confirm','Enable WGTools HUB and create the internal Node WireGuard tunnel?')))return; button.disabled=true;operationStatus('node-hub-status',t('nodes.applying','Configuring the WGTools Node tunnel…'),'working'); try{const r=await fetch('/api/nodes/hub/enable',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(payload)});const d=await r.json();if(!r.ok)throw new Error(nodeApiErrorMessage(d,t('nodes.enable_failed','Could not enable HUB')));renderNodes(d);modalShow('node-hub-modal',false);toast(t('nodes.hub_enabled','WGTools HUB enabled'));}catch(e){operationStatus('node-hub-status',e.message,'error');}finally{button.disabled=false;} } function openNodeConnectModal(){ $('node-connect-name').value=location.hostname||'WGTools Node';$('node-connect-hub-endpoint').value='';$('node-connect-code').value='';$('node-connect-extra').value=availableNodeNetworks().join('\n');operationStatus('node-connect-status','');modalShow('node-connect-modal',true); } async function connectNode(event){ event.preventDefault();const button=$('node-connect-save');if(!button)return; const payload={node_name:$('node-connect-name').value.trim(),hub_endpoint:$('node-connect-hub-endpoint').value.trim(),join_code:$('node-connect-code').value.trim(),published_networks:splitList($('node-connect-extra').value)}; button.disabled=true;operationStatus('node-connect-status',t('nodes.connecting','Pairing panels and creating the protected Node tunnel…'),'working'); try{const r=await fetch('/api/nodes/connect',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(payload)});const d=await r.json();if(!r.ok)throw new Error(nodeApiErrorMessage(d,t('nodes.connect_failed','Could not connect to HUB')));renderNodes(d);modalShow('node-connect-modal',false);toast(t('nodes.connected','Connected to WGTools HUB'));}catch(e){operationStatus('node-connect-status',e.message,'error');}finally{button.disabled=false;} } function openNodeSettings(){ const local=nodesData?.local||{}; const selected=(nodesData?.published_networks||nodeNetworks(local)); $('node-settings-name').value=local.name||'';$('node-settings-panel-url').value=local.panel_url||currentPanelUrl();$('node-settings-extra').value=selected.join('\n'); const detected=$('node-settings-available');if(detected){const available=detectedNodeNetworks();detected.textContent=available.length?t('nodes.available_networks_help','Currently detected: {networks}').replace('{networks}',available.join(', ')):t('nodes.available_networks_none','No additional local networks detected.');} const changed=$('node-settings-network-change'),changeText=nodeReviewMessage(nodesData);if(changed){changed.textContent=changeText;setHidden('node-settings-network-change',!changeText);} $('node-settings-extra')?.classList.toggle('network-drift-field',Boolean(changeText)); operationStatus('node-settings-status','');modalShow('node-settings-modal',true); } async function saveNodeSettings(event){ event.preventDefault();const button=$('node-settings-save');if(!button)return; const payload={node_name:$('node-settings-name').value.trim(),panel_url:$('node-settings-panel-url').value.trim(),published_networks:splitList($('node-settings-extra').value)}; button.disabled=true;operationStatus('node-settings-status',t('nodes.applying','Applying Node settings…'),'working'); try{const r=await fetch('/api/nodes/settings',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(payload)});const d=await r.json();if(!r.ok)throw new Error(nodeApiErrorMessage(d,t('nodes.settings_failed','Could not save Node settings')));renderNodes(d);modalShow('node-settings-modal',false);toast(t('nodes.settings_saved','Node settings saved'));}catch(e){operationStatus('node-settings-status',e.message,'error');}finally{button.disabled=false;} } async function createNodeCode(){ const button=$('nodes-create-code-button');if(button)button.disabled=true; try{const r=await fetch('/api/nodes/hub/code',{method:'POST'});const d=await r.json();if(!r.ok)throw new Error(d.error||t('nodes.code_failed','Could not create connection code'));$('nodes-join-code').value=d.code||'';setHidden('nodes-code-row',false);$('nodes-code-expiry').textContent=d.expires_at?t('nodes.code_expires','One-time code. Valid until {time}.').replace('{time}',new Date(Number(d.expires_at)*1000).toLocaleTimeString()):'';}catch(e){toast(e.message,5000);}finally{if(button)button.disabled=false;} } async function copyNodeCode(){ const field=$('nodes-join-code'),value=field?.value||'';if(!value)return; try{ if(navigator.clipboard?.writeText&&window.isSecureContext){await navigator.clipboard.writeText(value);} else{ field.focus();field.select();field.setSelectionRange(0,value.length); if(!document.execCommand('copy'))throw new Error('copy failed'); window.getSelection()?.removeAllRanges(); } toast(t('nodes.code_copied','Connection code copied')); }catch{ try{ field.focus();field.select();field.setSelectionRange(0,value.length); if(!document.execCommand('copy'))throw new Error('copy failed'); window.getSelection()?.removeAllRanges();toast(t('nodes.code_copied','Connection code copied')); }catch{toast(t('common.copy_failed','Could not copy'));} } } function renderNodeDetails(node){ const title=$('node-details-title'),sub=$('node-details-subtitle'),body=$('node-details-body');if(!body)return; if(title)title.textContent=node.name||t('nodes.details','Node details');if(sub)sub.textContent=`${node.online?t('common.online','Online'):t('common.offline','Offline')} · ${node.transport_ip||'—'} · WGTools v${node.version||'—'}`; const exports=node.exports||[], clients=node.clients||[], conflicts=new Set(node.conflicts||[]); const networkRows=exports.length?exports.map(item=>{const net=typeof item==='string'?item:item.network;const kind=typeof item==='string'?'':item.kind;return `${esc(net||'—')}${esc(kind==='vpn'?t('nodes.network_vpn','VPN clients'):kind==='site_to_site'?t('nodes.network_site_to_site','Site-to-site network'):kind==='custom'?t('nodes.network_custom','Additional network'):kind||'—')}${conflicts.has(net)?`${esc(t('nodes.conflict','Conflict'))}`:`${esc(t('common.enabled','Enabled'))}`}`;}).join(''):`${esc(t('nodes.no_published_networks','No published networks'))}`; const clientRows=clients.length?clients.map(c=>` ${esc(c.name||'—')}${esc(c.interface||'—')}${esc(c.vpn_address||'—')}${esc(c.type==='site_to_site'?t('clients.site_to_site','Site-to-site'):t('clients.client','Client'))}${esc(c.last_seen?ago(c.last_seen):t('common.never','Never'))}`).join(''):`${esc(t('nodes.no_clients','No clients reported'))}`; const searchEmpty=clients.length?`${esc(t('clients.quick_search_empty','No clients match the search'))}`:''; const error=node.last_error?`
${esc(node.last_error)}
`:''; body.innerHTML=`${error}
${esc(t('nodes.published_networks','Published networks'))}
${networkRows}
${esc(t('server.network','Network'))}${esc(t('common.type','Type'))}${esc(t('common.status','Status'))}
${esc(t('nodes.remote_clients','Clients (read-only)'))}
${clientRows}${searchEmpty}
${esc(t('clients.name','Name'))}${esc(t('server.interface','Interface'))}${esc(t('clients.vpn_address','VPN address'))}${esc(t('common.type','Type'))}${esc(t('clients.handshake','Handshake'))}
`; const search=$('node-details-client-search'),clear=$('node-details-client-search-clear'),empty=$('node-details-client-search-empty'); const applySearch=()=>{const query=String(search?.value||'').trim().toLocaleLowerCase();let visible=0;body.querySelectorAll('[data-node-client-row]').forEach(row=>{const show=!query||String(row.textContent||'').toLocaleLowerCase().includes(query);row.hidden=!show;if(show)visible+=1;});if(clear)clear.hidden=!query;if(empty)empty.hidden=!(query&&clients.length&&visible===0);}; search?.addEventListener('input',applySearch);search?.addEventListener('search',applySearch);clear?.addEventListener('click',()=>{if(!search)return;search.value='';applySearch();search.focus();}); modalShow('node-details-modal',true); } async function openNodeDetails(id){ try{const r=await fetch(`/api/nodes/${encodeURIComponent(id)}/details`,{cache:'no-store'});const d=await r.json();if(!r.ok)throw new Error(d.error||t('nodes.details_failed','Could not load Node details'));renderNodeDetails(d.node||{});}catch(e){toast(e.message,5000);} } function openRemoteNodePanel(id){const node=(nodesData?.nodes||[]).find(x=>String(x.node_id)===String(id));if(node?.panel_url)window.open(node.panel_url,'_blank','noopener');} async function removeNode(id){ const node=(nodesData?.nodes||[]).find(x=>String(x.node_id)===String(id));if(!confirm(t('nodes.remove_confirm','Remove node “{name}” from this HUB? Its Node tunnel access will be revoked.').replace('{name}',node?.name||id)))return; try{const r=await fetch(`/api/nodes/${encodeURIComponent(id)}`,{method:'DELETE'});const d=await r.json();if(!r.ok)throw new Error(d.error||t('nodes.remove_failed','Could not remove Node'));renderNodes(d);toast(t('nodes.removed','Node removed'));}catch(e){toast(e.message,5000);} } async function disableNodes(){ const message=nodesData?.mode==='hub'?t('nodes.disable_hub_confirm','Disable HUB and disconnect all WGTools Nodes? The internal Node tunnel will be removed.'):t('nodes.disconnect_confirm','Disconnect this WGTools panel from its HUB and remove the internal Node tunnel?');if(!confirm(message))return; try{const r=await fetch('/api/nodes/disable',{method:'POST'});const d=await r.json();if(!r.ok)throw new Error(d.error||t('nodes.disable_failed','Could not disable WGTools Nodes'));renderNodes(d);toast(t('nodes.disabled','WGTools Nodes disabled'));}catch(e){toast(e.message,5000);} } async function syncNodes(){const button=$('nodes-sync-button');if(button)button.disabled=true;try{const r=await fetch('/api/nodes/sync-now',{method:'POST'});const d=await r.json();if(!r.ok)throw new Error(nodeApiErrorMessage(d,t('nodes.sync_failed','Node synchronization failed')));await loadNodes();toast(t('nodes.synced','Node information synchronized'));}catch(e){toast(e.message,5000);}finally{if(button)button.disabled=false;}} function bindNodes(){ if(page!=='server')return; $('nodes-enable-hub-button')?.addEventListener('click',openNodeHubModal);$('node-hub-form')?.addEventListener('submit',enableNodeHub); $('nodes-connect-button')?.addEventListener('click',openNodeConnectModal);$('node-connect-form')?.addEventListener('submit',connectNode); $('nodes-settings-button')?.addEventListener('click',openNodeSettings);$('node-settings-form')?.addEventListener('submit',saveNodeSettings); $('nodes-create-code-button')?.addEventListener('click',createNodeCode);$('nodes-copy-code-button')?.addEventListener('click',copyNodeCode); $('nodes-refresh-button')?.addEventListener('click',()=>loadNodes(true));$('nodes-sync-button')?.addEventListener('click',syncNodes);$('nodes-disable-button')?.addEventListener('click',disableNodes); $('nodes-list')?.addEventListener('click',e=>{const details=e.target.closest('[data-node-details]');if(details){openNodeDetails(details.dataset.nodeDetails);return;}const open=e.target.closest('[data-node-open]');if(open){openRemoteNodePanel(open.dataset.nodeOpen);return;}const remove=e.target.closest('[data-node-remove]');if(remove)removeNode(remove.dataset.nodeRemove);}); } let activeSettingsTab = 'general'; function activateSettingsTab(name,{updateHash=true}={}){ if(page!=='settings')return; const allowed=['general','backups','telegram','mail','https','users','branding','about']; activeSettingsTab=allowed.includes(name)?name:'general'; document.querySelectorAll('[data-settings-tab]').forEach(button=>{ const active=button.dataset.settingsTab===activeSettingsTab; button.classList.toggle('active',active); button.setAttribute('aria-selected',active?'true':'false'); button.tabIndex=active?0:-1; }); document.querySelectorAll('[data-settings-tab-panel]').forEach(panel=>{panel.hidden=panel.dataset.settingsTabPanel!==activeSettingsTab;}); try{sessionStorage.setItem('wgtools.settings.tab',activeSettingsTab);}catch(_){} if(updateHash){ try{history.replaceState(null,'',`${location.pathname}${location.search}#${activeSettingsTab}`);}catch(_){} } } function bindSettingsTabs(){ if(page!=='settings')return; const allowed=['general','backups','telegram','mail','https','users','branding','about']; document.querySelectorAll('[data-settings-tab]').forEach(button=>{ button.addEventListener('click',()=>activateSettingsTab(button.dataset.settingsTab)); button.addEventListener('keydown',event=>{ if(!['ArrowLeft','ArrowRight'].includes(event.key))return; const buttons=[...document.querySelectorAll('[data-settings-tab]')].filter(x=>!x.hidden&&!x.disabled); const index=buttons.indexOf(button);if(index<0||!buttons.length)return; event.preventDefault();const next=buttons[(index+(event.key==='ArrowRight'?1:-1)+buttons.length)%buttons.length]; activateSettingsTab(next.dataset.settingsTab);next.focus(); }); }); let initial=String(location.hash||'').replace(/^#/,''); if(!allowed.includes(initial)){ try{initial=sessionStorage.getItem('wgtools.settings.tab')||'general';}catch(_){initial='general';} } activateSettingsTab(initial,{updateHash:false}); window.addEventListener('hashchange',()=>{ const hash=String(location.hash||'').replace(/^#/,''); if(allowed.includes(hash))activateSettingsTab(hash,{updateHash:false}); }); } let vpsItems = []; let vpsEditingId = ''; let vpsModalMode = 'new'; function vpsPayload(){ return { name:$('vps-name')?.value.trim()||'',host:$('vps-host')?.value.trim()||'', ssh_port:Number($('vps-ssh-port')?.value||22),ssh_user:$('vps-ssh-user')?.value.trim()||'', auth_method:$('vps-auth-method')?.value||'password',password:$('vps-password')?.value||'', private_key:$('vps-private-key')?.value||'',key_passphrase:$('vps-key-passphrase')?.value||'', endpoint_domain:$('vps-endpoint-domain')?.value.trim()||'',relay_port:Number($('vps-relay-port')?.value||51820), transport_port:Number($('vps-transport-port')?.value||51900), }; } function vpsCredentialPayload(){ return {auth_method:$('vps-auth-method')?.value||'password',password:$('vps-password')?.value||'',private_key:$('vps-private-key')?.value||'',key_passphrase:$('vps-key-passphrase')?.value||''}; } function setVpsIdentityReadonly(value){ ['vps-name','vps-host','vps-ssh-port','vps-ssh-user','vps-endpoint-domain','vps-relay-port','vps-transport-port'].forEach(id=>{if($(id))$(id).readOnly=Boolean(value);}); } function resetVpsVerification(){ vpsPreflight=null; if($('vps-save-button'))$('vps-save-button').disabled=true; if($('vps-install-button'))$('vps-install-button').disabled=true; setHidden('vps-preflight-result',true);operationStatus('vps-preflight-status',''); } function syncVpsAuthFields(){ const key=$('vps-auth-method')?.value==='key';setHidden('vps-password-wrap',key);setHidden('vps-key-wrap',!key);setHidden('vps-key-passphrase-wrap',!key); resetVpsVerification(); } function openVpsModal(item=null,mode='new'){ const form=$('vps-form');if(!form)return;form.reset();vpsEditingId=item?.id||'';vpsModalMode=mode; $('vps-ssh-port').value=String(item?.ssh_port||22);$('vps-ssh-user').value=item?.ssh_user||'root'; $('vps-name').value=item?.name||'';$('vps-host').value=item?.host||'';$('vps-endpoint-domain').value=item?.endpoint_domain||''; $('vps-relay-port').value=String(item?.relay_port||snapshot?.listen_port||snapshot?.config?.interface?.listen_port||51820); $('vps-transport-port').value=String(item?.transport_port||51900); $('vps-auth-method').value='password';setVpsIdentityReadonly(mode==='install');syncVpsAuthFields(); setHidden('vps-save-button',true);setHidden('vps-install-button',mode!=='install'); if($('vps-modal-title'))$('vps-modal-title').textContent=mode==='install'?t('vps.install_title','Install Relay'):t('vps.add_title','Add VPS'); if($('vps-install-button'))$('vps-install-button').textContent=t('vps.install_relay','Install Relay'); modalShow('vps-modal',true);setTimeout(()=>$(mode==='install'?'vps-password':'vps-name')?.focus(),30); } function renderVpsPreflight(data){ const el=$('vps-preflight-result');if(!el)return; const yes=t('common.yes','Yes'); const agent=data.relay_agent_installed ? `
${esc(t('vps.agent','Relay Agent'))}
${esc(t('vps.agent_found','Already installed'))} · ${esc(t('vps.saved_short','Saved'))}: ${esc(data.relay_tenant_count||0)} · ${esc(t('vps.active_short','Active'))}: ${esc(data.relay_active_tenant_count||0)}
` : `
${esc(t('vps.agent','Relay Agent'))}
${esc(t('vps.agent_will_install','Will be installed'))}
`; const portNote=data.ports_adjusted?` ${esc(t('vps.ports_adjusted','free ports selected'))}`:''; const note=data.reconnect_available ? `
${esc(t('vps.reconnect_note','An existing Relay connection created by this WGTools was found. WGTools will reconnect to it; no new tenant or UDP ports will be created.'))}
` : (data.relay_agent_installed?`
${esc(t('vps.multi_tenant_note','The existing Relay Agent will not be replaced. WGTools will create a separate isolated connection for this controller.'))}
`:''); el.innerHTML=`
${esc(t('vps.check_ok','VPS is compatible'))}
${esc(t('vps.os','Operating system'))}
${esc(data.os_name||'—')}
${esc(t('vps.arch','Architecture'))}
${esc(data.architecture||'—')}
${esc(t('vps.privilege','Privileges'))}
${esc(data.privilege_mode||'—')}
${esc(t('vps.host_key','SSH host key'))}
${esc(data.host_key_fingerprint||'—')}
${esc(t('vps.wireguard','WireGuard'))}
${esc(data.wireguard_installed?yes:t('vps.not_installed','Will be installed'))}
${esc(t('vps.iptables','iptables'))}
${esc(data.iptables_installed?yes:t('vps.not_installed','Will be installed'))}
${agent}
${esc(t('vps.port_pair','UDP ports'))}
${esc(data.relay_port)} / ${esc(data.transport_port)}${portNote}
${note}`; el.hidden=false; } async function checkVps(){ const button=$('vps-check-button');if(!button)return;button.disabled=true; if($('vps-save-button'))$('vps-save-button').disabled=true;if($('vps-install-button'))$('vps-install-button').disabled=true; vpsPreflight=null;setHidden('vps-preflight-result',true);operationStatus('vps-preflight-status',t('vps.checking','Checking SSH access and VPS compatibility…'),'working'); try{ const r=await fetch('/api/vps/preflight',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(vpsPayload())});const d=await r.json();if(!r.ok)throw new Error(d.error||t('vps.check_failed','VPS check failed')); vpsPreflight=d; if(d.relay_port)$('vps-relay-port').value=String(d.relay_port);if(d.transport_port)$('vps-transport-port').value=String(d.transport_port); operationStatus('vps-preflight-status','');renderVpsPreflight(d); setHidden('vps-install-button',false);$('vps-install-button').disabled=false; $('vps-install-button').textContent=d.reconnect_available?t('vps.reconnect_relay','Reconnect Relay'):t('vps.install_relay','Install Relay'); }catch(e){operationStatus('vps-preflight-status',e.message,'error');}finally{button.disabled=false;} } function renderVpsList(items){ const list=$('vps-list'),empty=$('vps-empty');if(!list)return;vpsItems=items||[];if(empty)empty.hidden=vpsItems.length>0; list.innerHTML=vpsItems.map(item=>{ const endpoint=item.endpoint_domain?`${item.endpoint_domain}:${item.relay_port}`:`${item.host}:${item.relay_port}`; const installed=item.status==='installed'; const status=installed?t('vps.status_installed','Relay connected'):t('vps.status_candidate','Ready for installation'); const meta=[item.os_name||item.os_id||'—',item.architecture||'—',endpoint]; if(installed&&item.published_interface){ const transport=item.transport_interface?` · ${item.transport_interface}`:''; meta.push(`${item.published_interface}${transport} → ${item.home_transport_ip||'—'} ↔ ${item.relay_transport_ip||'—'}`); } const side=installed ? `${esc(t('vps.tenant','Tenant'))}: ${esc((item.tenant_id||'').slice(0,10))}` : `${esc(t('vps.ready_help','SSH credentials are requested again only for installation.'))}`; return `
${esc(item.name)}${esc(status)}
${meta.map(x=>`${esc(x)}`).join('')}
${side}
`; }).join(''); } async function loadVpsList(){ if(page!=='server'||!$('vps-list'))return;try{const r=await fetch('/api/vps',{cache:'no-store'});const d=await r.json();if(!r.ok)throw new Error(d.error||'VPS list failed');renderVpsList(d.items||[]);}catch(e){$('vps-list').innerHTML=`
${esc(e.message)}
`;} } async function saveVpsCandidate(event){ event.preventDefault();if(vpsModalMode==='install')return;if(!vpsPreflight)return;const button=$('vps-save-button');button.disabled=true; try{const payload={...vpsPayload(),preflight:vpsPreflight};const r=await fetch('/api/vps/candidates',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(payload)});const d=await r.json();if(!r.ok)throw new Error(d.error||'Save failed');modalShow('vps-modal',false);toast(t('vps.saved','VPS candidate saved'));await loadVpsList();}catch(e){operationStatus('vps-preflight-status',e.message,'error');}finally{button.disabled=false;} } async function installVpsRelay(){ if(!vpsPreflight)return;const button=$('vps-install-button');if(!button)return;button.disabled=true;$('vps-check-button').disabled=true; operationStatus('vps-preflight-status',t('vps.installing','Installing Relay Agent and establishing the protected transport tunnel…'),'working'); let createdCandidate=false; try{ if(!vpsEditingId){ const savePayload={...vpsPayload(),preflight:vpsPreflight}; const sr=await fetch('/api/vps/candidates',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(savePayload)});const sd=await sr.json();if(!sr.ok)throw new Error(sd.error||'Could not prepare VPS installation'); vpsEditingId=sd.item?.id||'';createdCandidate=Boolean(vpsEditingId)&&!Boolean(vpsPreflight?.reconnect_available);if(!vpsEditingId)throw new Error('WGTools did not return a VPS installation id'); } const r=await fetch(`/api/vps/${encodeURIComponent(vpsEditingId)}/install`,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(vpsCredentialPayload())});const d=await r.json();if(!r.ok)throw new Error(d.error||'Relay installation failed'); modalShow('vps-modal',false);toast(d.reconnected?t('vps.reconnect_ok','Existing Relay reconnected successfully'):t('vps.install_ok','Relay installed and management tunnel verified'));await loadVpsList(); }catch(e){ if(createdCandidate&&vpsEditingId){try{await fetch(`/api/vps/candidates/${encodeURIComponent(vpsEditingId)}`,{method:'DELETE'});}catch{}vpsEditingId='';} operationStatus('vps-preflight-status',e.message,'error');button.disabled=false; }finally{$('vps-check-button').disabled=false;} } async function deleteVpsCandidate(id){ if(!confirm(t('vps.remove_confirm','Remove this VPS candidate? No remote changes have been made.')))return;try{const r=await fetch(`/api/vps/candidates/${encodeURIComponent(id)}`,{method:'DELETE'});const d=await r.json();if(!r.ok)throw new Error(d.error||'Delete failed');await loadVpsList();}catch(e){toast(e.message);} } async function removeInstalledVps(id){ const item=vpsItems.find(x=>x.id===id); const message=t('vps.delete_installed_confirm','Remove “{name}” from WGTools? The local Relay transport will be disconnected, but the Relay Agent and tenant on the VPS will be preserved so a WGTools backup can reconnect to it later. Clients using this Relay will stop connecting through it until the state is restored or they are reconfigured.').replace('{name}',item?.name||'VPS'); if(!confirm(message))return; try{ const r=await fetch(`/api/vps/${encodeURIComponent(id)}`,{method:'DELETE'});const d=await r.json();if(!r.ok)throw new Error(d.error||t('vps.delete_installed_failed','Could not remove VPS from WGTools')); toast(t('vps.delete_installed_ok','VPS removed from WGTools. The Relay on the remote VPS was preserved.'),5000); await loadVpsList(); }catch(e){toast(e.message,5000);} } function bindVps(){ if(page!=='server')return; $('vps-add-button')?.addEventListener('click',()=>openVpsModal());$('vps-auth-method')?.addEventListener('change',syncVpsAuthFields);$('vps-check-button')?.addEventListener('click',checkVps);$('vps-form')?.addEventListener('submit',e=>e.preventDefault());$('vps-install-button')?.addEventListener('click',installVpsRelay); $('vps-list')?.addEventListener('click',e=>{ const del=e.target.closest('[data-vps-delete]');if(del){deleteVpsCandidate(del.dataset.vpsDelete);return;} const remove=e.target.closest('[data-vps-remove]');if(remove){removeInstalledVps(remove.dataset.vpsRemove);return;} const install=e.target.closest('[data-vps-install]');if(install){const item=vpsItems.find(x=>x.id===install.dataset.vpsInstall);if(item)openVpsModal(item,'install');return;} const health=e.target.closest('[data-vps-health]');if(health){checkVpsHealth(health.dataset.vpsHealth);} }); ['vps-name','vps-host','vps-ssh-port','vps-ssh-user','vps-password','vps-private-key','vps-key-passphrase','vps-endpoint-domain','vps-relay-port','vps-transport-port'].forEach(id=>$(id)?.addEventListener('input',resetVpsVerification)); } function renderServer(d){ const installed=Boolean(d.wireguard?.installed); const configured=Boolean(d.wireguard?.config_exists); const configuredInterfaces=(interfacesData.interfaces||[]).filter(item=>item.configured); setHidden('edit-server-button', !configured); setHidden('add-interface-button', !installed || configuredInterfaces.length===0); setHidden('interface-manager-card', !installed || configuredInterfaces.length===0); setHidden('wireguard-install-card', installed); setHidden('create-server-card', !installed || configured || configuredInterfaces.length>0); setHidden('configured-server', !configured); renderInterfaceManager(); if(installed && !configured && configuredInterfaces.length===0){ const uplink=$('setup-uplink'), gateway=$('setup-gateway'), local=$('setup-local-network'); if(uplink && !uplink.dataset.touched) uplink.value=d.system?.default_uplink||''; if(gateway && !gateway.dataset.touched) gateway.value=d.system?.default_gateway||''; if(local && !local.dataset.touched) local.value=d.system?.local_network||''; } if(configured){ const i=d.config?.interface||{}, x=d.config?.detected||{}; $('interface-kv').innerHTML=[['Interface',d.interface], [t('server.address','Address'),i.address], [t('server.listen_port','Listen port'),i.listen_port||d.listen_port], [t('server.mtu','MTU'),i.mtu||t('server.mtu_auto','Auto')], [t('server.private_key','Private key'),i.private_key_set?t('server.private_hidden','Configured (hidden)'):t('server.not_set','Not set')], [t('server.save_config','SaveConfig'),i.save_config||'false']].map(([a,b])=>`
${esc(a)}
${esc(b||'—')}
`).join(''); $('routing-kv').innerHTML=[[t('server.vpn_network','VPN network'),x.vpn_network],[t('server.policy_table','Policy table'),x.policy_table],[t('server.uplink','Uplink interface'),x.uplink_interface||d.system?.default_uplink],[t('server.gateway','Gateway'),x.gateway||d.system?.default_gateway],[t('server.local_network','Local network'),x.local_network||d.system?.local_network],[t('server.ip_forwarding','IPv4 forwarding'),d.system?.ip_forwarding?t('common.enabled','Enabled'):t('common.disabled','Disabled')]].map(([a,b])=>`
${esc(a)}
${esc(b||'—')}
`).join(''); renderRoutes(d); renderFirewall(d); } if(Array.isArray(d.diagnostics)) renderDiagnostics(d.diagnostics); updateServerTabActions(); } function routeTypeText(category){ if(category==='server')return t('server.route_managed_server','Server setting'); if(category==='site_to_site')return t('server.route_managed_peer','Site-to-site peer'); return t('server.route_custom','Custom'); } function routeViaText(r){ const parts=[]; if(r.via)parts.push(`${t('server.via_word','via')} ${r.via}`); if(r.device)parts.push(`${t('server.dev_word','dev')} ${r.device}`); return parts.join(' · ')||'—'; } function renderRoutes(d){ const body=$('route-body'); if(!body)return; const routes=d.route_items||[]; if(!routes.length){body.innerHTML=`${esc(t('server.no_routes','No routes detected'))}`;return;} body.innerHTML=routes.map((r,index)=>` ${esc(r.network||'default')} ${esc(routeViaText(r))} ${esc(r.table||'main')} ${esc(routeTypeText(r.category))} ${r.editable?`
`:`${esc(t('server.managed_automatically','Managed automatically'))}`} `).join(''); } function firewallTypeText(item){ if(item.category==='server')return t('server.rule_managed_server','Server setting'); if(item.category==='access'&&item.access?.managed_tag&&item.access?.action==='ACCEPT')return t('server.rule_client_exception','Client exception'); if(item.category==='access'&&item.access?.managed_tag)return t('server.rule_client_policy','Client policy'); if(item.category==='access')return t('server.rule_access','Access rule'); return t('server.rule_advanced','Advanced'); } function commandAction(command){ const c=String(command||''); if(c.includes('MASQUERADE'))return 'MASQUERADE'; const m=c.match(/\s-j\s+(ACCEPT|REJECT|DROP)\b/); return m?m[1]:'—'; } function renderFirewall(d){ const body=$('firewall-body'); if(!body)return; const rules=d.firewall_items||[]; if(!rules.length){body.innerHTML=`${esc(t('server.no_firewall','No firewall rules detected'))}`;return;} body.innerHTML=rules.map((r,index)=>{ const a=r.access||{}; const simple=r.category==='access'; const source=simple?(a.source||t('server.any','Any')):'—'; const destination=simple?(a.destination||t('server.any','Any')):'—'; const action=simple?(a.action||'—'):commandAction(r.command); const details=simple?[a.protocol&&a.protocol!=='any'?String(a.protocol).toUpperCase():'',a.destination_port?`${t('server.port_word','port')} ${a.destination_port}`:''].filter(Boolean).join(' · ')||'—':r.command; return ` ${esc(firewallTypeText(r))} ${esc(source)}${esc(destination)}${esc(action)} ${esc(details)} ${r.editable?`
`:`${esc(r.category==='advanced'?t('server.use_raw_editor','Use raw editor'):t('server.managed_automatically','Managed automatically'))}`} `; }).join(''); } function openRouteEditor(item=null){ const form=$('route-edit-form'); if(!form)return; form.dataset.mode=item?'edit':'create'; form.dataset.originalCommand=item?.command||''; $('route-edit-title').textContent=item?t('server.edit_route','Edit route'):t('server.add_route','Add route'); $('route-network').value=item?.network||''; $('route-gateway').value=item?.via||''; $('route-device').value=item?.device||''; $('route-table').value=item?.table||'main'; operationStatus('route-edit-status',''); modalShow('route-edit-modal',true); setTimeout(()=>$('route-network')?.focus(),30); } function routePayload(){ return {network:$('route-network').value.trim(),gateway:$('route-gateway').value.trim(),device:$('route-device').value.trim(),table:$('route-table').value.trim()||'main'}; } async function saveRoute(event){ event.preventDefault(); const form=$('route-edit-form'), button=$('route-edit-save'); if(!form||!button)return; const editing=form.dataset.mode==='edit'; const payload=routePayload(); if(editing)payload.original_command=form.dataset.originalCommand; if(!confirm(t('server.route_apply_confirm','Save this route and apply it now? WireGuard will be restarted briefly and a backup will be created.')))return; button.disabled=true; operationStatus('route-edit-status',t('server.applying_rule','Creating backup and applying…'),'working'); try{ const r=await fetch(editing?'/api/server/routes/update':'/api/server/routes/create',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(payload)}); const d=await r.json(); if(!r.ok)throw new Error(d.error||'Operation failed'); await fetchSnapshot(false); modalShow('route-edit-modal',false); toast(t('server.route_saved','Route saved and applied.')); }catch(e){operationStatus('route-edit-status',e.message,'error');toast(e.message);}finally{button.disabled=false;} } async function deleteRoute(item){ if(!item?.editable)return; if(!confirm(t('server.delete_route_confirm','Delete this custom route and apply the change?')))return; try{const r=await fetch('/api/server/routes/delete',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({original_command:item.command})});const d=await r.json();if(!r.ok)throw new Error(d.error||'Delete failed');toast(t('server.route_deleted','Route deleted.'));await fetchSnapshot(false);}catch(e){toast(e.message);} } function openAccessRuleEditor(item=null){ const form=$('access-rule-form'); if(!form)return; const a=item?.access||{}; form.dataset.mode=item?'edit':'create'; form.dataset.originalCommand=item?.command||''; $('access-rule-title').textContent=item?t('server.edit_access_rule','Edit access rule'):t('server.add_access_rule','Add access rule'); $('access-source').value=a.source||''; $('access-destination').value=a.destination||''; $('access-action').value=a.action||'REJECT'; $('access-protocol').value=a.protocol||'any'; $('access-dport').value=a.destination_port||''; operationStatus('access-rule-status',''); modalShow('access-rule-modal',true); setTimeout(()=>$('access-source')?.focus(),30); } function accessPayload(){ return {source:$('access-source').value.trim(),destination:$('access-destination').value.trim(),action:$('access-action').value,protocol:$('access-protocol').value,destination_port:$('access-dport').value.trim()}; } async function saveAccessRule(event){ event.preventDefault(); const form=$('access-rule-form'), button=$('access-rule-save'); if(!form||!button)return; const editing=form.dataset.mode==='edit'; const payload=accessPayload(); if(editing)payload.original_command=form.dataset.originalCommand; if(!confirm(t('server.access_apply_confirm','Save this firewall rule and apply it now? WireGuard will be restarted briefly and a backup will be created.')))return; button.disabled=true; operationStatus('access-rule-status',t('server.applying_rule','Creating backup and applying…'),'working'); try{ const r=await fetch(editing?'/api/server/access-rules/update':'/api/server/access-rules/create',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(payload)}); const d=await r.json(); if(!r.ok)throw new Error(d.error||'Operation failed'); await fetchSnapshot(false); modalShow('access-rule-modal',false); toast(t('server.access_rule_saved','Access rule saved and applied.')); }catch(e){operationStatus('access-rule-status',e.message,'error');toast(e.message);}finally{button.disabled=false;} } async function deleteAccessRule(item){ if(!item?.editable)return; if(!confirm(t('server.delete_access_confirm','Delete this access rule and apply the change?')))return; try{const r=await fetch('/api/server/access-rules/delete',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({original_command:item.command})});const d=await r.json();if(!r.ok)throw new Error(d.error||'Delete failed');toast(t('server.access_rule_deleted','Access rule deleted.'));await fetchSnapshot(false);}catch(e){toast(e.message);} } function bindServerRules(){ $('add-route-button')?.addEventListener('click',()=>openRouteEditor()); $('route-edit-form')?.addEventListener('submit',saveRoute); $('route-body')?.addEventListener('click',e=>{const b=e.target.closest('[data-route-action]');if(!b)return;const item=snapshot?.route_items?.[Number(b.dataset.routeIndex)];if(!item)return;if(b.dataset.routeAction==='edit')openRouteEditor(item);else if(b.dataset.routeAction==='delete')deleteRoute(item);}); $('add-access-rule-button')?.addEventListener('click',()=>openAccessRuleEditor()); $('access-rule-form')?.addEventListener('submit',saveAccessRule); $('firewall-body')?.addEventListener('click',e=>{const b=e.target.closest('[data-firewall-action]');if(!b)return;const item=snapshot?.firewall_items?.[Number(b.dataset.firewallIndex)];if(!item)return;if(b.dataset.firewallAction==='edit')openAccessRuleEditor(item);else if(b.dataset.firewallAction==='delete')deleteAccessRule(item);}); } function setPolicyFieldsEnabled(enabled){ ['server-edit-policy-table','server-edit-gateway'].forEach(id=>{const el=$(id);if(el)el.disabled=!enabled;}); const box=$('server-policy-fields'); if(box)box.classList.toggle('disabled-fields',!enabled); } let hostIpDevices = {}; function syncNetworkBinding(prefix){ const mode=$(`${prefix}-listen-mode`)?.value||'all'; const address=mode==='address'||mode==='both', device=mode==='interface'||mode==='both'; $(`${prefix}-listen-address-wrap`).hidden=!address;$(`${prefix}-listen-address`).required=address; $(`${prefix}-listen-interface-wrap`).hidden=!device;$(`${prefix}-listen-interface`).required=device; const snat=$(`${prefix}-snat-mode`).value==='address';$(`${prefix}-snat-address-wrap`).hidden=!snat;$(`${prefix}-snat-address`).required=snat; } function networkBindingPayload(prefix){ const mode=$(`${prefix}-listen-mode`).value; return {listen_address:['address','both'].includes(mode)?$(`${prefix}-listen-address`).value.trim():'',listen_interface:['interface','both'].includes(mode)?$(`${prefix}-listen-interface`).value.trim():'',snat_address:$(`${prefix}-snat-mode`).value==='address'?$(`${prefix}-snat-address`).value.trim():'',forward_sources:$(`${prefix}-forward-sources`).value.trim()}; } async function openServerEditor(){ if(!snapshot?.wireguard?.config_exists)return; const i=snapshot.config?.interface||{}, x=snapshot.config?.detected||{}; $('server-edit-interface').value=snapshot.interface||'wg0'; const activeItem=activeInterfaceItem(); $('server-edit-display-name').value=(activeItem?.display_name&&activeItem.display_name!==snapshot.interface)?activeItem.display_name:''; $('server-edit-vpn-network').value=x.vpn_network||''; $('server-edit-address').value=i.address||''; const serverAddress=$('server-edit-address');if(serverAddress)delete serverAddress.dataset.touched; $('server-edit-port').value=i.listen_port||snapshot.listen_port||51820; $('server-edit-mtu').value=i.mtu||''; $('server-edit-uplink').value=x.uplink_interface||snapshot.system?.default_uplink||''; $('server-edit-local-network').value=x.local_network||snapshot.system?.local_network||''; const policy=Boolean(x.policy_table); $('server-edit-policy-enabled').checked=policy; $('server-edit-policy-table').value=x.policy_table||'200'; $('server-edit-gateway').value=x.gateway||snapshot.system?.default_gateway||''; $('server-edit-ip-forwarding').checked=Boolean(snapshot.system?.ip_forwarding); $('server-edit-forward-from').checked=x.forward_from_vpn !== false; $('server-edit-forward-to').checked=x.forward_to_vpn !== false; $('server-edit-nat').checked=Boolean(x.nat_enabled); try{ const [lr,sr,gr]=await Promise.all([fetch(appUrl('/api/server/extended-listen')),fetch(appUrl('/api/server/extended-snat')),fetch(appUrl('/api/extended/ip-groups'))]); const [listen,snat,groups]=await Promise.all([lr.json(),sr.json(),gr.json()]);if(!lr.ok||!sr.ok||!gr.ok)throw new Error(listen.error||snat.error||groups.error||'Nie udało się odczytać ustawień sieci.'); $('server-edit-listen-address').value=listen.address||'';$('server-edit-listen-interface').value=listen.interface||''; $('server-edit-listen-mode').value=listen.address?(listen.interface?'both':'address'):(listen.interface?'interface':'all'); $('server-edit-snat-address').value=snat.address||'';$('server-edit-snat-mode').value=snat.address?'address':'auto';syncNetworkBinding('server-edit'); $('server-edit-forward-sources').value=(groups.groups?.[`_wgext_network_${snapshot.interface}`]?.sources||[]).join(', '); }catch(err){toast(err.message);return;} setPolicyFieldsEnabled(policy); operationStatus('server-edit-status',''); modalShow('server-edit-modal',true); } function syncServerEditAddress(){ const net=$('server-edit-vpn-network'),addr=$('server-edit-address'); if(!net||!addr||addr.dataset.touched)return; const first=firstHostFromCidr(net.value); if(first)addr.value=first; } function localizedServerError(message){ const raw=String(message||''); const map=[ ['VPN network must be a valid IPv4 network such as 10.77.0.0/24','server.error_vpn_network_invalid','VPN-сеть должна быть корректной IPv4-сетью, например 10.0.0.0/24.'], ['Only IPv4 VPN networks are supported in this version','server.error_vpn_ipv4_only','Поддерживаются только IPv4 VPN-сети.'], ['VPN network must contain at least two usable addresses','server.error_vpn_network_too_small','VPN-сеть должна содержать как минимум два доступных адреса.'], ['VPN network has no usable host addresses','server.error_vpn_network_no_hosts','В выбранной VPN-сети нет доступных адресов для сервера.'], ['Server address must include a prefix, for example 10.77.0.1/24','server.error_server_address_prefix','VPN-адрес сервера должен содержать префикс, например 10.0.0.1/24.'], ['Server address must belong to the selected VPN network and use the same prefix','server.error_server_address_network','VPN-адрес сервера должен принадлежать выбранному пулу VPN-адресов и использовать тот же префикс.'], ['Server address cannot be the network or broadcast address','server.error_server_address_reserved','VPN-адрес сервера не может быть адресом сети или широковещательным адресом.'], ['Listen port must be a number','server.error_listen_port_number','Порт WireGuard должен быть числом.'], ['Listen port must be between 1 and 65535','server.error_listen_port_range','Порт WireGuard должен быть в диапазоне от 1 до 65535.'], ['MTU must be a number','server.error_mtu_number','MTU должен быть числом.'] ]; for(const [needle,key,fallback] of map){if(raw.includes(needle))return t(key,fallback);} return raw; } async function applyServerSettings(event){ event.preventDefault(); const button=$('server-edit-save'); if(!button)return; const policy=$('server-edit-policy-enabled').checked; const payload={ vpn_network:$('server-edit-vpn-network').value.trim(), server_address:$('server-edit-address').value.trim(), listen_port:Number($('server-edit-port').value), mtu:Number($('server-edit-mtu').value||0), uplink_interface:$('server-edit-uplink').value.trim(), gateway:policy?$('server-edit-gateway').value.trim():'', local_network:$('server-edit-local-network').value.trim(), policy_table:policy?$('server-edit-policy-table').value.trim():'', nat_enabled:$('server-edit-nat').checked, ip_forwarding:$('server-edit-ip-forwarding').checked, forward_from_vpn:$('server-edit-forward-from').checked, forward_to_vpn:$('server-edit-forward-to').checked, ...networkBindingPayload('server-edit'), }; if(!confirm(t('server.apply_confirm','Save these server settings and apply them now? WireGuard will be restarted briefly. A backup is created first and WGTools will roll back automatically if the new configuration does not start.')))return; button.disabled=true; operationStatus('server-edit-status',t('server.applying_settings','Validating settings, creating backup and applying…'),'working'); try{ const r=await fetch('/api/server/settings/apply',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(payload)}); const d=await r.json(); if(!r.ok)throw new Error(d.error||t('server.settings_apply_failed','Server settings could not be applied')); const iface=snapshot?.interface||document.body.dataset.interface||'wg0'; const displayName=$('server-edit-display-name').value.trim(); const nr=await fetch('/api/interfaces/name',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({interface:iface,display_name:displayName})}); const nd=await nr.json(); if(!nr.ok)throw new Error(nd.error||t('interfaces.rename_failed','Interface display name could not be saved')); operationStatus('server-edit-status',t('server.settings_applied','Server settings saved and applied successfully.'),'success'); toast(t('server.settings_applied','Server settings saved and applied successfully.')); await fetchInterfaces(true); await fetchSnapshot(false); setTimeout(()=>modalShow('server-edit-modal',false),450); }catch(e){const message=localizedServerError(e.message);operationStatus('server-edit-status',message,'error');toast(message);}finally{button.disabled=false;} } function bindServerEditor(){ if(page==='server'){ for(const prefix of ['setup','new-interface','server-edit']){for(const name of ['listen-mode','snat-mode'])$(`${prefix}-${name}`)?.addEventListener('change',()=>syncNetworkBinding(prefix));$(`${prefix}-snat-address`)?.addEventListener('change',e=>{const device=hostIpDevices[e.target.value.trim()];if(device)$(`${prefix}-uplink`).value=device;});syncNetworkBinding(prefix);} fetch(appUrl('/api/server/host-ips')).then(async r=>{const d=await r.json();if(!r.ok)throw new Error(d.error);hostIpDevices=d.addresses||{};const items=Object.entries(hostIpDevices),devices=[...new Set(items.map(([,dev])=>dev))];$('host-ip-options').innerHTML=items.map(([ip,dev])=>``).join('');$('host-interface-options').innerHTML=devices.map(dev=>``).join('');$('host-forward-options').innerHTML=[...items.map(([ip])=>ip),...devices].map(value=>``).join('');}).catch(err=>toast(err.message)); } if(page==='server' && $('extended-group-form')){ const loadGroups=async()=>{ try{const r=await fetch(appUrl('/api/extended/ip-groups'));const d=await r.json();if(!r.ok)throw new Error(d.error); $('extended-groups-list').innerHTML=Object.entries(d.groups||{}).filter(([name])=>!name.startsWith('_wgext_network_')).map(([name,g])=>`
${esc(name)}

${esc((g.addresses||[]).join(', '))}

Sieci: ${esc((g.interfaces||[]).join(', '))}

`).join('')||'

Brak grup adresów.

'; $('extended-groups-list').insertAdjacentHTML('beforeend',`

Przegląd przekierowań

`+(d.forwards||[]).map(f=>`

${esc(f.interface)}: ${esc(f.public_ip)}:${Number(f.public_port)} / ${esc(f.protocol)} → ${esc(f.target_ip)}:${Number(f.target_port)}${f.service?' · Usługa: '+esc(f.service):''}${f.responsibility?' · Potwierdził: '+esc(f.responsibility.user)+' ('+esc(new Date(f.responsibility.time*1000).toLocaleString('pl-PL'))+')':''}

`).join('')); return d.groups||{}; }catch(err){operationStatus('extended-group-status',err.message,'error');return {};} }; const save=async p=>{const r=await fetch(appUrl('/api/extended/ip-groups'),{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(p)});const d=await r.json();if(!r.ok)throw new Error(d.error);await loadGroups();}; $('extended-group-form').addEventListener('submit',async e=>{e.preventDefault();try{await save({name:$('extended-group-name').value.trim(),addresses:$('extended-group-addresses').value.split(',').map(x=>x.trim()).filter(Boolean),interfaces:$('extended-group-interfaces').value.split(',').map(x=>x.trim()).filter(Boolean)});operationStatus('extended-group-status','Zapisano grupę.','success');}catch(err){operationStatus('extended-group-status',err.message,'error');}}); $('extended-groups-list').addEventListener('click',async e=>{const edit=e.target.closest('[data-ext-group-edit]'), del=e.target.closest('[data-ext-group-delete]');try{if(edit){const groups=await loadGroups(),name=edit.dataset.extGroupEdit,g=groups[name];if(g){$('extended-group-name').value=name;$('extended-group-addresses').value=g.addresses.join(', ');$('extended-group-interfaces').value=g.interfaces.join(', ');operationStatus('extended-group-status',`Edytujesz grupę ${name}. Zmień pola i kliknij Zapisz grupę.`, 'working');$('extended-group-form').scrollIntoView({behavior:'smooth',block:'center'});$('extended-group-addresses').focus();}}else if(del && confirm('Usunąć grupę adresów?')){await save({name:del.dataset.extGroupDelete,delete:true});}}catch(err){operationStatus('extended-group-status',err.message,'error');}}); loadGroups(); } if(page==='clients' && $('extended-forward-form')){ let forwards=[], editing=''; let servicePolicy={enabled:false,mode:'list',services:[]}; const syncService=()=>{ const on=servicePolicy.enabled, mode=servicePolicy.mode, selected=$('forward-service-select').value; $('forward-service-section').hidden=!on; $('forward-service-select-wrap').hidden=!on||mode==='custom'; $('forward-service-custom-wrap').hidden=!on||(mode!=='custom'&&selected!=='__other__'); $('forward-service-select').required=on&&mode!=='custom'; $('forward-service-custom').required=on&&(mode==='custom'||selected==='__other__'); $('forward-service-confirmation').required=on; }; $('forward-service-select').addEventListener('change',syncService); const confirmation=$('forward-service-confirmation'); const example=$('forward-confirmation-example'); const validateConfirmation=()=>confirmation.setCustomValidity(confirmation.value && confirmation.value!==example.textContent?'Przepisz dokładnie podany tekst.':''); confirmation.addEventListener('input',validateConfirmation); ['paste','drop'].forEach(name=>confirmation.addEventListener(name,e=>e.preventDefault())); ['copy','cut','dragstart','contextmenu'].forEach(name=>example.addEventListener(name,e=>e.preventDefault())); const reset=()=>{editing='';$('extended-forward-form').reset();confirmation.setCustomValidity('');$('extended-forward-restrict').checked=false;syncSources();$('extended-forward-submit').textContent='Dodaj przekierowanie';$('extended-forward-cancel').hidden=true;syncService();}; const syncSources=()=>{const enabled=$('extended-forward-restrict').checked;$('extended-forward-sources-wrap').hidden=!enabled;$('extended-forward-sources').required=enabled;}; const loadForwards=async()=>{const r=await fetch(appUrl('/api/extended/forwardings'));const d=await r.json();if(!r.ok)throw new Error(d.error);forwards=d.forwards||[];servicePolicy=d.service_policy||servicePolicy;const sel=$('forward-service-select');sel.innerHTML=''+servicePolicy.services.map(x=>``).join('')+(servicePolicy.mode==='combo'?'':'');syncService();const current=$('extended-forward-public').value;$('extended-forward-public').innerHTML=(d.addresses||[]).map(ip=>``).join('');if((d.addresses||[]).includes(current))$('extended-forward-public').value=current;$('extended-forward-list').innerHTML=forwards.map(f=>`
${esc(f.public_ip)}:${Number(f.public_port)} / ${esc(f.protocol)} → ${esc(f.target_ip)}:${Number(f.target_port)}

${f.allowed_sources?.length?'Dozwolone adresy: '+esc(f.allowed_sources.join(', ')):'Dostęp ze wszystkich adresów'}

`).join('')||'

Brak przekierowań.

';}; $('extended-forward-restrict').addEventListener('change',syncSources);$('extended-forward-cancel').addEventListener('click',reset); $('extended-forward-form').addEventListener('submit',async e=>{e.preventDefault();const restricted=$('extended-forward-restrict').checked;const payload={public_ip:$('extended-forward-public').value,public_port:Number($('extended-forward-public-port').value),target_ip:$('extended-forward-target').value,target_port:Number($('extended-forward-target-port').value),protocol:$('extended-forward-protocol').value,service:servicePolicy.enabled?(servicePolicy.mode==='custom'||$('forward-service-select').value==='__other__' ? $('forward-service-custom').value : $('forward-service-select').value):'',confirmation:servicePolicy.enabled?$('forward-service-confirmation').value:'',restrict_sources:restricted,allowed_sources:restricted?$('extended-forward-sources').value.split(',').map(x=>x.trim()).filter(Boolean):[]};if(editing)payload.id=editing;const button=$('extended-forward-submit');button.disabled=true;try{const r=await fetch(appUrl(editing?'/api/extended/forwardings/update':'/api/extended/forwardings'),{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(payload)});const d=await r.json();if(!r.ok)throw new Error(d.error);reset();await loadForwards();operationStatus('extended-forward-status','Zapisano przekierowanie.','success');}catch(err){operationStatus('extended-forward-status',err.message,'error');}finally{button.disabled=false;}}); $('extended-forward-list').addEventListener('click',async e=>{const edit=e.target.closest('[data-ext-forward-edit]'),del=e.target.closest('[data-ext-forward-delete]');if(edit){const f=forwards.find(x=>x.id===edit.dataset.extForwardEdit);if(!f)return;editing=f.id;$('extended-forward-public').value=f.public_ip;$('extended-forward-public-port').value=f.public_port;$('extended-forward-target').value=f.target_ip;$('extended-forward-target-port').value=f.target_port;$('extended-forward-protocol').value=f.protocol;const custom=servicePolicy.mode==='custom'||!servicePolicy.services.includes(f.service);$('forward-service-select').value=custom?'__other__':(f.service||'');$('forward-service-custom').value=custom?(f.service||''):'';$('forward-service-confirmation').value='';confirmation.setCustomValidity('');syncService();$('extended-forward-restrict').checked=Boolean(f.allowed_sources?.length);$('extended-forward-sources').value=(f.allowed_sources||[]).join(', ');syncSources();$('extended-forward-submit').textContent='Zapisz zmiany';$('extended-forward-cancel').hidden=false;operationStatus('extended-forward-status','Edytujesz przekierowanie.','working');$('extended-forward-form').scrollIntoView({behavior:'smooth',block:'center'});return;}if(!del||!confirm('Usunąć przekierowanie?'))return;try{const r=await fetch(appUrl('/api/extended/forwardings/delete'),{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({id:del.dataset.extForwardDelete})});const d=await r.json();if(!r.ok)throw new Error(d.error);if(editing===del.dataset.extForwardDelete)reset();await loadForwards();}catch(err){operationStatus('extended-forward-status',err.message,'error');}}); loadForwards().catch(err=>operationStatus('extended-forward-status',err.message,'error')); } if(page==='server' && $('extended-listen-form')){ fetch(appUrl('/api/server/extended-listen')).then(async r=>{const d=await r.json();if(!r.ok)throw new Error(d.error);$('extended-listen-address').value=d.address||'';$('extended-listen-interface').value=d.interface||'';}).catch(e=>operationStatus('extended-listen-status',e.message,'error')); $('extended-listen-form').addEventListener('submit',async e=>{ e.preventDefault(); const button=e.currentTarget.querySelector('button'); button.disabled=true; try{const r=await fetch(appUrl('/api/server/extended-listen'),{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({address:$('extended-listen-address').value.trim(),interface:$('extended-listen-interface').value.trim()})});const d=await r.json();if(!r.ok)throw new Error(d.error);operationStatus('extended-listen-status','Zapisano ograniczenie nasłuchiwania.','success');await fetchSnapshot(false);}catch(err){operationStatus('extended-listen-status',err.message,'error');}finally{button.disabled=false;} }); } if(page==='server' && $('extended-snat-form')){ fetch(appUrl('/api/server/extended-snat')).then(async r=>{const d=await r.json();if(!r.ok)throw new Error(d.error);$('extended-snat-address').value=d.address||'';$('extended-snat-uplink').value=d.uplink||'';}).catch(e=>operationStatus('extended-snat-status',e.message,'error')); $('extended-snat-form').addEventListener('submit',async e=>{ e.preventDefault(); const button=e.currentTarget.querySelector('button'); button.disabled=true; try{const r=await fetch(appUrl('/api/server/extended-snat'),{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({address:$('extended-snat-address').value.trim(),uplink:$('extended-snat-uplink').value.trim()})});const d=await r.json();if(!r.ok)throw new Error(d.error);operationStatus('extended-snat-status','Zapisano ustawienia SNAT.','success');await fetchSnapshot(false);}catch(err){operationStatus('extended-snat-status',err.message,'error');}finally{button.disabled=false;} }); } $('edit-server-button')?.addEventListener('click',openServerEditor); $('server-edit-form')?.addEventListener('submit',applyServerSettings); $('server-edit-policy-enabled')?.addEventListener('change',e=>setPolicyFieldsEnabled(e.currentTarget.checked)); $('server-edit-vpn-network')?.addEventListener('input',syncServerEditAddress); $('server-edit-address')?.addEventListener('input',e=>e.currentTarget.dataset.touched='1'); } function renderDiagnostics(checks){ const el=$('diagnostics-list'); if(!el)return; el.innerHTML=checks.map(c=>`
${c.ok?'✓':'✕'}${esc(c.label)}${esc(c.detail||'')}
`).join(''); } function clientGroups(){ return snapshot?.client_groups||[]; } function groupById(id){ return clientGroups().find(g=>String(g.id||'')===String(id||''))||null; } function accessWord(value){ return value==='block'?t('groups.blocked','Blocked'):t('groups.allowed','Allowed'); } function renderGroupSelect(select,selected='',includeNone=true){ if(!select)return; const options=[]; if(includeNone)options.push(``); for(const g of clientGroups())options.push(``); select.innerHTML=options.join(''); select.value=selected||''; } function clientQuickSearchValue(){ return String($('client-quick-search')?.value||'').trim().toLocaleLowerCase(); } function clientMatchesQuickSearch(peer){ const query=clientQuickSearchValue(); if(!query)return true; const statusBits=[]; if(peer?.schedule_disabled)statusBits.push(t('clients.status_schedule_blocked','Blocked by schedule'),t('clients.schedule_blocked_short','Schedule · blocked')); else if(peer?.expired_disabled)statusBits.push(t('clients.status_expired_disabled','Expired · disabled'),t('clients.expired_disabled_short','Expired · disabled')); else statusBits.push(online(peer)?t('common.online','Online'):t('common.offline','Offline')); const haystack=[ peer?.name, peer?.group_name, peer?.vpn_address, (peer?.remote_networks||[]).join(' '), peer?.persistent_keepalive, peer?.endpoint, peer?.client_endpoint, relayItems().find(item=>item.id===peer?.relay_vps_id)?.name, typeOf(peer), ...statusBits, peer?.preshared_key_enabled?t('clients.psk_short','PSK'):'', peer?.access_schedule_enabled?t('clients.schedule_short','Schedule'):'', ].map(value=>String(value||'').toLocaleLowerCase()).join(' '); return haystack.includes(query); } function syncClientQuickSearchClear(){ const clear=$('client-quick-search-clear'); if(clear)clear.hidden=!String($('client-quick-search')?.value||'').length; } function renderClients(d){ const peers=d.peers||[]; const body=$('client-body'); const add=$('add-client-button'); const manage=$('manage-groups-button'); const targets=$('extended-forward-target');if(targets){const selected=targets.value;const valid=peers.map(p=>({ip:String(p.vpn_address||'').split('/')[0],name:p.name||'Klient'})).filter(p=>/^\d{1,3}(?:\.\d{1,3}){3}$/.test(p.ip));targets.innerHTML=''+valid.map(p=>``).join('');if(valid.some(p=>p.ip===selected))targets.value=selected;} if(add)add.disabled=!d.wireguard?.config_exists; if(manage)manage.disabled=!d.wireguard?.config_exists; syncClientQuickSearchClear(); if(!peers.length){body.innerHTML=`${esc(t('clients.no_peers','No peers found'))}`;return;} const visible=peers.map((p,index)=>({p,index})).filter(item=>clientMatchesQuickSearch(item.p)); if(!visible.length){body.innerHTML=`${esc(t('clients.quick_search_empty','No clients match the search'))}`;return;} const rowsHtml=visible.map(({p,index})=>{ const grouped=Boolean(p.group_id&&p.group_name); const groupCell=grouped?`${esc(p.group_name)}${p.group_config_differs?`⚠`:''}`:'—'; const metaBits=[]; if(p.preshared_key_enabled)metaBits.push(t('clients.psk_short','PSK')); if(p.connection_mode==='relay'){const relay=relayItems().find(item=>item.id===p.relay_vps_id);metaBits.push(`${t('clients.relay_short','Relay')}: ${relay?.name||t('clients.relay_unknown','unavailable')}`);} if(p.expired_disabled)metaBits.push(t('clients.expired_disabled_short','Expired · disabled')); else if(Number(p.expires_at||0)>0)metaBits.push(expiryShort(Number(p.expires_at))); if(p.access_schedule_enabled)metaBits.push(p.schedule_disabled?t('clients.schedule_blocked_short','Schedule · blocked'):t('clients.schedule_short','Schedule')); const metaSuffix=metaBits.length?` · ${metaBits.map(esc).join(' · ')}`:''; return `
${esc(p.name||'Unnamed')}
${esc(typeOf(p))} · ${p.managed?esc(t('clients.managed','WGTools managed')):esc(t('clients.existing','Existing peer'))}${metaSuffix}
${(p.remote_networks||[]).length?'—':groupCell} ${esc(p.vpn_address||'—')} ${(p.remote_networks||[]).length?(p.remote_networks||[]).map(n=>`${esc(n)}`).join(''):'—'} ${esc(p.persistent_keepalive||'—')}${statusHtml(p)}${esc(ago(p.latest_handshake))}${fmtBytes(p.rx_bytes)} / ${fmtBytes(p.tx_bytes)}
${p.managed?``:''}${document.body.dataset.role==='admin'?``:''}
`}).join(''); renderPeerTable(body,rowsHtml,5); } function splitList(value){ return String(value||'').split(/[\n,]+/).map(x=>x.trim()).filter(Boolean); } function sameList(a,b){ const x=[...(a||[])].sort(), y=[...(b||[])].sort(); return x.length===y.length && x.every((v,i)=>v===y[i]); } function modalShow(id,show=true){ const el=$(id); if(el)el.hidden=!show; if(id==='audit-modal'&&!show)stopAuditAutoRefresh(); document.body.style.overflow=show?'hidden':''; } const CLIENT_EDITOR_TABS=['basic','policy','config','security']; function activateClientTab(name,focusId=''){ let target=CLIENT_EDITOR_TABS.includes(name)?name:'basic'; const wanted=$(`client-tab-button-${target}`); if(!wanted||wanted.hidden||wanted.disabled)target='basic'; document.querySelectorAll('[data-client-tab]').forEach(button=>{const active=button.dataset.clientTab===target;button.classList.toggle('active',active);button.setAttribute('aria-selected',active?'true':'false');button.tabIndex=active?0:-1;}); document.querySelectorAll('[data-client-tab-panel]').forEach(panel=>{panel.hidden=panel.dataset.clientTabPanel!==target;}); const body=document.querySelector('.client-editor-body'); if(body)body.scrollTop=0; if(focusId)setTimeout(()=>$(`${focusId}`)?.focus(),20); } function syncClientTabAvailability(){ const form=$('client-editor-form'); const managed=form?.dataset.managed==='true'; const site=$('client-type')?.value==='site_to_site'; const grouped=Boolean($('client-group')?.value)&&managed&&!site; const visibility={basic:true,policy:grouped,config:managed,security:managed}; for(const name of CLIENT_EDITOR_TABS){const button=$(`client-tab-button-${name}`);if(button)button.hidden=!visibility[name];} const active=document.querySelector('[data-client-tab].active')?.dataset.clientTab||'basic'; if(!visibility[active])activateClientTab('basic'); } const ENDPOINT_HISTORY_KEY='wgtools.endpointHistory'; function serverListenPort(){ return Number(snapshot?.listen_port||snapshot?.config?.interface?.listen_port||51820); } function relayItems(){ return (snapshot?.vps_relays||[]).filter(item=>item&&item.status==='installed'); } function relayEndpoint(item){ if(!item)return {host:'',port:0,text:''}; const host=String(item.endpoint_domain||item.host||'').trim(); const port=Number(item.relay_port||0); return {host,port,text:host&&port?`${host}:${port}`:''}; } function renderClientRelaySelect(selected=''){ const select=$('client-relay-vps'); if(!select)return; const items=relayItems(); select.innerHTML=items.map(item=>``).join(''); if(selected&&items.some(item=>item.id===selected))select.value=selected; else if(items.length)select.value=items[0].id; } function selectedClientRelay(){ const id=$('client-relay-vps')?.value||''; return relayItems().find(item=>item.id===id)||null; } function syncClientConnectionFields(){ const form=$('client-editor-form'); const managed=form?.dataset.managed==='true'; const items=relayItems(); const hasRelay=managed&&items.length>0; setHidden('client-relay-connection-section',!hasRelay); const mode=hasRelay?($('client-connection-mode')?.value||'direct'):'direct'; if($('client-connection-mode')&&!hasRelay)$('client-connection-mode').value='direct'; const relayMode=hasRelay&&mode==='relay'; setHidden('client-relay-vps-field',!relayMode); setHidden('client-relay-endpoint-note',!relayMode); const host=$('client-server-host'),port=$('client-server-port'); if(!managed)return; if(relayMode){ if(form&&form.dataset.connectionPrevious!=='relay'){form.dataset.directHost=host?.value||'';form.dataset.directPort=String(port?.value||serverListenPort());} const relay=selectedClientRelay(); const endpoint=relayEndpoint(relay); if(host){host.value=endpoint.host;host.readOnly=true;host.required=false;} if(port){port.value=String(endpoint.port||serverListenPort());port.readOnly=true;} const note=$('client-relay-endpoint-note'); if(note)note.textContent=t('clients.relay_endpoint_note','The generated client config will connect to {endpoint}. The WireGuard server itself remains on this WGTools host.').replace('{endpoint}',endpoint.text||'—'); }else{ if(host){host.readOnly=false;host.required=true;if(form?.dataset.connectionPrevious==='relay')host.value=form.dataset.directHost||'';} if(port){port.value=String(form?.dataset.directPort||serverListenPort());port.readOnly=true;} } if(form)form.dataset.connectionPrevious=relayMode?'relay':'direct'; } function loadEndpointHistory(){ try{ const value=JSON.parse(localStorage.getItem(ENDPOINT_HISTORY_KEY)||'[]'); return Array.isArray(value)?value.filter(x=>typeof x==='string'&&x.trim()).slice(0,12):[]; } catch{return [];} } function saveEndpointHistory(host){ const value=String(host||'').trim(); if(!value)return; const next=[value,...loadEndpointHistory().filter(x=>x!==value)].slice(0,12); try{localStorage.setItem(ENDPOINT_HISTORY_KEY,JSON.stringify(next));}catch{} renderEndpointHistory(); } function renderEndpointHistory(){ const list=$('client-endpoint-history'); if(list)list.innerHTML=loadEndpointHistory().map(host=>``).join(''); } function splitEndpoint(endpoint){ const value=String(endpoint||'').trim(); const fallbackPort=serverListenPort(); if(!value)return {host:'',port:fallbackPort}; const bracket=value.match(/^\[([^\]]+)\](?::(\d+))?$/); if(bracket)return {host:`[${bracket[1]}]`,port:Number(bracket[2]||fallbackPort)}; const m=value.match(/^(.*):(\d+)$/); if(m&&m[1])return {host:m[1],port:Number(m[2])}; return {host:value,port:fallbackPort}; } function joinEndpoint(host,port){ const h=String(host||'').trim(); return h?`${h}:${Number(port||serverListenPort())}`:''; } function siteToSiteNetworks(){ const out=[]; const seen=new Set(); for(const peer of (snapshot?.peers||[]))for(const raw of (peer?.remote_networks||[])){const value=String(raw||'').trim();if(!value||seen.has(value))continue;seen.add(value);out.push(value);} return out; } function localProtectedNetworks(){ const lan=snapshot?.config?.detected?.local_network||snapshot?.system?.local_network; return [lan,...siteToSiteNetworks()].filter(Boolean); } function presetRoutes(preset){ const vpn=snapshot?.config?.detected?.vpn_network; const lan=snapshot?.config?.detected?.local_network||snapshot?.system?.local_network; const site=siteToSiteNetworks(); if(preset==='full'||preset==='full_except_local')return ['0.0.0.0/0']; if(preset==='vpn')return vpn?[vpn]:[]; if(preset==='vpn_lan')return [vpn,lan,...site].filter(Boolean); return []; } function routePresetFor(routes, protectLocal=false){ const vpn=snapshot?.config?.detected?.vpn_network; const lan=snapshot?.config?.detected?.local_network||snapshot?.system?.local_network; const list=routes||[]; const site=siteToSiteNetworks(); if(protectLocal&&list.includes('0.0.0.0/0'))return 'full_except_local'; if(sameList(list,['0.0.0.0/0']))return 'full'; if(vpn&&sameList(list,[vpn]))return 'vpn'; if(vpn&&sameList(list,[vpn,lan,...site].filter(Boolean)))return 'vpn_lan'; return 'custom'; } function syncRoutePresetFields(){ const preset=$('client-route-preset')?.value; const grouped=Boolean($('client-group')?.value); const protectLocal=preset==='full_except_local'&&!grouped; setHidden('client-local-access-exceptions-field',!protectLocal); setHidden('client-protected-networks-reference',!protectLocal); if(!protectLocal&&$('client-local-access-exceptions'))$('client-local-access-exceptions').value=''; const list=$('client-protected-networks-list'); if(list)list.textContent=protectLocal?localProtectedNetworks().join('\n'):''; } function applyRoutePreset(clearCustom=false){ const preset=$('client-route-preset')?.value; const field=$('client-allowed-ips'); if(!field)return; syncRoutePresetFields(); if(preset==='custom'){if(clearCustom)field.value='';return;} field.value=presetRoutes(preset).join('\n'); } function setClientEditorManaged(managed){ setHidden('client-basic-managed-fields',!managed); setHidden('client-config-fields',!managed); setHidden('client-managed-options-section',!managed); setHidden('unmanaged-client-note',managed); const host=$('client-server-host'),allowed=$('client-allowed-ips'); if(host){host.required=managed;host.disabled=!managed;} if(allowed){allowed.required=managed;allowed.disabled=!managed;} syncClientTabAvailability(); syncClientConnectionFields(); } function syncClientTypeFields(){ const siteToSite=$('client-type')?.value==='site_to_site'; setHidden('client-remote-networks-field',!siteToSite); const remote=$('client-remote-networks');if(remote)remote.required=siteToSite; setHidden('client-group-field',siteToSite||$('client-editor-form')?.dataset.managed!=='true'); if(siteToSite&&$('client-group'))$('client-group').value=''; syncClientGroupFields(); syncClientExpiryFields(); syncClientScheduleFields(); } function uniqueDuplicateName(base){ const suffix=t('clients.duplicate_suffix','copy'); const stem=String(base||'Peer').trim()||'Peer'; const used=new Set((snapshot?.peers||[]).map(p=>String(p.name||'').trim().toLocaleLowerCase())); let candidate=`${stem} ${suffix}`; let n=2; while(used.has(candidate.toLocaleLowerCase()))candidate=`${stem} ${suffix} ${n++}`; return candidate; } function policySelectOptions(select,mode,current,groupValue){ if(!select)return; const items=[]; if(mode==='inherit')items.push({v:'inherit',label:`${t('groups.inherit','Inherit')} (${accessWord(groupValue)})`}); items.push({v:'allow',label:t('groups.allow','Allow')},{v:'block',label:t('groups.block','Block')}); select.innerHTML=items.map(x=>``).join(''); select.value=items.some(x=>x.v===current)?current:(mode==='inherit'?'inherit':'allow'); } function effectiveClientPolicy(){ const group=groupById($('client-group')?.value); if(!group)return null; const gp=group.policy||{}; const mode=$('client-policy-mode')?.value||'inherit'; const internetValue=$('client-internet-access')?.value||'inherit'; const localValue=$('client-local-access')?.value||'inherit'; const internet=mode==='inherit'&&internetValue==='inherit'?(gp.internet_access||'allow'):internetValue; const local=mode==='inherit'&&localValue==='inherit'?(gp.local_access||'allow'):localValue; const groupAllow=mode==='inherit'?(gp.allow||[]):[]; const groupDeny=mode==='inherit'?(gp.deny||[]):[]; return {internet,local,allow:[...groupAllow,...splitList($('client-policy-allow')?.value)],deny:[...groupDeny,...splitList($('client-policy-deny')?.value)]}; } function renderClientPolicyPreview(){ const el=$('client-policy-preview'); const policy=effectiveClientPolicy(); if(!el)return; if(!policy){el.innerHTML='';return;} const allow=policy.allow.length?policy.allow.join(', '):t('groups.none','None'); const deny=policy.deny.length?policy.deny.join(', '):t('groups.none','None'); el.innerHTML=`
${esc(t('groups.internet_access','Internet access'))}${esc(accessWord(policy.internet))}
${esc(t('groups.local_access','Local networks'))}${esc(accessWord(policy.local))}
${esc(t('groups.effective_allow','Allowed exceptions'))}${esc(allow)}
${esc(t('groups.effective_deny','Blocked exceptions'))}${esc(deny)}
`; } function syncClientGroupPolicyMode(){ const group=groupById($('client-group')?.value); const mode=$('client-policy-mode')?.value||'inherit'; if(!group)return; const internet=$('client-internet-access')?.value||'inherit', local=$('client-local-access')?.value||'inherit'; policySelectOptions($('client-internet-access'),mode,internet,group.policy?.internet_access||'allow'); policySelectOptions($('client-local-access'),mode,local,group.policy?.local_access||'allow'); const allowLabel=$('client-policy-allow-label'),denyLabel=$('client-policy-deny-label'); if(allowLabel)allowLabel.textContent=mode==='inherit'?t('groups.additional_allowed','Additional allowed addresses'):t('groups.allowed_addresses','Allowed addresses / networks'); if(denyLabel)denyLabel.textContent=mode==='inherit'?t('groups.additional_blocked','Additional blocked addresses'):t('groups.blocked_addresses','Blocked addresses / networks'); renderClientPolicyPreview(); } function clientFormDiffersFromGroup(){ const form=$('client-editor-form'),group=groupById($('client-group')?.value); if(form?.dataset.mode!=='edit'||!group||$('client-config-override')?.checked)return false; const d=group.resolved_defaults||group.defaults||{}; return ($('client-route-preset')?.value||'')!==(d.route_preset||'full') || !sameList(splitList($('client-allowed-ips')?.value),(d.client_allowed_ips||presetRoutes(d.route_preset||'full'))) || !sameList(splitList($('client-dns')?.value),(d.dns||[])) || Number($('client-keepalive')?.value||0)!==Number(d.persistent_keepalive??25); } function setClientConfigFieldsDisabled(disabled){ for(const id of ['client-route-preset','client-dns','client-allowed-ips','client-keepalive']){const el=$(id);if(el)el.disabled=Boolean(disabled);} } function syncClientGroupConfigMode(){ const form=$('client-editor-form'); const group=groupById($('client-group')?.value); const grouped=Boolean(group)&&form?.dataset.managed==='true'&&$('client-type')?.value!=='site_to_site'; setHidden('client-group-defaults-wrap',!grouped); if(!grouped){setClientConfigFieldsDisabled(false);setHidden('client-group-config-warning',true);setHidden('apply-group-defaults-button',true);return;} const custom=Boolean($('client-config-override')?.checked); setClientConfigFieldsDisabled(!custom); const differs=!custom&&clientFormDiffersFromGroup(); setHidden('client-group-config-warning',!differs); setHidden('apply-group-defaults-button',!differs); } function syncClientGroupConfigWarning(){syncClientGroupConfigMode();} function syncClientGroupFields(){ const form=$('client-editor-form'); const managed=form?.dataset.managed==='true'; const site=$('client-type')?.value==='site_to_site'; const group=managed&&!site?groupById($('client-group')?.value):null; setHidden('client-group-policy-section',!group); syncClientTabAvailability(); if(!group){syncRoutePresetFields();syncClientGroupConfigMode();return;} syncClientGroupPolicyMode(); syncRoutePresetFields(); syncClientGroupConfigMode(); } function applySelectedGroupDefaults(showToast=true){ const group=groupById($('client-group')?.value); if(!group)return; const d=group.resolved_defaults||group.defaults||{}; $('client-keepalive').value=d.persistent_keepalive??25; $('client-dns').value=(d.dns||[]).join(', '); $('client-route-preset').value=d.route_preset||'full'; $('client-allowed-ips').value=(d.client_allowed_ips||presetRoutes(d.route_preset||'full')).join('\n'); syncRoutePresetFields(); syncClientGroupConfigMode(); if(showToast)toast(t('groups.defaults_applied','Group client defaults applied. Save the client to use the updated template.')); } function toLocalDateTimeValue(timestamp){ if(!timestamp)return ''; const d=new Date(Number(timestamp)*1000); if(Number.isNaN(d.getTime()))return ''; const local=new Date(d.getTime()-d.getTimezoneOffset()*60000); return local.toISOString().slice(0,16); } function syncClientExpiryFields(){ const preset=$('client-expiry-preset')?.value||'never'; const siteToSite=$('client-type')?.value==='site_to_site'; setHidden('client-expiry-custom-field',preset!=='custom'); setHidden('client-expiry-action-field',preset==='never'||siteToSite); if(preset==='custom')ensureExpiryDateTimeValue(); if(siteToSite&&$('client-expiry-delete'))$('client-expiry-delete').checked=true; } function expiryFromForm(){ const preset=$('client-expiry-preset')?.value||'never'; const now=Math.floor(Date.now()/1000); const seconds={"1h":3600,"3h":10800,"6h":21600,"1d":86400}[preset]; if(seconds)return now+seconds; if(preset!=='custom')return 0; const raw=$('client-expiry-custom')?.value||''; const ms=Date.parse(raw); return Number.isFinite(ms)?Math.floor(ms/1000):0; } function ensureExpiryDateTimeValue(){ const field=$('client-expiry-custom'); if(!field||field.value)return; field.value=toLocalDateTimeValue(Math.floor(Date.now()/1000)); } function selectedScheduleDays(){return [...document.querySelectorAll('[data-schedule-day]')].filter(el=>el.checked).map(el=>Number(el.dataset.scheduleDay)).filter(n=>Number.isInteger(n)&&n>=0&&n<=6);} function setScheduleDays(days){const chosen=new Set((days||[]).map(Number));document.querySelectorAll('[data-schedule-day]').forEach(el=>{el.checked=chosen.has(Number(el.dataset.scheduleDay));});} function syncClientScheduleFields(){ const siteToSite=$('client-type')?.value==='site_to_site'; const enabled=Boolean($('client-schedule-enabled')?.checked)&&!siteToSite; setHidden('client-schedule-title',siteToSite); setHidden('client-schedule-section',siteToSite); setHidden('client-schedule-editor',!enabled); setHidden('client-peer-isolation-field',siteToSite); if(siteToSite&&$('client-schedule-enabled'))$('client-schedule-enabled').checked=false; if(siteToSite&&$('client-peer-isolation'))$('client-peer-isolation').checked=false; } function expiryShort(timestamp){ const seconds=Math.max(0,Number(timestamp||0)-Math.floor(Date.now()/1000)); if(seconds<=0)return t('clients.expired','Expired'); if(seconds<3600)return t('clients.expires_minutes','Expires in {n}m').replace('{n}',String(Math.max(1,Math.ceil(seconds/60)))); if(seconds<86400)return t('clients.expires_hours','Expires in {n}h').replace('{n}',String(Math.max(1,Math.ceil(seconds/3600)))); return t('clients.expires_days','Expires in {n}d').replace('{n}',String(Math.max(1,Math.ceil(seconds/86400)))); } function syncClientPskFields(){ const form=$('client-editor-form'); const editing=form?.dataset.mode==='edit'; const managed=form?.dataset.managed==='true'; setHidden('client-rotate-credentials-wrap',!(editing&&managed)); } async function rotateClientCredentials(){ const form=$('client-editor-form'),button=$('rotate-credentials-button'); const publicKey=form?.dataset.publicKey||''; if(!publicKey||!button)return; const pskEnabled=form?.dataset.hadPsk==='true'; const fallback=pskEnabled?'Generate a new client key pair and a new PSK now? An active session for this client will be disconnected immediately. Send a new config or QR afterward.':'Generate a new client key pair now? An active session for this client will be disconnected immediately. Send a new config or QR afterward.'; if(!confirm(t(pskEnabled?'clients.credentials_rotate_confirm_psk':'clients.credentials_rotate_confirm',fallback)))return; button.disabled=true; operationStatus('client-editor-status',t('clients.credentials_rotating','Generating new client keys and disconnecting the old client session…'),'working'); try{ const r=await fetch('/api/clients/credentials/rotate',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({public_key:publicKey}),keepalive:true}); const d=await r.json(); if(!r.ok)throw new Error(d.error||'Client key rotation failed'); if(d.public_key)form.dataset.publicKey=d.public_key; form.dataset.hadPsk=String(Boolean(d.psk_enabled)); syncClientPskFields(); operationStatus('client-editor-status',t('clients.credentials_rotated','Client keys changed. If the client was connected, its old session was disconnected. The old config no longer works; send a new config or QR before reconnecting.'),'success'); toast(t('clients.credentials_rotated_short','Client keys changed — new config required')); // Key rotation intentionally removes the old runtime peer. If this panel // is being reached through that very client, the next status refresh can // lose its network path even though the rotation itself succeeded. A // refresh failure must therefore never overwrite the successful result. fetchSnapshot().then(()=>syncClientPskFields()).catch(()=>{}); }catch(e){ const message=String(e?.message||e||''); const networkLost=/networkerror|failed to fetch|network request failed|load failed/i.test(message); operationStatus( 'client-editor-status', networkLost ? t('clients.credentials_connection_lost','The connection to WGTools was interrupted. If this panel was opened through the client whose keys were just rotated, this is expected: its old WireGuard session is disconnected immediately. Reconnect to WGTools by another path and issue the new config/QR.') : message, networkLost?'working':'error' ); }finally{button.disabled=false;} } function usePanelHostForClient(){ const field=$('client-server-host');if(!field)return; let host=String(location.hostname||'').trim(); if(host.startsWith('[')&&host.endsWith(']'))host=host.slice(1,-1); if(!host){toast(t('clients.use_panel_host_failed','Could not determine the panel address from the browser URL.'));return;} field.value=host;field.dispatchEvent(new Event('input',{bubbles:true}));field.focus(); toast(t('clients.use_panel_host_done','Panel address inserted: {host}').replace('{host}',host)); } function openClientEditor(peer=null,options={}){ const duplicate=Boolean(options.duplicate&&peer); const editing=Boolean(peer)&&!duplicate; const source=peer; const form=$('client-editor-form'); if(!form)return; form.dataset.mode=editing?'edit':'create'; form.dataset.duplicate=String(duplicate); form.dataset.publicKey=editing?(source?.public_key||''):''; form.dataset.managed=editing?String(Boolean(source?.managed)):'true'; form.dataset.hadPsk=String(Boolean(editing&&source?.preshared_key_enabled)); $('client-editor-title').textContent=editing?t('clients.edit_title','Edit client'):t('clients.create_title','Create client'); $('client-editor-subtitle').textContent=editing?t('clients.edit_subtitle','Update the server-side peer. Changes are applied without restarting WireGuard.'):t('clients.create_subtitle','Create a WireGuard peer and generate its client configuration.'); $('client-name').value=duplicate?uniqueDuplicateName(source?.name):source?.name||''; $('client-type').value=(source?.remote_networks||[]).length?'site_to_site':'client'; $('client-vpn-address').value=duplicate?(snapshot?.next_free_address||''):(source?.vpn_address||snapshot?.next_free_address||''); $('client-keepalive').value=source?.persistent_keepalive??25; $('client-remote-networks').value=duplicate&&$('client-type').value==='site_to_site'?'':(source?.remote_networks||[]).join('\n'); const managed=duplicate||!editing||Boolean(source?.managed); setClientEditorManaged(managed); form.dataset.managed=String(managed); renderGroupSelect($('client-group'),source?.group_id||'',true); if($('client-type').value==='site_to_site'||!managed)$('client-group').value=''; $('client-policy-mode').value=source?.policy_mode||'inherit'; $('client-policy-allow').value=(source?.policy_allow||[]).join(', '); $('client-policy-deny').value=(source?.policy_deny||[]).join(', '); if(managed){ const routes=source?.managed&&source?.client_allowed_ips?.length?source.client_allowed_ips:['0.0.0.0/0']; const endpoint=splitEndpoint(source?.managed?source?.client_endpoint:''); $('client-server-host').value=endpoint.host; $('client-server-port').value=serverListenPort(); $('client-dns').value=source?.managed?(source?.client_dns||[]).join(', '):''; $('client-allowed-ips').value=routes.join('\n'); $('client-local-access-exceptions').value=(source?.managed?source?.local_access_exceptions||[]:[]).join(', '); const wantedRelay=(editing||duplicate)?(source?.relay_vps_id||''):''; renderClientRelaySelect(wantedRelay); const sourceRelayAvailable=Boolean(wantedRelay&&relayItems().some(item=>item.id===wantedRelay)); $('client-connection-mode').value=(editing||duplicate)&&source?.connection_mode==='relay'&&sourceRelayAvailable?'relay':'direct'; form.dataset.directHost=$('client-connection-mode').value==='relay'?'':endpoint.host; form.dataset.directPort=String(serverListenPort()); form.dataset.connectionPrevious=''; $('client-route-preset').value=source?.client_route_preset||routePresetFor(routes,Boolean(source?.managed&&source?.protect_local_networks)); $('client-use-psk').checked=(editing||duplicate)?Boolean(source?.preshared_key_enabled):true; $('client-expiry-preset').value=(editing&&Number(source?.expires_at||0)>0)?'custom':'never'; $('client-expiry-custom').value=(editing&&Number(source?.expires_at||0)>0)?toLocalDateTimeValue(source.expires_at):''; $('client-expiry-delete').checked=(source?.expiration_action||'delete')!=='disable'; setHidden('client-expired-disabled-note',!Boolean(editing&&source?.expired_disabled)); $('client-peer-isolation').checked=Boolean((editing||duplicate)&&source?.peer_isolation); $('client-schedule-enabled').checked=Boolean((editing||duplicate)&&source?.access_schedule_enabled); setScheduleDays((editing||duplicate)&&source?.access_schedule_days?.length?source.access_schedule_days:[0,1,2,3,4]); $('client-schedule-start').value=(editing||duplicate)?(source?.access_schedule_start||'08:00'):'08:00'; $('client-schedule-end').value=(editing||duplicate)?(source?.access_schedule_end||'19:00'):'19:00'; setHidden('client-schedule-disabled-note',!Boolean(editing&&source?.schedule_disabled)); }else{$('client-server-host').value='';$('client-server-port').value=serverListenPort();$('client-dns').value='';$('client-allowed-ips').value='';$('client-local-access-exceptions').value='';$('client-route-preset').value='custom';$('client-use-psk').checked=true;$('client-expiry-preset').value='never';$('client-expiry-custom').value='';$('client-expiry-delete').checked=true;setHidden('client-expired-disabled-note',true);$('client-peer-isolation').checked=false;$('client-schedule-enabled').checked=false;setScheduleDays([0,1,2,3,4]);$('client-schedule-start').value='08:00';$('client-schedule-end').value='19:00';setHidden('client-schedule-disabled-note',true);if($('client-connection-mode'))$('client-connection-mode').value='direct';renderClientRelaySelect();} syncClientTypeFields(); const group=groupById($('client-group').value); policySelectOptions($('client-internet-access'),$('client-policy-mode').value,source?.internet_access||'inherit',group?.policy?.internet_access||'allow'); policySelectOptions($('client-local-access'),$('client-policy-mode').value,source?.local_access||'inherit',group?.policy?.local_access||'allow'); if(group){const legacyCustom=editing&&!source?.config_mode&&Boolean(source?.group_config_differs);$('client-config-override').checked=duplicate?Boolean(source?.config_mode==='custom'):(editing?Boolean(source?.config_mode==='custom'||legacyCustom):false);if(!editing&&!duplicate)applySelectedGroupDefaults(false);}else $('client-config-override').checked=false; syncClientGroupFields(); syncClientGroupConfigWarning(); syncClientExpiryFields(); syncClientScheduleFields(); syncClientPskFields(); syncClientConnectionFields(); renderEndpointHistory(); activateClientTab('basic'); operationStatus('client-editor-status',duplicate?(($('client-type').value==='site_to_site'?`${t('clients.duplicate_ready','A copy is ready.')}\n${t('clients.duplicate_site_hint','Remote networks were cleared to prevent duplicate routes.')}`:t('clients.duplicate_ready','A copy is ready.'))):'','info'); modalShow('client-editor-modal',true); setTimeout(()=>$('client-name')?.focus(),30); } function clientPayloadFromForm(){ const managed=$('client-editor-form')?.dataset.managed==='true'; const siteToSite=$('client-type').value==='site_to_site'; const host=managed?$('client-server-host').value.trim():''; const port=managed?Number($('client-server-port').value||serverListenPort()):serverListenPort(); const groupId=managed&&!siteToSite?$('client-group')?.value||'':''; const protectLocal=managed&&!groupId&&$('client-route-preset')?.value==='full_except_local'; const connectionMode=managed&&relayItems().length?($('client-connection-mode')?.value||'direct'):'direct'; return {name:$('client-name').value.trim(),type:$('client-type').value,vpn_address:$('client-vpn-address').value.trim(),remote_networks:siteToSite?splitList($('client-remote-networks').value):[],persistent_keepalive:Number($('client-keepalive').value||0),endpoint:managed&&connectionMode==='direct'?joinEndpoint(host,port):'',client_allowed_ips:managed?splitList($('client-allowed-ips').value):[],route_preset:managed?$('client-route-preset').value:'',protect_local_networks:protectLocal,local_access_exceptions:protectLocal?splitList($('client-local-access-exceptions').value):[],dns:managed?splitList($('client-dns').value):[],group_id:groupId,policy_mode:groupId?$('client-policy-mode').value:'',internet_access:groupId?$('client-internet-access').value:'',local_access:groupId?$('client-local-access').value:'',policy_allow:groupId?splitList($('client-policy-allow').value):[],policy_deny:groupId?splitList($('client-policy-deny').value):[],config_mode:groupId?($('client-config-override')?.checked?'custom':'inherit'):'',use_preshared_key:managed?Boolean($('client-use-psk')?.checked):false,peer_isolation:managed&&!siteToSite?Boolean($('client-peer-isolation')?.checked):false,expires_at:managed?expiryFromForm():0,expiration_action:managed&&!siteToSite&&$('client-expiry-preset')?.value!=='never'&&!$('client-expiry-delete')?.checked?'disable':'delete',access_schedule_enabled:managed&&!siteToSite?Boolean($('client-schedule-enabled')?.checked):false,access_schedule_days:managed&&!siteToSite&&$('client-schedule-enabled')?.checked?selectedScheduleDays():[],access_schedule_start:managed?($('client-schedule-start')?.value||'08:00'):'08:00',access_schedule_end:managed?($('client-schedule-end')?.value||'19:00'):'19:00',connection_mode:connectionMode,relay_vps_id:connectionMode==='relay'?($('client-relay-vps')?.value||''):''}; } async function saveClient(event){ event.preventDefault(); const form=$('client-editor-form'),button=$('save-client-button');if(!form||!button)return;const editing=form.dataset.mode==='edit',managed=form.dataset.managed==='true',payload=clientPayloadFromForm();if(editing)payload.public_key=form.dataset.publicKey; if(!payload.name||!payload.vpn_address){operationStatus('client-editor-status',t('clients.required','Name and VPN address are required.'),'error');activateClientTab('basic',!payload.name?'client-name':'client-vpn-address');return;} if(managed&&payload.connection_mode==='direct'&&!$('client-server-host')?.value.trim()){operationStatus('client-editor-status',t('clients.server_host_required','Server address / domain is required for a generated client configuration.'),'error');activateClientTab('basic','client-server-host');return;} if(managed&&payload.connection_mode==='relay'&&!payload.relay_vps_id){operationStatus('client-editor-status',t('clients.relay_required','Choose a VPS Relay for this client.'),'error');activateClientTab('config','client-relay-vps');return;} if(managed&&!payload.client_allowed_ips.length){operationStatus('client-editor-status',t('clients.allowed_ips_required','Enter at least one AllowedIPs network for the client configuration.'),'error');activateClientTab('config','client-allowed-ips');return;} if(managed&&$('client-expiry-preset')?.value==='custom'&&(!payload.expires_at||payload.expires_at<=Math.floor(Date.now()/1000))){operationStatus('client-editor-status',t('clients.expiration_future_required','Choose a future expiration date and time.'),'error');activateClientTab('security','client-expiry-custom');return;} if(managed&&payload.access_schedule_enabled&&!payload.access_schedule_days.length){operationStatus('client-editor-status',t('clients.schedule_days_required','Choose at least one day for the access schedule.'),'error');activateClientTab('security');return;} if(managed&&payload.access_schedule_enabled&&(!payload.access_schedule_start||!payload.access_schedule_end)){operationStatus('client-editor-status',t('clients.schedule_time_required','Set both start and end times for the access schedule.'),'error');activateClientTab('security',!payload.access_schedule_start?'client-schedule-start':'client-schedule-end');return;} if(payload.type==='site_to_site'&&!payload.remote_networks.length){operationStatus('client-editor-status',t('clients.remote_required','Enter at least one remote network for a Site-to-site peer.'),'error');activateClientTab('basic','client-remote-networks');return;} const others=(snapshot?.peers||[]).filter(p=>!editing||p.public_key!==form.dataset.publicKey); if(others.some(p=>String(p.name||'').trim().toLocaleLowerCase()===payload.name.toLocaleLowerCase())){operationStatus('client-editor-status',t('clients.duplicate_name_error','A peer with this name already exists.'),'error');activateClientTab('basic','client-name');return;} const wantedIp=payload.vpn_address.split('/')[0]; if(others.some(p=>String(p.vpn_address||'').split('/')[0]===wantedIp)){operationStatus('client-editor-status',t('clients.duplicate_address_error','This VPN address is already used by another peer.'),'error');activateClientTab('basic','client-vpn-address');return;} button.disabled=true; operationStatus('client-editor-status',editing?t('clients.updating','Updating client…'):t('clients.creating','Creating keys and applying client…'),'working'); try{const r=await fetch(editing?'/api/clients/update':'/api/clients/create',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(payload)});const d=await r.json();if(!r.ok)throw new Error(d.error||'Operation failed');operationStatus('client-editor-status',d.message||t('clients.saved','Client saved'),'success');if(managed&&payload.connection_mode==='direct')saveEndpointHistory($('client-server-host')?.value);await fetchSnapshot();modalShow('client-editor-modal',false);toast(t('clients.saved','Client saved'));if(!editing&&managed&&d.public_key)await openClientConfig(d.public_key);}catch(e){operationStatus('client-editor-status',e.message,'error');}finally{button.disabled=false;} } async function deleteClient(peer){if(!peer)return;if(!confirm(`${t('clients.delete_confirm','Delete this client from WireGuard? A backup of the selected interface configuration will be created first.')}\n\n${peer.name||peer.vpn_address||''}`))return;try{const r=await fetch('/api/clients/delete',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({public_key:peer.public_key})});const d=await r.json();if(!r.ok)throw new Error(d.error||'Delete failed');toast(t('clients.deleted','Client deleted'));await fetchSnapshot();}catch(e){toast(e.message);}} function groupPolicySummary(group){const p=group.policy||{};return `${t('groups.internet_short','Internet')}: ${accessWord(p.internet_access||'allow')} · ${t('groups.local_short','Local')}: ${accessWord(p.local_access||'allow')}`;} function groupDefaultsSummary(group){const d=group.resolved_defaults||group.defaults||{};const routeKey={full:'clients.route_full',full_except_local:'clients.route_full_except_local',vpn_lan:'clients.route_vpn_lan',vpn:'clients.route_vpn',custom:'clients.route_custom'}[d.route_preset]||'clients.route_custom';return `${t('groups.new_clients_short','New clients')}: ${t(routeKey,d.route_preset||'Custom')} · DNS ${(d.dns||[]).join(', ')||'—'} · KA ${d.persistent_keepalive??25}`;} function renderGroups(){ const list=$('groups-list');if(!list)return;const groups=clientGroups();if(!groups.length){list.innerHTML=`
${esc(t('groups.empty','No client groups yet. Create one to reuse access policies and client defaults.'))}
`;return;} list.innerHTML=groups.map((g,i)=>`
${esc(g.name||'')}${esc(t('groups.members_count','{count} clients').replace('{count}',String(g.member_count||0)))}
${g.description?`
${esc(g.description)}
`:''}
${esc(groupPolicySummary(g))}
${esc(groupDefaultsSummary(g))}
`).join(''); } function openGroups(){renderGroups();modalShow('groups-modal',true);} function applyGroupRoutePreset(clearCustom=false){const preset=$('group-route-preset')?.value,field=$('group-allowed-ips');if(!field)return;if(preset==='custom'){if(clearCustom)field.value='';return;}field.value=presetRoutes(preset).join('\n');} function openGroupEditor(group=null){ const form=$('group-editor-form');if(!form)return;form.dataset.mode=group?'edit':'create';form.dataset.groupId=group?.id||'';$('group-editor-title').textContent=group?t('groups.edit_title','Edit group'):t('groups.create_title','Create group');$('group-name').value=group?.name||'';$('group-description').value=group?.description||'';$('group-internet-access').value=group?.policy?.internet_access||'allow';$('group-local-access').value=group?.policy?.local_access||'allow';$('group-policy-allow').value=(group?.policy?.allow||[]).join(', ');$('group-policy-deny').value=(group?.policy?.deny||[]).join(', ');const d=group?.resolved_defaults||group?.defaults||{};$('group-route-preset').value=d.route_preset||'full';$('group-allowed-ips').value=(d.client_allowed_ips||presetRoutes(d.route_preset||'full')).join('\n');$('group-dns').value=(d.dns||[]).join(', ');$('group-keepalive').value=d.persistent_keepalive??25;operationStatus('group-editor-status','');modalShow('group-editor-modal',true);setTimeout(()=>$('group-name')?.focus(),30); } function groupPayload(){return {name:$('group-name').value.trim(),description:$('group-description').value.trim(),internet_access:$('group-internet-access').value,local_access:$('group-local-access').value,policy_allow:splitList($('group-policy-allow').value),policy_deny:splitList($('group-policy-deny').value),route_preset:$('group-route-preset').value,client_allowed_ips:splitList($('group-allowed-ips').value),dns:splitList($('group-dns').value),persistent_keepalive:Number($('group-keepalive').value||0)};} async function saveGroup(event){event.preventDefault();const form=$('group-editor-form'),button=$('save-group-button');if(!form||!button)return;const editing=form.dataset.mode==='edit',payload=groupPayload();if(editing)payload.group_id=form.dataset.groupId;if(!payload.name){operationStatus('group-editor-status',t('groups.name_required','Group name is required.'),'error');$('group-name')?.focus();return;}if(!payload.client_allowed_ips.length){operationStatus('group-editor-status',t('groups.routes_required','Client routes cannot be empty.'),'error');return;}button.disabled=true;operationStatus('group-editor-status',editing?t('groups.updating','Updating group policy…'):t('groups.creating','Creating group…'),'working');try{const r=await fetch(editing?'/api/client-groups/update':'/api/client-groups/create',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(payload)});const d=await r.json();if(!r.ok)throw new Error(d.error||'Operation failed');await fetchSnapshot();renderGroups();modalShow('group-editor-modal',false);toast(editing?t('groups.updated','Group updated'):t('groups.created','Group created'));}catch(e){operationStatus('group-editor-status',e.message,'error');}finally{button.disabled=false;}} let deletingGroupId=''; function openGroupDelete(group){deletingGroupId=group?.id||'';if(!deletingGroupId)return;$('group-delete-text').textContent=t('groups.delete_message','Delete “{name}”? Client configurations are never deleted with a group.').replace('{name}',group.name||'');const targets=clientGroups().filter(g=>g.id!==deletingGroupId),target=$('group-delete-target');if(target){target.innerHTML=targets.map(g=>``).join('');target.value=targets[0]?.id||'';target.disabled=true;}const moveRadio=document.querySelector('input[name="group-delete-mode"][value="move"]');if(moveRadio)moveRadio.disabled=!targets.length;const unassignRadio=document.querySelector('input[name="group-delete-mode"][value="unassign"]');if(unassignRadio)unassignRadio.checked=true;operationStatus('group-delete-status','');modalShow('group-delete-modal',true);} async function confirmDeleteGroup(){const button=$('confirm-delete-group-button');if(!button||!deletingGroupId)return;const mode=document.querySelector('input[name="group-delete-mode"]:checked')?.value||'unassign';const moveTo=mode==='move'?$('group-delete-target').value:'';button.disabled=true;operationStatus('group-delete-status',t('groups.deleting','Updating clients and deleting group…'),'working');try{const r=await fetch('/api/client-groups/delete',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({group_id:deletingGroupId,move_to_group_id:moveTo})});const d=await r.json();if(!r.ok)throw new Error(d.error||'Delete failed');await fetchSnapshot();renderGroups();modalShow('group-delete-modal',false);toast(t('groups.deleted','Group deleted'));}catch(e){operationStatus('group-delete-status',e.message,'error');}finally{button.disabled=false;}} let currentConfigKey=''; let qrObjectUrl=''; let configFilename='wireguard-client.conf'; async function openClientConfig(publicKey){currentConfigKey=publicKey;modalShow('client-config-modal',true);$('client-config-text').value='';$('client-qr-image').hidden=true;$('client-qr-loading').hidden=false;$('client-qr-loading').textContent=t('clients.qr_loading','Generating QR…');try{const r=await fetch('/api/clients/config',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({public_key:publicKey})});const d=await r.json();if(!r.ok)throw new Error(d.error||t('clients.config_unavailable','Configuration unavailable'));$('client-config-text').value=d.config||'';configFilename=d.filename||'wireguard-client.conf';$('client-config-title').textContent=d.name||t('clients.config_title','Client configuration');const qr=await fetch('/api/clients/qr',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({public_key:publicKey})});if(!qr.ok){const err=await qr.json().catch(()=>({}));throw new Error(err.error||'QR failed');}const blob=await qr.blob();if(qrObjectUrl)URL.revokeObjectURL(qrObjectUrl);qrObjectUrl=URL.createObjectURL(blob);$('client-qr-image').src=qrObjectUrl;$('client-qr-image').hidden=false;$('client-qr-loading').hidden=true;}catch(e){$('client-qr-loading').textContent=e.message;toast(e.message);}} async function downloadClientConfig(){if(!currentConfigKey)return;try{const r=await fetch('/api/clients/config/download',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({public_key:currentConfigKey})});if(!r.ok){const d=await r.json().catch(()=>({}));throw new Error(d.error||'Download failed');}const blob=await r.blob();const url=URL.createObjectURL(blob);const a=document.createElement('a');a.href=url;a.download=configFilename;a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);}catch(e){toast(e.message);}} async function copyClientConfig(){const text=$('client-config-text')?.value||'';if(!text)return;try{await navigator.clipboard.writeText(text);toast(t('clients.copy_done','Configuration copied'));}catch{toast('Clipboard unavailable');}} function bindClientManagement(){ document.querySelectorAll('[data-client-tab]').forEach(button=>{button.addEventListener('click',()=>activateClientTab(button.dataset.clientTab));button.addEventListener('keydown',event=>{if(!['ArrowLeft','ArrowRight'].includes(event.key))return;const visible=CLIENT_EDITOR_TABS.map(name=>$(`client-tab-button-${name}`)).filter(item=>item&&!item.hidden&&!item.disabled);const index=visible.indexOf(button);if(index<0||!visible.length)return;event.preventDefault();const step=event.key==='ArrowRight'?1:-1;const next=visible[(index+step+visible.length)%visible.length];activateClientTab(next.dataset.clientTab);next.focus();});}); const clientSearch=$('client-quick-search'), clientSearchClear=$('client-quick-search-clear'); clientSearch?.addEventListener('input',()=>{syncClientQuickSearchClear();if(snapshot)renderClients(snapshot);}); clientSearchClear?.addEventListener('click',()=>{if(!clientSearch)return;clientSearch.value='';syncClientQuickSearchClear();clientSearch.focus();if(snapshot)renderClients(snapshot);}); syncClientQuickSearchClear(); $('client-expiry-custom')?.addEventListener('pointerdown',ensureExpiryDateTimeValue);$('client-expiry-custom')?.addEventListener('focus',ensureExpiryDateTimeValue); $('client-schedule-enabled')?.addEventListener('change',syncClientScheduleFields); $('add-client-button')?.addEventListener('click',()=>openClientEditor());$('manage-groups-button')?.addEventListener('click',openGroups);$('client-use-panel-host')?.addEventListener('click',usePanelHostForClient);$('client-editor-form')?.addEventListener('submit',saveClient);$('client-type')?.addEventListener('change',syncClientTypeFields);$('client-route-preset')?.addEventListener('change',()=>{applyRoutePreset(true);syncClientGroupConfigWarning();});$('client-allowed-ips')?.addEventListener('input',()=>{if($('client-route-preset')){$('client-route-preset').value='custom';syncRoutePresetFields();syncClientGroupConfigWarning();}});$('client-group')?.addEventListener('change',()=>{const form=$('client-editor-form');$('client-policy-mode').value='inherit';$('client-internet-access').value='inherit';$('client-local-access').value='inherit';$('client-policy-allow').value='';$('client-policy-deny').value='';$('client-config-override').checked=false;if($('client-group').value)applySelectedGroupDefaults(false);syncClientGroupFields();});$('client-policy-mode')?.addEventListener('change',syncClientGroupPolicyMode);$('client-internet-access')?.addEventListener('change',renderClientPolicyPreview);$('client-local-access')?.addEventListener('change',renderClientPolicyPreview);$('client-policy-allow')?.addEventListener('input',renderClientPolicyPreview);$('client-policy-deny')?.addEventListener('input',renderClientPolicyPreview);$('apply-group-defaults-button')?.addEventListener('click',()=>applySelectedGroupDefaults(true));$('client-config-override')?.addEventListener('change',syncClientGroupConfigMode);$('client-dns')?.addEventListener('input',syncClientGroupConfigWarning);$('client-keepalive')?.addEventListener('input',syncClientGroupConfigWarning);$('client-expiry-preset')?.addEventListener('change',syncClientExpiryFields);$('client-use-psk')?.addEventListener('change',syncClientPskFields);$('client-connection-mode')?.addEventListener('change',syncClientConnectionFields);$('client-relay-vps')?.addEventListener('change',syncClientConnectionFields);$('rotate-credentials-button')?.addEventListener('click',rotateClientCredentials);renderEndpointHistory(); $('client-body')?.addEventListener('click',e=>{const b=e.target.closest('[data-client-action]');if(!b||!snapshot)return;const peer=(snapshot.peers||[])[Number(b.dataset.clientIndex)];if(!peer)return;if(b.dataset.clientAction==='duplicate')openClientEditor(peer,{duplicate:true});else if(b.dataset.clientAction==='edit')openClientEditor(peer);else if(b.dataset.clientAction==='delete')deleteClient(peer);else if(b.dataset.clientAction==='config')openClientConfig(peer.public_key);}); $('create-group-button')?.addEventListener('click',()=>openGroupEditor());$('group-editor-form')?.addEventListener('submit',saveGroup);$('group-route-preset')?.addEventListener('change',()=>applyGroupRoutePreset(true));$('group-allowed-ips')?.addEventListener('input',()=>{if($('group-route-preset'))$('group-route-preset').value='custom';});$('groups-list')?.addEventListener('click',e=>{const b=e.target.closest('[data-group-action]');if(!b)return;const g=clientGroups()[Number(b.dataset.groupIndex)];if(!g)return;if(b.dataset.groupAction==='edit')openGroupEditor(g);else if(b.dataset.groupAction==='delete')openGroupDelete(g);});document.querySelectorAll('input[name="group-delete-mode"]').forEach(r=>r.addEventListener('change',()=>{$('group-delete-target').disabled=document.querySelector('input[name="group-delete-mode"]:checked')?.value!=='move';}));$('confirm-delete-group-button')?.addEventListener('click',confirmDeleteGroup); document.querySelectorAll('[data-modal-close]').forEach(b=>b.addEventListener('click',()=>modalShow(b.dataset.modalClose,false)));document.querySelectorAll('.modal-backdrop').forEach(m=>m.addEventListener('click',e=>{if(e.target===m)modalShow(m.id,false);}));document.addEventListener('keydown',e=>{if(e.key==='Escape')document.querySelectorAll('.modal-backdrop:not([hidden])').forEach(m=>modalShow(m.id,false));});$('download-config-button')?.addEventListener('click',downloadClientConfig);$('copy-config-button')?.addEventListener('click',copyClientConfig); } function traceMs(value){ if(value===null||value===undefined||value==='')return '—'; const n=Number(value); if(!Number.isFinite(n))return '—'; return `${n<10?n.toFixed(1):n.toFixed(0)} ${t('trace.ms','ms')}`; } function tracePrivateIpv4(ip){ const parts=String(ip||'').split('.').map(Number); if(parts.length!==4||parts.some(x=>!Number.isInteger(x)||x<0||x>255))return false; return parts[0]===10||parts[0]===127||(parts[0]===192&&parts[1]===168)||(parts[0]===172&&parts[1]>=16&&parts[1]<=31)||(parts[0]===169&&parts[1]===254); } function traceLocation(hop){ if(!hop?.ip)return t('trace.no_reply','No reply'); const g=hop.geo; if(g){ const place=[g.city,g.region,g.country].filter(Boolean).filter((v,i,a)=>a.indexOf(v)===i).join(', '); const net=[g.asn,g.org].filter(Boolean).join(' · '); return [place,net].filter(Boolean).join(' — ')||t('trace.unknown','Unknown'); } if(tracePrivateIpv4(hop.ip))return t('trace.private','Private network'); return t('trace.unknown','Unknown'); } function traceRttClass(value){ if(value===null||value===undefined||value==='')return ''; const n=Number(value); if(!Number.isFinite(n))return ''; if(n>=120)return 'trace-rtt-bad'; if(n>=50)return 'trace-rtt-warn'; return ''; } function traceDeltaLevel(value){ if(value===null||value===undefined||value==='')return 'unknown'; const n=Number(value); if(!Number.isFinite(n))return 'unknown'; if(n>20)return 'bad'; if(n>5)return 'warn'; return 'ok'; } function traceDeltaClass(value){ const level=traceDeltaLevel(value); return level==='bad'?'trace-delta-bad':level==='warn'?'trace-delta-warn':level==='ok'?'trace-delta-ok':''; } function traceHopRowClass(hop){ const level=traceDeltaLevel(hop?.delta_ms); return level==='bad'?'trace-hop-latency-bad':level==='warn'?'trace-hop-latency-warn':''; } function traceSegmentClass(hop){ const level=traceDeltaLevel(hop?.delta_ms); return level==='bad'?'latency-bad':level==='warn'?'latency-warn':level==='ok'?'latency-ok':'latency-unknown'; } const traceMapState={ center:{lon:30,lat:35},zoom:2,minZoom:2,maxZoom:12,points:[],fitted:false, drag:null,resizeObserver:null,popupIndex:null }; function traceGeoPoint(geo){ const lon=Number(geo?.longitude),lat=Number(geo?.latitude); if(!Number.isFinite(lon)||!Number.isFinite(lat))return null; return {lon:Math.max(-180,Math.min(180,lon)),lat:Math.max(-85.0511,Math.min(85.0511,lat))}; } function traceWorldPoint(lon,lat,zoom){ const size=256*Math.pow(2,zoom),x=(lon+180)/360*size; const clamped=Math.max(-85.0511,Math.min(85.0511,lat)); const sin=Math.sin(clamped*Math.PI/180); const y=(0.5-Math.log((1+sin)/(1-sin))/(4*Math.PI))*size; return {x,y,size}; } function traceWorldToLonLat(x,y,zoom){ const size=256*Math.pow(2,zoom); x=((x%size)+size)%size;y=Math.max(0,Math.min(size,y)); const lon=x/size*360-180; const n=Math.PI-2*Math.PI*y/size; const lat=180/Math.PI*Math.atan(Math.sinh(n)); return {lon,lat}; } function traceMapViewport(){return $('network-trace-map');} function traceMapScreenPoint(point,width,height){ const z=traceMapState.zoom,center=traceWorldPoint(traceMapState.center.lon,traceMapState.center.lat,z),p=traceWorldPoint(point.lon,point.lat,z); let dx=p.x-center.x;if(dx>p.size/2)dx-=p.size;if(dx<-p.size/2)dx+=p.size; return {x:width/2+dx,y:height/2+(p.y-center.y)}; } function traceMapClosePopup(){const pop=$('network-trace-map-popup');if(pop)pop.hidden=true;traceMapState.popupIndex=null;} function traceMapShowPopup(index,screen){ const item=traceMapState.points[index],pop=$('network-trace-map-popup'),map=traceMapViewport();if(!item||!pop||!map)return; const h=item.hop||{},location=traceLocation(h),hasReply=!!h.ip&&Array.isArray(h.samples_ms)&&h.samples_ms.length>0; const loss=hasReply&&Number.isFinite(Number(h.loss_percent))?`${Number(h.loss_percent).toFixed(0)}%`:t('trace.no_reply','No reply'); const delta=h.delta_ms===null||h.delta_ms===undefined?null:Number(h.delta_ms); const deltaText=delta!==null&&Number.isFinite(delta)?`${delta>=0?'+':''}${delta.toFixed(Math.abs(delta)<10?1:0)} ${t('trace.ms','ms')}`:'—'; pop.innerHTML=`#${esc(h.hop)} · ${esc(h.ip||'')}${esc(location)}RTT: ${esc(traceMs(h.avg_ms))} · Δ RTT: ${esc(deltaText)} · ${esc(t('trace.loss','Loss'))}: ${esc(loss)}`; pop.hidden=false;traceMapState.popupIndex=index; const mw=map.clientWidth,mh=map.clientHeight,pw=pop.offsetWidth,ph=pop.offsetHeight; pop.style.left=`${Math.max(8,Math.min(mw-pw-8,screen.x+14))}px`; pop.style.top=`${Math.max(8,Math.min(mh-ph-8,screen.y-ph/2))}px`; } function traceMapFitRoute(){ const map=traceMapViewport(),points=traceMapState.points;if(!map||!points.length)return; const w=map.clientWidth||900,h=map.clientHeight||420,pad=88; let chosen=traceMapState.minZoom,center={lon:points[0].p.lon,lat:points[0].p.lat}; for(let z=traceMapState.maxZoom;z>=traceMapState.minZoom;z--){ const ps=points.map(x=>traceWorldPoint(x.p.lon,x.p.lat,z)); let xs=ps.map(x=>x.x),ys=ps.map(x=>x.y),size=ps[0].size; // unwrap around first point so routes close to the date line still fit correctly const anchor=xs[0];xs=xs.map(x=>{while(x-anchor>size/2)x-=size;while(x-anchor<-size/2)x+=size;return x;}); const minX=Math.min(...xs),maxX=Math.max(...xs),minY=Math.min(...ys),maxY=Math.max(...ys); if(maxX-minX<=Math.max(60,w-pad*2)&&maxY-minY<=Math.max(60,h-pad*2)){ chosen=z;center=traceWorldToLonLat((minX+maxX)/2,(minY+maxY)/2,z);break; } } traceMapState.zoom=chosen;traceMapState.center=center;traceMapState.fitted=true;traceMapClosePopup();renderTraceSlippyMap(); } function traceMapSetZoom(next,anchorX,anchorY){ const map=traceMapViewport();if(!map)return; next=Math.max(traceMapState.minZoom,Math.min(traceMapState.maxZoom,next));if(next===traceMapState.zoom)return; const w=map.clientWidth,h=map.clientHeight,ax=Number.isFinite(anchorX)?anchorX:w/2,ay=Number.isFinite(anchorY)?anchorY:h/2; const old=traceWorldPoint(traceMapState.center.lon,traceMapState.center.lat,traceMapState.zoom); const geo=traceWorldToLonLat(old.x+(ax-w/2),old.y+(ay-h/2),traceMapState.zoom); const gp=traceWorldPoint(geo.lon,geo.lat,next); const newCenter=traceWorldToLonLat(gp.x-(ax-w/2),gp.y-(ay-h/2),next); traceMapState.zoom=next;traceMapState.center=newCenter;traceMapClosePopup();renderTraceSlippyMap(); } function renderTraceSlippyMap(){ const map=traceMapViewport(),tiles=$('network-trace-map-tiles'),svg=$('network-trace-map-svg');if(!map||!tiles||!svg||map.hidden||!map.offsetParent)return; const w=map.clientWidth,h=map.clientHeight,z=traceMapState.zoom,center=traceWorldPoint(traceMapState.center.lon,traceMapState.center.lat,z),size=center.size; const left=center.x-w/2,top=center.y-h/2,tileSize=256,n=Math.pow(2,z); const minTX=Math.floor(left/tileSize),maxTX=Math.floor((left+w)/tileSize),minTY=Math.max(0,Math.floor(top/tileSize)),maxTY=Math.min(n-1,Math.floor((top+h)/tileSize)); const tileHtml=[]; for(let ty=minTY;ty<=maxTY;ty++)for(let tx=minTX;tx<=maxTX;tx++){ const wrap=((tx%n)+n)%n,x=tx*tileSize-left,y=ty*tileSize-top; tileHtml.push(``); } tiles.innerHTML=tileHtml.join('');svg.setAttribute('viewBox',`0 0 ${w} ${h}`);svg.setAttribute('width',w);svg.setAttribute('height',h); const screen=traceMapState.points.map((item,index)=>({item,index,...traceMapScreenPoint(item.p,w,h)})); // Fan out hops that geolocate to the same city so they remain individually clickable. const buckets=new Map();screen.forEach(p=>{const key=`${Math.round(p.x/5)}:${Math.round(p.y/5)}`;(buckets.get(key)||buckets.set(key,[]).get(key)).push(p);}); buckets.forEach(group=>{if(group.length<2)return;group.forEach((p,i)=>{const a=Math.PI*2*i/group.length,r=Math.min(58,16+group.length*2.2);p.x+=Math.cos(a)*r;p.y+=Math.sin(a)*r;});}); const chunks=[]; for(let i=1;i`); chunks.push(``); } screen.forEach(p=>{const h=p.item.hop||{},label=String(h.hop),latency=p.item.synthetic?'latency-unknown':traceSegmentClass(h);chunks.push(`${esc(label)}`);}); svg.innerHTML=chunks.join(''); if(traceMapState.popupIndex!==null){const p=screen.find(x=>x.index===traceMapState.popupIndex);if(p)traceMapShowPopup(p.index,p);} } function renderNetworkTraceMap(hops,targetGeo,targetIp){ const panel=$('network-trace-map-panel'),summary=$('network-trace-map-route-summary');if(!panel)return; const points=(hops||[]).map(h=>({hop:h,p:traceGeoPoint(h.geo)})).filter(x=>x.p); const hasTarget=points.some(x=>x.hop?.reached||String(x.hop?.ip||'')===String(targetIp||'')); if(!hasTarget&&targetGeo){const p=traceGeoPoint(targetGeo);if(p)points.push({hop:{hop:'T',ip:targetIp,avg_ms:null,reached:true,geo:targetGeo},p,synthetic:true});} panel.hidden=!points.length;traceMapState.points=points;traceMapState.fitted=false;traceMapClosePopup(); if(summary){ const labels=[]; points.forEach(({hop})=>{ const g=hop?.geo||{}; const label=[g.city,g.country].filter(Boolean).filter((v,i,a)=>a.indexOf(v)===i).join(', ')||String(hop?.ip||''); if(label&&labels[labels.length-1]!==label)labels.push(label); }); summary.innerHTML=labels.length?`${esc(t('trace.route_path','Route'))}: ${labels.map(esc).join(' ')}`:''; summary.hidden=!labels.length; } if(points.length){ // Wait until the newly-unhidden tab and map have a real layout size before fitting. window.requestAnimationFrame(()=>window.requestAnimationFrame(traceMapFitRoute)); }else{ $('network-trace-map-tiles')?.replaceChildren();$('network-trace-map-svg')?.replaceChildren(); } } function bindTraceMap(){ const map=traceMapViewport(),svg=$('network-trace-map-svg');if(!map||map.dataset.traceBound==='1')return;map.dataset.traceBound='1'; $('network-trace-map-zoom-in')?.addEventListener('click',()=>traceMapSetZoom(traceMapState.zoom+1)); $('network-trace-map-zoom-out')?.addEventListener('click',()=>traceMapSetZoom(traceMapState.zoom-1)); $('network-trace-map-fit')?.addEventListener('click',traceMapFitRoute); map.addEventListener('wheel',e=>{e.preventDefault();const r=map.getBoundingClientRect();traceMapSetZoom(traceMapState.zoom+(e.deltaY<0?1:-1),e.clientX-r.left,e.clientY-r.top);},{passive:false}); map.addEventListener('pointerdown',e=>{if(e.button!==0||e.target.closest('.trace-map-control,.trace-route-marker,.trace-map-popup,a'))return;map.setPointerCapture?.(e.pointerId);const c=traceWorldPoint(traceMapState.center.lon,traceMapState.center.lat,traceMapState.zoom);traceMapState.drag={x:e.clientX,y:e.clientY,cx:c.x,cy:c.y,moved:false};map.classList.add('dragging');traceMapClosePopup();}); map.addEventListener('pointermove',e=>{const d=traceMapState.drag;if(!d)return;const dx=e.clientX-d.x,dy=e.clientY-d.y;if(Math.abs(dx)+Math.abs(dy)>3)d.moved=true;traceMapState.center=traceWorldToLonLat(d.cx-dx,d.cy-dy,traceMapState.zoom);renderTraceSlippyMap();}); const endDrag=()=>{traceMapState.drag=null;map.classList.remove('dragging');};map.addEventListener('pointerup',endDrag);map.addEventListener('pointercancel',endDrag); svg?.addEventListener('click',e=>{const marker=e.target.closest?.('.trace-route-marker');if(!marker)return;e.stopPropagation();const index=Number(marker.dataset.tracePoint),r=map.getBoundingClientRect(),m=marker.getCTM(),pt=svg.createSVGPoint();pt.x=0;pt.y=0;const screen=pt.matrixTransform(m);traceMapShowPopup(index,{x:screen.x,y:screen.y});}); map.addEventListener('click',e=>{if(!e.target.closest?.('.trace-route-marker,.trace-map-popup,.trace-map-control,a')&&!traceMapState.drag?.moved)traceMapClosePopup();}); if(window.ResizeObserver){traceMapState.resizeObserver=new ResizeObserver(()=>renderTraceSlippyMap());traceMapState.resizeObserver.observe(map);} } function renderNetworkTrace(data){ const results=$('network-trace-results'),summary=$('network-trace-summary'),body=$('network-trace-body'); if(!results||!summary||!body)return; results.hidden=false; const ping=data.ping||{}; const pingText=ping.avg_ms!==null&&ping.avg_ms!==undefined&&Number.isFinite(Number(ping.avg_ms))?traceMs(ping.avg_ms):t('trace.no_reply','No reply'); const loss=Number.isFinite(Number(ping.loss_percent))?`${Number(ping.loss_percent).toFixed(Number(ping.loss_percent)%1?1:0)}%`:'—'; summary.innerHTML=[ [t('trace.summary_target','Target'),data.target_ip||data.target||'—',data.target&&data.target!==data.target_ip?data.target:''], [t('trace.summary_ping','Average ping'),pingText,data.reached?t('trace.reached','Target reached'):(ping.reachable?t('trace.ping_ok_trace_filtered','Target responds to ping; final traceroute hops do not reply.'):t('trace.not_reached','Target was not reached by traceroute.'))], [t('trace.summary_loss','Ping loss'),loss,`${Number(ping.received||0)}/${Number(ping.sent||0)}`], [t('trace.summary_hops','Hops'),String(data.hop_count||0),`${Number(data.trace_seconds||0).toFixed(1)} s`] ].map(([label,value,small])=>`
${esc(label)}${esc(value)}${small?`${esc(small)}`:''}
`).join(''); const hops=data.hops||[]; // Keep unanswered hops only when they are inside the observed route. Once the // last responding router has been passed, the remaining probe ceiling adds no // useful information and only stretches the table. let lastReplyIndex=-1; for(let i=hops.length-1;i>=0;i--){ const h=hops[i]; if(h?.ip&&Array.isArray(h.samples_ms)&&h.samples_ms.length>0){lastReplyIndex=i;break;} } const visibleHops=lastReplyIndex>=0?hops.slice(0,lastReplyIndex+1):[]; const lastVisibleHop=visibleHops.length?Number(visibleHops[visibleHops.length-1].hop)||visibleHops.length:0; const hopSummary=summary.querySelector('.trace-summary-item:last-child b'); if(hopSummary)hopSummary.textContent=String(lastVisibleHop||0); body.innerHTML=visibleHops.length?visibleHops.map(h=>{ const hasReply=!!h.ip&&Array.isArray(h.samples_ms)&&h.samples_ms.length>0; const ip=h.ip||'*'; const location=traceLocation(h); const delta=h.delta_ms===null||h.delta_ms===undefined?null:Number(h.delta_ms); const deltaText=delta!==null&&Number.isFinite(delta)?`${delta>=0?'+':''}${delta.toFixed(Math.abs(delta)<10?1:0)} ${t('trace.ms','ms')}`:'—'; const loss=hasReply&&Number.isFinite(Number(h.loss_percent))?`${Number(h.loss_percent).toFixed(0)}%`:t('trace.no_reply','No reply'); const lossClass=!hasReply?'trace-loss-none':Number(h.loss_percent)>=50?'trace-loss-bad':Number(h.loss_percent)>0?'trace-loss-warn':''; const rowClass=traceHopRowClass(h); return `${h.hop}
${esc(ip)}${h.reached?' ✓':''}
${esc(location)}${esc(traceMs(h.avg_ms))}${esc(deltaText)}${esc(loss)}`; }).join(''):`${esc(t('trace.no_reply','No reply'))}`; renderNetworkTraceMap(visibleHops,data.target_geo,data.target_ip); } async function runNetworkTrace(event){ event?.preventDefault(); const button=$('network-trace-button'),target=$('network-trace-target'),geo=$('network-trace-geolocate'); if(!target||!button)return; const value=String(target.value||'').trim(); if(!value)return; button.disabled=true; $('network-trace-results')?.setAttribute('hidden',''); operationStatus('network-trace-status',t('trace.running','Running ping and traceroute… This can take up to a minute.'),'working'); try{ const r=await fetch('/api/network/trace',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({target:value,geolocate:!!geo?.checked,language:window.WGToolsI18n?.getLanguage?.()||'en'})}); const d=await r.json(); if(!r.ok)throw new Error(d.error||t('trace.failed','Network trace failed')); renderNetworkTrace(d); let message=t('trace.done','Network trace completed.'); if(d.geo_partial)message+=` ${t('trace.partial_geo','Some public hops could not be geolocated.')}`; operationStatus('network-trace-status',message,(d.reached||d.ping?.reachable)?'success':'info'); }catch(e){operationStatus('network-trace-status',e.message||t('trace.failed','Network trace failed'),'error');} finally{button.disabled=false;} } async function diagnostics(){ const b=$('diagnostics-button'); if(b)b.disabled=true; try{const r=await fetch('/api/diagnostics',{cache:'no-store'});const d=await r.json();if(!r.ok)throw new Error(d.error||'Failed');renderDiagnostics(d.diagnostics||[]);toast(t('server.diagnostics_done','Diagnostics completed'));} catch(e){toast(e.message);}finally{if(b)b.disabled=false;} } async function installWireGuard(){ const b=$('install-wireguard-button'); if(!b)return; b.disabled=true; operationStatus('install-status',t('server.installing','Installing WireGuard… This may take a minute.'),'working'); try{ const r=await fetch('/api/server/install',{method:'POST',headers:{'Content-Type':'application/json'},body:'{}'}); const d=await r.json(); if(!r.ok) throw new Error(d.error||'Installation failed'); operationStatus('install-status',d.message||t('server.install_success','WireGuard installed successfully.'),'success'); toast(t('server.install_success','WireGuard installed successfully.')); await fetchSnapshot(); }catch(e){ operationStatus('install-status',e.message,'error'); toast(e.message); } finally{ b.disabled=false; } } function ipToInt(ip){ const parts=String(ip).split('.').map(Number); if(parts.length!==4||parts.some(x=>!Number.isInteger(x)||x<0||x>255)) return null; return (((parts[0]<<24)>>>0)+((parts[1]<<16)>>>0)+((parts[2]<<8)>>>0)+parts[3])>>>0; } function intToIp(n){ return [n>>>24,(n>>>16)&255,(n>>>8)&255,n&255].join('.'); } function firstHostFromCidr(cidr){ const [ip,prefixRaw]=String(cidr).trim().split('/'); const prefix=Number(prefixRaw); const n=ipToInt(ip); if(n===null||!Number.isInteger(prefix)||prefix<0||prefix>30)return null; const mask=prefix===0?0:((0xffffffff << (32-prefix))>>>0); const network=(n&mask)>>>0; return `${intToIp((network+1)>>>0)}/${prefix}`; } function syncServerAddress(){ const net=$('setup-vpn-network'),addr=$('setup-server-address'); if(!net||!addr||addr.dataset.touched)return; const first=firstHostFromCidr(net.value); if(first)addr.value=first; } async function createServer(event){ event.preventDefault(); const b=$('create-server-button'); if(!b)return; const payload={ display_name:$('setup-display-name').value.trim(), vpn_network:$('setup-vpn-network').value.trim(), server_address:$('setup-server-address').value.trim(), listen_port:Number($('setup-port').value), mtu:Number($('setup-mtu').value||0), uplink_interface:$('setup-uplink').value.trim(), gateway:$('setup-gateway').value.trim(), local_network:$('setup-local-network').value.trim(), policy_table:$('setup-policy-table').value.trim(), nat_enabled:$('setup-nat').checked, ip_forwarding:$('setup-forwarding').checked, ...networkBindingPayload('setup'), }; const ok=confirm(t('server.create_confirm','Create and start the WireGuard server with these settings?')); if(!ok)return; b.disabled=true; operationStatus('create-status',t('server.creating','Generating keys, writing configuration and starting WireGuard…'),'working'); try{ const r=await fetch('/api/server/create',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(payload)}); const d=await r.json(); if(!r.ok)throw new Error(d.error||'Server creation failed'); operationStatus('create-status',d.message||t('server.create_success','WireGuard server created successfully.'),'success'); toast(t('server.create_success','WireGuard server created successfully.')); await fetchInterfaces(true); await fetchSnapshot(); }catch(e){ const message=localizedServerError(e.message); operationStatus('create-status',message,'error'); toast(message); } finally{ b.disabled=false; } } function renderSettings(d){ const button=$('raw-config-button'); if(button) button.disabled=!d.wireguard?.config_exists; if($('settings-backup-count')) $('settings-backup-count').textContent=String(d.backups?.count??0); if($('settings-last-backup')) $('settings-last-backup').textContent=d.backups?.latest_modified_at?formatDate(d.backups.latest_modified_at):t('settings.no_backups','No backups yet'); } function highlightWireGuardConfig(text){ return String(text||'').split('\n').map(line=>{ if(/^\s*[#;]/.test(line)) return `${esc(line)}`; if(/^\s*\[[^\]]+\]\s*$/.test(line)) return `${esc(line)}`; const match=line.match(/^(\s*)([A-Za-z][A-Za-z0-9]*)(\s*=\s*)(.*)$/); if(match){ return `${esc(match[1])}${esc(match[2])}${esc(match[3])}${esc(match[4])}`; } return esc(line); }).join('\n')+'\n'; } function updateRawConfigHighlight(){ const textarea=$('raw-config-text'), pre=$('raw-config-highlight'); if(!textarea||!pre)return; pre.innerHTML=highlightWireGuardConfig(textarea.value); pre.scrollTop=textarea.scrollTop; pre.scrollLeft=textarea.scrollLeft; } async function loadRawConfig(){ const button=$('raw-config-button'); if(button)button.disabled=true; operationStatus('raw-config-status',t('settings.loading_config','Loading configuration…'),'working'); try{ const r=await fetch('/api/server/config/raw',{cache:'no-store'}); const d=await r.json(); if(!r.ok)throw new Error(d.error||t('settings.config_load_failed','Could not load configuration')); $('raw-config-text').value=d.content||''; $('raw-config-path').textContent=d.path||`/etc/wireguard/${snapshot?.interface||'wg0'}.conf`; updateRawConfigHighlight(); operationStatus('raw-config-status',''); modalShow('raw-config-modal',true); setTimeout(()=>$('raw-config-text')?.focus(),30); }catch(e){operationStatus('raw-config-status',e.message,'error');toast(e.message);}finally{if(button)button.disabled=!snapshot?.wireguard?.config_exists;} } async function applyRawConfig(){ const textarea=$('raw-config-text'), button=$('apply-raw-config-button'); if(!textarea||!button)return; const ok=confirm(t('settings.raw_config_confirm','Save this WireGuard configuration and apply it now? The selected interface will be restarted. A backup is created first and WGTools will roll back automatically if the new configuration does not start.')); if(!ok)return; button.disabled=true; operationStatus('raw-config-status',t('settings.applying_config','Validating configuration, creating backup and applying…'),'working'); try{ const r=await fetch('/api/server/config/apply',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({content:textarea.value})}); const d=await r.json(); if(!r.ok)throw new Error(d.error||t('settings.config_apply_failed','Configuration could not be applied')); await fetchSnapshot(false); const message=d.restarted?t('settings.config_applied_restarted','Configuration applied and WireGuard restarted.'):t('settings.config_applied_stopped','Configuration saved. WireGuard remains stopped.'); operationStatus('raw-config-status',''); modalShow('raw-config-modal',false); toast(message,4200); }catch(e){operationStatus('raw-config-status',e.message,'error');toast(e.message);}finally{button.disabled=false;} } function bindRawConfigEditor(){ $('raw-config-button')?.addEventListener('click',loadRawConfig); $('reload-raw-config-button')?.addEventListener('click',loadRawConfig); $('apply-raw-config-button')?.addEventListener('click',applyRawConfig); const textarea=$('raw-config-text'); if(textarea){ textarea.addEventListener('input',updateRawConfigHighlight); textarea.addEventListener('scroll',updateRawConfigHighlight); textarea.addEventListener('keydown',e=>{ if(e.key==='Tab'){ e.preventDefault(); const start=textarea.selectionStart, end=textarea.selectionEnd; textarea.setRangeText(' ',start,end,'end'); updateRawConfigHighlight(); } }); } } function formatDate(ts){ const n=Number(ts||0); if(!n)return t('settings.never_logged_in','Never'); try{return new Intl.DateTimeFormat(window.WGToolsI18n?.getLanguage?.()==='ru'?'ru-RU':'en-GB',{dateStyle:'medium',timeStyle:'short'}).format(new Date(n*1000));} catch(_){return new Date(n*1000).toLocaleString();} } async function loadUsers(){ const body=$('users-table-body'); if(!body)return; try{ const r=await fetch('/api/users',{cache:'no-store'}); const d=await r.json(); if(!r.ok)throw new Error(d.error||'Failed'); const users=d.users||[]; const current=Number(d.current_user_id||0); const mailConfigured=Boolean(d.mail_configured); body.innerHTML=users.map(u=>{ const email=String(u.email||''); const isCurrent=Number(u.id)===current; const mfaEnabled=Boolean(u.mfa_enabled); const resetDisabled=!mailConfigured||!email; const resetTitle=!mailConfigured?t('settings.user_reset_mail_not_configured','Configure and enable mail first.'):(!email?t('settings.user_reset_email_missing','Add an email address first.'):''); const mfaBadge=mfaEnabled?`${esc(t('settings.mfa_enabled','Enabled'))}`:`${esc(t('settings.mfa_disabled','Disabled'))}`; const mfaButton=isCurrent?``:''; return `
${esc(u.username)}
${isCurrent?`
${esc(t('settings.current_user','Current user'))}
`:''}${email?esc(email):'—'}${mfaBadge}${esc(formatDate(u.created_at))}${esc(formatDate(u.last_login))}
${mfaButton}
`; }).join('') || `—`; }catch(e){body.innerHTML=`${esc(e.message)}`;} } function openAddUser(){ $('user-form')?.reset(); operationStatus('user-form-status',''); modalShow('user-modal',true); setTimeout(()=>$('new-user-name')?.focus(),30); } async function createUser(event){ event.preventDefault(); const password=$('new-user-password').value; const repeat=$('new-user-password-repeat').value; if(password!==repeat){operationStatus('user-form-status',t('settings.passwords_mismatch','Passwords do not match.'),'error');return;} const button=event.currentTarget.querySelector('button[type="submit"]'); button.disabled=true; try{ const r=await fetch('/api/users',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({username:$('new-user-name').value.trim(),email:$('new-user-email')?.value.trim()||'',password})}); const d=await r.json(); if(!r.ok)throw new Error(d.error||'Failed'); modalShow('user-modal',false); toast(t('settings.user_created_ok','User created.')); await loadUsers(); }catch(e){operationStatus('user-form-status',e.message,'error');}finally{button.disabled=false;} } function openPasswordUser(id,name){ $('password-form')?.reset(); $('password-user-id').value=String(id); $('password-user-name').textContent=name; operationStatus('password-form-status',''); modalShow('password-modal',true); setTimeout(()=>$('password-new')?.focus(),30); } async function saveUserPassword(event){ event.preventDefault(); const password=$('password-new').value; const repeat=$('password-repeat').value; if(password!==repeat){operationStatus('password-form-status',t('settings.passwords_mismatch','Passwords do not match.'),'error');return;} const id=Number($('password-user-id').value); const button=event.currentTarget.querySelector('button[type="submit"]'); button.disabled=true; try{ const r=await fetch(`/api/users/${id}/password`,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({password})}); const d=await r.json(); if(!r.ok)throw new Error(d.error||'Failed'); modalShow('password-modal',false); toast(t('settings.password_changed','Password changed.')); if(d.reauthenticate){setTimeout(()=>location.replace(appUrl('/login')),450);} }catch(e){operationStatus('password-form-status',e.message,'error');}finally{button.disabled=false;} } function openEmailUser(id,name,email){ $('email-form')?.reset(); $('email-user-id').value=String(id); $('email-user-name').textContent=name; $('email-new').value=email||''; operationStatus('email-form-status',''); modalShow('email-modal',true); setTimeout(()=>$('email-new')?.focus(),30); } async function saveUserEmail(event){ event.preventDefault(); const id=Number($('email-user-id').value); const button=event.currentTarget.querySelector('button[type="submit"]'); if(button)button.disabled=true; try{ const r=await fetch(`/api/users/${id}/email`,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({email:$('email-new').value.trim()})}); const d=await r.json(); if(!r.ok)throw new Error(d.error||'Failed'); modalShow('email-modal',false); toast(t('settings.user_email_saved','E-mail saved.')); await loadUsers(); }catch(e){operationStatus('email-form-status',e.message,'error');}finally{if(button)button.disabled=false;} } async function sendUserPasswordReset(id,name,email){ const template=t('settings.user_reset_confirm','Send a password reset code to {name} at {email}?'); if(!confirm(template.replace('{name}',name).replace('{email}',email)))return; try{ const r=await fetch(`/api/users/${id}/password-reset`,{method:'POST'}); const d=await r.json(); if(!r.ok)throw new Error(d.error||'Failed'); toast(t('settings.user_reset_sent','Password reset code sent to {email}.').replace('{email}',d.masked_email||email),4200); }catch(e){toast(e.message,4200);} } async function deleteUser(id,name){ const template=t('settings.delete_user_confirm','Delete user {name}?'); if(!confirm(template.replace('{name}',name)))return; try{const r=await fetch(`/api/users/${id}`,{method:'DELETE'});const d=await r.json();if(!r.ok)throw new Error(d.error||'Failed');toast(t('settings.user_deleted','User deleted.'));await loadUsers();}catch(e){toast(e.message);} } function mfaErrorText(message){ const value=String(message||''); const map={ 'Invalid current password':t('settings.mfa_error_password','Invalid current password.'), 'Invalid authentication code':t('settings.mfa_error_code','Invalid authentication code.'), 'MFA is already enabled':t('settings.mfa_error_already_enabled','MFA is already enabled.'), 'MFA is not enabled':t('settings.mfa_error_not_enabled','MFA is not enabled.'), 'MFA setup has not been started':t('settings.mfa_error_not_started','Start MFA setup again.'), }; return map[value]||value; } function setMfaMode(enabled,recoveryRemaining=0){ const disabled=$('mfa-disabled-panel'), active=$('mfa-enabled-panel'); if(disabled)disabled.hidden=Boolean(enabled); if(active)active.hidden=!enabled; const remain=$('mfa-recovery-remaining'); if(remain)remain.textContent=t('settings.mfa_recovery_remaining','Recovery codes remaining: {count}').replace('{count}',String(Number(recoveryRemaining||0))); } function showMfaRecoveryCodes(codes){ const list=Array.isArray(codes)?codes:[]; const panel=$('mfa-recovery-panel'), pre=$('mfa-recovery-codes'); if(pre)pre.textContent=list.join('\n'); if(panel)panel.hidden=list.length===0; } function openMfaUser(id,name,enabled,recoveryRemaining){ $('mfa-user-name').textContent=name; $('mfa-modal').dataset.userId=String(id); $('mfa-setup-password').value=''; $('mfa-confirm-code').value=''; $('mfa-manage-password').value=''; $('mfa-manage-code').value=''; $('mfa-start-button').hidden=false; $('mfa-qr-image').removeAttribute('src'); $('mfa-secret').textContent=''; $('mfa-setup-details').hidden=true; showMfaRecoveryCodes([]); operationStatus('mfa-form-status',''); setMfaMode(enabled,recoveryRemaining); modalShow('mfa-modal',true); setTimeout(()=>$(enabled?'mfa-manage-password':'mfa-setup-password')?.focus(),30); } async function startMfaSetup(){ const button=$('mfa-start-button'); if(button)button.disabled=true; operationStatus('mfa-form-status',''); try{ const r=await fetch('/api/users/mfa/setup',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({password:$('mfa-setup-password').value})}); const d=await r.json(); if(!r.ok)throw new Error(d.error||'Failed'); $('mfa-qr-image').src=d.qr||''; $('mfa-secret').textContent=d.secret||''; $('mfa-setup-details').hidden=false; $('mfa-start-button').hidden=true; setTimeout(()=>$('mfa-confirm-code')?.focus(),30); }catch(e){operationStatus('mfa-form-status',mfaErrorText(e.message),'error');}finally{if(button)button.disabled=false;} } async function confirmMfaSetup(){ const button=$('mfa-confirm-button'); if(button)button.disabled=true; operationStatus('mfa-form-status',''); try{ const r=await fetch('/api/users/mfa/confirm',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({code:$('mfa-confirm-code').value.trim()})}); const d=await r.json(); if(!r.ok)throw new Error(d.error||'Failed'); setMfaMode(true,(d.recovery_codes||[]).length); showMfaRecoveryCodes(d.recovery_codes||[]); $('mfa-setup-details').hidden=true; $('mfa-start-button').hidden=false; toast(t('settings.mfa_enabled_ok','MFA enabled.')); await loadUsers(); }catch(e){operationStatus('mfa-form-status',mfaErrorText(e.message),'error');}finally{if(button)button.disabled=false;} } function mfaManagePayload(){return {password:$('mfa-manage-password').value,code:$('mfa-manage-code').value.trim()};} async function disableMfa(){ if(!confirm(t('settings.mfa_disable_confirm','Disable two-factor authentication for this account?')))return; const button=$('mfa-disable-button'); if(button)button.disabled=true; operationStatus('mfa-form-status',''); try{ const r=await fetch('/api/users/mfa/disable',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(mfaManagePayload())}); const d=await r.json(); if(!r.ok)throw new Error(d.error||'Failed'); setMfaMode(false,0); showMfaRecoveryCodes([]); $('mfa-start-button').hidden=false; $('mfa-setup-password').value=''; toast(t('settings.mfa_disabled_ok','MFA disabled.')); await loadUsers(); }catch(e){operationStatus('mfa-form-status',mfaErrorText(e.message),'error');}finally{if(button)button.disabled=false;} } async function regenerateMfaRecovery(){ if(!confirm(t('settings.mfa_regenerate_confirm','Replace all existing recovery codes?')))return; const button=$('mfa-regenerate-button'); if(button)button.disabled=true; operationStatus('mfa-form-status',''); try{ const r=await fetch('/api/users/mfa/recovery-codes',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(mfaManagePayload())}); const d=await r.json(); if(!r.ok)throw new Error(d.error||'Failed'); showMfaRecoveryCodes(d.recovery_codes||[]); setMfaMode(true,(d.recovery_codes||[]).length); $('mfa-manage-code').value=''; toast(t('settings.mfa_recovery_regenerated','New recovery codes created.')); await loadUsers(); }catch(e){operationStatus('mfa-form-status',mfaErrorText(e.message),'error');}finally{if(button)button.disabled=false;} } async function copyMfaRecovery(){ const text=$('mfa-recovery-codes')?.textContent||''; if(!text)return; try{ if(navigator.clipboard?.writeText)await navigator.clipboard.writeText(text); else throw new Error('clipboard unavailable'); toast(t('common.copied','Copied.')); return; }catch(_){ try{const area=document.createElement('textarea');area.value=text;area.style.position='fixed';area.style.opacity='0';document.body.appendChild(area);area.focus();area.select();const ok=document.execCommand('copy');area.remove();if(!ok)throw new Error('copy failed');toast(t('common.copied','Copied.'));return;}catch(__){} } toast(t('common.copy_failed','Copy failed.')); } async function logout(){ try{await fetch('/api/auth/logout',{method:'POST'});}finally{location.replace(appUrl('/login'));} } function bindUserManagement(){ if($('service-policy-form')){ const sync=()=>{$('service-policy-options').hidden=!$('service-policy-enabled').checked;$('service-policy-list-wrap').hidden=$('service-policy-mode').value==='custom';}; $('service-policy-enabled').addEventListener('change',sync);$('service-policy-mode').addEventListener('change',sync); fetch(appUrl('/api/service-policy')).then(r=>r.json()).then(d=>{if(!d.ok)throw new Error(d.error);$('service-policy-enabled').checked=d.policy.enabled;$('service-policy-mode').value=d.policy.mode;$('service-policy-list').value=d.policy.services.join('\n');sync();}).catch(e=>operationStatus('service-policy-status',e.message,'error')); $('service-policy-form').addEventListener('submit',async e=>{e.preventDefault();try{const r=await fetch(appUrl('/api/service-policy'),{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({enabled:$('service-policy-enabled').checked,mode:$('service-policy-mode').value,services:$('service-policy-list').value.split(/\r?\n/).map(x=>x.trim()).filter(Boolean)})});const d=await r.json();if(!r.ok)throw new Error(d.error);operationStatus('service-policy-status','Zapisano ustawienia usług.','success');}catch(err){operationStatus('service-policy-status',err.message,'error');}}); } $('branding-form')?.addEventListener('submit', async e=>{ e.preventDefault(); try { const file=$('branding-logo').files[0]; let logo=$('branding-reset-logo').checked?'':$('branding-current-logo').value; if(file){ if(file.type!=='image/png'||file.size>300000)throw new Error('Wybierz plik PNG o rozmiarze do 300 KB.'); logo=await new Promise((resolve,reject)=>{const reader=new FileReader();reader.onload=()=>resolve(reader.result);reader.onerror=()=>reject(new Error('Nie udało się odczytać logo.'));reader.readAsDataURL(file);}); } const r=await fetch(appUrl('/api/branding'),{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({name:$('branding-name').value,color:$('branding-color').value,logo})}); const data=await r.json(); if(!r.ok)throw new Error(data.error||'Nie udało się zapisać.'); location.reload(); } catch(err){operationStatus('branding-status',err.message,'error');} }); $('add-user-button')?.addEventListener('click',openAddUser); $('user-form')?.addEventListener('submit',createUser); $('password-form')?.addEventListener('submit',saveUserPassword); $('email-form')?.addEventListener('submit',saveUserEmail); $('logout-button')?.addEventListener('click',logout); $('mfa-start-button')?.addEventListener('click',startMfaSetup); $('mfa-confirm-button')?.addEventListener('click',confirmMfaSetup); $('mfa-disable-button')?.addEventListener('click',disableMfa); $('mfa-regenerate-button')?.addEventListener('click',regenerateMfaRecovery); $('mfa-copy-recovery-button')?.addEventListener('click',copyMfaRecovery); $('users-table-body')?.addEventListener('click',async e=>{const b=e.target.closest('[data-user-action]');if(!b||b.disabled)return;const id=Number(b.dataset.userId),name=b.dataset.userName||'',email=b.dataset.userEmail||'';if(b.dataset.userAction==='access'){ try{const data=await fetchInterfaces(false);if(!data)throw new Error('Nie udało się pobrać sieci.');const selected=(b.dataset.interfaces||'').split(',').map(x=>x.trim());let previous={};try{previous=JSON.parse(b.dataset.permissions||'{}');}catch(_){} $('user-access-id').value=String(id);$('user-access-name').textContent=name;$('user-access-role').value=b.dataset.role||'user'; $('user-access-networks').innerHTML=(data.interfaces||[]).filter(x=>x.configured).map(x=>{const checked=selected.includes(x.name),p=previous[x.name]||[];return `
${[['add','Dodawanie klientów'],['edit','Edycja klientów'],['forward','Przekierowania portów']].map(([key,label])=>``).join('')}
`;}).join('')||'

Brak skonfigurowanych sieci WireGuard.

'; operationStatus('user-access-status','');modalShow('user-access-modal',true); }catch(err){alert(err.message);} }else if(b.dataset.userAction==='mfa')openMfaUser(id,name,b.dataset.mfaEnabled==='1',Number(b.dataset.mfaRecovery||0));else if(b.dataset.userAction==='password')openPasswordUser(id,name);else if(b.dataset.userAction==='email')openEmailUser(id,name,email);else if(b.dataset.userAction==='reset')sendUserPasswordReset(id,name,email);else if(b.dataset.userAction==='delete')deleteUser(id,name);}); $('user-access-form')?.addEventListener('submit',async e=>{e.preventDefault();const interfaces=[],permissions={};document.querySelectorAll('[data-access-network]').forEach(row=>{if(row.querySelector('[data-access-enabled]').checked){const name=row.dataset.accessNetwork;interfaces.push(name);permissions[name]=[...row.querySelectorAll('[data-access-permission]:checked')].map(x=>x.dataset.accessPermission);}});try{const r=await fetch(appUrl(`/api/users/${Number($('user-access-id').value)}/access`),{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({role:$('user-access-role').value,interfaces,permissions})});const d=await r.json();if(!r.ok)throw new Error(d.error);modalShow('user-access-modal',false);await loadUsers();}catch(err){operationStatus('user-access-status',err.message,'error');}}); if(page==='settings')loadUsers(); } function auditActionLabel(action){ const key=`audit.action.${String(action||'').replace(/[^a-z0-9_.-]/gi,'_')}`; return t(key,String(action||'—').replace(/[._-]+/g,' ')); } function auditResultLabel(result){ const value=String(result||'—'); const lower=value.toLocaleLowerCase(); if(lower.startsWith('endpoint '))return `${t('audit.result.endpoint','Endpoint')} ${value.slice(9)}`; if(lower.startsWith('error:'))return `${t('audit.result.error','Error')}: ${value.slice(value.indexOf(':')+1).trim()}`; const key=`audit.result.${value.replace(/[^a-z0-9_.-]/gi,'_')}`; return t(key,value); } let auditItems=[]; let auditLoaded=false; let auditLoadPromise=null; let auditAutoRefreshTimer=null; function auditRefreshSeconds(){ const value=Number($('audit-modal')?.dataset.refreshSeconds||5); return Number.isFinite(value)?Math.max(2,Math.min(value,60)):5; } function stopAuditAutoRefresh(){ if(auditAutoRefreshTimer){clearInterval(auditAutoRefreshTimer);auditAutoRefreshTimer=null;} } function startAuditAutoRefresh(){ stopAuditAutoRefresh(); const interval=auditRefreshSeconds()*1000; auditAutoRefreshTimer=setInterval(()=>{ const modal=$('audit-modal'); if(!modal||modal.hidden){stopAuditAutoRefresh();return;} if(document.hidden)return; loadAudit({showLoading:false}); },interval); } function auditTone(item){ const action=String(item?.action||'').toLocaleLowerCase(), result=String(item?.result||'').toLocaleLowerCase(); if(action==='wireguard.client_connected')return 'connection'; if(/failed|deleted|stopped|detached/.test(action)||/failed|error|invalid|denied/.test(result))return 'danger'; if(/created|started|installed|restored|completed|auth\.login$/.test(action))return 'success'; if(/updated|applied|changed|rotated|scheduled|restarted/.test(action))return 'warning'; return 'info'; } function compactAuditUsername(username){ const value=String(username||'system'); if(value.startsWith('Telegram ·'))return `${t('audit.user.telegram_short','TG')} ·${value.slice('Telegram ·'.length)}`; return value; } function syncAuditSearchClear(){ const clear=$('audit-quick-search-clear'); if(clear)clear.hidden=!String($('audit-quick-search')?.value||'').length; } function renderAudit(){ const body=$('audit-table-body'); if(!body)return; const query=String($('audit-quick-search')?.value||'').trim().toLocaleLowerCase(); const items=query?auditItems.filter(item=>{ const haystack=[formatDate(item.created_at),item.username,compactAuditUsername(item.username),auditActionLabel(item.action),item.action,item.object,auditResultLabel(item.result),item.result].map(value=>String(value||'').toLocaleLowerCase()).join(' '); return haystack.includes(query); }):auditItems; syncAuditSearchClear(); if(!auditItems.length){body.innerHTML=`${esc(t('settings.audit_empty','No audit events yet'))}`;return;} if(!items.length){body.innerHTML=`${esc(t('settings.audit_search_empty','No audit events match the search'))}`;return;} body.innerHTML=items.map(item=>{ const tone=auditTone(item); const rawUsername=item.username||'system', username=compactAuditUsername(rawUsername), userClass=rawUsername==='system'?'system':'user'; return `${esc(formatDate(item.created_at))}${esc(username)}${esc(auditActionLabel(item.action))}${esc(item.object||'—')}${esc(auditResultLabel(item.result))}`; }).join(''); } async function loadAudit({showLoading=true}={}){ const body=$('audit-table-body'); if(!body)return; if(auditLoadPromise)return auditLoadPromise; if(showLoading&&!auditLoaded)body.innerHTML=`${esc(t('common.loading','Loading…'))}`; auditLoadPromise=(async()=>{ try{ const r=await fetch('/api/audit?limit=1000',{cache:'no-store'});const d=await r.json();if(!r.ok)throw new Error(d.error||'Failed'); auditItems=d.items||[];auditLoaded=true;renderAudit(); }catch(e){ if(showLoading||!auditLoaded)body.innerHTML=`${esc(e.message)}`; }finally{auditLoadPromise=null;} })(); return auditLoadPromise; } function bindAudit(){ const search=$('audit-quick-search'), clear=$('audit-quick-search-clear'); const openAudit=()=>{ modalShow('audit-modal'); if(auditLoaded)renderAudit();else loadAudit(); startAuditAutoRefresh(); }; $('audit-log-button')?.addEventListener('click',openAudit); $('topbar-audit-button')?.addEventListener('click',openAudit); $('audit-refresh-button')?.addEventListener('click',()=>loadAudit({showLoading:false})); search?.addEventListener('input',renderAudit); clear?.addEventListener('click',()=>{if(!search)return;search.value='';syncAuditSearchClear();search.focus();renderAudit();}); syncAuditSearchClear(); if(page==='settings')loadAudit({showLoading:false}); } let mailState = null; function renderMailSettings(data){ mailState=data||{}; if($('mail-enabled'))$('mail-enabled').checked=Boolean(data?.enabled); if($('mail-smtp-host'))$('mail-smtp-host').value=data?.smtp_host||''; if($('mail-smtp-port'))$('mail-smtp-port').value=Number(data?.smtp_port||587); if($('mail-security'))$('mail-security').value=data?.security||'starttls'; if($('mail-username'))$('mail-username').value=data?.username||''; if($('mail-password')){$('mail-password').value='';$('mail-password').placeholder=data?.password_masked||'';} if($('mail-from-name'))$('mail-from-name').value=data?.from_name||'WGTools'; const remove=$('mail-remove-password-button');if(remove)remove.disabled=!data?.password_configured; const badge=$('mail-status-badge'); if(badge){ let label=t('settings.mail_not_configured','Not configured'),cls='badge'; if(data?.enabled&&data?.configured){label=t('settings.mail_enabled_badge','Enabled');cls='badge managed';} else if(data?.configured){label=t('settings.mail_disabled_badge','Disabled');cls='badge';} badge.className=cls;badge.textContent=label; } } async function loadMailSettings(){ if(page!=='settings'||!$('mail-settings-form'))return; try{const r=await fetch('/api/mail/settings',{cache:'no-store'});const d=await r.json();if(!r.ok)throw new Error(d.error||'Failed');renderMailSettings(d.settings||{});} catch(e){operationStatus('mail-settings-status',e.message,'error');} } async function saveMailSettings(event){ event.preventDefault();const button=event.currentTarget.querySelector('button[type="submit"]');if(button)button.disabled=true;operationStatus('mail-settings-status',t('settings.saving','Saving settings…'),'working'); try{ const username=$('mail-username')?.value.trim()||''; const payload={enabled:Boolean($('mail-enabled')?.checked),smtp_host:$('mail-smtp-host')?.value.trim()||'',smtp_port:Number($('mail-smtp-port')?.value||587),security:$('mail-security')?.value||'starttls',username,password:$('mail-password')?.value||'',clear_password:false,from_email:username||(mailState?.from_email||''),from_name:$('mail-from-name')?.value.trim()||'WGTools'}; const r=await fetch('/api/mail/settings',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(payload)});const d=await r.json();if(!r.ok)throw new Error(d.error||'Failed'); renderMailSettings(d.settings||{});operationStatus('mail-settings-status',t('settings.mail_saved','Mail settings saved.'),'success');toast(t('settings.mail_saved','Mail settings saved.'));await loadUsers(); }catch(e){operationStatus('mail-settings-status',e.message,'error');}finally{if(button)button.disabled=false;} } async function removeMailPassword(){ if(!confirm(t('settings.mail_remove_password_confirm','Remove the saved SMTP password?')))return; const current=mailState||{}; try{ const payload={enabled:false,smtp_host:current.smtp_host||'',smtp_port:Number(current.smtp_port||587),security:current.security||'starttls',username:current.username||'',password:'',clear_password:true,from_email:current.username||current.from_email||'',from_name:current.from_name||'WGTools'}; const r=await fetch('/api/mail/settings',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(payload)});const d=await r.json();if(!r.ok)throw new Error(d.error||'Failed');renderMailSettings(d.settings||{});operationStatus('mail-settings-status',t('settings.mail_password_removed','SMTP password removed and mail disabled.'),'success');await loadUsers(); }catch(e){operationStatus('mail-settings-status',e.message,'error');} } async function testMail(){ const recipient=$('mail-test-recipient')?.value.trim()||'';if(!recipient){operationStatus('mail-settings-status',t('settings.mail_test_recipient_required','Enter a test recipient email.'),'error');return;} const button=$('mail-test-button');if(button)button.disabled=true;operationStatus('mail-settings-status',t('settings.mail_testing','Sending a test email…'),'working'); try{const r=await fetch('/api/mail/test',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({recipient})});const d=await r.json();if(!r.ok)throw new Error(d.error||'Failed');operationStatus('mail-settings-status',t('settings.mail_test_ok','Test email sent successfully.'),'success');toast(t('settings.mail_test_ok','Test email sent successfully.'));} catch(e){operationStatus('mail-settings-status',e.message,'error');}finally{if(button)button.disabled=false;} } function defaultSmtpPort(security){ if(security==='tls')return 465; if(security==='none')return 25; return 587; } function bindMailSettings(){ $('mail-settings-form')?.addEventListener('submit',saveMailSettings); $('mail-test-button')?.addEventListener('click',testMail); $('mail-remove-password-button')?.addEventListener('click',removeMailPassword); $('mail-security')?.addEventListener('change',event=>{ const port=$('mail-smtp-port'); if(port)port.value=String(defaultSmtpPort(event.currentTarget.value)); }); if(page==='settings')loadMailSettings(); } let httpsState = null; function normalizedHttpsAccessPath(value){ const core=String(value||'').trim().replace(/^\/+|\/+$/g,''); return core?`/${core}/`:''; } function httpsPayload(){ return { target_type:$('https-target-type')?.value||'domain', target:$('https-target')?.value.trim()||'', email:$('https-email')?.value.trim()||'', https_port:Number($('https-port')?.value||443), access_path:normalizedHttpsAccessPath($('https-access-path')?.value||''), }; } function httpsUrlHost(value){const host=String(value||'').trim().replace(/^\[|\]$/g,'');return host.includes(':')?`[${host}]`:host;} function httpsOrigin(host,port){const p=Number(port||443);return `https://${httpsUrlHost(host)}${p===443?'':`:${p}`}`;} function httpsPanelUrl(host,port,path,suffix=''){return `${httpsOrigin(host,port)}${normalizedHttpsAccessPath(path)}${String(suffix||'').replace(/^\//,'')}`;} function usePanelHostForHttps(){ const field=$('https-target'),type=$('https-target-type'); if(!field)return; const host=String(location.hostname||'').replace(/^\[|\]$/g,''); if(!host)return; field.value=host; if(type){ const isIpv4=/^(?:\d{1,3}\.){3}\d{1,3}$/.test(host); const isIpv6=host.includes(':'); type.value=(isIpv4||isIpv6)?'ip':'domain'; field.placeholder=type.value==='ip'?'203.0.113.10':'wg.example.com'; } } function httpsReconnectUrl(payload,suffix='settings#https'){ return httpsPanelUrl(payload.target||location.hostname,payload.https_port||443,payload.access_path||'',suffix); } const wait = ms => new Promise(resolve=>setTimeout(resolve,ms)); async function currentPanelInstance(){ try{ const r=await fetch('/healthz',{cache:'no-store'}); if(!r.ok)return ''; const d=await r.json(); return String(d?.instance||''); }catch(_){return '';} } async function waitForHttpsReady(payload,previousInstance='',timeoutMs=35000){ const health=httpsPanelUrl(payload.target||location.hostname,payload.https_port||443,payload.access_path||'','healthz'); const deadline=Date.now()+Math.max(5000,Number(timeoutMs||35000)); while(Date.now()null); const instance=String(d?.instance||''); if(d?.ok && (!previousInstance || (instance && instance!==previousInstance)))return true; } }catch(_){} await wait(650); } return false; } async function reconnectAfterHttpsSwitch(payload,previousInstance='',initialDelay=4800){ const destination=httpsReconnectUrl(payload); // The privileged helper schedules a guarded service restart after the API // response has had time to flush. Do not navigate on a fixed timer: the // first browser request can otherwise hit the old route (404) or the TLS // socket while Uvicorn is still coming up (PR_END_OF_FILE_ERROR). await wait(Math.max(0,Number(initialDelay||0))); await waitForHttpsReady(payload,previousInstance); location.replace(destination); } function httpsPortLabel(item,port){ if(!item)return '—'; if(item.free)return t('settings.https_port_free','Free'); if(item.wgtools)return 'WGTools'; return `${t('settings.https_port_busy','Busy')}${item.owner?` · ${item.owner}`:''}`; } function renderHttpsPorts(ports,httpsPort){ const port=Number(httpsPort||$('https-port')?.value||443),p80=ports?.['80'],panel=ports?.[String(port)]; const e80=$('https-port-80'),ep=$('https-panel-port'),label=$('https-panel-port-label'); if(label)label.textContent=`TCP ${port}`; if(e80){e80.textContent=httpsPortLabel(p80,80);e80.className=p80?.free?'text-ok':'text-warn';} if(ep){const ok=Boolean(panel?.free||panel?.wgtools);ep.textContent=httpsPortLabel(panel,port);ep.className=ok?'text-ok':'text-warn';} } function httpsCertificateMatchesTarget(cert,targetType,target){ if(!cert?.exists||!target)return false; const expires=Number(cert?.expires_at||0); if(!expires||expires<=Math.floor(Date.now()/1000)+300)return false; const wanted=String(target||'').trim(); const sans=Array.isArray(cert?.sans)?cert.sans:[]; if(targetType==='ip')return sans.some(item=>String(item||'').trim()===wanted); const normalized=wanted.replace(/\.$/,'').toLowerCase(); return sans.some(item=>String(item||'').trim().replace(/\.$/,'').toLowerCase()===normalized); } function httpsEnableRequirement(){ const cert=httpsState?.certificate||{},payload=httpsPayload(); if(!cert.exists)return {ready:false,message:t('settings.https_enable_need_certificate','First obtain a certificate.')}; if(Number(cert.expires_at||0)<=Math.floor(Date.now()/1000)+300)return {ready:false,message:t('settings.https_enable_certificate_expired','The certificate has expired. Renew it before enabling HTTPS.')}; if(!httpsCertificateMatchesTarget(cert,payload.target_type,payload.target))return {ready:false,message:t('settings.https_enable_certificate_mismatch','Obtain a certificate for the current domain/public IP first.')}; return {ready:true,message:t('settings.https_enable_certificate_ready','Certificate is ready. Built-in HTTPS can now be enabled.')}; } function syncHttpsEnableAvailability(){ const checkbox=$('https-enabled'),help=$('https-enable-help'),certState=$('https-certificate-state'); if(!checkbox)return; const cert=httpsState?.certificate||{},payload=httpsPayload(); const expired=Boolean(cert.exists&&Number(cert.expires_at||0)<=Math.floor(Date.now()/1000)+300); const matches=Boolean(cert.exists&&!expired&&httpsCertificateMatchesTarget(cert,payload.target_type,payload.target)); if(certState){ if(!cert.exists)certState.textContent=t('settings.https_certificate_missing','Not issued'); else if(expired)certState.textContent=t('settings.https_certificate_expired','Expired'); else if(!matches)certState.textContent=t('settings.https_certificate_wrong_target','For another address'); else certState.textContent=t('settings.https_certificate_ready','Ready'); } if(httpsState?.enabled){ checkbox.disabled=false; if(help)help.textContent=t('settings.https_enable_active_help','Clear the checkbox and save to return to HTTP.'); return; } const requirement=httpsEnableRequirement(); checkbox.disabled=!requirement.ready; checkbox.checked=false; if(help)help.textContent=requirement.message; } function localizedHttpsError(message){ const raw=String(message||''); if(raw.includes("Obtain a Let's Encrypt certificate before enabling HTTPS"))return t('settings.https_enable_need_certificate','First obtain a certificate.'); if(raw.includes('existing certificate does not contain the requested domain/IP')||raw.includes('existing certificate belongs to a different domain/IP'))return t('settings.https_enable_certificate_mismatch','Obtain a certificate for the current domain/public IP first.'); if(raw.includes('existing certificate is expired'))return t('settings.https_enable_certificate_expired','The certificate has expired. Renew it before enabling HTTPS.'); return raw; } function renderHttpsStatus(data){ httpsState=data||{}; if($('https-enabled'))$('https-enabled').checked=Boolean(data?.enabled); if($('https-target-type'))$('https-target-type').value=data?.target_type||'domain'; if($('https-target'))$('https-target').value=data?.target||''; if($('https-email'))$('https-email').value=data?.email||''; if($('https-port'))$('https-port').value=String(data?.https_port||443); if($('https-access-path'))$('https-access-path').value=data?.access_path||''; const badge=$('https-status-badge');if(badge){badge.textContent=data?.enabled?t('settings.https_enabled','Enabled'):t('settings.https_disabled','Disabled');badge.className=data?.enabled?'badge managed':'badge';} const cert=data?.certificate||{}; if($('https-certificate-state'))$('https-certificate-state').textContent=cert.exists?t('settings.https_certificate_ready','Ready'):t('settings.https_certificate_missing','Not issued'); if($('https-certificate-expiry'))$('https-certificate-expiry').textContent=cert.expires_at?formatDate(cert.expires_at):'—'; if($('https-renewal-state'))$('https-renewal-state').textContent=data?.renewal_timer_enabled?t('settings.https_renewal_enabled','Enabled'):t('settings.https_renewal_disabled','Disabled'); if($('https-certbot-version'))$('https-certbot-version').textContent=data?.certbot_version?`v${data.certbot_version}`:'—'; const paths=$('https-paths');if(paths)paths.hidden=!cert.exists; if($('https-certificate-path'))$('https-certificate-path').value=cert.certificate_path||''; if($('https-private-key-path'))$('https-private-key-path').value=cert.private_key_path||''; renderHttpsPorts(data?.ports||{},data?.https_port||443); const target=$('https-target');if(target)target.placeholder=(data?.target_type||'domain')==='ip'?'203.0.113.10':'wg.example.com'; syncHttpsEnableAvailability(); } async function loadHttpsStatus(){ if(page!=='settings'||!$('https-settings-form'))return; try{const r=await fetch('/api/https/status',{cache:'no-store'});const d=await r.json();if(!r.ok)throw new Error(d.error||'Failed');renderHttpsStatus(d);} catch(e){operationStatus('https-settings-status',e.message,'error');} } async function checkHttpsPorts(){ const button=$('https-check-ports-button'),port=Number($('https-port')?.value||443);if(button)button.disabled=true; try{const r=await fetch('/api/https/ports',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({https_port:port})});const d=await r.json();if(!r.ok)throw new Error(d.error||'Failed');renderHttpsPorts(d.ports||{},d.https_port||port);operationStatus('https-settings-status',t('settings.https_ports_checked','Port check completed.'),'success');} catch(e){operationStatus('https-settings-status',e.message,'error');}finally{if(button)button.disabled=false;} } async function issueHttpsCertificate(){ const payload=httpsPayload(),button=$('https-issue-button'),wasEnabled=Boolean(httpsState?.enabled); if(!payload.target||!payload.email||!payload.access_path){operationStatus('https-settings-status',t('settings.https_issue_fields_required','Enter the domain/public IP, Let’s Encrypt e-mail, and panel access path.'),'error');return;} if(!confirm(t('settings.https_issue_confirm','Request or renew the Let’s Encrypt certificate for {target}? The entered HTTPS settings will be saved. TCP port 80 must be reachable from the Internet.').replace('{target}',payload.target)))return; if(button)button.disabled=true;operationStatus('https-settings-status',t('settings.https_issuing','Requesting certificate from Let’s Encrypt…'),'working'); try{ const previousInstance=wasEnabled?await currentPanelInstance():''; const r=await fetch('/api/https/issue',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(payload)}); const d=await r.json(); if(!r.ok)throw new Error(d.error||'Failed'); operationStatus('https-settings-status',t('settings.https_issue_ok_saved','Certificate is ready and HTTPS settings are saved.'),'success'); toast(t('settings.https_issue_ok','Certificate is ready.')); if(wasEnabled){ const host=httpsState?.target||location.hostname,port=httpsState?.https_port||443,path=httpsState?.access_path||basePath; void reconnectAfterHttpsSwitch({target:host,https_port:port,access_path:path},previousInstance,4800); }else{ await loadHttpsStatus(); } } catch(e){ const message=localizedHttpsError(e.message); if(!wasEnabled)await loadHttpsStatus(); operationStatus('https-settings-status',message,'error'); }finally{if(button)button.disabled=false;} } async function saveHttpsSettings(event){ event.preventDefault();const enabled=Boolean($('https-enabled')?.checked),payload=httpsPayload();const button=event.currentTarget.querySelector('button[type="submit"]');if(button)button.disabled=true; try{ if(enabled){ if(!payload.target||!payload.email||!payload.access_path)throw new Error(t('settings.https_enable_fields_required','Enter the domain/public IP, Let’s Encrypt e-mail, and panel access path.')); const requirement=httpsEnableRequirement(); if(!requirement.ready)throw new Error(requirement.message); const unchanged=Boolean(httpsState?.enabled&&httpsState?.target===payload.target&&httpsState?.target_type===payload.target_type&&Number(httpsState?.https_port||443)===payload.https_port&&normalizedHttpsAccessPath(httpsState?.access_path)===payload.access_path); if(unchanged){operationStatus('https-settings-status',t('settings.https_already_enabled','Built-in HTTPS is already enabled.'),'success');return;} const confirmText=t('settings.https_enable_confirm','Enable built-in HTTPS on TCP {port} with path {path}? WGTools will restart and this page will reconnect at the new address.').replace('{port}',String(payload.https_port)).replace('{path}',payload.access_path); if(!confirm(confirmText))return; const previousInstance=await currentPanelInstance(); operationStatus('https-settings-status',t('settings.https_switching','Enabling HTTPS and restarting WGTools…'),'working'); let r; try{ r=await fetch('/api/https/enable',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(payload),keepalive:true}); }catch(networkError){ // Changing the HTTPS port/path restarts this very web service. If the // response socket is cut during the hand-off, continue to the exact // requested HTTPS URL instead of leaving the browser on the old origin. operationStatus('https-settings-status',t('settings.https_reconnecting','WGTools is switching to the new HTTPS address…'),'working'); void reconnectAfterHttpsSwitch(payload,previousInstance,4800); return; } const d=await r.json();if(!r.ok)throw new Error(d.error||'Failed'); const destination={target:String(d.redirect_host||payload.target),https_port:Number(d.redirect_port||payload.https_port),access_path:d.access_path||payload.access_path}; operationStatus('https-settings-status',t('settings.https_reconnecting','WGTools is switching to the new HTTPS address…'),'working'); void reconnectAfterHttpsSwitch(destination,previousInstance,4800); }else{ if(!httpsState?.enabled){operationStatus('https-settings-status',t('settings.https_already_disabled','Built-in HTTPS is already disabled.'),'success');return;} if(!confirm(t('settings.https_disable_confirm','Disable built-in HTTPS and return WGTools to HTTP?')))return; operationStatus('https-settings-status',t('settings.https_switching_http','Disabling HTTPS and restarting WGTools…'),'working'); const r=await fetch('/api/https/disable',{method:'POST'});const d=await r.json();if(!r.ok)throw new Error(d.error||'Failed'); const host=httpsUrlHost(location.hostname),port=Number(d.http_port||8341);setTimeout(()=>{location.replace(`http://${host}:${port}/settings#https`);},6500); } }catch(e){operationStatus('https-settings-status',localizedHttpsError(e.message),'error');if(httpsState)$('https-enabled').checked=Boolean(httpsState.enabled);syncHttpsEnableAvailability();}finally{if(button)button.disabled=false;} } async function copyHttpsPath(id){ const field=$(id);if(!field?.value)return; try{await navigator.clipboard.writeText(field.value);toast(t('common.copied','Copied'));} catch(_){field.focus();field.select();document.execCommand('copy');field.setSelectionRange(0,0);toast(t('common.copied','Copied'));} } function bindHttpsSettings(){ $('https-settings-form')?.addEventListener('submit',saveHttpsSettings); $('https-check-ports-button')?.addEventListener('click',checkHttpsPorts); $('https-issue-button')?.addEventListener('click',issueHttpsCertificate); $('https-use-panel-host')?.addEventListener('click',()=>{usePanelHostForHttps();syncHttpsEnableAvailability();}); $('https-port')?.addEventListener('input',()=>renderHttpsPorts(httpsState?.ports||{},Number($('https-port')?.value||443))); $('https-target')?.addEventListener('input',syncHttpsEnableAvailability); $('https-target-type')?.addEventListener('change',e=>{const f=$('https-target');if(f)f.placeholder=e.currentTarget.value==='ip'?'203.0.113.10':'wg.example.com';syncHttpsEnableAvailability();}); document.querySelectorAll('[data-copy-path]').forEach(button=>button.addEventListener('click',()=>copyHttpsPath(button.dataset.copyPath))); if(page==='settings')loadHttpsStatus(); } let telegramState = null; function parseNumericLines(value){ const items=String(value||'').split(/[\s,;]+/).map(x=>x.trim()).filter(Boolean); const result=[]; for(const item of items){ if(!/^\d+$/.test(item) || Number(item)<=0) throw new Error(`${t('settings.telegram_allowed_ids','Allowed Telegram user IDs')}: ${item}`); const n=Number(item); if(!result.includes(n))result.push(n); } return result; } function parseTextList(value){ return String(value||'').split(/[\s,;]+/).map(x=>x.trim()).filter(Boolean); } function renderTelegramSettings(data){ telegramState=data||{}; const enabled=$('telegram-enabled'); if(enabled)enabled.checked=Boolean(data?.enabled); const token=$('telegram-token'); if(token){token.value='';token.placeholder=data?.token_masked||t('settings.telegram_not_configured','Not configured');} const ids=$('telegram-allowed-ids'); if(ids)ids.value=(data?.allowed_user_ids||[]).join('\n'); const endpoint=$('telegram-endpoint'); if(endpoint)endpoint.value=data?.default_endpoint||''; const dns=$('telegram-dns'); if(dns)dns.value=(data?.default_dns||[]).join(', '); const language=$('telegram-language'); if(language)language.value=data?.language||'auto'; const remove=$('telegram-remove-token-button'); if(remove)remove.disabled=!data?.token_configured; const botName=$('telegram-bot-name'); if(botName)botName.textContent=data?.bot_username?`@${data.bot_username}`:t('settings.telegram_not_configured','Not configured'); const last=$('telegram-last-poll'); if(last)last.textContent=`${t('settings.telegram_last_poll','Last Telegram contact')}: ${data?.last_poll_at?formatDate(data.last_poll_at):'—'}`; const badge=$('telegram-status-badge'); if(badge){ let label=t('settings.telegram_not_configured','Not configured'), cls='badge'; if(!data?.enabled){label=data?.token_configured?t('settings.telegram_disabled','Disabled'):t('settings.telegram_not_configured','Not configured');cls='badge';} else if(data?.last_error){label=t('common.error','Error');cls='badge warn';} else if(data?.last_poll_at && (Date.now()/1000-Number(data.last_poll_at)<90)){label=t('settings.telegram_connected','Connected');cls='badge managed';} else if(data?.token_configured){label=t('settings.telegram_waiting','Configured, waiting for bot service');cls='badge warn';} badge.textContent=label;badge.className=cls; } if(data?.last_error)operationStatus('telegram-settings-status',data.last_error,'error'); else operationStatus('telegram-settings-status',''); } async function loadTelegramSettings(){ if(page!=='settings'||!$('telegram-settings-form'))return; try{ const r=await fetch('/api/telegram/settings',{cache:'no-store'});const d=await r.json();if(!r.ok)throw new Error(d.error||'Failed');renderTelegramSettings(d.settings||{}); }catch(e){operationStatus('telegram-settings-status',e.message,'error');} } async function saveTelegramSettings(event){ event.preventDefault(); const button=event.currentTarget.querySelector('button[type="submit"]');if(button)button.disabled=true; operationStatus('telegram-settings-status',t('settings.saving','Saving settings…'),'working'); try{ const payload={ enabled:Boolean($('telegram-enabled')?.checked), bot_token:$('telegram-token')?.value.trim()||'', clear_token:false, allowed_user_ids:parseNumericLines($('telegram-allowed-ids')?.value||''), default_endpoint:$('telegram-endpoint')?.value.trim()||'', default_dns:parseTextList($('telegram-dns')?.value||''), language:$('telegram-language')?.value||'auto', }; const r=await fetch('/api/telegram/settings',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(payload)});const d=await r.json();if(!r.ok)throw new Error(d.error||'Failed'); renderTelegramSettings(d.settings||{});operationStatus('telegram-settings-status',t('settings.telegram_saved','Telegram settings saved.'),'success');toast(t('settings.telegram_saved','Telegram settings saved.')); setTimeout(loadTelegramSettings,1800); }catch(e){operationStatus('telegram-settings-status',e.message,'error');}finally{if(button)button.disabled=false;} } async function testTelegram(){ const button=$('telegram-test-button');if(button)button.disabled=true;operationStatus('telegram-settings-status',t('common.checking','Checking…'),'working'); try{ const r=await fetch('/api/telegram/test',{method:'POST'});const d=await r.json();if(!r.ok)throw new Error(d.error||'Failed'); const text=d.verified_by_last_poll ? t('settings.telegram_test_recent_ok','Telegram bot is working. The direct check timed out, but the bot contacted Telegram recently.') : t('settings.telegram_test_ok','Telegram connection is working: @{username}').replace('{username}',d.username||'bot'); operationStatus('telegram-settings-status',text,'success');toast(text);await loadTelegramSettings(); }catch(e){operationStatus('telegram-settings-status',e.message,'error');}finally{if(button)button.disabled=false;} } async function removeTelegramToken(){ if(!confirm(t('settings.telegram_remove_token_confirm','Remove the saved Telegram bot token and disable the bot?')))return; const button=$('telegram-remove-token-button');if(button)button.disabled=true; try{ const current=telegramState||{}; const payload={enabled:false,bot_token:'',clear_token:true,allowed_user_ids:current.allowed_user_ids||[],default_endpoint:current.default_endpoint||'',default_dns:current.default_dns||[],language:current.language||'auto'}; const r=await fetch('/api/telegram/settings',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(payload)});const d=await r.json();if(!r.ok)throw new Error(d.error||'Failed');renderTelegramSettings(d.settings||{});toast(t('settings.telegram_saved','Telegram settings saved.')); }catch(e){operationStatus('telegram-settings-status',e.message,'error');}finally{if(button)button.disabled=false;} } function bindTelegramSettings(){ $('telegram-settings-form')?.addEventListener('submit',saveTelegramSettings); $('telegram-test-button')?.addEventListener('click',testTelegram); $('telegram-remove-token-button')?.addEventListener('click',removeTelegramToken); if(page==='settings')loadTelegramSettings(); } async function saveAppSettings(event){ event.preventDefault(); const payload={ refresh_seconds:Number($('settings-refresh-seconds')?.value||5), online_threshold_seconds:Number($('settings-online-threshold')?.value||180), backup_retention:Number($('settings-backup-retention')?.value||20), }; const button=event.currentTarget.querySelector('button[type="submit"]'); if(button)button.disabled=true; operationStatus('app-settings-status',t('settings.saving','Saving settings…'),'working'); try{ const r=await fetch('/api/app-settings',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(payload)}); const d=await r.json(); if(!r.ok)throw new Error(d.error||'Failed'); operationStatus('app-settings-status',t('settings.saved_reload','Settings saved. Reloading…'),'success'); toast(t('settings.saved','Settings saved.')); setTimeout(()=>location.reload(),450); }catch(e){operationStatus('app-settings-status',e.message,'error'); if(button)button.disabled=false;} } function bindHelp(){ const button=$('help-button'); if(!button)return; const selectSection=id=>{ document.querySelectorAll('[data-help-target]').forEach(b=>b.classList.toggle('active',b.dataset.helpTarget===id)); document.querySelectorAll('[data-help-section]').forEach(section=>section.hidden=section.dataset.helpSection!==id); const content=document.querySelector('#help-modal .help-content'); if(content)content.scrollTop=0; }; button.addEventListener('click',()=>{ const current={dashboard:'dashboard',server:'server',clients:'clients',settings:'settings'}[page]||'dashboard'; selectSection(current); modalShow('help-modal',true); }); document.querySelectorAll('[data-help-target]').forEach(b=>b.addEventListener('click',()=>selectSection(b.dataset.helpTarget))); } function migrationFilenameFromDisposition(value){ const text=String(value||''); const utf=text.match(/filename\*=UTF-8''([^;]+)/i); if(utf){try{return decodeURIComponent(utf[1].replace(/^"|"$/g,''));}catch(_){}} const plain=text.match(/filename="?([^";]+)"?/i); return plain?plain[1]:'WGTools-backup.wgtbackup'; } async function downloadMigrationBackup(){ const button=$('migration-backup-download-button'); if(!button)return; button.disabled=true; operationStatus('migration-backup-status',t('settings.full_backup_creating','Creating a complete backup…'),'working'); try{ const r=await fetch('/api/migration/backup',{cache:'no-store'}); if(!r.ok){const d=await r.json().catch(()=>({}));throw new Error(d.error||t('settings.full_backup_create_failed','Could not create the full backup'));} const blob=await r.blob(); const name=migrationFilenameFromDisposition(r.headers.get('content-disposition')); const url=URL.createObjectURL(blob); const a=document.createElement('a'); a.href=url; a.download=name; document.body.appendChild(a); a.click(); a.remove(); setTimeout(()=>URL.revokeObjectURL(url),2000); operationStatus('migration-backup-status',t('settings.full_backup_downloaded','Backup created and downloaded. Store it securely.'),'success'); toast(t('settings.full_backup_downloaded_short','Full backup downloaded.')); }catch(e){operationStatus('migration-backup-status',e.message,'error');toast(e.message);} finally{button.disabled=false;} } function migrationFileChanged(){ const input=$('migration-backup-file'), label=$('migration-selected-file'), restore=$('migration-backup-restore-button'); const file=input?.files?.[0]||null; if(label) label.textContent=file?`${file.name} · ${fmtBytes(file.size)}`:t('settings.full_backup_no_file','No backup selected'); if(restore) restore.disabled=!file; operationStatus('migration-backup-status',''); } async function restoreMigrationBackup(){ const input=$('migration-backup-file'), file=input?.files?.[0], button=$('migration-backup-restore-button'); if(!file||!button)return; if(!confirm(t('settings.full_backup_restore_confirm','Restore this full WGTools backup? Current users, settings, managed client data and WireGuard configuration will be replaced. WireGuard may restart.')))return; button.disabled=true; const download=$('migration-backup-download-button'), select=$('migration-backup-select-button'); if(download)download.disabled=true;if(select)select.disabled=true; operationStatus('migration-backup-status',t('settings.full_backup_restoring','Validating backup, creating a safety copy and restoring…'),'working'); try{ const r=await fetch('/api/migration/restore',{method:'POST',headers:{'Content-Type':'application/octet-stream','X-WGTools-Backup-Name':file.name},body:file}); const d=await r.json(); if(!r.ok)throw new Error(d.error||t('settings.full_backup_restore_failed','Restore failed')); operationStatus('migration-backup-status',t('settings.full_backup_restored','Backup restored successfully. Sign in with an account from the restored backup.'),'success'); toast(t('settings.full_backup_restored_short','Backup restored.')); setTimeout(()=>{location.href=appUrl('/login');},1200); }catch(e){ operationStatus('migration-backup-status',e.message,'error'); toast(e.message); button.disabled=false; if(download)download.disabled=false;if(select)select.disabled=false; } } function bindMigrationBackup(){ const input=$('migration-backup-file'); $('migration-backup-download-button')?.addEventListener('click',downloadMigrationBackup); $('migration-backup-select-button')?.addEventListener('click',()=>input?.click()); input?.addEventListener('change',migrationFileChanged); $('migration-backup-restore-button')?.addEventListener('click',restoreMigrationBackup); } let updateRelease=null; let updatePollTimer=null; let updateNoticeTimer=null; const updateNoticeStorageKey='wgtools.updateNotice'; function rememberUpdateNotice(data){ try{ if(data?.update_available&&data?.latest_version)localStorage.setItem(updateNoticeStorageKey,JSON.stringify({update_available:true,latest_version:data.latest_version,current_version:data.current_version||'',tag_name:data.tag_name||'',checked_at:data.checked_at||Math.floor(Date.now()/1000)})); else if(data&&data.update_available===false&&data.latest_version&&!data.check_error)localStorage.removeItem(updateNoticeStorageKey); }catch(_){} } function restoreUpdateNotice(){ try{ const raw=localStorage.getItem(updateNoticeStorageKey); if(!raw)return; const data=JSON.parse(raw); if(data?.update_available&&data?.latest_version)renderSidebarUpdateNotice(data); }catch(_){} } function renderSidebarUpdateNotice(data){ const notice=null; // The topbar is the sole update notification. const header=$('topbar-update-notice'); const available=Boolean(data?.update_available&&data?.latest_version); if(notice)notice.hidden=!available; if(header)header.hidden=!available; if(!available)return; const version=$('sidebar-update-version'); if(version)version.textContent=`v${data.latest_version}`; const headVersion=$('topbar-update-version'); if(headVersion)headVersion.textContent=`v${data.latest_version}`; const label=`${t('settings.update_sidebar','Update available')} · v${data.latest_version}`; if(notice)notice.setAttribute('aria-label',label); if(header)header.setAttribute('aria-label',label); } async function refreshUpdateNotice(){ try{ const r=await fetch('/api/update/notice',{cache:'no-store'});const d=await r.json();if(!r.ok)return; if(d?.check_error&&!d?.latest_version){ if(page==='settings'&&$('check-updates-button')){ setUpdateBadge(t('settings.update_check_failed','Check failed'),'warn'); operationStatus('update-operation-status',d.check_error,'error'); } return; // Network failure must not clear a previously confirmed update. } rememberUpdateNotice(d); renderSidebarUpdateNotice(d); if(page==='settings'&&$('check-updates-button')&&d?.latest_version)renderUpdateRelease(d); }catch(_){} } function setUpdateBadge(text,kind=''){ const badge=$('update-status-badge'); if(!badge)return; badge.textContent=text; badge.className=`badge ${kind}`.trim(); } function renderUpdateRelease(data){ updateRelease=data||null; rememberUpdateNotice(data); renderSidebarUpdateNotice(data); const latest=$('update-latest-version'); if(latest)latest.textContent=data?.latest_version?`v${data.latest_version}`:'—'; const current=$('update-current-version'); if(current&&data?.current_version)current.textContent=data.current_version; const notesWrap=$('update-release-notes-wrap'), notes=$('update-release-notes'), link=$('update-release-link'); if(notesWrap)notesWrap.hidden=!data?.release_notes; if(notes)notes.textContent=data?.release_notes||''; if(link&&data?.release_url)link.href=data.release_url; const apply=$('apply-update-button'); if(data?.check_error&&(!data?.latest_version||data?.stale)){ setUpdateBadge(t('settings.update_check_failed','Check failed'),'warn'); operationStatus('update-operation-status',String(data.check_error),'error'); }else if(data?.update_available){ setUpdateBadge(t('settings.update_available','Update available'),'warn'); if(apply){apply.hidden=false;apply.disabled=false;apply.textContent=`${t('settings.update_wgtools','Update WGTools')} · v${data.latest_version}`;} operationStatus('update-operation-status',`${t('settings.update_available','Update available')}: v${data.current_version} → v${data.latest_version}`,'working'); }else{ setUpdateBadge(t('settings.update_current','Up to date'),'managed'); if(apply){apply.hidden=true;apply.disabled=true;} operationStatus('update-operation-status',t('settings.update_no_update','WGTools is already up to date.'),'success'); } } async function checkUpdates(){ const check=$('check-updates-button'), apply=$('apply-update-button'); if(check)check.disabled=true;if(apply)apply.disabled=true; setUpdateBadge(t('common.checking','Checking…'),'warn'); operationStatus('update-operation-status',t('settings.update_checking','Checking the latest published GitHub Release…'),'working'); try{ const r=await fetch('/api/update/check',{cache:'no-store'});const d=await r.json();if(!r.ok)throw new Error(d.error||t('settings.update_check_failed','Could not check for updates')); renderUpdateRelease(d); }catch(e){ setUpdateBadge(t('settings.update_check_failed','Check failed'),''); operationStatus('update-operation-status',e.message,'error');toast(e.message); }finally{ if(check)check.disabled=false; if(apply&&updateRelease?.update_available)apply.disabled=false; } } function updateProgressText(data){ if(data?.state==='queued')return t('settings.update_queued','Update queued. Waiting for the updater service…'); if(data?.state==='rolling_back')return t('settings.update_rolling_back','Update failed. Restoring the previous WGTools application…'); if(data?.state==='running'){ if(data.phase==='backup')return t('settings.update_backup_running','Creating the automatic full backup before update…'); if(data.phase==='download')return t('settings.update_downloading','Downloading and validating the GitHub release…'); if(data.phase==='install')return t('settings.update_installing','Installing the update. The web interface may be unavailable briefly…'); return t('settings.update_running','Creating safety backups…'); } return data?.message||t('settings.update_status_unknown','Update status is unavailable. Retrying…'); } async function pollUpdateStatus(deadline=Date.now()+12*60*1000){ if(updatePollTimer){clearTimeout(updatePollTimer);updatePollTimer=null;} if(Date.now()>deadline){operationStatus('update-operation-status',t('settings.update_status_unknown','Update status is unavailable. Retrying…'),'error');return;} try{ const r=await fetch('/api/update/status',{cache:'no-store'});const d=await r.json();if(!r.ok)throw new Error(d.error||'Status unavailable'); if(d.state==='success'){ const version=d.target_version||d.current_version||''; rememberUpdateNotice({update_available:false}); setUpdateBadge(t('settings.update_current','Up to date'),'managed'); operationStatus('update-operation-status',t('settings.update_success','WGTools was updated successfully to v{version}. Reloading…').replace('{version}',version),'success'); setTimeout(()=>location.reload(),1400);return; } if(d.state==='error'){ setUpdateBadge(t('settings.update_failed','Update failed'),''); let message=d.error||d.message||t('settings.update_failed','WGTools update failed.'); if(d.rollback_ok)message+=`\n${t('settings.update_rollback_ok','The previous WGTools application was restored automatically.')}`; operationStatus('update-operation-status',message,'error'); const check=$('check-updates-button'), apply=$('apply-update-button');if(check)check.disabled=false;if(apply)apply.disabled=false;if($('update-upload-button'))$('update-upload-button').disabled=false; return; } setUpdateBadge(d.state==='rolling_back'?t('settings.update_failed','Update failed'):t('settings.update_available','Updating…'),'warn'); operationStatus('update-operation-status',updateProgressText(d),'working'); }catch(_){ operationStatus('update-operation-status',t('settings.update_installing','Installing the update. The web interface may be unavailable briefly…'),'working'); } updatePollTimer=setTimeout(()=>pollUpdateStatus(deadline),2000); } async function applyUpdate(){ if(!updateRelease?.update_available||!updateRelease?.tag_name)return; const current=updateRelease.current_version||$('update-current-version')?.textContent||''; const latest=updateRelease.latest_version||''; const question=t('settings.update_confirm','Update WGTools from v{current} to v{latest}? A full backup and application rollback copy will be created first. The web interface will restart briefly.').replace('{current}',current).replace('{latest}',latest); if(!confirm(question))return; const check=$('check-updates-button'), apply=$('apply-update-button');if(check)check.disabled=true;if(apply)apply.disabled=true; setUpdateBadge(t('settings.update_available','Updating…'),'warn'); operationStatus('update-operation-status',t('settings.update_starting','Starting the update…'),'working'); try{ const r=await fetch('/api/update/apply',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({tag:updateRelease.tag_name})}); const d=await r.json();if(!r.ok)throw new Error(d.error||t('settings.update_failed','WGTools update failed.')); if(!d.scheduled){operationStatus('update-operation-status',d.message||t('settings.update_no_update','WGTools is already up to date.'),'success');if(check)check.disabled=false;return;} operationStatus('update-operation-status',t('settings.update_backup_queued','Update queued. WGTools will create an automatic full backup before installing it…'),'working'); setTimeout(()=>pollUpdateStatus(),1200); }catch(e){operationStatus('update-operation-status',e.message,'error');setUpdateBadge(t('settings.update_failed','Update failed'),'');if(check)check.disabled=false;if(apply)apply.disabled=false;} } async function resumeUpdateStatus(){ if(page!=='settings'||!$('check-updates-button'))return; try{ const r=await fetch('/api/update/status',{cache:'no-store'});const d=await r.json();if(!r.ok)return; const age=Date.now()/1000-Number(d.updated_at||0); if(['queued','running','rolling_back'].includes(d.state)){const check=$('check-updates-button'),apply=$('apply-update-button');if(check)check.disabled=true;if(apply)apply.disabled=true;pollUpdateStatus();} else if(d.state==='success'&&age<300){operationStatus('update-operation-status',String(d.message||''),'success');} else if(d.state==='error'&&age<300){let msg=d.error||d.message||t('settings.update_failed','WGTools update failed.');if(d.rollback_ok)msg+=`\n${t('settings.update_rollback_ok','The previous WGTools application was restored automatically.')}`;operationStatus('update-operation-status',msg,'error');} }catch(_){} } function bindUpdates(){ $('update-upload-button')?.addEventListener('click',async()=>{ const file=$('update-upload-file')?.files[0]; if(!file){operationStatus('update-operation-status','Wybierz pakiet .bin.','error');return;} if(file.size>64*1024*1024){operationStatus('update-operation-status','Pakiet przekracza 64 MB.','error');return;} if(!confirm('Zainstalować wybrany pakiet? Aplikacja zostanie na chwilę uruchomiona ponownie.'))return; const button=$('update-upload-button');button.disabled=true;operationStatus('update-operation-status','Sprawdzanie pakietu aktualizacji…','working'); try{const r=await fetch(appUrl('/api/update/upload'),{method:'POST',headers:{'Content-Type':'application/octet-stream'},body:file});const d=await r.json();if(!r.ok)throw new Error(d.error||'Nie udało się uruchomić aktualizacji.');operationStatus('update-operation-status','Aktualizacja została uruchomiona.','working');pollUpdateStatus();}catch(err){operationStatus('update-operation-status',err.message,'error');button.disabled=false;} }); $('check-updates-button')?.addEventListener('click',checkUpdates); $('apply-update-button')?.addEventListener('click',applyUpdate); resumeUpdateStatus(); } function bindAppSettings(){ $('app-settings-form')?.addEventListener('submit',saveAppSettings); $('save-backup-settings-button')?.addEventListener('click',()=>$('app-settings-form')?.requestSubmit()); } function setTheme(value){ localStorage.setItem('wgtools.theme',value); let actual=value; if(value==='system')actual=matchMedia('(prefers-color-scheme: light)').matches?'light':'dark'; document.documentElement.dataset.theme=actual; const select=$('theme-select');if(select)select.value=value; const button=$('topbar-theme-toggle');if(button){ const label=actual==='dark'?t('settings.theme_light','Light theme'):t('settings.theme_dark','Dark theme'); button.setAttribute('aria-label',label);button.dataset.tooltip=label;button.removeAttribute('title'); } } function setSidebarCollapsed(collapsed,persist=true){ const next=Boolean(collapsed); document.body.classList.toggle('sidebar-collapsed',next); document.documentElement.classList.remove('sidebar-pref-collapsed'); if(persist){try{localStorage.setItem('wgtools.sidebar.collapsed',next?'1':'0');}catch(_){}} const toggle=$('sidebar-collapsed-toggle');if(toggle)toggle.checked=next; const button=$('sidebar-collapse-button');if(button){button.setAttribute('aria-expanded',String(!next));const label=next?t('settings.expand_sidebar','Expand sidebar'):t('settings.collapse_sidebar','Collapse sidebar');button.dataset.tooltip=label;button.setAttribute('aria-label',label);button.classList.toggle('is-collapsed',next);} } function initSettings(){ const theme=localStorage.getItem('wgtools.theme')||'dark';setTheme(theme); const s=$('theme-select');if(s){s.value=theme;s.addEventListener('change',()=>setTheme(s.value));} $('topbar-theme-toggle')?.addEventListener('click',()=>setTheme(document.documentElement.dataset.theme==='dark'?'light':'dark')); try{matchMedia('(prefers-color-scheme: light)').addEventListener('change',()=>{if(localStorage.getItem('wgtools.theme')==='system')setTheme('system');});}catch(_){} const l=$('language-select');if(l){l.value=window.WGToolsI18n.getLanguage();l.addEventListener('change',()=>window.WGToolsI18n.setLanguage(l.value));} const sidebarToggle=$('sidebar-collapsed-toggle'); if(sidebarToggle){ let collapsed=false;try{collapsed=localStorage.getItem('wgtools.sidebar.collapsed')==='1';}catch(_){} sidebarToggle.checked=collapsed; sidebarToggle.addEventListener('change',()=>setSidebarCollapsed(sidebarToggle.checked)); } } function initSidebar(){ let collapsed=false; try{collapsed=localStorage.getItem('wgtools.sidebar.collapsed')==='1';}catch(_){} setSidebarCollapsed(collapsed,false); $('sidebar-collapse-button')?.addEventListener('click',()=>setSidebarCollapsed(!document.body.classList.contains('sidebar-collapsed'))); } function fillCreateInterfaceForm(){ const x=interfacesData.suggested||{}; if($('new-interface-name'))$('new-interface-name').value=x.interface||'wg1'; if($('new-interface-display-name'))$('new-interface-display-name').value=x.display_name||''; if($('new-interface-vpn-network'))$('new-interface-vpn-network').value=x.vpn_network||'10.0.1.0/24'; if($('new-interface-server-address'))$('new-interface-server-address').value=x.server_address||firstHostFromCidr(x.vpn_network||'10.0.1.0/24')||''; if($('new-interface-port'))$('new-interface-port').value=x.listen_port||51821; if($('new-interface-mtu'))$('new-interface-mtu').value=x.mtu||''; if($('new-interface-uplink'))$('new-interface-uplink').value=x.uplink_interface||snapshot?.system?.default_uplink||''; if($('new-interface-gateway'))$('new-interface-gateway').value=x.gateway||snapshot?.system?.default_gateway||''; if($('new-interface-local-network'))$('new-interface-local-network').value=x.local_network||snapshot?.system?.local_network||''; if($('new-interface-policy-table'))$('new-interface-policy-table').value=x.policy_table||''; if($('new-interface-forwarding'))$('new-interface-forwarding').checked=x.ip_forwarding!==false; if($('new-interface-nat'))$('new-interface-nat').checked=x.nat_enabled!==false; const addr=$('new-interface-server-address');if(addr)delete addr.dataset.touched; operationStatus('interface-create-status',''); } async function openCreateInterface(){ await fetchInterfaces(true);fillCreateInterfaceForm();modalShow('interface-create-modal',true);setTimeout(()=>$('new-interface-display-name')?.focus(),30); } function syncNewInterfaceAddress(){const net=$('new-interface-vpn-network'),addr=$('new-interface-server-address');if(!net||!addr||addr.dataset.touched)return;const first=firstHostFromCidr(net.value);if(first)addr.value=first;} async function createInterface(event){ event.preventDefault();const button=$('interface-create-save');if(!button)return; const payload={ interface:$('new-interface-name').value.trim(),display_name:$('new-interface-display-name').value.trim(), vpn_network:$('new-interface-vpn-network').value.trim(),server_address:$('new-interface-server-address').value.trim(),listen_port:Number($('new-interface-port').value),mtu:Number($('new-interface-mtu').value||0), uplink_interface:$('new-interface-uplink').value.trim(),gateway:$('new-interface-gateway').value.trim(),local_network:$('new-interface-local-network').value.trim(),policy_table:$('new-interface-policy-table').value.trim(), nat_enabled:$('new-interface-nat').checked,ip_forwarding:$('new-interface-forwarding').checked, ...networkBindingPayload('new-interface'), }; const label=payload.display_name?`${payload.interface} · ${payload.display_name}`:payload.interface; if(!confirm(t('interfaces.create_confirm','Create and start interface {name}?').replace('{name}',label)))return; button.disabled=true;operationStatus('interface-create-status',t('interfaces.creating','Generating keys, writing the new configuration and starting WireGuard…'),'working'); try{ const r=await fetch('/api/interfaces/create',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(payload)});const d=await r.json();if(!r.ok)throw new Error(d.error||t('interfaces.create_failed','Interface could not be created')); operationStatus('interface-create-status',t('interfaces.created','Interface created successfully.'),'success');toast(t('interfaces.created','Interface created successfully.')); setInterfaceCookie(payload.interface);setTimeout(()=>{location.href=appUrl('/server');},500); }catch(e){const message=localizedServerError(e.message);operationStatus('interface-create-status',message,'error');toast(message);}finally{button.disabled=false;} } async function deleteInterface(name){ const item=(interfacesData.interfaces||[]).find(x=>x.name===name);if(!item)return; const configured=(interfacesData.interfaces||[]).filter(x=>x.configured); if(configured.length<=1){toast(t('interfaces.delete_last','The last configured WireGuard interface cannot be deleted here.'));return;} const label=interfaceDisplay(item); const message=t('interfaces.delete_confirm','Delete interface {name}? This removes its WireGuard configuration and all peers on this interface. A configuration backup is created first.').replace('{name}',label); if(!confirm(message))return; const button=document.querySelector(`[data-interface-delete="${CSS.escape(name)}"]`);if(button)button.disabled=true; toast(t('interfaces.deleting','Stopping WireGuard and deleting the interface…'),5000); try{ const r=await fetch('/api/interfaces/delete',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({interface:name})});const d=await r.json();if(!r.ok)throw new Error(d.error||t('interfaces.delete_failed','Interface could not be deleted')); const backupName=String(d.backup||'').split('/').pop()||'—'; toast(t('interfaces.deleted','Interface deleted. Backup: {backup}').replace('{backup}',backupName),5000); if(d.next_interface)setInterfaceCookie(d.next_interface); setTimeout(()=>{location.href=appUrl('/server');},600); }catch(e){toast(e.message,5000);if(button)button.disabled=false;} } function bindInterfaceManager(){ $('add-interface-button')?.addEventListener('click',openCreateInterface);$('interface-create-form')?.addEventListener('submit',createInterface); $('new-interface-vpn-network')?.addEventListener('input',syncNewInterfaceAddress);$('new-interface-server-address')?.addEventListener('input',e=>e.currentTarget.dataset.touched='1'); } function bindProvisioning(){ $('install-wireguard-button')?.addEventListener('click',installWireGuard); $('create-server-form')?.addEventListener('submit',createServer); $('setup-vpn-network')?.addEventListener('input',syncServerAddress); $('setup-server-address')?.addEventListener('input',e=>e.currentTarget.dataset.touched='1'); ['setup-uplink','setup-gateway','setup-local-network'].forEach(id=>$(id)?.addEventListener('input',e=>e.currentTarget.dataset.touched='1')); } async function boot(){ setTheme(localStorage.getItem('wgtools.theme')||'dark'); initSettings(); initSidebar(); bindDelayedTooltips(); bindHelp(); bindInterfaceSwitcher(); bindInterfaceManager(); bindServerTabs(); bindSettingsTabs(); bindNodes(); bindVps(); bindAppSettings(); bindUpdates(); bindMigrationBackup(); bindTelegramSettings(); bindMailSettings(); bindHttpsSettings(); bindWireGuardControls(); bindProvisioning(); bindServerEditor(); bindServerRules(); bindClientManagement(); bindRawConfigEditor(); bindUserManagement(); bindAudit(); try{localStorage.removeItem(updateNoticeStorageKey);}catch(_){} $('refresh-button')?.addEventListener('click',()=>fetchSnapshot(true)); $('traffic-reset-button')?.addEventListener('click',resetTraffic); const dashboardSearch=$('dashboard-peer-search'), dashboardSearchClear=$('dashboard-peer-search-clear'); const syncDashboardSearchClear=()=>{if(dashboardSearchClear) dashboardSearchClear.hidden=!String(dashboardSearch?.value||'').length;}; dashboardSearch?.addEventListener('input',()=>{syncDashboardSearchClear();if(snapshot)renderDashboard(snapshot);}); dashboardSearchClear?.addEventListener('click',()=>{if(!dashboardSearch)return;dashboardSearch.value='';syncDashboardSearchClear();dashboardSearch.focus();if(snapshot)renderDashboard(snapshot);}); syncDashboardSearchClear(); $('diagnostics-button')?.addEventListener('click',diagnostics); $('network-trace-form')?.addEventListener('submit',runNetworkTrace);bindTraceMap(); await Promise.all([fetchInterfaces(true),fetchSnapshot()]); if(snapshot)renderHeader(snapshot); if(page==='dashboard'){ loadMetricsHistory(); if(document.body.dataset.role==='admin')loadDashboardDiagnostics(); historyTimer=setInterval(()=>{if(!document.hidden)loadMetricsHistory();},60*1000); if(document.body.dataset.role==='admin')dashboardDiagnosticsTimer=setInterval(()=>{if(!document.hidden)loadDashboardDiagnostics();},60*1000); } if(page==='server'){ loadServerDiagnostics(); serverDiagnosticsTimer=setInterval(()=>{if(!document.hidden)loadServerDiagnostics();},60*1000); } if(page!=='settings'){ let refreshing=false; const refreshVisible=async()=>{if(document.hidden||refreshing)return;refreshing=true;try{await fetchSnapshot(false);}finally{refreshing=false;}}; timer=setInterval(refreshVisible,Math.max(2,refreshSeconds)*1000); document.addEventListener('visibilitychange',()=>{if(!document.hidden)refreshVisible();}); } } boot(); })();