app.js 216 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170
  1. // Proxmox RouterOS Frontend Application Logic
  2. let state = {
  3. interfaces: [],
  4. vlans: [],
  5. systemStatus: null,
  6. vpnStatus: null,
  7. routes: [],
  8. activeTab: 'dashboard',
  9. fwSubTab: 'filter',
  10. routesSubTab: 'routes',
  11. pppSubTab: 'secrets',
  12. eoipTunnels: [],
  13. pppSecrets: [],
  14. pppProfiles: [],
  15. pppActiveSessions: [],
  16. pppoeServer: null,
  17. pptpServer: null,
  18. l2tpServer: null,
  19. ipsecServer: null,
  20. ifaceFilter: 'all',
  21. currentModalIface: null,
  22. isPolling: true,
  23. expandedParents: new Set(['eth0']),
  24. pppoeData: null,
  25. wgData: null,
  26. ipsecData: null,
  27. l2tpData: null,
  28. pptpData: null,
  29. fwSummary: null,
  30. filterRules: [],
  31. natRules: [],
  32. mangleRules: [],
  33. addressLists: [],
  34. connections: [],
  35. policyRules: [],
  36. routingTables: []
  37. };
  38. const API_BASE = '/api';
  39. // Initialize on page load
  40. document.addEventListener('DOMContentLoaded', () => {
  41. const hash = window.location.hash.replace('#', '') || 'dashboard';
  42. navigate(hash);
  43. fetchData();
  44. // Live polling every 2.5 seconds
  45. setInterval(() => {
  46. if (state.isPolling) {
  47. fetchData(false);
  48. }
  49. }, 2500);
  50. });
  51. // Navigation Handler
  52. function navigate(tabName) {
  53. state.activeTab = tabName;
  54. window.location.hash = tabName;
  55. // Update nav links styling
  56. document.querySelectorAll('.nav-link').forEach(link => {
  57. link.className = 'nav-link flex items-center justify-between px-3 py-2 rounded-lg text-xs font-medium transition-all group text-slate-300 hover:bg-slate-800/80 hover:text-white';
  58. });
  59. const activeNav = document.getElementById(`nav-${tabName}`);
  60. if (activeNav) {
  61. activeNav.className = 'nav-link flex items-center justify-between px-3 py-2 rounded-lg text-xs font-medium transition-all group bg-brand-500/10 text-brand-400 border border-brand-500/20';
  62. }
  63. // Update page headers
  64. const titles = {
  65. dashboard: { title: 'Dashboard Overview', sub: 'Live router performance and network telemetry' },
  66. interfaces: { title: 'Network Interfaces', sub: 'Hierarchical view of physical interfaces and nested 802.1Q VLANs' },
  67. vlans: { title: 'VLAN Virtual Networks', sub: 'IEEE 802.1Q sub-interface segmentation and routing' },
  68. firewall: { title: 'MikroTik Firewall', sub: 'Filter rules, NAT, Mangle, Address Lists & Active Connections tracking' },
  69. routes: { title: 'Routing & Policy', sub: 'Routing tables, static routes (DAS/DAC), and policy routing rules' },
  70. 'dynamic-routing': { title: 'Dynamic Routing (BGP & OSPF)', sub: 'FRRouting BGP peering sessions, advertised networks, and OSPFv2 link-state routing' },
  71. ppp: { title: 'PPP Servers & Secrets', sub: 'MikroTik RouterOS user accounts, IP pools and VPN server concentrators' },
  72. eoip: { title: 'EoIP Tunnels', sub: 'Ethernet over IP Layer 2 tunneling (MikroTik RouterOS style)' },
  73. pppoe: { title: 'PPPoE Client WAN', sub: 'Point-to-Point Protocol over Ethernet WAN access' },
  74. wireguard: { title: 'WireGuard Kernel VPN', sub: 'Modern ultra-fast cryptographic VPN tunnel manager' },
  75. ipsec: { title: 'IPSec (IKEv2) strongSwan', sub: 'Enterprise Site-to-Site & Roadwarrior IPSec controller' },
  76. l2tp: { title: 'L2TP VPN Client', sub: 'Layer 2 Tunneling Protocol via xl2tpd' },
  77. pptp: { title: 'PPTP VPN Client', sub: 'Point-to-Point Tunneling Protocol with MPPE-128 encryption' },
  78. persistence: { title: 'Debian Configuration', sub: 'Native /etc/network/interfaces.d/ persistence manager' }
  79. };
  80. const header = titles[tabName] || titles.dashboard;
  81. const pTitle = document.getElementById('page-title');
  82. if (pTitle) pTitle.innerText = header.title;
  83. const pSub = document.getElementById('page-subtitle');
  84. if (pSub) pSub.innerText = header.sub;
  85. // Toggle sections dynamically for all section elements
  86. document.querySelectorAll('main section[id^="section-"]').forEach(el => {
  87. if (el.id === `section-${tabName}`) {
  88. el.classList.remove('hidden');
  89. } else {
  90. el.classList.add('hidden');
  91. }
  92. });
  93. if (tabName === 'firewall') loadFirewall();
  94. if (tabName === 'routes') loadRoutes();
  95. if (tabName === 'dynamic-routing') loadDynamicRouting();
  96. if (tabName === 'ppp') loadPPP();
  97. if (tabName === 'eoip') loadEoIP();
  98. if (tabName === 'persistence') loadDebianConfig();
  99. if (tabName === 'pppoe') loadPPPoE();
  100. if (tabName === 'wireguard') loadWireGuard();
  101. if (tabName === 'ipsec') loadIPSec();
  102. if (tabName === 'l2tp') loadL2TP();
  103. if (tabName === 'pptp') loadPPTP();
  104. }
  105. // Fetch all core system, network and VPN telemetry
  106. async function fetchData(isManual = false) {
  107. const spinner = document.getElementById('refresh-spinner');
  108. if (isManual && spinner) spinner.classList.add('animate-spin');
  109. try {
  110. const [statusRes, ifacesRes, vlansRes, vpnRes, fwRes, dynRes] = await Promise.all([
  111. fetch(`${API_BASE}/system/status`),
  112. fetch(`${API_BASE}/interfaces`),
  113. fetch(`${API_BASE}/vlans`),
  114. fetch(`${API_BASE}/vpn/status`),
  115. fetch(`${API_BASE}/firewall/summary`),
  116. fetch(`${API_BASE}/routing/dynamic/summary`)
  117. ]);
  118. if (statusRes.ok) state.systemStatus = await statusRes.json();
  119. if (ifacesRes.ok) {
  120. const ifacesData = await ifacesRes.json();
  121. state.interfaces = Array.isArray(ifacesData) ? ifacesData : [];
  122. }
  123. if (vlansRes.ok) {
  124. const vlansData = await vlansRes.json();
  125. state.vlans = Array.isArray(vlansData) ? vlansData : [];
  126. }
  127. if (vpnRes.ok) state.vpnStatus = await vpnRes.json();
  128. if (fwRes && fwRes.ok) state.fwSummary = await fwRes.json();
  129. if (dynRes && dynRes.ok) state.dynSummary = await dynRes.json();
  130. updateSystemMetrics();
  131. updateBadges();
  132. if (state.activeTab === 'dashboard') renderDashboard();
  133. if (state.activeTab === 'interfaces') renderInterfacesList();
  134. if (state.activeTab === 'vlans') renderVlansList();
  135. if (state.activeTab === 'firewall') loadFirewall(false);
  136. if (state.activeTab === 'routes') loadRoutes(false);
  137. if (state.activeTab === 'dynamic-routing') loadDynamicRouting(false);
  138. if (state.activeTab === 'ppp') loadPPP(false);
  139. if (state.activeTab === 'eoip') loadEoIP(false);
  140. if (state.activeTab === 'pppoe') loadPPPoE(false);
  141. if (state.activeTab === 'wireguard') loadWireGuard(false);
  142. if (state.activeTab === 'ipsec') loadIPSec(false);
  143. if (state.activeTab === 'l2tp') loadL2TP(false);
  144. if (state.activeTab === 'pptp') loadPPTP(false);
  145. } catch (err) {
  146. console.error('Failed to fetch router state:', err);
  147. } finally {
  148. if (isManual && spinner) {
  149. setTimeout(() => spinner.classList.remove('animate-spin'), 300);
  150. }
  151. }
  152. }
  153. // Update Top KPI and Sidebar Telemetry
  154. function updateSystemMetrics() {
  155. const s = state.systemStatus;
  156. const v = state.vpnStatus;
  157. if (!s) return;
  158. // Sidebar
  159. document.getElementById('side-hostname').innerText = s.hostname || 'debian-lxc';
  160. document.getElementById('side-uptime').innerText = s.uptime_human || '0m';
  161. document.getElementById('side-gateway-ip').innerText = s.default_gateway ? `GW: ${s.default_gateway}` : 'GW: Isolated';
  162. if (s.cpu_pct !== undefined) {
  163. const pct = s.cpu_pct;
  164. document.getElementById('side-cpu-val').innerText = `${pct.toFixed(1)}%`;
  165. document.getElementById('side-cpu-bar').style.width = `${Math.max(4, Math.min(100, pct))}%`;
  166. const loadStr = s.cpu_load ? s.cpu_load.join(', ') : '-';
  167. document.getElementById('side-cpu-bar').title = `Container: ${pct}% | Host Loadavg: ${loadStr} (${s.cpu_cores || 1} cores)`;
  168. } else if (s.cpu_load && s.cpu_load.length > 0) {
  169. const cores = s.cpu_cores || 4;
  170. const pct = Math.min(100, Math.round((parseFloat(s.cpu_load[0]) / cores) * 100));
  171. document.getElementById('side-cpu-val').innerText = `${pct}%`;
  172. document.getElementById('side-cpu-bar').style.width = `${Math.max(4, pct)}%`;
  173. }
  174. document.getElementById('side-ram-val').innerText = `${Math.round(s.mem_usage_pct || 0)}%`;
  175. document.getElementById('side-ram-bar').style.width = `${Math.max(5, Math.round(s.mem_usage_pct || 0))}%`;
  176. // Dashboard Stats
  177. document.getElementById('stat-ifaces-up').innerText = s.up_ifaces || 0;
  178. document.getElementById('stat-ifaces-total').innerText = `${s.total_ifaces || 0} Total`;
  179. document.getElementById('stat-ifaces-down').innerText = `${s.down_ifaces || 0} DOWN`;
  180. document.getElementById('stat-vlans-count').innerText = s.vlan_ifaces || 0;
  181. // VPN Status Indicators
  182. if (v) {
  183. const totalActive = v.total_active_tunnels || 0;
  184. const statVpnActive = document.getElementById('stat-vpn-active');
  185. if (statVpnActive) statVpnActive.innerText = totalActive;
  186. const tunnelsDot = document.getElementById('tunnels-dot');
  187. const tunnelsLabel = document.getElementById('tunnels-label');
  188. if (tunnelsDot && tunnelsLabel) {
  189. if (totalActive > 0) {
  190. tunnelsDot.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  191. tunnelsLabel.innerText = `${totalActive} Active VPN Tunnel${totalActive > 1 ? 's' : ''}`;
  192. } else {
  193. tunnelsDot.className = 'w-2 h-2 rounded-full bg-slate-500';
  194. tunnelsLabel.innerText = '0 Active VPN Tunnels';
  195. }
  196. }
  197. setDotBadge('badge-pppoe-status', (v.active_pppoe || 0) > 0 || v.pppoe_connected);
  198. setDotBadge('badge-wg-status', (v.active_wireguard || 0) > 0 || v.wireguard_active);
  199. setDotBadge('badge-ipsec-status', (v.active_ipsec || 0) > 0 || v.ipsec_active);
  200. setDotBadge('badge-l2tp-status', (v.active_l2tp || 0) > 0 || v.l2tp_connected);
  201. setDotBadge('badge-pptp-status', (v.active_pptp || 0) > 0 || v.pptp_connected);
  202. }
  203. // Total Live Bandwidth Rate
  204. let totalRx = 0;
  205. let totalTx = 0;
  206. (state.interfaces || []).forEach(i => {
  207. if (i.rate) {
  208. totalRx += i.rate.rx_bytes_sec || 0;
  209. totalTx += i.rate.tx_bytes_sec || 0;
  210. }
  211. });
  212. document.getElementById('stat-traffic-rx').innerText = formatTraffic(totalRx);
  213. document.getElementById('stat-traffic-tx').innerText = formatTraffic(totalTx);
  214. }
  215. function setDotBadge(id, active) {
  216. const el = document.getElementById(id);
  217. if (!el) return;
  218. if (active) {
  219. el.className = 'w-2 h-2 rounded-full bg-emerald-400 shadow-sm shadow-emerald-400/80';
  220. } else {
  221. el.className = 'w-2 h-2 rounded-full bg-slate-600';
  222. }
  223. }
  224. function updateBadges() {
  225. const bIfaces = document.getElementById('badge-ifaces-count');
  226. if (bIfaces) bIfaces.innerText = (state.interfaces || []).length;
  227. const bVlans = document.getElementById('badge-vlans-count');
  228. if (bVlans) bVlans.innerText = (state.vlans || []).length;
  229. if (state.fwSummary) {
  230. const totalFwRules = (state.fwSummary.filter_rules_count || 0) + (state.fwSummary.nat_rules_count || 0) + (state.fwSummary.mangle_rules_count || 0);
  231. const badgeFw = document.getElementById('badge-firewall-count');
  232. if (badgeFw) badgeFw.innerText = totalFwRules;
  233. }
  234. if (state.vpnStatus) {
  235. const v = state.vpnStatus;
  236. const bEoIP = document.getElementById('badge-eoip-count');
  237. if (bEoIP) bEoIP.innerText = v.total_eoip || 0;
  238. const bPPPSess = document.getElementById('badge-ppp-sessions');
  239. if (bPPPSess) bPPPSess.innerText = v.total_ppp_sessions || 0;
  240. setDotBadge('badge-pppoe-status', v.active_pppoe > 0 || v.pppoe_server_running);
  241. setDotBadge('badge-wg-status', v.active_wireguard > 0);
  242. setDotBadge('badge-ipsec-status', v.active_ipsec > 0 || v.ipsec_server_running);
  243. setDotBadge('badge-l2tp-status', v.active_l2tp > 0 || v.l2tp_server_running);
  244. setDotBadge('badge-pptp-status', v.active_pptp > 0 || v.pptp_server_running);
  245. }
  246. if (state.dynSummary) {
  247. const d = state.dynSummary;
  248. setDotBadge('badge-bgp-dot', d.bgp_running);
  249. setDotBadge('badge-ospf-dot', d.ospf_running);
  250. }
  251. }
  252. // Render Dashboard View
  253. function renderDashboard() {
  254. const matrix = document.getElementById('port-matrix');
  255. matrix.innerHTML = '';
  256. (state.interfaces || []).forEach(iface => {
  257. const isUp = iface.state === 'UP';
  258. const isVlan = iface.is_vlan;
  259. const portCard = document.createElement('div');
  260. portCard.className = `p-3 rounded-xl border transition-all cursor-pointer select-none group ${
  261. isUp
  262. ? (isVlan ? 'bg-cyan-950/20 border-cyan-800/60 hover:border-cyan-500' : 'bg-slate-800/80 border-slate-700/80 hover:border-brand-500')
  263. : 'bg-slate-900/40 border-slate-800/60 opacity-60 hover:opacity-100 hover:border-slate-700'
  264. }`;
  265. portCard.onclick = () => openIfaceModal(iface.name);
  266. let statusPillClass = isUp ? 'bg-emerald-500 shadow-sm shadow-emerald-500/50' : 'bg-rose-500';
  267. if (isVlan) statusPillClass = isUp ? 'bg-cyan-400 shadow-sm shadow-cyan-400/50' : 'bg-rose-500';
  268. portCard.innerHTML = `
  269. <div class="flex items-center justify-between mb-2">
  270. <span class="font-bold text-xs font-mono text-white group-hover:text-brand-400 transition truncate">${iface.name}</span>
  271. <span class="w-2 h-2 rounded-full ${statusPillClass}"></span>
  272. </div>
  273. <div class="text-[11px] font-mono text-slate-300 truncate">${iface.ipv4 && iface.ipv4.length > 0 ? iface.ipv4[0] : (iface.mac || 'No IP')}</div>
  274. <div class="mt-2 flex items-center justify-between text-[10px] text-slate-400">
  275. <span class="uppercase tracking-wider font-semibold">${isVlan ? `VLAN ${iface.vlan_id}` : iface.type}</span>
  276. <span>${iface.rate?.rx_human || '0 B/s'}</span>
  277. </div>
  278. `;
  279. matrix.appendChild(portCard);
  280. });
  281. const ifaceTbody = document.getElementById('quick-interfaces-table');
  282. ifaceTbody.innerHTML = '';
  283. (state.interfaces || []).slice(0, 6).forEach(i => {
  284. const isUp = i.state === 'UP';
  285. const tr = document.createElement('tr');
  286. tr.className = 'hover:bg-slate-800/40 transition cursor-pointer';
  287. tr.onclick = () => openIfaceModal(i.name);
  288. tr.innerHTML = `
  289. <td class="py-2.5 font-bold text-white flex items-center gap-2">
  290. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  291. <span>${i.name}</span>
  292. </td>
  293. <td class="py-2.5 text-slate-300 font-sans"><span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 text-slate-300">${i.role || 'LAN'}</span></td>
  294. <td class="py-2.5 text-slate-300">${i.ipv4 && i.ipv4.length > 0 ? i.ipv4[0] : '<span class="text-slate-600">-</span>'}</td>
  295. <td class="py-2.5 text-right font-sans font-semibold ${isUp ? 'text-emerald-400' : 'text-rose-400'}">${i.state}</td>
  296. `;
  297. ifaceTbody.appendChild(tr);
  298. });
  299. const vlanTbody = document.getElementById('quick-vlans-table');
  300. vlanTbody.innerHTML = '';
  301. const vlans = state.vlans || [];
  302. if (vlans.length === 0) {
  303. vlanTbody.innerHTML = `<tr><td colspan="4" class="py-4 text-center text-slate-500 font-sans">No VLANs configured. Click "+ Add" above to create one.</td></tr>`;
  304. } else {
  305. vlans.slice(0, 6).forEach(v => {
  306. const tr = document.createElement('tr');
  307. tr.className = 'hover:bg-slate-800/40 transition cursor-pointer';
  308. tr.onclick = () => openIfaceModal(v.name);
  309. tr.innerHTML = `
  310. <td class="py-2.5"><span class="px-2 py-0.5 rounded text-[11px] bg-cyan-950 text-cyan-400 border border-cyan-800 font-bold">VLAN ${v.vlan_id}</span></td>
  311. <td class="py-2.5 text-white font-bold">${v.name}</td>
  312. <td class="py-2.5 text-slate-300">${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600">Unnumbered</span>'}</td>
  313. <td class="py-2.5 text-right text-slate-400">${v.parent_name || 'eth0'}</td>
  314. `;
  315. vlanTbody.appendChild(tr);
  316. });
  317. }
  318. }
  319. // Expand / Collapse Handlers
  320. function toggleExpand(parentName) {
  321. if (state.expandedParents.has(parentName)) {
  322. state.expandedParents.delete(parentName);
  323. } else {
  324. state.expandedParents.add(parentName);
  325. }
  326. renderInterfacesList();
  327. }
  328. function expandAllIfaces(expand) {
  329. if (expand) {
  330. (state.interfaces || []).forEach(i => {
  331. if (!i.is_vlan) state.expandedParents.add(i.name);
  332. });
  333. } else {
  334. state.expandedParents.clear();
  335. }
  336. renderInterfacesList();
  337. }
  338. // Filter and Render Hierarchical Interfaces List
  339. function filterIfaces(filter) {
  340. state.ifaceFilter = filter;
  341. document.querySelectorAll('.filter-btn').forEach(btn => {
  342. btn.className = 'filter-btn px-3 py-1.5 rounded-lg text-xs font-medium text-slate-400 hover:bg-slate-800 hover:text-white';
  343. });
  344. const activeBtn = document.getElementById(`filter-${filter}`);
  345. if (activeBtn) {
  346. activeBtn.className = 'filter-btn px-3 py-1.5 rounded-lg text-xs font-medium bg-slate-800 text-white border border-slate-700';
  347. }
  348. renderInterfacesList();
  349. }
  350. function renderInterfacesList() {
  351. const tbody = document.getElementById('interfaces-tree-tbody');
  352. const emptyState = document.getElementById('interfaces-empty-state');
  353. const summary = document.getElementById('ifaces-list-summary');
  354. const query = (document.getElementById('iface-search')?.value || '').toLowerCase();
  355. tbody.innerHTML = '';
  356. const allIfaces = state.interfaces || [];
  357. const allVlans = state.vlans || [];
  358. const parentIfaces = allIfaces.filter(i => !i.is_vlan);
  359. const filteredParents = parentIfaces.filter(parent => {
  360. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  361. if (query) {
  362. const matchParent = parent.name.toLowerCase().includes(query) || (parent.role || '').toLowerCase().includes(query);
  363. const matchVlan = childVlans.some(v => v.name.toLowerCase().includes(query) || String(v.vlan_id).includes(query) || (v.description || '').toLowerCase().includes(query));
  364. if (!matchParent && !matchVlan) return false;
  365. }
  366. if (state.ifaceFilter === 'has_vlans') return childVlans.length > 0;
  367. if (state.ifaceFilter === 'physical') return parent.type !== 'loopback';
  368. if (state.ifaceFilter === 'up') return parent.state === 'UP';
  369. return true;
  370. });
  371. if (summary) {
  372. summary.innerText = `${parentIfaces.length} Physical/Parent Links • ${allVlans.length} Active VLANs`;
  373. }
  374. if (filteredParents.length === 0) {
  375. emptyState?.classList.remove('hidden');
  376. return;
  377. }
  378. emptyState?.classList.add('hidden');
  379. filteredParents.forEach(parent => {
  380. const isUp = parent.state === 'UP';
  381. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  382. const isExpanded = state.expandedParents.has(parent.name);
  383. const parentRow = document.createElement('tr');
  384. parentRow.className = `hover:bg-slate-800/50 transition border-b border-slate-800/80 ${isExpanded ? 'bg-slate-900/80' : ''}`;
  385. parentRow.innerHTML = `
  386. <td class="py-3 px-3 text-center">
  387. <button onclick="toggleExpand('${parent.name}')" title="${isExpanded ? 'Collapse VLANs' : 'Expand VLANs'}"
  388. class="w-6 h-6 rounded flex items-center justify-center hover:bg-slate-800 text-slate-400 hover:text-white transition">
  389. <svg class="w-4 h-4 chevron-icon ${isExpanded ? 'chevron-open text-cyan-400' : 'text-slate-500'}" fill="none" stroke="currentColor" viewBox="0 0 24 24">
  390. <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M9 5l7 7-7 7" />
  391. </svg>
  392. </button>
  393. </td>
  394. <td class="py-3 px-4">
  395. <div class="flex items-center space-x-2.5">
  396. <div class="w-7 h-7 rounded-lg bg-slate-800 border border-slate-700/80 flex items-center justify-center text-[10px] font-bold text-slate-300">
  397. ${parent.type === 'loopback' ? 'LO' : 'NIC'}
  398. </div>
  399. <div>
  400. <div class="flex items-center gap-2">
  401. <span class="font-bold text-white text-sm cursor-pointer hover:text-cyan-400" onclick="toggleExpand('${parent.name}')">${parent.name}</span>
  402. ${childVlans.length > 0
  403. ? `<span onclick="toggleExpand('${parent.name}')" class="cursor-pointer text-[10px] bg-cyan-950 text-cyan-400 border border-cyan-800/60 px-2 py-0.5 rounded-full font-bold hover:bg-cyan-900 transition">${childVlans.length} VLAN${childVlans.length > 1 ? 's' : ''}</span>`
  404. : `<span onclick="toggleExpand('${parent.name}')" class="cursor-pointer text-[10px] bg-slate-800/60 text-slate-500 px-1.5 py-0.5 rounded font-mono hover:text-slate-300">0 VLANs</span>`
  405. }
  406. </div>
  407. <div class="text-[10px] text-slate-500 font-sans mt-0.5">${parent.type}</div>
  408. </div>
  409. </div>
  410. </td>
  411. <td class="py-3 px-4 font-sans">
  412. <div class="flex items-center gap-1.5">
  413. <span class="px-2 py-0.5 rounded text-[10px] font-semibold bg-slate-800 text-slate-300 border border-slate-700/60">${parent.role || 'LAN'}</span>
  414. <span class="text-xs text-slate-400 truncate max-w-[120px]">${parent.description || '-'}</span>
  415. </div>
  416. </td>
  417. <td class="py-3 px-4">
  418. ${parent.ipv4 && parent.ipv4.length > 0
  419. ? `<div class="text-white font-medium">${parent.ipv4[0]}</div>`
  420. : '<span class="text-slate-600 font-sans">Unassigned</span>'
  421. }
  422. </td>
  423. <td class="py-3 px-4 text-slate-400 text-[11px]">
  424. <div>${parent.mac || 'N/A'}</div>
  425. <div class="text-[10px] text-slate-500">MTU ${parent.mtu}</div>
  426. </td>
  427. <td class="py-3 px-4 text-[11px]">
  428. <div class="flex items-center space-x-2">
  429. <span class="text-emerald-400">↓ ${parent.rate?.rx_human || '0 B/s'}</span>
  430. <span class="text-cyan-400">↑ ${parent.rate?.tx_human || '0 B/s'}</span>
  431. </div>
  432. </td>
  433. <td class="py-3 px-4 font-sans">
  434. <button onclick="toggleInterfaceState('${parent.name}', '${isUp ? 'down' : 'up'}')"
  435. class="flex items-center gap-1.5 text-xs font-semibold px-2.5 py-1 rounded-full transition ${
  436. isUp ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/30 hover:bg-rose-500/10 hover:text-rose-400 hover:border-rose-500/30' : 'bg-rose-500/10 text-rose-400 border border-rose-500/30 hover:bg-emerald-500/10 hover:text-emerald-400'
  437. }" title="Click to toggle link status">
  438. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  439. <span>${parent.state}</span>
  440. </button>
  441. </td>
  442. <td class="py-3 px-4 text-right space-x-2 font-sans">
  443. <button onclick="openVlanModal('${parent.name}')"
  444. class="text-xs bg-cyan-950/60 hover:bg-cyan-900 text-cyan-300 font-semibold px-2.5 py-1 rounded-lg border border-cyan-800/70 shadow-sm transition">
  445. + Add VLAN
  446. </button>
  447. <button onclick="openIfaceModal('${parent.name}')"
  448. class="text-xs bg-slate-800 hover:bg-slate-700 text-white font-medium px-2.5 py-1 rounded-lg border border-slate-700 transition">
  449. Configure
  450. </button>
  451. </td>
  452. `;
  453. tbody.appendChild(parentRow);
  454. if (isExpanded) {
  455. const drawerRow = document.createElement('tr');
  456. drawerRow.className = 'bg-slate-950/80 border-b border-slate-800/90';
  457. const drawerCell = document.createElement('td');
  458. drawerCell.colSpan = 8;
  459. drawerCell.className = 'p-0';
  460. drawerCell.innerHTML = `
  461. <div class="py-4 pl-12 pr-6 border-l-4 border-cyan-500 bg-gradient-to-r from-cyan-950/20 via-slate-900/40 to-transparent">
  462. <div class="flex items-center justify-between mb-3">
  463. <div class="flex items-center space-x-3">
  464. <span class="font-bold text-xs text-white uppercase tracking-wider flex items-center gap-1.5 font-sans">
  465. <span>VLAN Sub-interfaces on <code class="text-cyan-300 lowercase">${parent.name}</code></span>
  466. </span>
  467. <span class="text-[11px] bg-cyan-950 text-cyan-400 px-2 py-0.5 rounded-full border border-cyan-800/60 font-mono">
  468. ${childVlans.length} Attached
  469. </span>
  470. </div>
  471. <button onclick="openVlanModal('${parent.name}')"
  472. class="flex items-center space-x-1.5 text-xs bg-cyan-600 hover:bg-cyan-500 text-white font-semibold px-3 py-1.5 rounded-lg shadow-md shadow-cyan-500/20 transition font-sans">
  473. <span>+ Create VLAN on ${parent.name}</span>
  474. </button>
  475. </div>
  476. ${childVlans.length === 0 ? `
  477. <div class="p-6 text-center border border-dashed border-slate-800 rounded-xl bg-slate-900/40 font-sans">
  478. <p class="text-xs text-slate-400 mb-2">No 802.1Q tagged VLANs have been created under <strong class="text-white">${parent.name}</strong> yet.</p>
  479. <button onclick="openVlanModal('${parent.name}')" class="inline-flex items-center space-x-1.5 text-xs text-cyan-400 hover:text-cyan-300 bg-cyan-950/60 border border-cyan-800/70 px-3 py-1.5 rounded-lg transition font-medium">
  480. <span>+ Create Your First VLAN on ${parent.name}</span>
  481. </button>
  482. </div>
  483. ` : `
  484. <div class="overflow-x-auto rounded-lg border border-slate-800 bg-slate-900/90 shadow-inner">
  485. <table class="w-full text-left text-xs font-mono">
  486. <thead class="text-slate-400 bg-slate-950/70 border-b border-slate-800 uppercase tracking-wider text-[10px] font-sans">
  487. <tr>
  488. <th class="py-2.5 px-4">VLAN ID</th>
  489. <th class="py-2.5 px-4">Interface Device</th>
  490. <th class="py-2.5 px-4">Subnet Gateway</th>
  491. <th class="py-2.5 px-4">Role / Alias</th>
  492. <th class="py-2.5 px-4">MTU</th>
  493. <th class="py-2.5 px-4">Throughput</th>
  494. <th class="py-2.5 px-4">Status</th>
  495. <th class="py-2.5 px-4 text-right">Actions</th>
  496. </tr>
  497. </thead>
  498. <tbody class="divide-y divide-slate-800/70">
  499. ${childVlans.map(v => {
  500. const isVlanUp = v.state === 'UP';
  501. return `
  502. <tr class="hover:bg-slate-800/40 transition">
  503. <td class="py-2.5 px-4">
  504. <span class="px-2 py-0.5 rounded text-xs font-bold bg-cyan-950 text-cyan-300 border border-cyan-800 shadow-sm">
  505. VLAN ${v.vlan_id}
  506. </span>
  507. </td>
  508. <td class="py-2.5 px-4 font-bold text-white flex items-center gap-1.5">
  509. <span class="text-cyan-500">└─</span>
  510. <span>${v.name}</span>
  511. </td>
  512. <td class="py-2.5 px-4 text-emerald-400 font-medium">
  513. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  514. </td>
  515. <td class="py-2.5 px-4 font-sans text-slate-300">
  516. <span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 text-slate-300 mr-1.5">${v.role || 'VLAN'}</span>
  517. <span class="text-slate-400 text-xs">${v.description || '-'}</span>
  518. </td>
  519. <td class="py-2.5 px-4 text-slate-400">${v.mtu}</td>
  520. <td class="py-2.5 px-4 text-[11px]">
  521. <span class="text-emerald-400">↓ ${v.rate?.rx_human || '0 B/s'}</span>
  522. <span class="text-cyan-400 ml-1.5">↑ ${v.rate?.tx_human || '0 B/s'}</span>
  523. </td>
  524. <td class="py-2.5 px-4 font-sans">
  525. <button onclick="toggleInterfaceState('${v.name}', '${isVlanUp ? 'down' : 'up'}')"
  526. class="flex items-center gap-1 text-[11px] font-semibold px-2 py-0.5 rounded-full ${
  527. isVlanUp ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/30' : 'bg-rose-500/10 text-rose-400 border border-rose-500/30'
  528. }">
  529. <span class="w-1.5 h-1.5 rounded-full ${isVlanUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  530. <span>${v.state}</span>
  531. </button>
  532. </td>
  533. <td class="py-2.5 px-4 text-right space-x-1.5 font-sans">
  534. <button onclick="openIfaceModal('${v.name}')" class="text-xs bg-slate-800 hover:bg-slate-700 text-slate-200 px-2 py-0.5 rounded border border-slate-700">Edit</button>
  535. <button onclick="confirmDeleteVlan('${v.name}')" class="text-xs text-rose-400 hover:text-rose-300 hover:bg-rose-950/40 px-2 py-0.5 rounded transition">Delete</button>
  536. </td>
  537. </tr>
  538. `;
  539. }).join('')}
  540. </tbody>
  541. </table>
  542. </div>
  543. `}
  544. </div>
  545. `;
  546. drawerRow.appendChild(drawerCell);
  547. tbody.appendChild(drawerRow);
  548. }
  549. });
  550. }
  551. // Render VLANs Dedicated View
  552. function renderVlansList() {
  553. const tbody = document.getElementById('vlans-table-body');
  554. const emptyState = document.getElementById('vlans-empty-state');
  555. const countBadge = document.getElementById('vlans-table-count');
  556. const query = (document.getElementById('vlan-search')?.value || '').toLowerCase();
  557. tbody.innerHTML = '';
  558. const allVlans = state.vlans || [];
  559. countBadge.innerText = allVlans.length;
  560. const filtered = allVlans.filter(v => {
  561. if (!query) return true;
  562. return v.name.toLowerCase().includes(query) ||
  563. String(v.vlan_id).includes(query) ||
  564. (v.description || '').toLowerCase().includes(query) ||
  565. (v.ipv4 && v.ipv4.some(ip => ip.includes(query)));
  566. });
  567. if (allVlans.length === 0) {
  568. emptyState.classList.remove('hidden');
  569. return;
  570. }
  571. emptyState.classList.add('hidden');
  572. filtered.forEach(v => {
  573. const isUp = v.state === 'UP';
  574. const tr = document.createElement('tr');
  575. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  576. tr.innerHTML = `
  577. <td class="py-3 px-4">
  578. <span class="px-2.5 py-1 rounded-md text-xs font-bold bg-cyan-950 text-cyan-300 border border-cyan-800/70 shadow-sm">
  579. VLAN ${v.vlan_id}
  580. </span>
  581. </td>
  582. <td class="py-3 px-4 font-bold text-white">${v.name}</td>
  583. <td class="py-3 px-4 text-slate-300">
  584. <span class="bg-slate-800 text-slate-200 px-2 py-0.5 rounded text-[11px]">${v.parent_name || 'eth0'}</span>
  585. </td>
  586. <td class="py-3 px-4 text-emerald-400 font-medium">
  587. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  588. </td>
  589. <td class="py-3 px-4 text-slate-300 font-sans">
  590. <span class="text-slate-400 text-xs">${v.description || v.role || '-'}</span>
  591. </td>
  592. <td class="py-3 px-4 text-slate-400">${v.mtu}</td>
  593. <td class="py-3 px-4 font-sans">
  594. <button onclick="toggleInterfaceState('${v.name}', '${isUp ? 'down' : 'up'}')"
  595. class="flex items-center gap-1.5 text-xs font-semibold px-2 py-0.5 rounded-full ${
  596. isUp ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/30' : 'bg-rose-500/10 text-rose-400 border border-rose-500/30'
  597. }">
  598. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  599. <span>${v.state}</span>
  600. </button>
  601. </td>
  602. <td class="py-3 px-4 text-right space-x-2 font-sans">
  603. <button onclick="openIfaceModal('${v.name}')" class="text-xs bg-slate-800 hover:bg-slate-700 text-slate-200 px-2.5 py-1 rounded border border-slate-700">Edit</button>
  604. <button onclick="confirmDeleteVlan('${v.name}')" class="text-xs text-rose-400 hover:text-rose-300 hover:bg-rose-950/40 px-2 py-1 rounded transition">Delete</button>
  605. </td>
  606. `;
  607. tbody.appendChild(tr);
  608. });
  609. }
  610. // Toggle interface UP / DOWN
  611. async function toggleInterfaceState(name, newState) {
  612. try {
  613. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(name)}/state`, {
  614. method: 'POST',
  615. headers: { 'Content-Type': 'application/json' },
  616. body: JSON.stringify({ state: newState })
  617. });
  618. const data = await res.json();
  619. if (res.ok) {
  620. showToast('Interface Updated', `Interface ${name} is now ${newState.toUpperCase()}`, 'success');
  621. fetchData(false);
  622. } else {
  623. showToast('Error', data.message || 'Failed to toggle interface state', 'error');
  624. }
  625. } catch (err) {
  626. showToast('Error', err.message, 'error');
  627. }
  628. }
  629. // ---------------- MikroTik Flag & Utilities ----------------
  630. function renderMikroTikFlag(running, disabled) {
  631. if (running) {
  632. return `<span class="inline-flex items-center justify-center w-5 h-5 rounded-md font-mono font-bold text-[11px] bg-emerald-500/20 text-emerald-400 border border-emerald-500/40 shadow-sm" title="Running (Connected)">R</span>`;
  633. }
  634. if (disabled) {
  635. return `<span class="inline-flex items-center justify-center w-5 h-5 rounded-md font-mono font-bold text-[11px] bg-rose-500/20 text-rose-400 border border-rose-500/40 shadow-sm" title="Disabled">X</span>`;
  636. }
  637. return `<span class="inline-flex items-center justify-center w-5 h-5 rounded-md font-mono font-bold text-[11px] text-slate-500 bg-slate-800/80 border border-slate-700/60" title="Idle / Disconnected">-</span>`;
  638. }
  639. function copyToClipboard(text, label = 'Text') {
  640. navigator.clipboard.writeText(text).then(() => {
  641. showToast('Copied', `${label} copied to clipboard`, 'success');
  642. }).catch(() => {
  643. prompt('Copy value:', text);
  644. });
  645. }
  646. // ======================== PPPoE Multi-Instance ========================
  647. async function loadPPPoE(populateInputs = true) {
  648. try {
  649. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`);
  650. const list = await res.json();
  651. state.pppoeList = Array.isArray(list) ? list : [];
  652. const badge = document.getElementById('pppoe-count-badge');
  653. if (badge) badge.innerText = `${state.pppoeList.length} Interface${state.pppoeList.length !== 1 ? 's' : ''}`;
  654. const tbody = document.getElementById('pppoe-table-body');
  655. const empty = document.getElementById('pppoe-empty');
  656. if (!tbody) return;
  657. tbody.innerHTML = '';
  658. if (state.pppoeList.length === 0) {
  659. if (empty) empty.classList.remove('hidden');
  660. } else {
  661. if (empty) empty.classList.add('hidden');
  662. state.pppoeList.forEach(inst => {
  663. const tr = document.createElement('tr');
  664. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  665. tr.innerHTML = `
  666. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  667. <td class="py-2.5 px-3 font-bold text-white">${inst.name}</td>
  668. <td class="py-2.5 px-3 text-cyan-400 font-mono">${inst.interface}</td>
  669. <td class="py-2.5 px-3 text-slate-300 font-mono">${inst.username || '-'}</td>
  670. <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${inst.assigned_ip || '-'}</td>
  671. <td class="py-2.5 px-3 text-slate-400 font-mono">${inst.ppp_device || '-'}</td>
  672. <td class="py-2.5 px-3 text-center">
  673. <span class="px-2 py-0.5 rounded text-[10px] font-sans ${inst.default_route ? 'bg-blue-500/20 text-blue-300 border border-blue-500/30' : 'bg-slate-800 text-slate-500'}">
  674. ${inst.default_route ? 'Yes' : 'No'}
  675. </span>
  676. </td>
  677. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  678. ${inst.running ? `
  679. <button onclick="disconnectPPPoEInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  680. ` : `
  681. <button onclick="connectPPPoEInstance('${inst.name}')" class="text-xs bg-blue-600/30 hover:bg-blue-600/50 text-blue-300 px-2 py-0.5 rounded border border-blue-500/30">Connect</button>
  682. `}
  683. <button onclick="togglePPPoEState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  684. ${inst.disabled ? 'Enable' : 'Disable'}
  685. </button>
  686. <button onclick="openEditPPPoEModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  687. <button onclick="deletePPPoEInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  688. </td>
  689. `;
  690. tbody.appendChild(tr);
  691. });
  692. }
  693. } catch (err) {
  694. console.error('Failed to load PPPoE:', err);
  695. }
  696. }
  697. function openAddPPPoEModal() {
  698. document.getElementById('pppoe-modal-title').innerText = 'Add PPPoE Client Interface';
  699. document.getElementById('pppoe-modal-edit-orig').value = '';
  700. document.getElementById('pppoe-modal-name').value = `pppoe-out${(state.pppoeList || []).length + 1}`;
  701. document.getElementById('pppoe-modal-name').readOnly = false;
  702. document.getElementById('pppoe-modal-user').value = '';
  703. document.getElementById('pppoe-modal-pass').value = '';
  704. document.getElementById('pppoe-modal-service').value = '';
  705. document.getElementById('pppoe-modal-mtu').value = '1492';
  706. document.getElementById('pppoe-modal-defroute').checked = true;
  707. document.getElementById('pppoe-modal-reconnect').checked = true;
  708. document.getElementById('pppoe-modal-disabled').checked = false;
  709. // Populate interfaces
  710. const sel = document.getElementById('pppoe-modal-iface');
  711. sel.innerHTML = '';
  712. (state.interfaces || []).forEach(i => {
  713. if (i.name === 'lo') return;
  714. const opt = document.createElement('option');
  715. opt.value = i.name;
  716. opt.innerText = `${i.name} (${i.role || i.type})`;
  717. sel.appendChild(opt);
  718. });
  719. document.getElementById('pppoe-modal').classList.remove('hidden');
  720. }
  721. function openEditPPPoEModal(name) {
  722. const inst = (state.pppoeList || []).find(i => i.name === name);
  723. if (!inst) return;
  724. document.getElementById('pppoe-modal-title').innerText = `Edit PPPoE Client: ${name}`;
  725. document.getElementById('pppoe-modal-edit-orig').value = name;
  726. document.getElementById('pppoe-modal-name').value = inst.name;
  727. document.getElementById('pppoe-modal-name').readOnly = true;
  728. document.getElementById('pppoe-modal-user').value = inst.username || '';
  729. document.getElementById('pppoe-modal-pass').value = inst.password || '';
  730. document.getElementById('pppoe-modal-service').value = inst.service_name || '';
  731. document.getElementById('pppoe-modal-mtu').value = inst.mtu || 1492;
  732. document.getElementById('pppoe-modal-defroute').checked = inst.default_route ?? true;
  733. document.getElementById('pppoe-modal-reconnect').checked = inst.auto_reconnect ?? true;
  734. document.getElementById('pppoe-modal-disabled').checked = !!inst.disabled;
  735. const sel = document.getElementById('pppoe-modal-iface');
  736. sel.innerHTML = '';
  737. (state.interfaces || []).forEach(i => {
  738. if (i.name === 'lo') return;
  739. const opt = document.createElement('option');
  740. opt.value = i.name;
  741. opt.innerText = `${i.name} (${i.role || i.type})`;
  742. if (i.name === inst.interface) opt.selected = true;
  743. sel.appendChild(opt);
  744. });
  745. document.getElementById('pppoe-modal').classList.remove('hidden');
  746. }
  747. function closePPPoEModal() {
  748. document.getElementById('pppoe-modal').classList.add('hidden');
  749. }
  750. async function submitSavePPPoE(e) {
  751. e.preventDefault();
  752. const name = document.getElementById('pppoe-modal-name').value.trim();
  753. const iface = document.getElementById('pppoe-modal-iface').value;
  754. const user = document.getElementById('pppoe-modal-user').value.trim();
  755. const pass = document.getElementById('pppoe-modal-pass').value;
  756. const service = document.getElementById('pppoe-modal-service').value.trim();
  757. const mtu = parseInt(document.getElementById('pppoe-modal-mtu').value, 10) || 1492;
  758. const defRoute = document.getElementById('pppoe-modal-defroute').checked;
  759. const reconnect = document.getElementById('pppoe-modal-reconnect').checked;
  760. const disabled = document.getElementById('pppoe-modal-disabled').checked;
  761. try {
  762. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`, {
  763. method: 'POST',
  764. headers: { 'Content-Type': 'application/json' },
  765. body: JSON.stringify({
  766. name,
  767. interface: iface,
  768. username: user,
  769. password: pass,
  770. service_name: service,
  771. mtu,
  772. default_route: defRoute,
  773. auto_reconnect: reconnect,
  774. disabled
  775. })
  776. });
  777. if (res.ok) {
  778. showToast('PPPoE Saved', `Configuration for ${name} saved`, 'success');
  779. closePPPoEModal();
  780. loadPPPoE(false);
  781. fetchData(false);
  782. } else {
  783. const err = await res.json();
  784. showToast('Error', err.message || 'Failed to save PPPoE', 'error');
  785. }
  786. } catch (err) {
  787. showToast('Error', err.message, 'error');
  788. }
  789. }
  790. async function connectPPPoEInstance(name) {
  791. try {
  792. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  793. if (res.ok) {
  794. showToast('Connecting', `Dialing ${name}...`, 'info');
  795. setTimeout(() => loadPPPoE(false), 2000);
  796. }
  797. } catch (err) {
  798. showToast('Error', err.message, 'error');
  799. }
  800. }
  801. async function disconnectPPPoEInstance(name) {
  802. try {
  803. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  804. if (res.ok) {
  805. showToast('Disconnected', `${name} session terminated`, 'info');
  806. setTimeout(() => loadPPPoE(false), 1000);
  807. }
  808. } catch (err) {
  809. showToast('Error', err.message, 'error');
  810. }
  811. }
  812. async function togglePPPoEState(name, enable) {
  813. try {
  814. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/state`, {
  815. method: 'POST',
  816. headers: { 'Content-Type': 'application/json' },
  817. body: JSON.stringify({ enabled: enable })
  818. });
  819. if (res.ok) {
  820. showToast(enable ? 'Enabled' : 'Disabled', `${name} is now ${enable ? 'enabled' : 'disabled'}`, 'info');
  821. loadPPPoE(false);
  822. }
  823. } catch (err) {
  824. showToast('Error', err.message, 'error');
  825. }
  826. }
  827. async function deletePPPoEInstance(name) {
  828. if (!confirm(`Are you sure you want to delete PPPoE client ${name}?`)) return;
  829. try {
  830. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  831. if (res.ok) {
  832. showToast('Deleted', `PPPoE client ${name} removed`, 'success');
  833. loadPPPoE(false);
  834. fetchData(false);
  835. }
  836. } catch (err) {
  837. showToast('Error', err.message, 'error');
  838. }
  839. }
  840. // ======================== WireGuard Multi-Interface & Multi-Peer ========================
  841. state.wgSubTab = 'ifaces';
  842. function switchWGSubTab(tab) {
  843. state.wgSubTab = tab;
  844. const ifacesPanel = document.getElementById('wg-subtab-ifaces');
  845. const peersPanel = document.getElementById('wg-subtab-peers');
  846. const ifacesBtn = document.getElementById('wg-subtab-btn-ifaces');
  847. const peersBtn = document.getElementById('wg-subtab-btn-peers');
  848. if (tab === 'ifaces') {
  849. ifacesPanel?.classList.remove('hidden');
  850. peersPanel?.classList.add('hidden');
  851. ifacesBtn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-rose-500 text-white transition flex items-center gap-2';
  852. peersBtn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition flex items-center gap-2';
  853. } else {
  854. ifacesPanel?.classList.add('hidden');
  855. peersPanel?.classList.remove('hidden');
  856. ifacesBtn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition flex items-center gap-2';
  857. peersBtn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-rose-500 text-white transition flex items-center gap-2';
  858. renderWGPeers();
  859. }
  860. }
  861. async function loadWireGuard(populateInputs = true) {
  862. try {
  863. const [ifacesRes, peersRes] = await Promise.all([
  864. fetch(`${API_BASE}/vpn/wireguard/interfaces`),
  865. fetch(`${API_BASE}/vpn/wireguard/peers`)
  866. ]);
  867. const ifaces = ifacesRes.ok ? await ifacesRes.json() : [];
  868. const peers = peersRes.ok ? await peersRes.json() : [];
  869. state.wgInterfaces = Array.isArray(ifaces) ? ifaces : [];
  870. state.wgPeers = Array.isArray(peers) ? peers : [];
  871. // Badges
  872. const ifacesCountBadge = document.getElementById('wg-ifaces-count');
  873. if (ifacesCountBadge) ifacesCountBadge.innerText = `${state.wgInterfaces.length} Interfaces`;
  874. const peersCountBadge = document.getElementById('wg-peers-count');
  875. if (peersCountBadge) peersCountBadge.innerText = `${state.wgPeers.length} Peers`;
  876. const subTabIfaces = document.getElementById('wg-subtab-badge-ifaces');
  877. if (subTabIfaces) subTabIfaces.innerText = state.wgInterfaces.length;
  878. const subTabPeers = document.getElementById('wg-subtab-badge-peers');
  879. if (subTabPeers) subTabPeers.innerText = state.wgPeers.length;
  880. // Render Interfaces
  881. const ifacesTbody = document.getElementById('wg-ifaces-table-body');
  882. const ifacesEmpty = document.getElementById('wg-ifaces-empty');
  883. if (ifacesTbody) {
  884. ifacesTbody.innerHTML = '';
  885. if (state.wgInterfaces.length === 0) {
  886. if (ifacesEmpty) ifacesEmpty.classList.remove('hidden');
  887. } else {
  888. if (ifacesEmpty) ifacesEmpty.classList.add('hidden');
  889. state.wgInterfaces.forEach(iface => {
  890. const peersOnIface = state.wgPeers.filter(p => p.interface === iface.name).length;
  891. const tr = document.createElement('tr');
  892. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  893. tr.innerHTML = `
  894. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(iface.running, iface.disabled)}</td>
  895. <td class="py-2.5 px-3 font-bold text-white">${iface.name}</td>
  896. <td class="py-2.5 px-3 text-amber-400 font-mono">${iface.listen_port}</td>
  897. <td class="py-2.5 px-3 text-emerald-400 font-mono">${iface.address || '-'}</td>
  898. <td class="py-2.5 px-3 text-slate-300 font-mono">
  899. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${iface.public_key}', 'Public Key')" title="Click to copy: ${iface.public_key}">
  900. ${(iface.public_key || '').substring(0, 10)}... 📋
  901. </span>
  902. </td>
  903. <td class="py-2.5 px-3 text-slate-400 font-mono">${iface.mtu || 1420}</td>
  904. <td class="py-2.5 px-3 text-center">
  905. <span class="px-2 py-0.5 rounded text-[10px] font-sans bg-slate-800 text-slate-300">${peersOnIface} peer${peersOnIface !== 1 ? 's' : ''}</span>
  906. </td>
  907. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  908. ${iface.running ? `
  909. <button onclick="stopWGInterface('${iface.name}')" class="text-xs text-rose-400 hover:text-rose-300">Stop</button>
  910. ` : `
  911. <button onclick="startWGInterface('${iface.name}')" class="text-xs bg-rose-600/30 hover:bg-rose-600/50 text-rose-300 px-2 py-0.5 rounded border border-rose-500/30">Start</button>
  912. `}
  913. <button onclick="toggleWGInterfaceState('${iface.name}', ${iface.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  914. ${iface.disabled ? 'Enable' : 'Disable'}
  915. </button>
  916. <button onclick="openEditWGInterfaceModal('${iface.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  917. <button onclick="deleteWGInterface('${iface.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  918. </td>
  919. `;
  920. ifacesTbody.appendChild(tr);
  921. });
  922. }
  923. }
  924. // Populate filter dropdown in peers tab
  925. const filterSel = document.getElementById('wg-peers-filter-iface');
  926. if (filterSel) {
  927. const currentVal = filterSel.value;
  928. filterSel.innerHTML = '<option value="">All Interfaces</option>';
  929. state.wgInterfaces.forEach(i => {
  930. const opt = document.createElement('option');
  931. opt.value = i.name;
  932. opt.innerText = i.name;
  933. if (i.name === currentVal) opt.selected = true;
  934. filterSel.appendChild(opt);
  935. });
  936. }
  937. renderWGPeers();
  938. } catch (err) {
  939. console.error('Failed to load WireGuard:', err);
  940. }
  941. }
  942. function renderWGPeers() {
  943. const filterSel = document.getElementById('wg-peers-filter-iface');
  944. const selectedIface = filterSel ? filterSel.value : '';
  945. const tbody = document.getElementById('wg-peers-table-body');
  946. const empty = document.getElementById('wg-peers-empty');
  947. if (!tbody) return;
  948. tbody.innerHTML = '';
  949. const filtered = selectedIface ? state.wgPeers.filter(p => p.interface === selectedIface) : state.wgPeers;
  950. if (filtered.length === 0) {
  951. if (empty) empty.classList.remove('hidden');
  952. } else {
  953. if (empty) empty.classList.add('hidden');
  954. filtered.forEach(p => {
  955. const isOnline = p.latest_handshake && !p.latest_handshake.includes('Never');
  956. const tr = document.createElement('tr');
  957. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  958. tr.innerHTML = `
  959. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(isOnline, p.disabled)}</td>
  960. <td class="py-2.5 px-3 font-mono font-bold text-rose-400">${p.interface}</td>
  961. <td class="py-2.5 px-3 font-bold text-white font-sans">${p.name || 'Unnamed'}</td>
  962. <td class="py-2.5 px-3 text-slate-300 font-mono">
  963. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${p.public_key}', 'Peer Public Key')" title="${p.public_key}">
  964. ${p.public_key.substring(0, 10)}... 📋
  965. </span>
  966. </td>
  967. <td class="py-2.5 px-3 text-emerald-400 font-mono font-semibold">${(p.allowed_ips || []).join(', ')}</td>
  968. <td class="py-2.5 px-3 text-slate-400 font-mono">${p.endpoint_address ? (p.endpoint_address + (p.endpoint_port ? ':' + p.endpoint_port : '')) : '-'}</td>
  969. <td class="py-2.5 px-3 text-slate-300 font-sans">${p.latest_handshake || 'Never'}</td>
  970. <td class="py-2.5 px-3 font-mono text-[11px]">
  971. <span class="text-emerald-400">↓ ${p.transfer_rx_human || '0 B'}</span>
  972. <span class="text-cyan-400 ml-1">↑ ${p.transfer_tx_human || '0 B'}</span>
  973. </td>
  974. <td class="py-2.5 px-3 text-right font-sans space-x-2">
  975. <button onclick="openWGClientConfModal('${p.interface}', '${(p.allowed_ips || [])[0] || '10.10.0.2/32'}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold" title="Generate WireGuard Client Profile (.conf)">Config (.conf)</button>
  976. <button onclick="deleteWGPeer('${p.interface}', '${p.public_key}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  977. </td>
  978. `;
  979. tbody.appendChild(tr);
  980. });
  981. }
  982. }
  983. function openAddWGInterfaceModal() {
  984. document.getElementById('wg-iface-modal-title').innerText = 'Add WireGuard Interface';
  985. document.getElementById('wg-iface-modal-edit-orig').value = '';
  986. document.getElementById('wg-iface-modal-name').value = `wg${(state.wgInterfaces || []).length}`;
  987. document.getElementById('wg-iface-modal-name').readOnly = false;
  988. document.getElementById('wg-iface-modal-port').value = 51820 + (state.wgInterfaces || []).length;
  989. document.getElementById('wg-iface-modal-addr').value = `10.${10 + (state.wgInterfaces || []).length}.0.1/24`;
  990. document.getElementById('wg-iface-modal-mtu').value = '1420';
  991. document.getElementById('wg-iface-modal-pubkey').value = '';
  992. document.getElementById('wg-iface-modal-privkey').value = '';
  993. document.getElementById('wg-iface-modal-disabled').checked = false;
  994. generateWGInterfaceKeys();
  995. document.getElementById('wg-iface-modal').classList.remove('hidden');
  996. }
  997. function openEditWGInterfaceModal(name) {
  998. const iface = (state.wgInterfaces || []).find(i => i.name === name);
  999. if (!iface) return;
  1000. document.getElementById('wg-iface-modal-title').innerText = `Edit WireGuard Interface: ${name}`;
  1001. document.getElementById('wg-iface-modal-edit-orig').value = name;
  1002. document.getElementById('wg-iface-modal-name').value = iface.name;
  1003. document.getElementById('wg-iface-modal-name').readOnly = true;
  1004. document.getElementById('wg-iface-modal-port').value = iface.listen_port || 51820;
  1005. document.getElementById('wg-iface-modal-addr').value = iface.address || '';
  1006. document.getElementById('wg-iface-modal-mtu').value = iface.mtu || 1420;
  1007. document.getElementById('wg-iface-modal-pubkey').value = iface.public_key || '';
  1008. document.getElementById('wg-iface-modal-privkey').value = iface.private_key || '';
  1009. document.getElementById('wg-iface-modal-disabled').checked = !!iface.disabled;
  1010. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1011. }
  1012. function closeAddWGInterfaceModal() {
  1013. document.getElementById('wg-iface-modal').classList.add('hidden');
  1014. }
  1015. async function generateWGInterfaceKeys() {
  1016. try {
  1017. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1018. const keys = await res.json();
  1019. if (res.ok) {
  1020. document.getElementById('wg-iface-modal-privkey').value = keys.private_key;
  1021. document.getElementById('wg-iface-modal-pubkey').value = keys.public_key;
  1022. }
  1023. } catch (err) {
  1024. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  1025. }
  1026. }
  1027. async function submitSaveWGInterface(e) {
  1028. e.preventDefault();
  1029. const name = document.getElementById('wg-iface-modal-name').value.trim();
  1030. const port = parseInt(document.getElementById('wg-iface-modal-port').value, 10) || 51820;
  1031. const addr = document.getElementById('wg-iface-modal-addr').value.trim();
  1032. const mtu = parseInt(document.getElementById('wg-iface-modal-mtu').value, 10) || 1420;
  1033. const pub = document.getElementById('wg-iface-modal-pubkey').value.trim();
  1034. const priv = document.getElementById('wg-iface-modal-privkey').value.trim();
  1035. const disabled = document.getElementById('wg-iface-modal-disabled').checked;
  1036. try {
  1037. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces`, {
  1038. method: 'POST',
  1039. headers: { 'Content-Type': 'application/json' },
  1040. body: JSON.stringify({
  1041. name,
  1042. listen_port: port,
  1043. address: addr,
  1044. mtu,
  1045. public_key: pub,
  1046. private_key: priv,
  1047. disabled
  1048. })
  1049. });
  1050. if (res.ok) {
  1051. showToast('WireGuard Saved', `Interface ${name} configured`, 'success');
  1052. closeAddWGInterfaceModal();
  1053. loadWireGuard(false);
  1054. fetchData(false);
  1055. }
  1056. } catch (err) {
  1057. showToast('Error', err.message, 'error');
  1058. }
  1059. }
  1060. async function startWGInterface(name) {
  1061. try {
  1062. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/start`, { method: 'POST' });
  1063. if (res.ok) {
  1064. showToast('Interface UP', `Started WireGuard interface ${name}`, 'success');
  1065. loadWireGuard(false);
  1066. fetchData(false);
  1067. }
  1068. } catch (err) {
  1069. showToast('Error', err.message, 'error');
  1070. }
  1071. }
  1072. async function stopWGInterface(name) {
  1073. try {
  1074. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  1075. if (res.ok) {
  1076. showToast('Interface DOWN', `Stopped WireGuard interface ${name}`, 'info');
  1077. loadWireGuard(false);
  1078. fetchData(false);
  1079. }
  1080. } catch (err) {
  1081. showToast('Error', err.message, 'error');
  1082. }
  1083. }
  1084. async function toggleWGInterfaceState(name, enable) {
  1085. try {
  1086. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/state`, {
  1087. method: 'POST',
  1088. headers: { 'Content-Type': 'application/json' },
  1089. body: JSON.stringify({ enabled: enable })
  1090. });
  1091. if (res.ok) {
  1092. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  1093. loadWireGuard(false);
  1094. }
  1095. } catch (err) {
  1096. showToast('Error', err.message, 'error');
  1097. }
  1098. }
  1099. async function deleteWGInterface(name) {
  1100. if (!confirm(`Are you sure you want to delete WireGuard interface ${name}?`)) return;
  1101. try {
  1102. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1103. if (res.ok) {
  1104. showToast('Deleted', `Interface ${name} removed`, 'success');
  1105. loadWireGuard(false);
  1106. fetchData(false);
  1107. }
  1108. } catch (err) {
  1109. showToast('Error', err.message, 'error');
  1110. }
  1111. }
  1112. function openAddWGPeerModal() {
  1113. const sel = document.getElementById('wg-peer-modal-iface');
  1114. sel.innerHTML = '';
  1115. (state.wgInterfaces || []).forEach(i => {
  1116. const opt = document.createElement('option');
  1117. opt.value = i.name;
  1118. opt.innerText = `${i.name} (${i.address || 'No IP'})`;
  1119. sel.appendChild(opt);
  1120. });
  1121. if ((state.wgInterfaces || []).length === 0) {
  1122. showToast('No Interfaces', 'Please add a WireGuard interface first before adding peers', 'warning');
  1123. openAddWGInterfaceModal();
  1124. return;
  1125. }
  1126. document.getElementById('wg-peer-modal-name').value = '';
  1127. document.getElementById('wg-peer-modal-pubkey').value = '';
  1128. document.getElementById('wg-peer-modal-allowedips').value = '10.10.0.2/32';
  1129. document.getElementById('wg-peer-modal-endpoint').value = '';
  1130. document.getElementById('wg-peer-modal-keepalive').value = '25';
  1131. document.getElementById('wg-peer-modal-preshared').value = '';
  1132. document.getElementById('wg-peer-modal-disabled').checked = false;
  1133. document.getElementById('wg-peer-modal').classList.remove('hidden');
  1134. }
  1135. function closeAddWGPeerModal() {
  1136. document.getElementById('wg-peer-modal').classList.add('hidden');
  1137. }
  1138. async function submitSaveWGPeer(e) {
  1139. e.preventDefault();
  1140. const iface = document.getElementById('wg-peer-modal-iface').value;
  1141. const name = document.getElementById('wg-peer-modal-name').value.trim();
  1142. const pub = document.getElementById('wg-peer-modal-pubkey').value.trim();
  1143. const allowed = document.getElementById('wg-peer-modal-allowedips').value.split(',').map(s => s.trim());
  1144. const ep = document.getElementById('wg-peer-modal-endpoint').value.trim();
  1145. const keepalive = parseInt(document.getElementById('wg-peer-modal-keepalive').value, 10) || 25;
  1146. const psk = document.getElementById('wg-peer-modal-preshared').value.trim();
  1147. const disabled = document.getElementById('wg-peer-modal-disabled').checked;
  1148. let epAddr = ep;
  1149. let epPort = 0;
  1150. if (ep.includes(':')) {
  1151. const parts = ep.split(':');
  1152. epAddr = parts[0];
  1153. epPort = parseInt(parts[1], 10) || 0;
  1154. }
  1155. try {
  1156. const res = await fetch(`${API_BASE}/vpn/wireguard/peers`, {
  1157. method: 'POST',
  1158. headers: { 'Content-Type': 'application/json' },
  1159. body: JSON.stringify({
  1160. interface: iface,
  1161. name,
  1162. public_key: pub,
  1163. allowed_ips: allowed,
  1164. endpoint_address: epAddr,
  1165. endpoint_port: epPort,
  1166. persistent_keepalive: keepalive,
  1167. preshared_key: psk,
  1168. disabled
  1169. })
  1170. });
  1171. if (res.ok) {
  1172. showToast('Peer Saved', `Peer ${name} added to ${iface}`, 'success');
  1173. closeAddWGPeerModal();
  1174. loadWireGuard(false);
  1175. }
  1176. } catch (err) {
  1177. showToast('Error', err.message, 'error');
  1178. }
  1179. }
  1180. async function deleteWGPeer(iface, pubkey) {
  1181. if (!confirm(`Are you sure you want to remove peer from ${iface}?`)) return;
  1182. try {
  1183. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/${encodeURIComponent(iface)}/${encodeURIComponent(pubkey)}`, {
  1184. method: 'DELETE'
  1185. });
  1186. if (res.ok) {
  1187. showToast('Peer Deleted', 'WireGuard peer removed', 'success');
  1188. loadWireGuard(false);
  1189. }
  1190. } catch (err) {
  1191. showToast('Error', err.message, 'error');
  1192. }
  1193. }
  1194. // ======================== IPSec Multi-Tunnel ========================
  1195. async function loadIPSec(populateInputs = true) {
  1196. try {
  1197. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`);
  1198. const list = await res.json();
  1199. state.ipsecTunnels = Array.isArray(list) ? list : [];
  1200. const activeCount = state.ipsecTunnels.filter(t => t.running || t.status === 'ESTABLISHED').length;
  1201. const badge = document.getElementById('ipsec-sas-badge');
  1202. if (badge) badge.innerText = `${activeCount} Active SAs`;
  1203. const tbody = document.getElementById('ipsec-table-body');
  1204. const empty = document.getElementById('ipsec-empty');
  1205. if (!tbody) return;
  1206. tbody.innerHTML = '';
  1207. if (state.ipsecTunnels.length === 0) {
  1208. if (empty) empty.classList.remove('hidden');
  1209. } else {
  1210. if (empty) empty.classList.add('hidden');
  1211. state.ipsecTunnels.forEach(c => {
  1212. const isEstablished = c.running || c.status === 'ESTABLISHED';
  1213. const tr = document.createElement('tr');
  1214. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1215. tr.innerHTML = `
  1216. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(isEstablished, c.disabled)}</td>
  1217. <td class="py-2.5 px-4 font-bold text-white">${c.name}</td>
  1218. <td class="py-2.5 px-4 text-emerald-400 font-mono">${c.local_subnet || '-'}</td>
  1219. <td class="py-2.5 px-4 text-slate-300 font-mono">${c.remote_addrs || '-'}</td>
  1220. <td class="py-2.5 px-4 text-cyan-400 font-mono">${c.remote_subnet || '-'}</td>
  1221. <td class="py-2.5 px-4 font-sans">
  1222. <span class="px-2 py-0.5 rounded-full text-[10px] font-semibold ${
  1223. isEstablished ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/30' : 'bg-slate-800 text-slate-400'
  1224. }">${c.status || (isEstablished ? 'ESTABLISHED' : 'DISCONNECTED')}</span>
  1225. </td>
  1226. <td class="py-2.5 px-4 text-right space-x-2 font-sans">
  1227. ${isEstablished ? `
  1228. <button onclick="stopIPSecTunnel('${c.name}')" class="text-xs text-rose-400 hover:text-rose-300">Terminate</button>
  1229. ` : `
  1230. <button onclick="startIPSecTunnel('${c.name}')" class="text-xs bg-amber-600/30 hover:bg-amber-600/50 text-amber-300 px-2 py-0.5 rounded border border-amber-500/30">Initiate</button>
  1231. `}
  1232. <button onclick="toggleIPSecState('${c.name}', ${c.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1233. ${c.disabled ? 'Enable' : 'Disable'}
  1234. </button>
  1235. <button onclick="openEditIPSecModal('${c.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  1236. <button onclick="deleteIPSecConn('${c.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1237. </td>
  1238. `;
  1239. tbody.appendChild(tr);
  1240. });
  1241. }
  1242. } catch (err) {
  1243. console.error('Failed to load IPSec:', err);
  1244. }
  1245. }
  1246. function openAddIPSecModal() {
  1247. document.getElementById('ipsec-modal-title').innerText = 'Configure IPSec IKEv2 Tunnel';
  1248. document.getElementById('ipsec-modal-name').value = `ipsec-${(state.ipsecTunnels || []).length + 1}`;
  1249. document.getElementById('ipsec-modal-name').readOnly = false;
  1250. document.getElementById('ipsec-modal-localts').value = '192.168.10.0/24';
  1251. document.getElementById('ipsec-modal-remotets').value = '192.168.20.0/24';
  1252. document.getElementById('ipsec-modal-remotegw').value = '';
  1253. document.getElementById('ipsec-modal-psk').value = '';
  1254. document.getElementById('ipsec-modal-ikeprop').value = 'aes256-sha256-modp2048,default';
  1255. document.getElementById('ipsec-modal-espprop').value = 'aes256-sha256-modp2048,default';
  1256. document.getElementById('ipsec-modal-autostart').checked = true;
  1257. document.getElementById('ipsec-modal-disabled').checked = false;
  1258. document.getElementById('ipsec-modal').classList.remove('hidden');
  1259. }
  1260. function openEditIPSecModal(name) {
  1261. const conn = (state.ipsecTunnels || []).find(c => c.name === name);
  1262. if (!conn) return;
  1263. document.getElementById('ipsec-modal-title').innerText = `Edit IPSec Tunnel: ${name}`;
  1264. document.getElementById('ipsec-modal-name').value = conn.name;
  1265. document.getElementById('ipsec-modal-name').readOnly = true;
  1266. document.getElementById('ipsec-modal-localts').value = conn.local_subnet || '';
  1267. document.getElementById('ipsec-modal-remotets').value = conn.remote_subnet || '';
  1268. document.getElementById('ipsec-modal-remotegw').value = conn.remote_addrs || '';
  1269. document.getElementById('ipsec-modal-psk').value = conn.preshared_key || '';
  1270. document.getElementById('ipsec-modal-ikeprop').value = conn.ike_proposals || 'aes256-sha256-modp2048,default';
  1271. document.getElementById('ipsec-modal-espprop').value = conn.esp_proposals || 'aes256-sha256-modp2048,default';
  1272. document.getElementById('ipsec-modal-autostart').checked = conn.auto_start ?? true;
  1273. document.getElementById('ipsec-modal-disabled').checked = !!conn.disabled;
  1274. document.getElementById('ipsec-modal').classList.remove('hidden');
  1275. }
  1276. function closeAddIPSecModal() {
  1277. document.getElementById('ipsec-modal').classList.add('hidden');
  1278. }
  1279. async function submitSaveIPSec(e) {
  1280. e.preventDefault();
  1281. const name = document.getElementById('ipsec-modal-name').value.trim();
  1282. const localts = document.getElementById('ipsec-modal-localts').value.trim();
  1283. const remotets = document.getElementById('ipsec-modal-remotets').value.trim();
  1284. const remotegw = document.getElementById('ipsec-modal-remotegw').value.trim();
  1285. const psk = document.getElementById('ipsec-modal-psk').value;
  1286. const ike = document.getElementById('ipsec-modal-ikeprop').value.trim();
  1287. const esp = document.getElementById('ipsec-modal-espprop').value.trim();
  1288. const autostart = document.getElementById('ipsec-modal-autostart').checked;
  1289. const disabled = document.getElementById('ipsec-modal-disabled').checked;
  1290. try {
  1291. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`, {
  1292. method: 'POST',
  1293. headers: { 'Content-Type': 'application/json' },
  1294. body: JSON.stringify({
  1295. name,
  1296. local_addrs: '%any',
  1297. remote_addrs: remotegw,
  1298. local_subnet: localts,
  1299. remote_subnet: remotets,
  1300. preshared_key: psk,
  1301. ike_proposals: ike,
  1302. esp_proposals: esp,
  1303. auto_start: autostart,
  1304. disabled
  1305. })
  1306. });
  1307. if (res.ok) {
  1308. showToast('IPSec Saved', `Tunnel ${name} configured`, 'success');
  1309. closeAddIPSecModal();
  1310. loadIPSec(false);
  1311. fetchData(false);
  1312. }
  1313. } catch (err) {
  1314. showToast('Error', err.message, 'error');
  1315. }
  1316. }
  1317. async function startIPSecTunnel(name) {
  1318. try {
  1319. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/start`, { method: 'POST' });
  1320. if (res.ok) {
  1321. showToast('Initiating Tunnel', `Attempting SA handshake for ${name}...`, 'info');
  1322. setTimeout(() => loadIPSec(false), 2000);
  1323. }
  1324. } catch (err) {
  1325. showToast('Error', err.message, 'error');
  1326. }
  1327. }
  1328. async function stopIPSecTunnel(name) {
  1329. try {
  1330. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  1331. if (res.ok) {
  1332. showToast('Terminated', `IPSec SA for ${name} closed`, 'info');
  1333. loadIPSec(false);
  1334. }
  1335. } catch (err) {
  1336. showToast('Error', err.message, 'error');
  1337. }
  1338. }
  1339. async function toggleIPSecState(name, enable) {
  1340. try {
  1341. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/state`, {
  1342. method: 'POST',
  1343. headers: { 'Content-Type': 'application/json' },
  1344. body: JSON.stringify({ enabled: enable })
  1345. });
  1346. if (res.ok) {
  1347. showToast(enable ? 'Enabled' : 'Disabled', `IPSec tunnel ${name} updated`, 'info');
  1348. loadIPSec(false);
  1349. }
  1350. } catch (err) {
  1351. showToast('Error', err.message, 'error');
  1352. }
  1353. }
  1354. async function deleteIPSecConn(name) {
  1355. if (!confirm(`Are you sure you want to delete IPSec tunnel ${name}?`)) return;
  1356. try {
  1357. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1358. if (res.ok) {
  1359. showToast('Deleted', `IPSec connection ${name} removed`, 'success');
  1360. loadIPSec(false);
  1361. fetchData(false);
  1362. }
  1363. } catch (err) {
  1364. showToast('Error', err.message, 'error');
  1365. }
  1366. }
  1367. // ======================== L2TP Multi-Instance ========================
  1368. async function loadL2TP(populateInputs = true) {
  1369. try {
  1370. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`);
  1371. const list = await res.json();
  1372. state.l2tpList = Array.isArray(list) ? list : [];
  1373. const badge = document.getElementById('l2tp-count-badge');
  1374. if (badge) badge.innerText = `${state.l2tpList.length} Client${state.l2tpList.length !== 1 ? 's' : ''}`;
  1375. const tbody = document.getElementById('l2tp-table-body');
  1376. const empty = document.getElementById('l2tp-empty');
  1377. if (!tbody) return;
  1378. tbody.innerHTML = '';
  1379. if (state.l2tpList.length === 0) {
  1380. if (empty) empty.classList.remove('hidden');
  1381. } else {
  1382. if (empty) empty.classList.add('hidden');
  1383. state.l2tpList.forEach(inst => {
  1384. const tr = document.createElement('tr');
  1385. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1386. tr.innerHTML = `
  1387. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  1388. <td class="py-2.5 px-3 font-bold text-white">${inst.name}</td>
  1389. <td class="py-2.5 px-3 text-cyan-400 font-mono">${inst.connect_to}</td>
  1390. <td class="py-2.5 px-3 text-slate-300 font-mono">${inst.username || '-'}</td>
  1391. <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${inst.assigned_ip || '-'}</td>
  1392. <td class="py-2.5 px-3 text-slate-400 font-mono">${inst.ppp_device || '-'}</td>
  1393. <td class="py-2.5 px-3 text-center">
  1394. <span class="px-2 py-0.5 rounded text-[10px] font-sans ${inst.default_route ? 'bg-cyan-500/20 text-cyan-300 border border-cyan-500/30' : 'bg-slate-800 text-slate-500'}">
  1395. ${inst.default_route ? 'Yes' : 'No'}
  1396. </span>
  1397. </td>
  1398. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  1399. ${inst.running ? `
  1400. <button onclick="disconnectL2TPInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  1401. ` : `
  1402. <button onclick="connectL2TPInstance('${inst.name}')" class="text-xs bg-cyan-600/30 hover:bg-cyan-600/50 text-cyan-300 px-2 py-0.5 rounded border border-cyan-500/30">Connect</button>
  1403. `}
  1404. <button onclick="toggleL2TPState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1405. ${inst.disabled ? 'Enable' : 'Disable'}
  1406. </button>
  1407. <button onclick="openEditL2TPModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  1408. <button onclick="deleteL2TPInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1409. </td>
  1410. `;
  1411. tbody.appendChild(tr);
  1412. });
  1413. }
  1414. } catch (err) {
  1415. console.error('Failed to load L2TP:', err);
  1416. }
  1417. }
  1418. function openAddL2TPModal() {
  1419. document.getElementById('l2tp-modal-title').innerText = 'Add L2TP Client Interface';
  1420. document.getElementById('l2tp-modal-name').value = `l2tp-out${(state.l2tpList || []).length + 1}`;
  1421. document.getElementById('l2tp-modal-name').readOnly = false;
  1422. document.getElementById('l2tp-modal-server').value = '';
  1423. document.getElementById('l2tp-modal-user').value = '';
  1424. document.getElementById('l2tp-modal-pass').value = '';
  1425. document.getElementById('l2tp-modal-ipsec').value = '';
  1426. document.getElementById('l2tp-modal-defroute').checked = true;
  1427. document.getElementById('l2tp-modal-disabled').checked = false;
  1428. document.getElementById('l2tp-modal').classList.remove('hidden');
  1429. }
  1430. function openEditL2TPModal(name) {
  1431. const inst = (state.l2tpList || []).find(i => i.name === name);
  1432. if (!inst) return;
  1433. document.getElementById('l2tp-modal-title').innerText = `Edit L2TP Client: ${name}`;
  1434. document.getElementById('l2tp-modal-name').value = inst.name;
  1435. document.getElementById('l2tp-modal-name').readOnly = true;
  1436. document.getElementById('l2tp-modal-server').value = inst.connect_to || '';
  1437. document.getElementById('l2tp-modal-user').value = inst.username || '';
  1438. document.getElementById('l2tp-modal-pass').value = inst.password || '';
  1439. document.getElementById('l2tp-modal-ipsec').value = inst.ipsec_secret || '';
  1440. document.getElementById('l2tp-modal-defroute').checked = inst.default_route ?? true;
  1441. document.getElementById('l2tp-modal-disabled').checked = !!inst.disabled;
  1442. document.getElementById('l2tp-modal').classList.remove('hidden');
  1443. }
  1444. function closeL2TPModal() {
  1445. document.getElementById('l2tp-modal').classList.add('hidden');
  1446. }
  1447. async function submitSaveL2TP(e) {
  1448. e.preventDefault();
  1449. const name = document.getElementById('l2tp-modal-name').value.trim();
  1450. const server = document.getElementById('l2tp-modal-server').value.trim();
  1451. const user = document.getElementById('l2tp-modal-user').value.trim();
  1452. const pass = document.getElementById('l2tp-modal-pass').value;
  1453. const ipsec = document.getElementById('l2tp-modal-ipsec').value;
  1454. const defRoute = document.getElementById('l2tp-modal-defroute').checked;
  1455. const disabled = document.getElementById('l2tp-modal-disabled').checked;
  1456. try {
  1457. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`, {
  1458. method: 'POST',
  1459. headers: { 'Content-Type': 'application/json' },
  1460. body: JSON.stringify({
  1461. name,
  1462. connect_to: server,
  1463. username: user,
  1464. password: pass,
  1465. ipsec_secret: ipsec,
  1466. default_route: defRoute,
  1467. disabled
  1468. })
  1469. });
  1470. if (res.ok) {
  1471. showToast('L2TP Saved', `Client ${name} configuration saved`, 'success');
  1472. closeL2TPModal();
  1473. loadL2TP(false);
  1474. fetchData(false);
  1475. }
  1476. } catch (err) {
  1477. showToast('Error', err.message, 'error');
  1478. }
  1479. }
  1480. async function connectL2TPInstance(name) {
  1481. try {
  1482. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  1483. if (res.ok) {
  1484. showToast('Connecting', `Dialing L2TP ${name}...`, 'info');
  1485. setTimeout(() => loadL2TP(false), 2000);
  1486. }
  1487. } catch (err) {
  1488. showToast('Error', err.message, 'error');
  1489. }
  1490. }
  1491. async function disconnectL2TPInstance(name) {
  1492. try {
  1493. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  1494. if (res.ok) {
  1495. showToast('Disconnected', `L2TP tunnel ${name} terminated`, 'info');
  1496. loadL2TP(false);
  1497. }
  1498. } catch (err) {
  1499. showToast('Error', err.message, 'error');
  1500. }
  1501. }
  1502. async function toggleL2TPState(name, enable) {
  1503. try {
  1504. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/state`, {
  1505. method: 'POST',
  1506. headers: { 'Content-Type': 'application/json' },
  1507. body: JSON.stringify({ enabled: enable })
  1508. });
  1509. if (res.ok) {
  1510. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  1511. loadL2TP(false);
  1512. }
  1513. } catch (err) {
  1514. showToast('Error', err.message, 'error');
  1515. }
  1516. }
  1517. async function deleteL2TPInstance(name) {
  1518. if (!confirm(`Are you sure you want to delete L2TP client ${name}?`)) return;
  1519. try {
  1520. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1521. if (res.ok) {
  1522. showToast('Deleted', `L2TP client ${name} removed`, 'success');
  1523. loadL2TP(false);
  1524. fetchData(false);
  1525. }
  1526. } catch (err) {
  1527. showToast('Error', err.message, 'error');
  1528. }
  1529. }
  1530. // ======================== PPTP Multi-Instance ========================
  1531. async function loadPPTP(populateInputs = true) {
  1532. try {
  1533. const res = await fetch(`${API_BASE}/vpn/pptp/clients`);
  1534. const list = await res.json();
  1535. state.pptpList = Array.isArray(list) ? list : [];
  1536. const badge = document.getElementById('pptp-count-badge');
  1537. if (badge) badge.innerText = `${state.pptpList.length} Client${state.pptpList.length !== 1 ? 's' : ''}`;
  1538. const tbody = document.getElementById('pptp-table-body');
  1539. const empty = document.getElementById('pptp-empty');
  1540. if (!tbody) return;
  1541. tbody.innerHTML = '';
  1542. if (state.pptpList.length === 0) {
  1543. if (empty) empty.classList.remove('hidden');
  1544. } else {
  1545. if (empty) empty.classList.add('hidden');
  1546. state.pptpList.forEach(inst => {
  1547. const tr = document.createElement('tr');
  1548. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1549. tr.innerHTML = `
  1550. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  1551. <td class="py-2.5 px-3 font-bold text-white">${inst.name}</td>
  1552. <td class="py-2.5 px-3 text-purple-400 font-mono">${inst.connect_to}</td>
  1553. <td class="py-2.5 px-3 text-slate-300 font-mono">${inst.username || '-'}</td>
  1554. <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${inst.assigned_ip || '-'}</td>
  1555. <td class="py-2.5 px-3 text-slate-400 font-mono">${inst.ppp_device || '-'}</td>
  1556. <td class="py-2.5 px-3 text-center">
  1557. <span class="px-2 py-0.5 rounded text-[10px] font-sans ${inst.require_mppe ? 'bg-purple-500/20 text-purple-300 border border-purple-500/30' : 'bg-slate-800 text-slate-500'}">
  1558. ${inst.require_mppe ? 'MPPE-128' : 'None'}
  1559. </span>
  1560. </td>
  1561. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  1562. ${inst.running ? `
  1563. <button onclick="disconnectPPTPInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  1564. ` : `
  1565. <button onclick="connectPPTPInstance('${inst.name}')" class="text-xs bg-purple-600/30 hover:bg-purple-600/50 text-purple-300 px-2 py-0.5 rounded border border-purple-500/30">Connect</button>
  1566. `}
  1567. <button onclick="togglePPTPState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1568. ${inst.disabled ? 'Enable' : 'Disable'}
  1569. </button>
  1570. <button onclick="openEditPPTPModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  1571. <button onclick="deletePPTPInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1572. </td>
  1573. `;
  1574. tbody.appendChild(tr);
  1575. });
  1576. }
  1577. } catch (err) {
  1578. console.error('Failed to load PPTP:', err);
  1579. }
  1580. }
  1581. function openAddPPTPModal() {
  1582. document.getElementById('pptp-modal-title').innerText = 'Add PPTP Client Interface';
  1583. document.getElementById('pptp-modal-name').value = `pptp-out${(state.pptpList || []).length + 1}`;
  1584. document.getElementById('pptp-modal-name').readOnly = false;
  1585. document.getElementById('pptp-modal-server').value = '';
  1586. document.getElementById('pptp-modal-user').value = '';
  1587. document.getElementById('pptp-modal-pass').value = '';
  1588. document.getElementById('pptp-modal-mppe').checked = true;
  1589. document.getElementById('pptp-modal-defroute').checked = true;
  1590. document.getElementById('pptp-modal-disabled').checked = false;
  1591. document.getElementById('pptp-modal').classList.remove('hidden');
  1592. }
  1593. function openEditPPTPModal(name) {
  1594. const inst = (state.pptpList || []).find(i => i.name === name);
  1595. if (!inst) return;
  1596. document.getElementById('pptp-modal-title').innerText = `Edit PPTP Client: ${name}`;
  1597. document.getElementById('pptp-modal-name').value = inst.name;
  1598. document.getElementById('pptp-modal-name').readOnly = true;
  1599. document.getElementById('pptp-modal-server').value = inst.connect_to || '';
  1600. document.getElementById('pptp-modal-user').value = inst.username || '';
  1601. document.getElementById('pptp-modal-pass').value = inst.password || '';
  1602. document.getElementById('pptp-modal-mppe').checked = inst.require_mppe ?? true;
  1603. document.getElementById('pptp-modal-defroute').checked = inst.default_route ?? true;
  1604. document.getElementById('pptp-modal-disabled').checked = !!inst.disabled;
  1605. document.getElementById('pptp-modal').classList.remove('hidden');
  1606. }
  1607. function closePPTPModal() {
  1608. document.getElementById('pptp-modal').classList.add('hidden');
  1609. }
  1610. async function submitSavePPTP(e) {
  1611. e.preventDefault();
  1612. const name = document.getElementById('pptp-modal-name').value.trim();
  1613. const server = document.getElementById('pptp-modal-server').value.trim();
  1614. const user = document.getElementById('pptp-modal-user').value.trim();
  1615. const pass = document.getElementById('pptp-modal-pass').value;
  1616. const mppe = document.getElementById('pptp-modal-mppe').checked;
  1617. const defRoute = document.getElementById('pptp-modal-defroute').checked;
  1618. const disabled = document.getElementById('pptp-modal-disabled').checked;
  1619. try {
  1620. const res = await fetch(`${API_BASE}/vpn/pptp/clients`, {
  1621. method: 'POST',
  1622. headers: { 'Content-Type': 'application/json' },
  1623. body: JSON.stringify({
  1624. name,
  1625. connect_to: server,
  1626. username: user,
  1627. password: pass,
  1628. require_mppe: mppe,
  1629. default_route: defRoute,
  1630. auto_reconnect: true,
  1631. disabled
  1632. })
  1633. });
  1634. if (res.ok) {
  1635. showToast('PPTP Saved', `Client ${name} configuration saved`, 'success');
  1636. closePPTPModal();
  1637. loadPPTP(false);
  1638. fetchData(false);
  1639. }
  1640. } catch (err) {
  1641. showToast('Error', err.message, 'error');
  1642. }
  1643. }
  1644. async function connectPPTPInstance(name) {
  1645. try {
  1646. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  1647. if (res.ok) {
  1648. showToast('Connecting', `Dialing PPTP ${name}...`, 'info');
  1649. setTimeout(() => loadPPTP(false), 2000);
  1650. }
  1651. } catch (err) {
  1652. showToast('Error', err.message, 'error');
  1653. }
  1654. }
  1655. async function disconnectPPTPInstance(name) {
  1656. try {
  1657. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  1658. if (res.ok) {
  1659. showToast('Disconnected', `PPTP tunnel ${name} terminated`, 'info');
  1660. loadPPTP(false);
  1661. }
  1662. } catch (err) {
  1663. showToast('Error', err.message, 'error');
  1664. }
  1665. }
  1666. async function togglePPTPState(name, enable) {
  1667. try {
  1668. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/state`, {
  1669. method: 'POST',
  1670. headers: { 'Content-Type': 'application/json' },
  1671. body: JSON.stringify({ enabled: enable })
  1672. });
  1673. if (res.ok) {
  1674. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  1675. loadPPTP(false);
  1676. }
  1677. } catch (err) {
  1678. showToast('Error', err.message, 'error');
  1679. }
  1680. }
  1681. async function deletePPTPInstance(name) {
  1682. if (!confirm(`Are you sure you want to delete PPTP client ${name}?`)) return;
  1683. try {
  1684. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1685. if (res.ok) {
  1686. showToast('Deleted', `PPTP client ${name} removed`, 'success');
  1687. loadPPTP(false);
  1688. fetchData(false);
  1689. }
  1690. } catch (err) {
  1691. showToast('Error', err.message, 'error');
  1692. }
  1693. }
  1694. // ---------------- Modal & Helper Functions ----------------
  1695. function openVlanModal(defaultParent = '') {
  1696. const select = document.getElementById('vlan-parent');
  1697. select.innerHTML = '';
  1698. const allIfaces = state.interfaces || [];
  1699. const eligible = allIfaces.filter(i => !i.is_vlan && i.name !== 'lo');
  1700. if (eligible.length === 0) {
  1701. allIfaces.forEach(i => eligible.push(i));
  1702. }
  1703. eligible.forEach(i => {
  1704. const opt = document.createElement('option');
  1705. opt.value = i.name;
  1706. opt.innerText = `${i.name} (${i.role || 'Interface'} - ${i.state})`;
  1707. if (i.name === defaultParent) opt.selected = true;
  1708. select.appendChild(opt);
  1709. });
  1710. document.getElementById('vlan-id').value = '';
  1711. document.getElementById('vlan-name').value = '';
  1712. document.getElementById('vlan-ip').value = '';
  1713. document.getElementById('vlan-desc').value = '';
  1714. autoSuggestVlanName();
  1715. document.getElementById('vlan-modal').classList.remove('hidden');
  1716. }
  1717. function closeVlanModal() {
  1718. document.getElementById('vlan-modal').classList.add('hidden');
  1719. }
  1720. function autoSuggestVlanName() {
  1721. const parent = document.getElementById('vlan-parent').value;
  1722. const id = document.getElementById('vlan-id').value;
  1723. const nameInput = document.getElementById('vlan-name');
  1724. if (parent && id) nameInput.placeholder = `${parent}.${id}`;
  1725. }
  1726. function setSubnetPreset(cidr) {
  1727. const ipInput = document.getElementById('vlan-ip');
  1728. const id = document.getElementById('vlan-id').value || '10';
  1729. ipInput.value = `192.168.${id}.1${cidr}`;
  1730. }
  1731. async function submitCreateVlan(e) {
  1732. e.preventDefault();
  1733. const btn = document.getElementById('vlan-submit-btn');
  1734. btn.disabled = true;
  1735. btn.innerText = 'Creating...';
  1736. const parent = document.getElementById('vlan-parent').value;
  1737. const id = parseInt(document.getElementById('vlan-id').value, 10);
  1738. const name = document.getElementById('vlan-name').value.trim();
  1739. const ip = document.getElementById('vlan-ip').value.trim();
  1740. const role = document.getElementById('vlan-role').value;
  1741. const desc = document.getElementById('vlan-desc').value.trim();
  1742. try {
  1743. const res = await fetch(`${API_BASE}/vlans`, {
  1744. method: 'POST',
  1745. headers: { 'Content-Type': 'application/json' },
  1746. body: JSON.stringify({
  1747. parent_name: parent,
  1748. vlan_id: id,
  1749. name: name,
  1750. ip_address: ip,
  1751. role: role,
  1752. description: desc,
  1753. mtu: 1500,
  1754. auto_up: true
  1755. })
  1756. });
  1757. const data = await res.json();
  1758. if (res.ok) {
  1759. showToast('VLAN Created', `Created ${data.name} (VLAN ${data.vlan_id})`, 'success');
  1760. state.expandedParents.add(parent);
  1761. closeVlanModal();
  1762. await fetchData(true);
  1763. if (state.activeTab !== 'interfaces') navigate('interfaces');
  1764. } else {
  1765. showToast('Creation Failed', data.message || 'Failed to create VLAN', 'error');
  1766. }
  1767. } catch (err) {
  1768. showToast('Error', err.message, 'error');
  1769. } finally {
  1770. btn.disabled = false;
  1771. btn.innerText = 'Create VLAN';
  1772. }
  1773. }
  1774. async function confirmDeleteVlan(name) {
  1775. if (!confirm(`Delete VLAN interface ${name}?`)) return;
  1776. try {
  1777. const res = await fetch(`${API_BASE}/vlans/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1778. if (res.ok) {
  1779. showToast('VLAN Deleted', `Interface ${name} removed`, 'success');
  1780. closeIfaceModal();
  1781. fetchData(true);
  1782. }
  1783. } catch (err) {
  1784. showToast('Error', err.message, 'error');
  1785. }
  1786. }
  1787. function openIfaceModal(name) {
  1788. const iface = (state.interfaces || []).find(i => i.name === name);
  1789. if (!iface) return;
  1790. state.currentModalIface = iface.name;
  1791. document.getElementById('modal-iface-name').innerText = iface.name;
  1792. document.getElementById('modal-iface-badge').innerText = iface.is_vlan ? `VLAN ${iface.vlan_id}` : iface.type;
  1793. document.getElementById('modal-iface-mtu').value = iface.mtu;
  1794. document.getElementById('modal-iface-role').value = iface.role || 'LAN';
  1795. document.getElementById('modal-iface-desc').value = iface.description || '';
  1796. const delBtn = document.getElementById('modal-delete-vlan-btn');
  1797. if (iface.is_vlan) {
  1798. delBtn.classList.remove('hidden');
  1799. } else {
  1800. delBtn.classList.add('hidden');
  1801. }
  1802. renderModalIPs(iface);
  1803. document.getElementById('iface-modal').classList.remove('hidden');
  1804. }
  1805. function renderModalIPs(iface) {
  1806. const container = document.getElementById('modal-ip-list');
  1807. container.innerHTML = '';
  1808. const addrs = [...(iface.ipv4 || []), ...(iface.ipv6 || [])];
  1809. if (addrs.length === 0) {
  1810. container.innerHTML = `<span class="text-slate-500 text-xs font-sans">No IP addresses currently bound</span>`;
  1811. return;
  1812. }
  1813. addrs.forEach(addr => {
  1814. const row = document.createElement('div');
  1815. row.className = 'flex items-center justify-between p-2 rounded bg-slate-900 border border-slate-800';
  1816. row.innerHTML = `
  1817. <span class="text-white">${addr}</span>
  1818. <button onclick="removeInterfaceIP('${addr}')" class="text-[11px] text-rose-400 hover:text-rose-300 font-sans">Remove</button>
  1819. `;
  1820. container.appendChild(row);
  1821. });
  1822. }
  1823. function closeIfaceModal() {
  1824. document.getElementById('iface-modal').classList.add('hidden');
  1825. state.currentModalIface = null;
  1826. }
  1827. async function setIfaceState(name, newState) {
  1828. await toggleInterfaceState(name, newState);
  1829. const updated = (state.interfaces || []).find(i => i.name === name);
  1830. if (updated) openIfaceModal(name);
  1831. }
  1832. async function applyMTU() {
  1833. const mtu = parseInt(document.getElementById('modal-iface-mtu').value, 10);
  1834. try {
  1835. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/mtu`, {
  1836. method: 'POST',
  1837. headers: { 'Content-Type': 'application/json' },
  1838. body: JSON.stringify({ mtu })
  1839. });
  1840. if (res.ok) {
  1841. showToast('MTU Applied', `Set MTU to ${mtu} on ${state.currentModalIface}`, 'success');
  1842. fetchData(false);
  1843. }
  1844. } catch (err) {
  1845. showToast('Error', err.message, 'error');
  1846. }
  1847. }
  1848. async function addInterfaceIP() {
  1849. const ip = document.getElementById('modal-new-ip').value.trim();
  1850. if (!ip) return;
  1851. try {
  1852. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  1853. method: 'POST',
  1854. headers: { 'Content-Type': 'application/json' },
  1855. body: JSON.stringify({ ip })
  1856. });
  1857. if (res.ok) {
  1858. showToast('IP Added', `Bound ${ip} to ${state.currentModalIface}`, 'success');
  1859. document.getElementById('modal-new-ip').value = '';
  1860. await fetchData(false);
  1861. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  1862. if (iface) renderModalIPs(iface);
  1863. } else {
  1864. const err = await res.json();
  1865. showToast('Error', err.error || err.message || 'Failed to add IP address', 'error');
  1866. }
  1867. } catch (err) {
  1868. showToast('Error', err.message, 'error');
  1869. }
  1870. }
  1871. async function removeInterfaceIP(ip) {
  1872. if (!confirm(`Remove IP ${ip}?`)) return;
  1873. try {
  1874. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  1875. method: 'DELETE',
  1876. headers: { 'Content-Type': 'application/json' },
  1877. body: JSON.stringify({ ip })
  1878. });
  1879. if (res.ok) {
  1880. showToast('IP Removed', `Removed ${ip}`, 'success');
  1881. await fetchData(false);
  1882. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  1883. if (iface) renderModalIPs(iface);
  1884. }
  1885. } catch (err) {
  1886. showToast('Error', err.message, 'error');
  1887. }
  1888. }
  1889. async function saveInterfaceMetadata() {
  1890. const role = document.getElementById('modal-iface-role').value;
  1891. const desc = document.getElementById('modal-iface-desc').value.trim();
  1892. try {
  1893. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/metadata`, {
  1894. method: 'POST',
  1895. headers: { 'Content-Type': 'application/json' },
  1896. body: JSON.stringify({ role, description: desc })
  1897. });
  1898. if (res.ok) {
  1899. showToast('Saved', 'Metadata updated', 'success');
  1900. closeIfaceModal();
  1901. fetchData(false);
  1902. }
  1903. } catch (err) {
  1904. showToast('Error', err.message, 'error');
  1905. }
  1906. }
  1907. // ======================== MIKROTIK FIREWALL (/ip firewall) ========================
  1908. state.fwSubTab = 'filter';
  1909. state.routesSubTab = 'routes';
  1910. function renderRuleFlag(disabled, hasComment) {
  1911. let flags = '';
  1912. if (disabled) flags += '<span class="text-rose-400 font-bold" title="Disabled">X</span>';
  1913. if (hasComment) flags += '<span class="text-amber-400 font-bold ml-1" title="Has Comment">C</span>';
  1914. return flags || '<span class="text-slate-600">-</span>';
  1915. }
  1916. function renderActionBadge(action) {
  1917. const act = (action || '').toLowerCase();
  1918. let color = 'bg-slate-800 text-slate-300';
  1919. if (act === 'accept') color = 'bg-emerald-500/20 text-emerald-300 border border-emerald-500/30';
  1920. else if (act === 'drop' || act === 'reject') color = 'bg-rose-500/20 text-rose-300 border border-rose-500/30';
  1921. else if (act === 'masquerade' || act === 'src-nat' || act === 'dst-nat') color = 'bg-amber-500/20 text-amber-300 border border-amber-500/30';
  1922. else if (act.startsWith('mark-')) color = 'bg-purple-500/20 text-purple-300 border border-purple-500/30';
  1923. else if (act === 'log') color = 'bg-cyan-500/20 text-cyan-300 border border-cyan-500/30';
  1924. return `<span class="px-2 py-0.5 rounded text-[10px] font-mono font-semibold ${color}">${action}</span>`;
  1925. }
  1926. function switchFWSubTab(tab) {
  1927. state.fwSubTab = tab;
  1928. const tabs = ['filter', 'nat', 'mangle', 'addrlist', 'connections'];
  1929. tabs.forEach(t => {
  1930. const panel = document.getElementById(`fw-subtab-${t}`);
  1931. const btn = document.getElementById(`fw-subtab-btn-${t}`);
  1932. if (panel) {
  1933. if (t === tab) panel.classList.remove('hidden');
  1934. else panel.classList.add('hidden');
  1935. }
  1936. if (btn) {
  1937. if (t === tab) {
  1938. btn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-emerald-500 text-white transition flex items-center gap-2 whitespace-nowrap';
  1939. } else {
  1940. btn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition flex items-center gap-2 whitespace-nowrap';
  1941. }
  1942. }
  1943. });
  1944. const addBtn = document.getElementById('fw-primary-add-btn');
  1945. if (addBtn) {
  1946. if (tab === 'filter') addBtn.innerHTML = '<span>+ Add Filter Rule</span>';
  1947. else if (tab === 'nat') addBtn.innerHTML = '<span>+ Add NAT Rule</span>';
  1948. else if (tab === 'mangle') addBtn.innerHTML = '<span>+ Add Mangle Rule</span>';
  1949. else if (tab === 'addrlist') addBtn.innerHTML = '<span>+ Add Address List</span>';
  1950. else if (tab === 'connections') addBtn.innerHTML = '<span>Refresh Flows</span>';
  1951. }
  1952. if (tab === 'connections') loadConnections();
  1953. }
  1954. function openCurrentFWModal() {
  1955. if (state.fwSubTab === 'filter') openAddFilterModal();
  1956. else if (state.fwSubTab === 'nat') openAddNATModal();
  1957. else if (state.fwSubTab === 'mangle') openAddMangleModal();
  1958. else if (state.fwSubTab === 'addrlist') openAddAddrListModal();
  1959. else if (state.fwSubTab === 'connections') loadConnections();
  1960. }
  1961. async function loadFirewall(populateDropdowns = true) {
  1962. try {
  1963. const [summaryRes, filterRes, natRes, mangleRes, addrlistRes] = await Promise.all([
  1964. fetch(`${API_BASE}/firewall/summary`),
  1965. fetch(`${API_BASE}/firewall/filter`),
  1966. fetch(`${API_BASE}/firewall/nat`),
  1967. fetch(`${API_BASE}/firewall/mangle`),
  1968. fetch(`${API_BASE}/firewall/address-lists`)
  1969. ]);
  1970. if (summaryRes.ok) state.fwSummary = await summaryRes.json();
  1971. if (filterRes.ok) state.filterRules = await filterRes.json();
  1972. if (natRes.ok) state.natRules = await natRes.json();
  1973. if (mangleRes.ok) state.mangleRules = await mangleRes.json();
  1974. if (addrlistRes.ok) state.addressLists = await addrlistRes.json();
  1975. // Badges
  1976. const bFilter = document.getElementById('fw-badge-filter');
  1977. if (bFilter) bFilter.innerText = (state.filterRules || []).length;
  1978. const bNat = document.getElementById('fw-badge-nat');
  1979. if (bNat) bNat.innerText = (state.natRules || []).length;
  1980. const bMangle = document.getElementById('fw-badge-mangle');
  1981. if (bMangle) bMangle.innerText = (state.mangleRules || []).length;
  1982. const bAddr = document.getElementById('fw-badge-addrlist');
  1983. if (bAddr) bAddr.innerText = (state.addressLists || []).length;
  1984. renderFilterRules();
  1985. renderNATRules();
  1986. renderMangleRules();
  1987. renderAddressLists();
  1988. if (state.fwSubTab === 'connections') {
  1989. loadConnections();
  1990. }
  1991. } catch (err) {
  1992. console.error('Failed to load firewall:', err);
  1993. }
  1994. }
  1995. // ----------------- Filter Rules -----------------
  1996. function renderFilterRules() {
  1997. const chainFilter = document.getElementById('filter-filter-chain')?.value || '';
  1998. const tbody = document.getElementById('filter-table-body');
  1999. const empty = document.getElementById('filter-empty');
  2000. if (!tbody) return;
  2001. tbody.innerHTML = '';
  2002. const rules = (state.filterRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  2003. document.getElementById('filter-count-badge').innerText = `${rules.length} Rules`;
  2004. if (rules.length === 0) {
  2005. empty?.classList.remove('hidden');
  2006. return;
  2007. }
  2008. empty?.classList.add('hidden');
  2009. rules.forEach((r, idx) => {
  2010. const tr = document.createElement('tr');
  2011. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  2012. const ports = [r.src_port ? 's:' + r.src_port : '', r.dst_port ? 'd:' + r.dst_port : ''].filter(Boolean).join(' ');
  2013. const ifaces = [r.in_interface ? 'in:' + r.in_interface : '', r.out_interface ? 'out:' + r.out_interface : ''].filter(Boolean).join(' ');
  2014. tr.innerHTML = `
  2015. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  2016. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  2017. <td class="py-2.5 px-3 font-bold text-white">${r.chain}</td>
  2018. <td class="py-2.5 px-3 text-slate-300">${r.src_address || r.src_address_list ? (r.src_address || `list:${r.src_address_list}`) : '<span class="text-slate-600">0.0.0.0/0</span>'}</td>
  2019. <td class="py-2.5 px-3 text-slate-300">${r.dst_address || r.dst_address_list ? (r.dst_address || `list:${r.dst_address_list}`) : '<span class="text-slate-600">0.0.0.0/0</span>'}</td>
  2020. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}</td>
  2021. <td class="py-2.5 px-3 text-amber-400">${ports || '-'}</td>
  2022. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  2023. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  2024. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  2025. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  2026. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  2027. </td>
  2028. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  2029. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  2030. <button onclick="moveFilterRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  2031. <button onclick="moveFilterRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  2032. <button onclick="toggleFilterRuleState('${r.id}', ${!r.disabled})" class="text-xs ${r.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline">${r.disabled ? 'Enable' : 'Disable'}</button>
  2033. <button onclick="openEditFilterModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2034. <button onclick="deleteFilterRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2035. </td>
  2036. `;
  2037. tbody.appendChild(tr);
  2038. });
  2039. }
  2040. function populateInterfaceSelect(selectId, currentVal = '') {
  2041. const sel = document.getElementById(selectId);
  2042. if (!sel) return;
  2043. sel.innerHTML = '<option value="">(Any Interface)</option>';
  2044. (state.interfaces || []).forEach(i => {
  2045. const opt = document.createElement('option');
  2046. opt.value = i.name;
  2047. opt.innerText = `${i.name} (${i.role || i.type})`;
  2048. if (i.name === currentVal) opt.selected = true;
  2049. sel.appendChild(opt);
  2050. });
  2051. }
  2052. function populateAddressListSelect(selectId, currentVal = '') {
  2053. const sel = document.getElementById(selectId);
  2054. if (!sel) return;
  2055. sel.innerHTML = '<option value="">(None)</option>';
  2056. const set = new Set((state.addressLists || []).map(a => a.name));
  2057. set.forEach(name => {
  2058. const opt = document.createElement('option');
  2059. opt.value = name;
  2060. opt.innerText = name;
  2061. if (name === currentVal) opt.selected = true;
  2062. sel.appendChild(opt);
  2063. });
  2064. }
  2065. function openAddFilterModal() {
  2066. document.getElementById('filter-modal-title').innerText = 'Add Firewall Filter Rule';
  2067. document.getElementById('filter-modal-id').value = '';
  2068. document.getElementById('filter-modal-chain').value = 'forward';
  2069. document.getElementById('filter-modal-action').value = 'accept';
  2070. document.getElementById('filter-modal-proto').value = 'all';
  2071. document.getElementById('filter-modal-src').value = '';
  2072. document.getElementById('filter-modal-dst').value = '';
  2073. document.getElementById('filter-modal-sport').value = '';
  2074. document.getElementById('filter-modal-dport').value = '';
  2075. document.getElementById('filter-modal-connmark').value = '';
  2076. document.getElementById('filter-modal-comment').value = '';
  2077. document.getElementById('filter-modal-disabled').checked = false;
  2078. document.getElementById('filter-modal-cs-established').checked = false;
  2079. document.getElementById('filter-modal-cs-related').checked = false;
  2080. document.getElementById('filter-modal-cs-new').checked = false;
  2081. document.getElementById('filter-modal-cs-invalid').checked = false;
  2082. populateInterfaceSelect('filter-modal-iniface');
  2083. populateInterfaceSelect('filter-modal-outiface');
  2084. populateAddressListSelect('filter-modal-srclist');
  2085. populateAddressListSelect('filter-modal-dstlist');
  2086. toggleFilterActionFields();
  2087. document.getElementById('filter-modal').classList.remove('hidden');
  2088. }
  2089. function openEditFilterModal(id) {
  2090. const r = (state.filterRules || []).find(rule => rule.id === id);
  2091. if (!r) return;
  2092. document.getElementById('filter-modal-title').innerText = `Edit Filter Rule (#${r.order})`;
  2093. document.getElementById('filter-modal-id').value = r.id;
  2094. document.getElementById('filter-modal-chain').value = r.chain || 'forward';
  2095. document.getElementById('filter-modal-action').value = r.action || 'accept';
  2096. document.getElementById('filter-modal-proto').value = r.protocol || 'all';
  2097. document.getElementById('filter-modal-src').value = r.src_address || '';
  2098. document.getElementById('filter-modal-dst').value = r.dst_address || '';
  2099. document.getElementById('filter-modal-sport').value = r.src_port || '';
  2100. document.getElementById('filter-modal-dport').value = r.dst_port || '';
  2101. document.getElementById('filter-modal-connmark').value = r.connection_mark || '';
  2102. document.getElementById('filter-modal-comment').value = r.comment || '';
  2103. document.getElementById('filter-modal-disabled').checked = !!r.disabled;
  2104. const states = r.connection_state || [];
  2105. document.getElementById('filter-modal-cs-established').checked = states.includes('established');
  2106. document.getElementById('filter-modal-cs-related').checked = states.includes('related');
  2107. document.getElementById('filter-modal-cs-new').checked = states.includes('new');
  2108. document.getElementById('filter-modal-cs-invalid').checked = states.includes('invalid');
  2109. populateInterfaceSelect('filter-modal-iniface', r.in_interface);
  2110. populateInterfaceSelect('filter-modal-outiface', r.out_interface);
  2111. populateAddressListSelect('filter-modal-srclist', r.src_address_list);
  2112. populateAddressListSelect('filter-modal-dstlist', r.dst_address_list);
  2113. toggleFilterActionFields();
  2114. document.getElementById('filter-modal').classList.remove('hidden');
  2115. }
  2116. function closeFilterModal() {
  2117. document.getElementById('filter-modal').classList.add('hidden');
  2118. }
  2119. function toggleFilterActionFields() {
  2120. const act = document.getElementById('filter-modal-action').value;
  2121. const rejectBox = document.getElementById('filter-action-reject-box');
  2122. if (rejectBox) {
  2123. if (act === 'reject') rejectBox.classList.remove('hidden');
  2124. else rejectBox.classList.add('hidden');
  2125. }
  2126. }
  2127. async function submitSaveFilterRule(e) {
  2128. e.preventDefault();
  2129. const id = document.getElementById('filter-modal-id').value;
  2130. const chain = document.getElementById('filter-modal-chain').value;
  2131. const action = document.getElementById('filter-modal-action').value;
  2132. const proto = document.getElementById('filter-modal-proto').value;
  2133. const src = document.getElementById('filter-modal-src').value.trim();
  2134. const dst = document.getElementById('filter-modal-dst').value.trim();
  2135. const sport = document.getElementById('filter-modal-sport').value.trim();
  2136. const dport = document.getElementById('filter-modal-dport').value.trim();
  2137. const inIface = document.getElementById('filter-modal-iniface').value;
  2138. const outIface = document.getElementById('filter-modal-outiface').value;
  2139. const connmark = document.getElementById('filter-modal-connmark').value.trim();
  2140. const srclist = document.getElementById('filter-modal-srclist').value;
  2141. const dstlist = document.getElementById('filter-modal-dstlist').value;
  2142. const comment = document.getElementById('filter-modal-comment').value.trim();
  2143. const disabled = document.getElementById('filter-modal-disabled').checked;
  2144. const rejectWith = document.getElementById('filter-modal-rejectwith')?.value || '';
  2145. const states = [];
  2146. if (document.getElementById('filter-modal-cs-established').checked) states.push('established');
  2147. if (document.getElementById('filter-modal-cs-related').checked) states.push('related');
  2148. if (document.getElementById('filter-modal-cs-new').checked) states.push('new');
  2149. if (document.getElementById('filter-modal-cs-invalid').checked) states.push('invalid');
  2150. try {
  2151. const res = await fetch(`${API_BASE}/firewall/filter`, {
  2152. method: 'POST',
  2153. headers: { 'Content-Type': 'application/json' },
  2154. body: JSON.stringify({
  2155. id,
  2156. chain,
  2157. action,
  2158. reject_with: rejectWith,
  2159. protocol: proto,
  2160. src_address: src,
  2161. dst_address: dst,
  2162. src_port: sport,
  2163. dst_port: dport,
  2164. in_interface: inIface,
  2165. out_interface: outIface,
  2166. connection_state: states,
  2167. connection_mark: connmark,
  2168. src_address_list: srclist,
  2169. dst_address_list: dstlist,
  2170. comment,
  2171. disabled
  2172. })
  2173. });
  2174. if (res.ok) {
  2175. showToast('Filter Rule Saved', 'Rule applied successfully to firewall', 'success');
  2176. closeFilterModal();
  2177. loadFirewall(false);
  2178. } else {
  2179. const err = await res.json();
  2180. showToast('Error', err.message, 'error');
  2181. }
  2182. } catch (err) {
  2183. showToast('Error', err.message, 'error');
  2184. }
  2185. }
  2186. async function moveFilterRule(id, dir) {
  2187. try {
  2188. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/move`, {
  2189. method: 'POST',
  2190. headers: { 'Content-Type': 'application/json' },
  2191. body: JSON.stringify({ direction: dir })
  2192. });
  2193. if (res.ok) loadFirewall(false);
  2194. } catch (err) {
  2195. showToast('Error', err.message, 'error');
  2196. }
  2197. }
  2198. async function toggleFilterRuleState(id, disabled) {
  2199. try {
  2200. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/state`, {
  2201. method: 'POST',
  2202. headers: { 'Content-Type': 'application/json' },
  2203. body: JSON.stringify({ disabled })
  2204. });
  2205. if (res.ok) loadFirewall(false);
  2206. } catch (err) {
  2207. showToast('Error', err.message, 'error');
  2208. }
  2209. }
  2210. async function deleteFilterRule(id) {
  2211. if (!confirm('Are you sure you want to delete this filter rule?')) return;
  2212. try {
  2213. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}`, { method: 'DELETE' });
  2214. if (res.ok) {
  2215. showToast('Deleted', 'Filter rule removed', 'success');
  2216. loadFirewall(false);
  2217. }
  2218. } catch (err) {
  2219. showToast('Error', err.message, 'error');
  2220. }
  2221. }
  2222. // ----------------- NAT Rules -----------------
  2223. function renderNATRules() {
  2224. const chainFilter = document.getElementById('nat-filter-chain')?.value || '';
  2225. const tbody = document.getElementById('nat-table-body');
  2226. const empty = document.getElementById('nat-empty');
  2227. if (!tbody) return;
  2228. tbody.innerHTML = '';
  2229. const rules = (state.natRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  2230. document.getElementById('nat-count-badge').innerText = `${rules.length} Rules`;
  2231. if (rules.length === 0) {
  2232. empty?.classList.remove('hidden');
  2233. return;
  2234. }
  2235. empty?.classList.add('hidden');
  2236. rules.forEach((r, idx) => {
  2237. const tr = document.createElement('tr');
  2238. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  2239. const toTarget = [r.to_addresses, r.to_ports].filter(Boolean).join(':');
  2240. const ifaces = [r.out_interface ? 'out:' + r.out_interface : '', r.in_interface ? 'in:' + r.in_interface : ''].filter(Boolean).join(' ');
  2241. tr.innerHTML = `
  2242. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  2243. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  2244. <td class="py-2.5 px-3 font-bold text-amber-400">${r.chain}</td>
  2245. <td class="py-2.5 px-3 text-slate-300">${r.src_address || '<span class="text-slate-600">0.0.0.0/0</span>'}</td>
  2246. <td class="py-2.5 px-3 text-slate-300">${r.dst_address || '<span class="text-slate-600">0.0.0.0/0</span>'}</td>
  2247. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}${r.dst_port ? ':' + r.dst_port : ''}</td>
  2248. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  2249. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  2250. <td class="py-2.5 px-3 font-mono font-bold text-amber-300">${toTarget || '-'}</td>
  2251. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  2252. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  2253. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  2254. </td>
  2255. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  2256. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  2257. <button onclick="moveNATRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  2258. <button onclick="moveNATRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  2259. <button onclick="toggleNATRuleState('${r.id}', ${!r.disabled})" class="text-xs ${r.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline">${r.disabled ? 'Enable' : 'Disable'}</button>
  2260. <button onclick="openEditNATModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2261. <button onclick="deleteNATRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2262. </td>
  2263. `;
  2264. tbody.appendChild(tr);
  2265. });
  2266. }
  2267. function openAddNATModal() {
  2268. document.getElementById('nat-modal-title').innerText = 'Add NAT Rule';
  2269. document.getElementById('nat-modal-id').value = '';
  2270. document.getElementById('nat-modal-chain').value = 'srcnat';
  2271. document.getElementById('nat-modal-action').value = 'masquerade';
  2272. document.getElementById('nat-modal-toaddr').value = '';
  2273. document.getElementById('nat-modal-toport').value = '';
  2274. document.getElementById('nat-modal-proto').value = 'all';
  2275. document.getElementById('nat-modal-src').value = '';
  2276. document.getElementById('nat-modal-dst').value = '';
  2277. document.getElementById('nat-modal-dport').value = '';
  2278. document.getElementById('nat-modal-comment').value = '';
  2279. document.getElementById('nat-modal-disabled').checked = false;
  2280. populateInterfaceSelect('nat-modal-iniface');
  2281. populateInterfaceSelect('nat-modal-outiface');
  2282. toggleNATActionFields();
  2283. document.getElementById('nat-modal').classList.remove('hidden');
  2284. }
  2285. function openEditNATModal(id) {
  2286. const r = (state.natRules || []).find(rule => rule.id === id);
  2287. if (!r) return;
  2288. document.getElementById('nat-modal-title').innerText = `Edit NAT Rule (#${r.order})`;
  2289. document.getElementById('nat-modal-id').value = r.id;
  2290. document.getElementById('nat-modal-chain').value = r.chain || 'srcnat';
  2291. document.getElementById('nat-modal-action').value = r.action || 'masquerade';
  2292. document.getElementById('nat-modal-toaddr').value = r.to_addresses || '';
  2293. document.getElementById('nat-modal-toport').value = r.to_ports || '';
  2294. document.getElementById('nat-modal-proto').value = r.protocol || 'all';
  2295. document.getElementById('nat-modal-src').value = r.src_address || '';
  2296. document.getElementById('nat-modal-dst').value = r.dst_address || '';
  2297. document.getElementById('nat-modal-dport').value = r.dst_port || '';
  2298. document.getElementById('nat-modal-comment').value = r.comment || '';
  2299. document.getElementById('nat-modal-disabled').checked = !!r.disabled;
  2300. populateInterfaceSelect('nat-modal-iniface', r.in_interface);
  2301. populateInterfaceSelect('nat-modal-outiface', r.out_interface);
  2302. toggleNATActionFields();
  2303. document.getElementById('nat-modal').classList.remove('hidden');
  2304. }
  2305. function closeNATModal() {
  2306. document.getElementById('nat-modal').classList.add('hidden');
  2307. }
  2308. function toggleNATChainFields() {
  2309. const ch = document.getElementById('nat-modal-chain').value;
  2310. const actSel = document.getElementById('nat-modal-action');
  2311. if (ch === 'srcnat' && actSel.value === 'dst-nat') {
  2312. actSel.value = 'masquerade';
  2313. } else if (ch === 'dstnat' && actSel.value === 'masquerade') {
  2314. actSel.value = 'dst-nat';
  2315. }
  2316. toggleNATActionFields();
  2317. }
  2318. function toggleNATActionFields() {
  2319. const act = document.getElementById('nat-modal-action').value;
  2320. const toBox = document.getElementById('nat-action-to-box');
  2321. if (toBox) {
  2322. if (act === 'masquerade' || act === 'accept') toBox.classList.add('hidden');
  2323. else toBox.classList.remove('hidden');
  2324. }
  2325. }
  2326. async function submitSaveNATRule(e) {
  2327. e.preventDefault();
  2328. const id = document.getElementById('nat-modal-id').value;
  2329. const chain = document.getElementById('nat-modal-chain').value;
  2330. const action = document.getElementById('nat-modal-action').value;
  2331. const toaddr = document.getElementById('nat-modal-toaddr').value.trim();
  2332. const toport = document.getElementById('nat-modal-toport').value.trim();
  2333. const proto = document.getElementById('nat-modal-proto').value;
  2334. const src = document.getElementById('nat-modal-src').value.trim();
  2335. const dst = document.getElementById('nat-modal-dst').value.trim();
  2336. const dport = document.getElementById('nat-modal-dport').value.trim();
  2337. const inIface = document.getElementById('nat-modal-iniface').value;
  2338. const outIface = document.getElementById('nat-modal-outiface').value;
  2339. const comment = document.getElementById('nat-modal-comment').value.trim();
  2340. const disabled = document.getElementById('nat-modal-disabled').checked;
  2341. try {
  2342. const res = await fetch(`${API_BASE}/firewall/nat`, {
  2343. method: 'POST',
  2344. headers: { 'Content-Type': 'application/json' },
  2345. body: JSON.stringify({
  2346. id,
  2347. chain,
  2348. action,
  2349. to_addresses: toaddr,
  2350. to_ports: toport,
  2351. protocol: proto,
  2352. src_address: src,
  2353. dst_address: dst,
  2354. dst_port: dport,
  2355. in_interface: inIface,
  2356. out_interface: outIface,
  2357. comment,
  2358. disabled
  2359. })
  2360. });
  2361. if (res.ok) {
  2362. showToast('NAT Rule Saved', 'NAT mapping updated', 'success');
  2363. closeNATModal();
  2364. loadFirewall(false);
  2365. }
  2366. } catch (err) {
  2367. showToast('Error', err.message, 'error');
  2368. }
  2369. }
  2370. async function moveNATRule(id, dir) {
  2371. try {
  2372. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/move`, {
  2373. method: 'POST',
  2374. headers: { 'Content-Type': 'application/json' },
  2375. body: JSON.stringify({ direction: dir })
  2376. });
  2377. if (res.ok) loadFirewall(false);
  2378. } catch (err) {
  2379. showToast('Error', err.message, 'error');
  2380. }
  2381. }
  2382. async function toggleNATRuleState(id, disabled) {
  2383. try {
  2384. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/state`, {
  2385. method: 'POST',
  2386. headers: { 'Content-Type': 'application/json' },
  2387. body: JSON.stringify({ disabled })
  2388. });
  2389. if (res.ok) loadFirewall(false);
  2390. } catch (err) {
  2391. showToast('Error', err.message, 'error');
  2392. }
  2393. }
  2394. async function deleteNATRule(id) {
  2395. if (!confirm('Are you sure you want to delete this NAT rule?')) return;
  2396. try {
  2397. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}`, { method: 'DELETE' });
  2398. if (res.ok) {
  2399. showToast('Deleted', 'NAT rule removed', 'success');
  2400. loadFirewall(false);
  2401. }
  2402. } catch (err) {
  2403. showToast('Error', err.message, 'error');
  2404. }
  2405. }
  2406. // ----------------- Mangle Rules -----------------
  2407. function renderMangleRules() {
  2408. const chainFilter = document.getElementById('mangle-filter-chain')?.value || '';
  2409. const tbody = document.getElementById('mangle-table-body');
  2410. const empty = document.getElementById('mangle-empty');
  2411. if (!tbody) return;
  2412. tbody.innerHTML = '';
  2413. const rules = (state.mangleRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  2414. document.getElementById('mangle-count-badge').innerText = `${rules.length} Rules`;
  2415. if (rules.length === 0) {
  2416. empty?.classList.remove('hidden');
  2417. return;
  2418. }
  2419. empty?.classList.add('hidden');
  2420. rules.forEach((r, idx) => {
  2421. const tr = document.createElement('tr');
  2422. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  2423. const markVal = r.new_connection_mark || r.new_routing_mark || r.new_packet_mark || r.new_mss || (r.new_dscp ? 'DSCP:' + r.new_dscp : '');
  2424. tr.innerHTML = `
  2425. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  2426. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  2427. <td class="py-2.5 px-3 font-bold text-purple-400">${r.chain}</td>
  2428. <td class="py-2.5 px-3 text-slate-300">${r.src_address || '<span class="text-slate-600">0.0.0.0/0</span>'}</td>
  2429. <td class="py-2.5 px-3 text-slate-300">${r.dst_address || '<span class="text-slate-600">0.0.0.0/0</span>'}</td>
  2430. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  2431. <td class="py-2.5 px-3 font-mono font-bold text-cyan-300">${markVal || '-'}</td>
  2432. <td class="py-2.5 px-3 text-center">${r.passthrough ? '<span class="text-emerald-400">yes</span>' : '<span class="text-slate-500">no</span>'}</td>
  2433. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  2434. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  2435. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  2436. </td>
  2437. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  2438. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  2439. <button onclick="moveMangleRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  2440. <button onclick="moveMangleRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  2441. <button onclick="toggleMangleRuleState('${r.id}', ${!r.disabled})" class="text-xs ${r.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline">${r.disabled ? 'Enable' : 'Disable'}</button>
  2442. <button onclick="openEditMangleModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2443. <button onclick="deleteMangleRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2444. </td>
  2445. `;
  2446. tbody.appendChild(tr);
  2447. });
  2448. }
  2449. function openAddMangleModal() {
  2450. document.getElementById('mangle-modal-title').innerText = 'Add Mangle Rule';
  2451. document.getElementById('mangle-modal-id').value = '';
  2452. document.getElementById('mangle-modal-chain').value = 'prerouting';
  2453. document.getElementById('mangle-modal-action').value = 'mark-connection';
  2454. document.getElementById('mangle-modal-newmark').value = '';
  2455. document.getElementById('mangle-modal-passthrough').checked = true;
  2456. document.getElementById('mangle-modal-src').value = '';
  2457. document.getElementById('mangle-modal-dst').value = '';
  2458. document.getElementById('mangle-modal-connmark').value = '';
  2459. document.getElementById('mangle-modal-comment').value = '';
  2460. document.getElementById('mangle-modal-disabled').checked = false;
  2461. populateInterfaceSelect('mangle-modal-iniface');
  2462. document.getElementById('mangle-modal').classList.remove('hidden');
  2463. }
  2464. function openEditMangleModal(id) {
  2465. const r = (state.mangleRules || []).find(rule => rule.id === id);
  2466. if (!r) return;
  2467. document.getElementById('mangle-modal-title').innerText = `Edit Mangle Rule (#${r.order})`;
  2468. document.getElementById('mangle-modal-id').value = r.id;
  2469. document.getElementById('mangle-modal-chain').value = r.chain || 'prerouting';
  2470. document.getElementById('mangle-modal-action').value = r.action || 'mark-connection';
  2471. document.getElementById('mangle-modal-newmark').value = r.new_connection_mark || r.new_routing_mark || r.new_packet_mark || r.new_mss || '';
  2472. document.getElementById('mangle-modal-passthrough').checked = r.passthrough ?? true;
  2473. document.getElementById('mangle-modal-src').value = r.src_address || '';
  2474. document.getElementById('mangle-modal-dst').value = r.dst_address || '';
  2475. document.getElementById('mangle-modal-connmark').value = r.connection_mark || '';
  2476. document.getElementById('mangle-modal-comment').value = r.comment || '';
  2477. document.getElementById('mangle-modal-disabled').checked = !!r.disabled;
  2478. populateInterfaceSelect('mangle-modal-iniface', r.in_interface);
  2479. document.getElementById('mangle-modal').classList.remove('hidden');
  2480. }
  2481. function closeMangleModal() {
  2482. document.getElementById('mangle-modal').classList.add('hidden');
  2483. }
  2484. function toggleMangleActionFields() {
  2485. // Handled smoothly by single dynamic input
  2486. }
  2487. async function submitSaveMangleRule(e) {
  2488. e.preventDefault();
  2489. const id = document.getElementById('mangle-modal-id').value;
  2490. const chain = document.getElementById('mangle-modal-chain').value;
  2491. const action = document.getElementById('mangle-modal-action').value;
  2492. const newmark = document.getElementById('mangle-modal-newmark').value.trim();
  2493. const passthrough = document.getElementById('mangle-modal-passthrough').checked;
  2494. const src = document.getElementById('mangle-modal-src').value.trim();
  2495. const dst = document.getElementById('mangle-modal-dst').value.trim();
  2496. const inIface = document.getElementById('mangle-modal-iniface').value;
  2497. const connmark = document.getElementById('mangle-modal-connmark').value.trim();
  2498. const comment = document.getElementById('mangle-modal-comment').value.trim();
  2499. const disabled = document.getElementById('mangle-modal-disabled').checked;
  2500. const payload = {
  2501. id,
  2502. chain,
  2503. action,
  2504. passthrough,
  2505. src_address: src,
  2506. dst_address: dst,
  2507. in_interface: inIface,
  2508. connection_mark: connmark,
  2509. comment,
  2510. disabled
  2511. };
  2512. if (action === 'mark-connection') payload.new_connection_mark = newmark;
  2513. else if (action === 'mark-routing') payload.new_routing_mark = newmark;
  2514. else if (action === 'mark-packet') payload.new_packet_mark = newmark;
  2515. else if (action === 'change-mss') payload.new_mss = newmark || 'clamp-to-pmtu';
  2516. try {
  2517. const res = await fetch(`${API_BASE}/firewall/mangle`, {
  2518. method: 'POST',
  2519. headers: { 'Content-Type': 'application/json' },
  2520. body: JSON.stringify(payload)
  2521. });
  2522. if (res.ok) {
  2523. showToast('Mangle Rule Saved', 'Marking rule applied', 'success');
  2524. closeMangleModal();
  2525. loadFirewall(false);
  2526. }
  2527. } catch (err) {
  2528. showToast('Error', err.message, 'error');
  2529. }
  2530. }
  2531. async function moveMangleRule(id, dir) {
  2532. try {
  2533. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/move`, {
  2534. method: 'POST',
  2535. headers: { 'Content-Type': 'application/json' },
  2536. body: JSON.stringify({ direction: dir })
  2537. });
  2538. if (res.ok) loadFirewall(false);
  2539. } catch (err) {
  2540. showToast('Error', err.message, 'error');
  2541. }
  2542. }
  2543. async function toggleMangleRuleState(id, disabled) {
  2544. try {
  2545. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/state`, {
  2546. method: 'POST',
  2547. headers: { 'Content-Type': 'application/json' },
  2548. body: JSON.stringify({ disabled })
  2549. });
  2550. if (res.ok) loadFirewall(false);
  2551. } catch (err) {
  2552. showToast('Error', err.message, 'error');
  2553. }
  2554. }
  2555. async function deleteMangleRule(id) {
  2556. if (!confirm('Are you sure you want to delete this mangle rule?')) return;
  2557. try {
  2558. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}`, { method: 'DELETE' });
  2559. if (res.ok) {
  2560. showToast('Deleted', 'Mangle rule removed', 'success');
  2561. loadFirewall(false);
  2562. }
  2563. } catch (err) {
  2564. showToast('Error', err.message, 'error');
  2565. }
  2566. }
  2567. // ----------------- Address Lists -----------------
  2568. function renderAddressLists() {
  2569. const filterList = document.getElementById('addrlist-filter-name')?.value || '';
  2570. const tbody = document.getElementById('addrlist-table-body');
  2571. const empty = document.getElementById('addrlist-empty');
  2572. if (!tbody) return;
  2573. tbody.innerHTML = '';
  2574. const entries = (state.addressLists || []).filter(e => !filterList || e.name === filterList);
  2575. document.getElementById('addrlist-count-badge').innerText = `${entries.length} Entries`;
  2576. // Update filter select
  2577. const sel = document.getElementById('addrlist-filter-name');
  2578. if (sel) {
  2579. const cur = sel.value;
  2580. sel.innerHTML = '<option value="">All Lists</option>';
  2581. const set = new Set((state.addressLists || []).map(a => a.name));
  2582. set.forEach(n => {
  2583. const opt = document.createElement('option');
  2584. opt.value = n;
  2585. opt.innerText = n;
  2586. if (n === cur) opt.selected = true;
  2587. sel.appendChild(opt);
  2588. });
  2589. }
  2590. if (entries.length === 0) {
  2591. empty?.classList.remove('hidden');
  2592. return;
  2593. }
  2594. empty?.classList.add('hidden');
  2595. entries.forEach((e, idx) => {
  2596. const tr = document.createElement('tr');
  2597. tr.className = `hover:bg-slate-800/40 transition text-xs ${e.disabled ? 'opacity-50' : ''}`;
  2598. tr.innerHTML = `
  2599. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  2600. <td class="py-2.5 px-3 text-center">${e.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '<span class="text-slate-600">-</span>'}</td>
  2601. <td class="py-2.5 px-3 font-bold text-white font-mono">${e.name}</td>
  2602. <td class="py-2.5 px-3 font-mono font-bold text-emerald-400">${e.address}</td>
  2603. <td class="py-2.5 px-3 text-slate-400 italic">${e.comment || '-'}</td>
  2604. <td class="py-2.5 px-3 text-right font-sans">
  2605. <button onclick="deleteAddrList('${e.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2606. </td>
  2607. `;
  2608. tbody.appendChild(tr);
  2609. });
  2610. }
  2611. function openAddAddrListModal() {
  2612. document.getElementById('addrlist-modal-name').value = '';
  2613. document.getElementById('addrlist-modal-addr').value = '';
  2614. document.getElementById('addrlist-modal-comment').value = '';
  2615. document.getElementById('addrlist-modal').classList.remove('hidden');
  2616. }
  2617. function closeAddrListModal() {
  2618. document.getElementById('addrlist-modal').classList.add('hidden');
  2619. }
  2620. async function submitSaveAddrList(e) {
  2621. e.preventDefault();
  2622. const name = document.getElementById('addrlist-modal-name').value.trim();
  2623. const addr = document.getElementById('addrlist-modal-addr').value.trim();
  2624. const comment = document.getElementById('addrlist-modal-comment').value.trim();
  2625. try {
  2626. const res = await fetch(`${API_BASE}/firewall/address-lists`, {
  2627. method: 'POST',
  2628. headers: { 'Content-Type': 'application/json' },
  2629. body: JSON.stringify({ name, address: addr, comment, disabled: false })
  2630. });
  2631. if (res.ok) {
  2632. showToast('Address List Item Added', `Added ${addr} to ${name}`, 'success');
  2633. closeAddrListModal();
  2634. loadFirewall(false);
  2635. }
  2636. } catch (err) {
  2637. showToast('Error', err.message, 'error');
  2638. }
  2639. }
  2640. async function deleteAddrList(id) {
  2641. try {
  2642. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  2643. if (res.ok) {
  2644. showToast('Deleted', 'Address list item removed', 'info');
  2645. loadFirewall(false);
  2646. }
  2647. } catch (err) {
  2648. showToast('Error', err.message, 'error');
  2649. }
  2650. }
  2651. // ----------------- Active Connections Tracking -----------------
  2652. async function loadConnections() {
  2653. try {
  2654. const res = await fetch(`${API_BASE}/firewall/connections`);
  2655. const data = await res.json();
  2656. state.connections = Array.isArray(data) ? data : [];
  2657. document.getElementById('fw-badge-connections').innerText = state.connections.length;
  2658. document.getElementById('conns-count-badge').innerText = `${state.connections.length} Flows`;
  2659. renderConnections();
  2660. } catch (err) {
  2661. console.error('Failed to load connections:', err);
  2662. }
  2663. }
  2664. function renderConnections() {
  2665. const search = (document.getElementById('conns-search-input')?.value || '').toLowerCase();
  2666. const protoFilter = document.getElementById('conns-filter-proto')?.value || '';
  2667. const tbody = document.getElementById('conns-table-body');
  2668. const empty = document.getElementById('conns-empty');
  2669. if (!tbody) return;
  2670. tbody.innerHTML = '';
  2671. const conns = (state.connections || []).filter(c => {
  2672. if (protoFilter && c.protocol !== protoFilter) return false;
  2673. if (search) {
  2674. const line = `${c.protocol} ${c.src_address} ${c.dst_address} ${c.src_port} ${c.dst_port} ${c.tcp_state} ${c.connection_mark}`.toLowerCase();
  2675. if (!line.includes(search)) return false;
  2676. }
  2677. return true;
  2678. });
  2679. if (conns.length === 0) {
  2680. empty?.classList.remove('hidden');
  2681. return;
  2682. }
  2683. empty?.classList.add('hidden');
  2684. conns.slice(0, 150).forEach(c => {
  2685. const tr = document.createElement('tr');
  2686. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  2687. let stateColor = 'text-slate-400';
  2688. if (c.tcp_state === 'ESTABLISHED') stateColor = 'text-emerald-400 font-bold';
  2689. else if (c.tcp_state === 'TIME_WAIT' || c.tcp_state === 'SYN_SENT') stateColor = 'text-amber-400';
  2690. tr.innerHTML = `
  2691. <td class="py-2.5 px-3 font-bold text-cyan-400">${c.protocol}</td>
  2692. <td class="py-2.5 px-3 font-mono text-white">${c.src_address}:${c.src_port}</td>
  2693. <td class="py-2.5 px-3 font-mono text-white">${c.dst_address}:${c.dst_port}</td>
  2694. <td class="py-2.5 px-3 font-mono text-slate-400">${c.reply_src_address ? c.reply_src_address + ':' + c.reply_src_port : '-'}</td>
  2695. <td class="py-2.5 px-3 font-mono text-slate-400">${c.reply_dst_address ? c.reply_dst_address + ':' + c.reply_dst_port : '-'}</td>
  2696. <td class="py-2.5 px-3 font-mono ${stateColor}">${c.tcp_state}</td>
  2697. <td class="py-2.5 px-3 font-mono text-purple-300">${c.connection_mark || '-'}</td>
  2698. <td class="py-2.5 px-3 text-slate-500">${c.timeout ? c.timeout + 's' : '-'}</td>
  2699. <td class="py-2.5 px-3 text-right font-sans">
  2700. <button onclick="killConnection('${c.protocol}', '${c.src_address}', ${c.src_port}, '${c.dst_address}', ${c.dst_port})" class="text-xs text-rose-400 hover:text-rose-300">Kill</button>
  2701. </td>
  2702. `;
  2703. tbody.appendChild(tr);
  2704. });
  2705. }
  2706. async function killConnection(protocol, src, sport, dst, dport) {
  2707. try {
  2708. const res = await fetch(`${API_BASE}/firewall/connections/kill`, {
  2709. method: 'POST',
  2710. headers: { 'Content-Type': 'application/json' },
  2711. body: JSON.stringify({ protocol, src, sport, dst, dport })
  2712. });
  2713. if (res.ok) {
  2714. showToast('Terminated', `Killed flow ${src}:${sport} -> ${dst}:${dport}`, 'info');
  2715. loadConnections();
  2716. }
  2717. } catch (err) {
  2718. showToast('Error', err.message, 'error');
  2719. }
  2720. }
  2721. async function resetFirewallCounters() {
  2722. if (!confirm('Reset all firewall packet and byte counters to zero?')) return;
  2723. try {
  2724. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  2725. if (res.ok) {
  2726. showToast('Counters Reset', 'All rules counters reset to 0', 'success');
  2727. loadFirewall(false);
  2728. }
  2729. } catch (err) {
  2730. showToast('Error', err.message, 'error');
  2731. }
  2732. }
  2733. // ======================== MIKROTIK ROUTING & POLICY (/ip route) ========================
  2734. function switchRoutesSubTab(tab) {
  2735. state.routesSubTab = tab;
  2736. const tabs = ['routes', 'rules', 'tables'];
  2737. tabs.forEach(t => {
  2738. const panel = document.getElementById(`routes-subtab-${t}`);
  2739. const btn = document.getElementById(`routes-subtab-btn-${t}`);
  2740. if (panel) {
  2741. if (t === tab) panel.classList.remove('hidden');
  2742. else panel.classList.add('hidden');
  2743. }
  2744. if (btn) {
  2745. if (t === tab) {
  2746. btn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-cyan-500 text-white transition flex items-center gap-2';
  2747. } else {
  2748. btn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition flex items-center gap-2';
  2749. }
  2750. }
  2751. });
  2752. }
  2753. async function loadRoutes() {
  2754. try {
  2755. const [routesRes, rulesRes, tablesRes] = await Promise.all([
  2756. fetch(`${API_BASE}/routes`),
  2757. fetch(`${API_BASE}/routing/rules`),
  2758. fetch(`${API_BASE}/routing/tables`)
  2759. ]);
  2760. if (routesRes.ok) state.routes = await routesRes.json();
  2761. if (rulesRes.ok) state.policyRules = await rulesRes.json();
  2762. if (tablesRes.ok) state.routingTables = await tablesRes.json();
  2763. const bRoutes = document.getElementById('routes-badge-routes');
  2764. if (bRoutes) bRoutes.innerText = (state.routes || []).length;
  2765. const bRules = document.getElementById('routes-badge-rules');
  2766. if (bRules) bRules.innerText = (state.policyRules || []).length;
  2767. const bTables = document.getElementById('routes-badge-tables');
  2768. if (bTables) bTables.innerText = (state.routingTables || []).length;
  2769. const bRoutesCount = document.getElementById('badge-routes-count');
  2770. if (bRoutesCount) bRoutesCount.innerText = (state.routes || []).length;
  2771. renderRoutesList();
  2772. renderPolicyRules();
  2773. renderRoutingTables();
  2774. } catch (err) {
  2775. console.error('Failed to load routing:', err);
  2776. }
  2777. }
  2778. function renderRoutesList() {
  2779. const tableFilter = document.getElementById('routes-filter-table')?.value || '';
  2780. const tbody = document.getElementById('routes-table-body');
  2781. const empty = document.getElementById('routes-empty');
  2782. if (!tbody) return;
  2783. tbody.innerHTML = '';
  2784. // Update table filter select
  2785. const sel = document.getElementById('routes-filter-table');
  2786. if (sel) {
  2787. const cur = sel.value;
  2788. sel.innerHTML = '<option value="">All Tables</option>';
  2789. (state.routingTables || []).forEach(t => {
  2790. const opt = document.createElement('option');
  2791. opt.value = t.name;
  2792. opt.innerText = t.name;
  2793. if (t.name === cur) opt.selected = true;
  2794. sel.appendChild(opt);
  2795. });
  2796. }
  2797. const routes = (state.routes || []).filter(r => !tableFilter || r.routing_table === tableFilter);
  2798. document.getElementById('routes-count-badge').innerText = `${routes.length} Routes`;
  2799. if (routes.length === 0) {
  2800. empty?.classList.remove('hidden');
  2801. return;
  2802. }
  2803. empty?.classList.add('hidden');
  2804. routes.forEach(r => {
  2805. const tr = document.createElement('tr');
  2806. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${r.disabled ? 'opacity-50' : ''}`;
  2807. tr.setAttribute('ondblclick', `openEditRouteModal('${r.id}')`);
  2808. // MikroTik Flags string: D=Dynamic, A=Active, C=Connect, S=Static, X=Disabled
  2809. let flags = '';
  2810. if (r.dynamic) flags += 'D';
  2811. if (r.active) flags += 'A';
  2812. if (r.connect) flags += 'C';
  2813. if (r.static) flags += 'S';
  2814. if (r.disabled) flags += 'X';
  2815. const isDefault = r.dst_address === 'default' || r.dst_address === '0.0.0.0/0';
  2816. tr.innerHTML = `
  2817. <td class="py-2.5 px-3 text-center">
  2818. <span class="px-1.5 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 ${r.active ? 'text-cyan-400 border border-cyan-800/40' : 'text-slate-500'}">
  2819. ${flags || '-'}
  2820. </span>
  2821. </td>
  2822. <td class="py-2.5 px-3 font-bold ${isDefault ? 'text-cyan-300' : 'text-white'}">${r.dst_address}</td>
  2823. <td class="py-2.5 px-3 text-slate-300 font-mono">${r.gateway || '<span class="text-slate-600 font-sans">Direct link</span>'}</td>
  2824. <td class="py-2.5 px-3 text-slate-400 font-mono">${(r.distance !== undefined && r.distance !== null) ? r.distance : 0}</td>
  2825. <td class="py-2.5 px-3 font-mono font-semibold text-purple-300">${r.routing_table || 'main'}</td>
  2826. <td class="py-2.5 px-3 text-emerald-400 font-mono">${r.interface || '-'}</td>
  2827. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]">${r.comment || '-'}</td>
  2828. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  2829. ${r.static ? `
  2830. <button onclick="toggleRouteState('${r.id}', ${!r.disabled})" class="text-xs ${r.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline">${r.disabled ? 'Enable' : 'Disable'}</button>
  2831. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  2832. <button onclick="deleteRoute('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2833. ` : `
  2834. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">View</button>
  2835. `}
  2836. </td>
  2837. `;
  2838. tbody.appendChild(tr);
  2839. });
  2840. }
  2841. function openAddRouteModal() {
  2842. document.getElementById('route-modal-title').innerText = 'Add Static Route';
  2843. document.getElementById('route-modal-id').value = '';
  2844. document.getElementById('route-modal-old-dst').value = '';
  2845. document.getElementById('route-modal-old-gw').value = '';
  2846. document.getElementById('route-modal-old-distance').value = '';
  2847. document.getElementById('route-modal-old-table').value = '';
  2848. document.getElementById('route-modal-old-iface').value = '';
  2849. const dstInput = document.getElementById('route-modal-dst');
  2850. const gwInput = document.getElementById('route-modal-gw');
  2851. const distInput = document.getElementById('route-modal-distance');
  2852. const ifaceSelect = document.getElementById('route-modal-iface');
  2853. const tableSelect = document.getElementById('route-modal-table');
  2854. const commentInput = document.getElementById('route-modal-comment');
  2855. const disCheck = document.getElementById('route-modal-disabled');
  2856. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  2857. dstInput.disabled = false;
  2858. dstInput.value = '0.0.0.0/0';
  2859. gwInput.disabled = false;
  2860. gwInput.value = '';
  2861. distInput.disabled = false;
  2862. distInput.value = '1';
  2863. ifaceSelect.disabled = false;
  2864. tableSelect.disabled = false;
  2865. commentInput.disabled = false;
  2866. commentInput.value = '';
  2867. disCheck.disabled = false;
  2868. disCheck.checked = false;
  2869. if (saveBtn) saveBtn.classList.remove('hidden');
  2870. populateInterfaceSelect('route-modal-iface');
  2871. // Populate tables
  2872. tableSelect.innerHTML = '';
  2873. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  2874. const opt = document.createElement('option');
  2875. opt.value = t.name;
  2876. opt.innerText = t.name;
  2877. if (t.name === 'main') opt.selected = true;
  2878. tableSelect.appendChild(opt);
  2879. });
  2880. document.getElementById('route-modal').classList.remove('hidden');
  2881. }
  2882. function openEditRouteModal(id) {
  2883. const r = (state.routes || []).find(route => route.id === id);
  2884. if (!r) return;
  2885. const isStatic = !!r.static;
  2886. document.getElementById('route-modal-title').innerText = isStatic
  2887. ? `Edit Route: ${r.dst_address}`
  2888. : `Route Properties (Read Only): ${r.dst_address}`;
  2889. document.getElementById('route-modal-id').value = r.id;
  2890. document.getElementById('route-modal-old-dst').value = r.dst_address || '';
  2891. document.getElementById('route-modal-old-gw').value = r.gateway || '';
  2892. document.getElementById('route-modal-old-distance').value = (r.distance !== undefined && r.distance !== null) ? r.distance : '';
  2893. document.getElementById('route-modal-old-table').value = r.routing_table || 'main';
  2894. document.getElementById('route-modal-old-iface').value = r.interface || '';
  2895. const dstInput = document.getElementById('route-modal-dst');
  2896. const gwInput = document.getElementById('route-modal-gw');
  2897. const distInput = document.getElementById('route-modal-distance');
  2898. const ifaceSelect = document.getElementById('route-modal-iface');
  2899. const tableSelect = document.getElementById('route-modal-table');
  2900. const commentInput = document.getElementById('route-modal-comment');
  2901. const disCheck = document.getElementById('route-modal-disabled');
  2902. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  2903. dstInput.value = r.dst_address;
  2904. gwInput.value = r.gateway || '';
  2905. distInput.value = (r.distance !== undefined && r.distance !== null) ? r.distance : 1;
  2906. commentInput.value = r.comment || '';
  2907. disCheck.checked = !!r.disabled;
  2908. dstInput.disabled = !isStatic;
  2909. gwInput.disabled = !isStatic;
  2910. distInput.disabled = !isStatic;
  2911. ifaceSelect.disabled = !isStatic;
  2912. tableSelect.disabled = !isStatic;
  2913. commentInput.disabled = !isStatic;
  2914. disCheck.disabled = !isStatic;
  2915. if (saveBtn) {
  2916. if (isStatic) {
  2917. saveBtn.classList.remove('hidden');
  2918. } else {
  2919. saveBtn.classList.add('hidden');
  2920. }
  2921. }
  2922. populateInterfaceSelect('route-modal-iface', r.interface);
  2923. tableSelect.innerHTML = '';
  2924. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  2925. const opt = document.createElement('option');
  2926. opt.value = t.name;
  2927. opt.innerText = t.name;
  2928. if (t.name === (r.routing_table || 'main')) opt.selected = true;
  2929. tableSelect.appendChild(opt);
  2930. });
  2931. document.getElementById('route-modal').classList.remove('hidden');
  2932. }
  2933. function closeRouteModal() {
  2934. document.getElementById('route-modal').classList.add('hidden');
  2935. }
  2936. async function submitSaveRoute(e) {
  2937. e.preventDefault();
  2938. const id = document.getElementById('route-modal-id').value;
  2939. const oldDst = document.getElementById('route-modal-old-dst')?.value || '';
  2940. const oldGw = document.getElementById('route-modal-old-gw')?.value || '';
  2941. const oldDistStr = document.getElementById('route-modal-old-distance')?.value;
  2942. const oldTable = document.getElementById('route-modal-old-table')?.value || '';
  2943. const oldIface = document.getElementById('route-modal-old-iface')?.value || '';
  2944. const dst = document.getElementById('route-modal-dst').value.trim();
  2945. const gw = document.getElementById('route-modal-gw').value.trim();
  2946. const table = document.getElementById('route-modal-table').value;
  2947. const distance = parseInt(document.getElementById('route-modal-distance').value, 10) || 0;
  2948. const iface = document.getElementById('route-modal-iface').value;
  2949. const comment = document.getElementById('route-modal-comment').value.trim();
  2950. const disabled = document.getElementById('route-modal-disabled').checked;
  2951. if (!dst) {
  2952. showToast('Error', 'Destination address is required', 'error');
  2953. return;
  2954. }
  2955. if (!gw && !iface) {
  2956. showToast('Error', 'Either Gateway IP or Interface must be specified', 'error');
  2957. return;
  2958. }
  2959. const payload = {
  2960. id,
  2961. old_dst_address: oldDst,
  2962. old_gateway: oldGw,
  2963. old_routing_table: oldTable,
  2964. old_interface: oldIface,
  2965. dst_address: dst,
  2966. gateway: gw || iface,
  2967. routing_table: table,
  2968. distance,
  2969. interface: iface,
  2970. comment,
  2971. disabled
  2972. };
  2973. if (oldDistStr !== undefined && oldDistStr !== '') {
  2974. payload.old_distance = parseInt(oldDistStr, 10);
  2975. }
  2976. try {
  2977. const res = await fetch(`${API_BASE}/routes`, {
  2978. method: 'POST',
  2979. headers: { 'Content-Type': 'application/json' },
  2980. body: JSON.stringify(payload)
  2981. });
  2982. if (res.ok) {
  2983. showToast('Route Saved', `Route to ${dst} installed`, 'success');
  2984. closeRouteModal();
  2985. loadRoutes();
  2986. } else {
  2987. const err = await res.json();
  2988. showToast('Error', err.message || 'Failed to save route', 'error');
  2989. }
  2990. } catch (err) {
  2991. showToast('Error', err.message, 'error');
  2992. }
  2993. }
  2994. async function toggleRouteState(id, disabled) {
  2995. try {
  2996. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}/state`, {
  2997. method: 'POST',
  2998. headers: { 'Content-Type': 'application/json' },
  2999. body: JSON.stringify({ disabled })
  3000. });
  3001. if (res.ok) loadRoutes();
  3002. } catch (err) {
  3003. showToast('Error', err.message, 'error');
  3004. }
  3005. }
  3006. async function deleteRoute(id) {
  3007. if (!confirm('Are you sure you want to delete this route?')) return;
  3008. try {
  3009. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}`, { method: 'DELETE' });
  3010. if (res.ok) {
  3011. showToast('Deleted', 'Route removed', 'success');
  3012. loadRoutes();
  3013. }
  3014. } catch (err) {
  3015. showToast('Error', err.message, 'error');
  3016. }
  3017. }
  3018. // ----------------- Policy Rules (/ip route rule) -----------------
  3019. function renderPolicyRules() {
  3020. const tbody = document.getElementById('rules-table-body');
  3021. const empty = document.getElementById('rules-empty');
  3022. if (!tbody) return;
  3023. tbody.innerHTML = '';
  3024. const rules = state.policyRules || [];
  3025. document.getElementById('rules-count-badge').innerText = `${rules.length} Rules`;
  3026. if (rules.length === 0) {
  3027. empty?.classList.remove('hidden');
  3028. return;
  3029. }
  3030. empty?.classList.add('hidden');
  3031. rules.forEach(pr => {
  3032. const tr = document.createElement('tr');
  3033. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  3034. tr.innerHTML = `
  3035. <td class="py-2.5 px-3 font-mono text-cyan-400 font-bold">${pr.priority}</td>
  3036. <td class="py-2.5 px-3 font-mono text-white">${pr.src_address || '<span class="text-slate-600">all</span>'}</td>
  3037. <td class="py-2.5 px-3 font-mono text-white">${pr.dst_address || '<span class="text-slate-600">all</span>'}</td>
  3038. <td class="py-2.5 px-3 font-mono font-bold text-purple-300">${pr.routing_mark || '<span class="text-slate-600">-</span>'}</td>
  3039. <td class="py-2.5 px-3 font-mono font-bold text-amber-300">${pr.table}</td>
  3040. <td class="py-2.5 px-3 font-mono text-slate-300">${pr.action}</td>
  3041. <td class="py-2.5 px-3 text-right font-sans">
  3042. ${pr.priority < 32766 && pr.priority > 0 ? `
  3043. <button onclick="deletePolicyRule('${pr.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  3044. ` : `<span class="text-slate-600 text-[10px]">Default</span>`}
  3045. </td>
  3046. `;
  3047. tbody.appendChild(tr);
  3048. });
  3049. }
  3050. function openAddPolicyRuleModal() {
  3051. document.getElementById('prule-modal-pref').value = (state.policyRules || []).length * 10 + 1000;
  3052. document.getElementById('prule-modal-mark').value = '';
  3053. document.getElementById('prule-modal-src').value = '';
  3054. document.getElementById('prule-modal-dst').value = '';
  3055. const sel = document.getElementById('prule-modal-table');
  3056. sel.innerHTML = '';
  3057. (state.routingTables || []).forEach(t => {
  3058. const opt = document.createElement('option');
  3059. opt.value = t.name;
  3060. opt.innerText = t.name;
  3061. sel.appendChild(opt);
  3062. });
  3063. document.getElementById('prule-modal').classList.remove('hidden');
  3064. }
  3065. function closePolicyRuleModal() {
  3066. document.getElementById('prule-modal').classList.add('hidden');
  3067. }
  3068. async function submitSavePolicyRule(e) {
  3069. e.preventDefault();
  3070. const pref = parseInt(document.getElementById('prule-modal-pref').value, 10) || 1000;
  3071. const mark = document.getElementById('prule-modal-mark').value.trim();
  3072. const src = document.getElementById('prule-modal-src').value.trim();
  3073. const dst = document.getElementById('prule-modal-dst').value.trim();
  3074. const table = document.getElementById('prule-modal-table').value;
  3075. const action = document.getElementById('prule-modal-action').value;
  3076. try {
  3077. const res = await fetch(`${API_BASE}/routing/rules`, {
  3078. method: 'POST',
  3079. headers: { 'Content-Type': 'application/json' },
  3080. body: JSON.stringify({ priority: pref, routing_mark: mark, src_address: src, dst_address: dst, table, action })
  3081. });
  3082. if (res.ok) {
  3083. showToast('Rule Added', `Policy rule installed for table ${table}`, 'success');
  3084. closePolicyRuleModal();
  3085. loadRoutes();
  3086. } else {
  3087. const err = await res.json();
  3088. showToast('Error', err.message, 'error');
  3089. }
  3090. } catch (err) {
  3091. showToast('Error', err.message, 'error');
  3092. }
  3093. }
  3094. async function deletePolicyRule(id) {
  3095. if (!confirm('Are you sure you want to remove this policy rule?')) return;
  3096. try {
  3097. const res = await fetch(`${API_BASE}/routing/rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  3098. if (res.ok) {
  3099. showToast('Rule Removed', 'Policy rule deleted', 'success');
  3100. loadRoutes();
  3101. }
  3102. } catch (err) {
  3103. showToast('Error', err.message, 'error');
  3104. }
  3105. }
  3106. // ----------------- Routing Tables -----------------
  3107. function renderRoutingTables() {
  3108. const tbody = document.getElementById('tables-table-body');
  3109. if (!tbody) return;
  3110. tbody.innerHTML = '';
  3111. (state.routingTables || []).forEach(t => {
  3112. const tr = document.createElement('tr');
  3113. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  3114. tr.innerHTML = `
  3115. <td class="py-2.5 px-3 text-cyan-400 font-bold">${t.table_id}</td>
  3116. <td class="py-2.5 px-3 font-bold text-white">${t.name}</td>
  3117. <td class="py-2.5 px-3 text-slate-400 italic">${t.comment || '-'}</td>
  3118. `;
  3119. tbody.appendChild(tr);
  3120. });
  3121. }
  3122. function openAddTableModal() {
  3123. document.getElementById('table-modal-name').value = '';
  3124. document.getElementById('table-modal-id').value = '';
  3125. document.getElementById('table-modal-comment').value = '';
  3126. document.getElementById('table-modal').classList.remove('hidden');
  3127. }
  3128. function closeTableModal() {
  3129. document.getElementById('table-modal').classList.add('hidden');
  3130. }
  3131. async function submitSaveTable(e) {
  3132. e.preventDefault();
  3133. const name = document.getElementById('table-modal-name').value.trim();
  3134. const id = parseInt(document.getElementById('table-modal-id').value, 10) || 0;
  3135. const comment = document.getElementById('table-modal-comment').value.trim();
  3136. try {
  3137. const res = await fetch(`${API_BASE}/routing/tables`, {
  3138. method: 'POST',
  3139. headers: { 'Content-Type': 'application/json' },
  3140. body: JSON.stringify({ name, table_id: id, comment })
  3141. });
  3142. if (res.ok) {
  3143. showToast('Table Created', `Routing table ${name} registered`, 'success');
  3144. closeTableModal();
  3145. loadRoutes();
  3146. } else {
  3147. const err = await res.json();
  3148. showToast('Error', err.message, 'error');
  3149. }
  3150. } catch (err) {
  3151. showToast('Error', err.message, 'error');
  3152. }
  3153. }
  3154. async function loadDebianConfig() {
  3155. const view = document.getElementById('debian-config-view');
  3156. view.innerText = 'Generating live configuration...';
  3157. try {
  3158. const res = await fetch(`${API_BASE}/debian/config`);
  3159. const data = await res.json();
  3160. view.innerText = data.content || '# Empty config';
  3161. } catch (err) {
  3162. view.innerText = 'Failed to generate Debian network config.';
  3163. }
  3164. }
  3165. async function saveDebianConfig() {
  3166. try {
  3167. const res = await fetch(`${API_BASE}/debian/apply`, { method: 'POST' });
  3168. const data = await res.json();
  3169. if (res.ok) {
  3170. showToast('Configuration Saved', data.message || 'Saved to /etc/network/interfaces.d/vlans.cfg', 'success');
  3171. loadDebianConfig();
  3172. }
  3173. } catch (err) {
  3174. showToast('Error', err.message, 'error');
  3175. }
  3176. }
  3177. function showToast(title, message, type = 'info') {
  3178. const container = document.getElementById('toast-container');
  3179. const toast = document.createElement('div');
  3180. const borderColors = {
  3181. success: 'border-emerald-500/40 bg-slate-900/95 text-emerald-400',
  3182. error: 'border-rose-500/40 bg-slate-900/95 text-rose-400',
  3183. info: 'border-cyan-500/40 bg-slate-900/95 text-cyan-400'
  3184. };
  3185. toast.className = `pointer-events-auto border rounded-xl p-4 shadow-2xl backdrop-blur-md flex items-start space-x-3 w-80 transform transition-all duration-300 translate-y-2 opacity-0 ${borderColors[type] || borderColors.info}`;
  3186. toast.innerHTML = `
  3187. <div class="flex-1">
  3188. <div class="font-bold text-xs text-white">${title}</div>
  3189. <div class="text-[11px] text-slate-300 mt-0.5 leading-relaxed font-sans">${message}</div>
  3190. </div>
  3191. `;
  3192. container.appendChild(toast);
  3193. requestAnimationFrame(() => toast.classList.remove('translate-y-2', 'opacity-0'));
  3194. setTimeout(() => {
  3195. toast.classList.add('opacity-0', 'translate-y-2');
  3196. setTimeout(() => toast.remove(), 300);
  3197. }, 4000);
  3198. }
  3199. function formatTraffic(bytesPerSec) {
  3200. if (bytesPerSec < 1024) return `${Math.round(bytesPerSec)} B/s`;
  3201. const kb = bytesPerSec / 1024;
  3202. if (kb < 1024) return `${kb.toFixed(1)} KB/s`;
  3203. const mb = kb / 1024;
  3204. return `${mb.toFixed(2)} MB/s`;
  3205. }
  3206. function toggleSidebar() {
  3207. const sb = document.getElementById('sidebar');
  3208. sb.classList.toggle('-translate-x-full');
  3209. }
  3210. // ======================== EoIP (Ethernet over IP) ========================
  3211. async function loadEoIP(populate = true) {
  3212. try {
  3213. const res = await fetch(`${API_BASE}/vpn/eoip`);
  3214. const data = await res.json();
  3215. state.eoipTunnels = Array.isArray(data) ? data : [];
  3216. const badge = document.getElementById('eoip-count-badge');
  3217. if (badge) badge.innerText = `${state.eoipTunnels.length} Tunnels`;
  3218. const sideBadge = document.getElementById('badge-eoip-count');
  3219. if (sideBadge) sideBadge.innerText = state.eoipTunnels.length;
  3220. renderEoIPTunnels();
  3221. } catch (err) {
  3222. console.error('Failed to load EoIP:', err);
  3223. }
  3224. }
  3225. function renderEoIPTunnels() {
  3226. const tbody = document.getElementById('eoip-table-body');
  3227. const empty = document.getElementById('eoip-empty');
  3228. if (!tbody) return;
  3229. tbody.innerHTML = '';
  3230. const tunnels = state.eoipTunnels || [];
  3231. if (tunnels.length === 0) {
  3232. empty?.classList.remove('hidden');
  3233. return;
  3234. }
  3235. empty?.classList.add('hidden');
  3236. tunnels.forEach(t => {
  3237. const tr = document.createElement('tr');
  3238. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  3239. tr.innerHTML = `
  3240. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.running, t.disabled)}</td>
  3241. <td class="py-2.5 px-3 font-bold text-white font-mono">${t.name}</td>
  3242. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${t.tunnel_id}</td>
  3243. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${t.ip_address || '<span class="text-slate-500 font-normal">Unassigned</span>'}</td>
  3244. <td class="py-2.5 px-3 text-cyan-300 font-mono">${t.remote_address}</td>
  3245. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.local_address || '(any)'}</td>
  3246. <td class="py-2.5 px-3 text-slate-300 font-mono text-[11px]">${t.mac_address || '-'}</td>
  3247. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.mtu || 1500}</td>
  3248. <td class="py-2.5 px-3 font-mono text-[11px]">
  3249. <span class="text-emerald-400">↓ ${t.rx_human || '0 B'}</span>
  3250. <span class="text-cyan-400 ml-1">↑ ${t.tx_human || '0 B'}</span>
  3251. </td>
  3252. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${t.comment || ''}">${t.comment || '-'}</td>
  3253. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  3254. <button onclick="toggleEoIPState('${t.id}', ${!t.disabled})" class="text-xs ${t.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline">${t.disabled ? 'Enable' : 'Disable'}</button>
  3255. <button onclick="openEditEoIPModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  3256. <button onclick="deleteEoIP('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  3257. </td>
  3258. `;
  3259. tbody.appendChild(tr);
  3260. });
  3261. }
  3262. function openAddEoIPModal() {
  3263. document.getElementById('eoip-modal-title').innerText = 'Add EoIP Tunnel';
  3264. document.getElementById('eoip-modal-id').value = '';
  3265. document.getElementById('eoip-modal-name').value = `eoip-tunnel${(state.eoipTunnels || []).length + 1}`;
  3266. document.getElementById('eoip-modal-tunnelid').value = (state.eoipTunnels || []).length + 10;
  3267. document.getElementById('eoip-modal-remote').value = '';
  3268. document.getElementById('eoip-modal-ip').value = '';
  3269. document.getElementById('eoip-modal-local').value = '';
  3270. document.getElementById('eoip-modal-mac').value = '';
  3271. document.getElementById('eoip-modal-mtu').value = '1500';
  3272. document.getElementById('eoip-modal-comment').value = '';
  3273. document.getElementById('eoip-modal-clampmss').checked = true;
  3274. document.getElementById('eoip-modal-disabled').checked = false;
  3275. document.getElementById('eoip-modal').classList.remove('hidden');
  3276. }
  3277. function openEditEoIPModal(id) {
  3278. const t = (state.eoipTunnels || []).find(tun => tun.id === id);
  3279. if (!t) return;
  3280. document.getElementById('eoip-modal-title').innerText = `Edit EoIP Tunnel (${t.name})`;
  3281. document.getElementById('eoip-modal-id').value = t.id;
  3282. document.getElementById('eoip-modal-name').value = t.name;
  3283. document.getElementById('eoip-modal-tunnelid').value = t.tunnel_id;
  3284. document.getElementById('eoip-modal-remote').value = t.remote_address;
  3285. document.getElementById('eoip-modal-ip').value = t.ip_address || '';
  3286. document.getElementById('eoip-modal-local').value = t.local_address || '';
  3287. document.getElementById('eoip-modal-mac').value = t.mac_address || '';
  3288. document.getElementById('eoip-modal-mtu').value = t.mtu || 1500;
  3289. document.getElementById('eoip-modal-comment').value = t.comment || '';
  3290. document.getElementById('eoip-modal-clampmss').checked = !!t.clamp_mss;
  3291. document.getElementById('eoip-modal-disabled').checked = !!t.disabled;
  3292. document.getElementById('eoip-modal').classList.remove('hidden');
  3293. }
  3294. function closeEoIPModal() {
  3295. document.getElementById('eoip-modal').classList.add('hidden');
  3296. }
  3297. async function submitSaveEoIP(e) {
  3298. e.preventDefault();
  3299. const id = document.getElementById('eoip-modal-id').value;
  3300. const name = document.getElementById('eoip-modal-name').value.trim();
  3301. const tunnelId = parseInt(document.getElementById('eoip-modal-tunnelid').value);
  3302. const remote = document.getElementById('eoip-modal-remote').value.trim();
  3303. const ipAddress = document.getElementById('eoip-modal-ip').value.trim();
  3304. const local = document.getElementById('eoip-modal-local').value.trim();
  3305. const mac = document.getElementById('eoip-modal-mac').value.trim();
  3306. const mtu = parseInt(document.getElementById('eoip-modal-mtu').value) || 1500;
  3307. const comment = document.getElementById('eoip-modal-comment').value.trim();
  3308. const clampMss = document.getElementById('eoip-modal-clampmss').checked;
  3309. const disabled = document.getElementById('eoip-modal-disabled').checked;
  3310. try {
  3311. const res = await fetch(`${API_BASE}/vpn/eoip`, {
  3312. method: 'POST',
  3313. headers: { 'Content-Type': 'application/json' },
  3314. body: JSON.stringify({
  3315. id,
  3316. name,
  3317. tunnel_id: tunnelId,
  3318. remote_address: remote,
  3319. ip_address: ipAddress,
  3320. local_address: local,
  3321. mac_address: mac,
  3322. mtu,
  3323. clamp_mss: clampMss,
  3324. comment,
  3325. disabled
  3326. })
  3327. });
  3328. if (res.ok) {
  3329. showToast('EoIP Saved', `Tunnel ${name} configured successfully`, 'success');
  3330. closeEoIPModal();
  3331. loadEoIP(false);
  3332. fetchData(false);
  3333. } else {
  3334. const err = await res.json();
  3335. showToast('Error', err.message, 'error');
  3336. }
  3337. } catch (err) {
  3338. showToast('Error', err.message, 'error');
  3339. }
  3340. }
  3341. async function toggleEoIPState(id, disabled) {
  3342. try {
  3343. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}/state`, {
  3344. method: 'POST',
  3345. headers: { 'Content-Type': 'application/json' },
  3346. body: JSON.stringify({ disabled })
  3347. });
  3348. if (res.ok) {
  3349. showToast(disabled ? 'Disabled' : 'Enabled', 'EoIP tunnel state updated', 'info');
  3350. loadEoIP(false);
  3351. fetchData(false);
  3352. }
  3353. } catch (err) {
  3354. showToast('Error', err.message, 'error');
  3355. }
  3356. }
  3357. async function deleteEoIP(id) {
  3358. if (!confirm('Are you sure you want to delete this EoIP tunnel?')) return;
  3359. try {
  3360. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}`, { method: 'DELETE' });
  3361. if (res.ok) {
  3362. showToast('Deleted', 'EoIP tunnel removed', 'success');
  3363. loadEoIP(false);
  3364. fetchData(false);
  3365. }
  3366. } catch (err) {
  3367. showToast('Error', err.message, 'error');
  3368. }
  3369. }
  3370. // ======================== PPP Central Hub & Servers ========================
  3371. function switchPPPSubTab(tab) {
  3372. state.pppSubTab = tab;
  3373. const tabs = ['secrets', 'profiles', 'pppoe', 'pptp', 'l2tp', 'active'];
  3374. tabs.forEach(t => {
  3375. const panel = document.getElementById(`ppp-subtab-${t}`);
  3376. const btn = document.getElementById(`ppp-subtab-btn-${t}`);
  3377. if (panel) {
  3378. if (t === tab) panel.classList.remove('hidden');
  3379. else panel.classList.add('hidden');
  3380. }
  3381. if (btn) {
  3382. if (t === tab) {
  3383. btn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-violet-500 text-white transition flex items-center gap-2 whitespace-nowrap';
  3384. } else {
  3385. btn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition flex items-center gap-2 whitespace-nowrap';
  3386. }
  3387. }
  3388. });
  3389. const addBtn = document.getElementById('ppp-primary-add-btn');
  3390. if (addBtn) {
  3391. if (tab === 'secrets') addBtn.innerHTML = '<span>+ Add User (Secret)</span>';
  3392. else if (tab === 'profiles') addBtn.innerHTML = '<span>+ Add Profile</span>';
  3393. else if (tab === 'active') addBtn.innerHTML = '<span>Refresh Sessions</span>';
  3394. else addBtn.innerHTML = '<span>Save Config</span>';
  3395. }
  3396. if (tab === 'active') loadPPPSessions();
  3397. }
  3398. function openCurrentPPPModal() {
  3399. if (state.pppSubTab === 'secrets') openAddPPPSecretModal();
  3400. else if (state.pppSubTab === 'profiles') openAddPPPProfileModal();
  3401. else if (state.pppSubTab === 'active') loadPPPSessions();
  3402. else if (state.pppSubTab === 'pppoe') document.querySelector('#ppp-subtab-pppoe form')?.requestSubmit();
  3403. else if (state.pppSubTab === 'pptp') document.querySelector('#ppp-subtab-pptp form')?.requestSubmit();
  3404. else if (state.pppSubTab === 'l2tp') document.querySelector('#ppp-subtab-l2tp form')?.requestSubmit();
  3405. }
  3406. async function loadPPP(populateDropdowns = true) {
  3407. await Promise.all([
  3408. loadPPPSecrets(),
  3409. loadPPPProfiles(),
  3410. loadPPPServers(),
  3411. loadPPPSessions()
  3412. ]);
  3413. }
  3414. async function loadPPPSecrets() {
  3415. try {
  3416. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`);
  3417. const data = await res.json();
  3418. state.pppSecrets = Array.isArray(data) ? data : [];
  3419. const b = document.getElementById('ppp-badge-secrets');
  3420. if (b) b.innerText = state.pppSecrets.length;
  3421. const b2 = document.getElementById('secrets-count-badge');
  3422. if (b2) b2.innerText = `${state.pppSecrets.length} Users`;
  3423. renderPPPSecrets();
  3424. } catch (err) {
  3425. console.error('Failed to load PPP secrets:', err);
  3426. }
  3427. }
  3428. function renderPPPSecrets() {
  3429. const tbody = document.getElementById('secrets-table-body');
  3430. const empty = document.getElementById('secrets-empty');
  3431. if (!tbody) return;
  3432. tbody.innerHTML = '';
  3433. const secrets = state.pppSecrets || [];
  3434. if (secrets.length === 0) {
  3435. empty?.classList.remove('hidden');
  3436. return;
  3437. }
  3438. empty?.classList.add('hidden');
  3439. secrets.forEach(s => {
  3440. const tr = document.createElement('tr');
  3441. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  3442. tr.innerHTML = `
  3443. <td class="py-2.5 px-3 text-center">${renderRuleFlag(s.disabled, !!s.comment)}</td>
  3444. <td class="py-2.5 px-3 font-bold text-white font-mono">${s.name}</td>
  3445. <td class="py-2.5 px-3 text-purple-300 font-mono font-semibold">${s.service}</td>
  3446. <td class="py-2.5 px-3 text-amber-300 font-mono">${s.profile}</td>
  3447. <td class="py-2.5 px-3 text-slate-400 font-mono">${s.local_address || '(profile)'}</td>
  3448. <td class="py-2.5 px-3 text-cyan-400 font-mono font-bold">${s.remote_address || '(profile)'}</td>
  3449. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]">${s.comment || '-'}</td>
  3450. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  3451. <button onclick="togglePPPSecretState('${s.id}', ${!s.disabled})" class="text-xs ${s.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline">${s.disabled ? 'Enable' : 'Disable'}</button>
  3452. <button onclick="openEditPPPSecretModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  3453. <button onclick="deletePPPSecret('${s.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  3454. </td>
  3455. `;
  3456. tbody.appendChild(tr);
  3457. });
  3458. }
  3459. async function loadPPPProfiles() {
  3460. try {
  3461. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  3462. const data = await res.json();
  3463. state.pppProfiles = Array.isArray(data) ? data : [];
  3464. const b = document.getElementById('ppp-badge-profiles');
  3465. if (b) b.innerText = state.pppProfiles.length;
  3466. const b2 = document.getElementById('profiles-count-badge');
  3467. if (b2) b2.innerText = `${state.pppProfiles.length} Profiles`;
  3468. // Populate profile selects across modals
  3469. const selects = ['secret-modal-profile', 'pppoe-server-profile', 'pptp-server-profile', 'l2tp-server-profile'];
  3470. selects.forEach(sid => {
  3471. const el = document.getElementById(sid);
  3472. if (!el) return;
  3473. const cur = el.value;
  3474. el.innerHTML = '';
  3475. state.pppProfiles.forEach(p => {
  3476. const opt = document.createElement('option');
  3477. opt.value = p.name;
  3478. opt.innerText = `${p.name} (${p.remote_address})`;
  3479. if (p.name === cur) opt.selected = true;
  3480. el.appendChild(opt);
  3481. });
  3482. });
  3483. renderPPPProfiles();
  3484. } catch (err) {
  3485. console.error('Failed to load PPP profiles:', err);
  3486. }
  3487. }
  3488. function renderPPPProfiles() {
  3489. const tbody = document.getElementById('profiles-table-body');
  3490. if (!tbody) return;
  3491. tbody.innerHTML = '';
  3492. (state.pppProfiles || []).forEach(p => {
  3493. const isDefault = p.name.startsWith('default');
  3494. const tr = document.createElement('tr');
  3495. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  3496. tr.innerHTML = `
  3497. <td class="py-2.5 px-3 font-bold text-white">${p.name}</td>
  3498. <td class="py-2.5 px-3 text-slate-300">${p.local_address}</td>
  3499. <td class="py-2.5 px-3 text-cyan-400 font-bold">${p.remote_address}</td>
  3500. <td class="py-2.5 px-3 text-slate-400">${p.dns_servers || '-'}</td>
  3501. <td class="py-2.5 px-3 text-purple-300 font-semibold">${p.use_encryption}</td>
  3502. <td class="py-2.5 px-3 text-center">${p.only_one ? '<span class="text-emerald-400">yes</span>' : '<span class="text-slate-500">no</span>'}</td>
  3503. <td class="py-2.5 px-3 text-slate-400 italic">${p.comment || '-'}</td>
  3504. <td class="py-2.5 px-3 text-right font-sans whitespace-nowrap">
  3505. ${!isDefault ? `<button onclick="deletePPPProfile('${p.name}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>` : `<span class="text-slate-600 text-[10px]">Built-in</span>`}
  3506. </td>
  3507. `;
  3508. tbody.appendChild(tr);
  3509. });
  3510. }
  3511. async function loadPPPServers() {
  3512. try {
  3513. const [pppoeRes, pptpRes, l2tpRes, ipsecRes] = await Promise.all([
  3514. fetch(`${API_BASE}/vpn/servers/pppoe`),
  3515. fetch(`${API_BASE}/vpn/servers/pptp`),
  3516. fetch(`${API_BASE}/vpn/servers/l2tp`),
  3517. fetch(`${API_BASE}/vpn/servers/ipsec`)
  3518. ]);
  3519. if (pppoeRes.ok) {
  3520. state.pppoeServer = await pppoeRes.json();
  3521. const s = state.pppoeServer;
  3522. document.getElementById('pppoe-server-enabled').checked = !!s.enabled;
  3523. document.getElementById('pppoe-server-name').value = s.service_name || 'proxmox-pppoe';
  3524. populateInterfaceSelect('pppoe-server-iface', s.interface || 'eth0');
  3525. document.getElementById('pppoe-server-profile').value = s.default_profile || 'default';
  3526. document.getElementById('pppoe-server-mtu').value = s.max_mtu || 1480;
  3527. document.getElementById('pppoe-server-onesession').checked = !!s.one_session_per_host;
  3528. const pill = document.getElementById('pppoe-server-status-pill');
  3529. if (pill) {
  3530. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  3531. pill.className = s.running ? 'px-2 py-0.5 rounded text-[10px] font-mono font-semibold bg-blue-500/20 text-blue-300 border border-blue-500/40' : 'px-2 py-0.5 rounded text-[10px] font-mono font-semibold bg-slate-800 text-slate-400';
  3532. }
  3533. setDotBadge('ppp-badge-pppoe-state', s.running);
  3534. }
  3535. if (pptpRes.ok) {
  3536. state.pptpServer = await pptpRes.json();
  3537. const s = state.pptpServer;
  3538. document.getElementById('pptp-server-enabled').checked = !!s.enabled;
  3539. document.getElementById('pptp-server-port').value = s.port || 1723;
  3540. document.getElementById('pptp-server-profile').value = s.default_profile || 'default-encryption';
  3541. document.getElementById('pptp-server-mppe').checked = s.require_mppe !== false;
  3542. const pill = document.getElementById('pptp-server-status-pill');
  3543. if (pill) {
  3544. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  3545. pill.className = s.running ? 'px-2 py-0.5 rounded text-[10px] font-mono font-semibold bg-purple-500/20 text-purple-300 border border-purple-500/40' : 'px-2 py-0.5 rounded text-[10px] font-mono font-semibold bg-slate-800 text-slate-400';
  3546. }
  3547. setDotBadge('ppp-badge-pptp-state', s.running);
  3548. }
  3549. if (l2tpRes.ok) {
  3550. state.l2tpServer = await l2tpRes.json();
  3551. const s = state.l2tpServer;
  3552. document.getElementById('l2tp-server-enabled').checked = !!s.enabled;
  3553. document.getElementById('l2tp-server-port').value = s.port || 1701;
  3554. document.getElementById('l2tp-server-profile').value = s.default_profile || 'default';
  3555. document.getElementById('l2tp-server-useipsec').value = s.use_ipsec || 'no';
  3556. document.getElementById('l2tp-server-ipsecsecret').value = s.ipsec_secret || '';
  3557. const pill = document.getElementById('l2tp-server-status-pill');
  3558. if (pill) {
  3559. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  3560. pill.className = s.running ? 'px-2 py-0.5 rounded text-[10px] font-mono font-semibold bg-cyan-500/20 text-cyan-300 border border-cyan-500/40' : 'px-2 py-0.5 rounded text-[10px] font-mono font-semibold bg-slate-800 text-slate-400';
  3561. }
  3562. setDotBadge('ppp-badge-l2tp-state', s.running);
  3563. }
  3564. if (ipsecRes.ok) {
  3565. state.ipsecServer = await ipsecRes.json();
  3566. const s = state.ipsecServer;
  3567. const modalEn = document.getElementById('modal-ipsec-server-enabled');
  3568. if (modalEn) modalEn.checked = !!s.enabled;
  3569. const modalPsk = document.getElementById('modal-ipsec-server-psk');
  3570. if (modalPsk) modalPsk.value = s.preshared_key || '';
  3571. const modalPool = document.getElementById('modal-ipsec-server-pool');
  3572. if (modalPool) modalPool.value = s.pool_address || '10.10.30.0/24';
  3573. const modalDns = document.getElementById('modal-ipsec-server-dns');
  3574. if (modalDns) modalDns.value = s.dns_servers || '1.1.1.1,8.8.8.8';
  3575. const modalSubnet = document.getElementById('modal-ipsec-server-subnet');
  3576. if (modalSubnet) modalSubnet.value = s.local_subnet || '0.0.0.0/0';
  3577. const pill = document.getElementById('modal-ipsec-server-status');
  3578. if (pill) {
  3579. pill.innerText = s.running ? 'ACTIVE RESPONDER' : 'STOPPED';
  3580. pill.className = s.running ? 'px-2 py-0.5 rounded text-[10px] font-mono font-semibold bg-amber-500/20 text-amber-300 border border-amber-500/40' : 'px-2 py-0.5 rounded text-[10px] font-mono font-semibold bg-slate-800 text-slate-400';
  3581. }
  3582. }
  3583. } catch (err) {
  3584. console.error('Failed to load VPN servers:', err);
  3585. }
  3586. }
  3587. async function loadPPPSessions() {
  3588. try {
  3589. const res = await fetch(`${API_BASE}/vpn/ppp/active`);
  3590. const data = await res.json();
  3591. state.pppActiveSessions = Array.isArray(data) ? data : [];
  3592. const b = document.getElementById('ppp-badge-active');
  3593. if (b) b.innerText = state.pppActiveSessions.length;
  3594. const sideB = document.getElementById('badge-ppp-sessions');
  3595. if (sideB) sideB.innerText = state.pppActiveSessions.length;
  3596. renderPPPSessions();
  3597. } catch (err) {
  3598. console.error('Failed to load active PPP sessions:', err);
  3599. }
  3600. }
  3601. function renderPPPSessions() {
  3602. const tbody = document.getElementById('active-ppp-table-body');
  3603. const empty = document.getElementById('active-ppp-empty');
  3604. if (!tbody) return;
  3605. tbody.innerHTML = '';
  3606. const list = state.pppActiveSessions || [];
  3607. if (list.length === 0) {
  3608. empty?.classList.remove('hidden');
  3609. return;
  3610. }
  3611. empty?.classList.add('hidden');
  3612. list.forEach(s => {
  3613. const tr = document.createElement('tr');
  3614. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  3615. tr.innerHTML = `
  3616. <td class="py-2.5 px-3 font-bold text-white">${s.interface}</td>
  3617. <td class="py-2.5 px-3 font-semibold text-violet-300">${s.username}</td>
  3618. <td class="py-2.5 px-3 text-cyan-400 uppercase">${s.service}</td>
  3619. <td class="py-2.5 px-3 text-emerald-400 font-bold">${s.address || '-'}</td>
  3620. <td class="py-2.5 px-3 text-slate-400">${s.uptime}</td>
  3621. <td class="py-2.5 px-3 text-[11px]">
  3622. <span class="text-emerald-400">↓ ${s.rx_human || '0 B'}</span>
  3623. <span class="text-cyan-400 ml-1">↑ ${s.tx_human || '0 B'}</span>
  3624. </td>
  3625. <td class="py-2.5 px-3 text-right font-sans">
  3626. <button onclick="disconnectPPPSession('${s.interface}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  3627. </td>
  3628. `;
  3629. tbody.appendChild(tr);
  3630. });
  3631. }
  3632. async function disconnectPPPSession(iface) {
  3633. if (!confirm(`Disconnect session ${iface}?`)) return;
  3634. try {
  3635. const res = await fetch(`${API_BASE}/vpn/ppp/active/${encodeURIComponent(iface)}`, { method: 'DELETE' });
  3636. if (res.ok) {
  3637. showToast('Disconnected', `Session ${iface} terminated`, 'info');
  3638. loadPPPSessions();
  3639. }
  3640. } catch (err) {
  3641. showToast('Error', err.message, 'error');
  3642. }
  3643. }
  3644. // PPP Secret Modal handlers
  3645. function openAddPPPSecretModal() {
  3646. document.getElementById('secret-modal-title').innerText = 'Add PPP Secret';
  3647. document.getElementById('secret-modal-id').value = '';
  3648. document.getElementById('secret-modal-name').value = '';
  3649. document.getElementById('secret-modal-password').value = '';
  3650. document.getElementById('secret-modal-service').value = 'any';
  3651. document.getElementById('secret-modal-profile').value = 'default';
  3652. document.getElementById('secret-modal-local').value = '';
  3653. document.getElementById('secret-modal-remote').value = '';
  3654. document.getElementById('secret-modal-comment').value = '';
  3655. document.getElementById('secret-modal-disabled').checked = false;
  3656. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  3657. }
  3658. function openEditPPPSecretModal(id) {
  3659. const s = (state.pppSecrets || []).find(sec => sec.id === id);
  3660. if (!s) return;
  3661. document.getElementById('secret-modal-title').innerText = `Edit PPP Secret (${s.name})`;
  3662. document.getElementById('secret-modal-id').value = s.id;
  3663. document.getElementById('secret-modal-name').value = s.name;
  3664. document.getElementById('secret-modal-password').value = s.password;
  3665. document.getElementById('secret-modal-service').value = s.service || 'any';
  3666. document.getElementById('secret-modal-profile').value = s.profile || 'default';
  3667. document.getElementById('secret-modal-local').value = s.local_address || '';
  3668. document.getElementById('secret-modal-remote').value = s.remote_address || '';
  3669. document.getElementById('secret-modal-comment').value = s.comment || '';
  3670. document.getElementById('secret-modal-disabled').checked = !!s.disabled;
  3671. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  3672. }
  3673. function closePPPSecretModal() {
  3674. document.getElementById('ppp-secret-modal').classList.add('hidden');
  3675. }
  3676. async function submitSavePPPSecret(e) {
  3677. e.preventDefault();
  3678. const id = document.getElementById('secret-modal-id').value;
  3679. const name = document.getElementById('secret-modal-name').value.trim();
  3680. const password = document.getElementById('secret-modal-password').value.trim();
  3681. const service = document.getElementById('secret-modal-service').value;
  3682. const profile = document.getElementById('secret-modal-profile').value;
  3683. const local = document.getElementById('secret-modal-local').value.trim();
  3684. const remote = document.getElementById('secret-modal-remote').value.trim();
  3685. const comment = document.getElementById('secret-modal-comment').value.trim();
  3686. const disabled = document.getElementById('secret-modal-disabled').checked;
  3687. try {
  3688. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`, {
  3689. method: 'POST',
  3690. headers: { 'Content-Type': 'application/json' },
  3691. body: JSON.stringify({
  3692. id,
  3693. name,
  3694. password,
  3695. service,
  3696. profile,
  3697. local_address: local,
  3698. remote_address: remote,
  3699. comment,
  3700. disabled
  3701. })
  3702. });
  3703. if (res.ok) {
  3704. showToast('Secret Saved', `User ${name} saved to PPP database`, 'success');
  3705. closePPPSecretModal();
  3706. loadPPPSecrets();
  3707. } else {
  3708. const err = await res.json();
  3709. showToast('Error', err.message, 'error');
  3710. }
  3711. } catch (err) {
  3712. showToast('Error', err.message, 'error');
  3713. }
  3714. }
  3715. async function togglePPPSecretState(id, disabled) {
  3716. try {
  3717. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}/state`, {
  3718. method: 'POST',
  3719. headers: { 'Content-Type': 'application/json' },
  3720. body: JSON.stringify({ disabled })
  3721. });
  3722. if (res.ok) {
  3723. showToast(disabled ? 'Disabled' : 'Enabled', 'Secret user state updated', 'info');
  3724. loadPPPSecrets();
  3725. }
  3726. } catch (err) {
  3727. showToast('Error', err.message, 'error');
  3728. }
  3729. }
  3730. async function deletePPPSecret(id) {
  3731. if (!confirm('Are you sure you want to delete this secret account?')) return;
  3732. try {
  3733. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}`, { method: 'DELETE' });
  3734. if (res.ok) {
  3735. showToast('Deleted', 'Secret account removed', 'success');
  3736. loadPPPSecrets();
  3737. }
  3738. } catch (err) {
  3739. showToast('Error', err.message, 'error');
  3740. }
  3741. }
  3742. // PPP Profile Modal handlers
  3743. function openAddPPPProfileModal() {
  3744. document.getElementById('profile-modal-name').value = '';
  3745. document.getElementById('profile-modal-local').value = '10.10.10.1';
  3746. document.getElementById('profile-modal-remote').value = '10.10.10.10-10.10.10.50';
  3747. document.getElementById('profile-modal-dns').value = '1.1.1.1,8.8.8.8';
  3748. document.getElementById('profile-modal-encryption').value = 'required';
  3749. document.getElementById('profile-modal-onlyone').checked = true;
  3750. document.getElementById('profile-modal-comment').value = '';
  3751. document.getElementById('ppp-profile-modal').classList.remove('hidden');
  3752. }
  3753. function closePPPProfileModal() {
  3754. document.getElementById('ppp-profile-modal').classList.add('hidden');
  3755. }
  3756. async function submitSavePPPProfile(e) {
  3757. e.preventDefault();
  3758. const name = document.getElementById('profile-modal-name').value.trim();
  3759. const local = document.getElementById('profile-modal-local').value.trim();
  3760. const remote = document.getElementById('profile-modal-remote').value.trim();
  3761. const dns = document.getElementById('profile-modal-dns').value.trim();
  3762. const enc = document.getElementById('profile-modal-encryption').value;
  3763. const onlyone = document.getElementById('profile-modal-onlyone').checked;
  3764. const comment = document.getElementById('profile-modal-comment').value.trim();
  3765. try {
  3766. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`, {
  3767. method: 'POST',
  3768. headers: { 'Content-Type': 'application/json' },
  3769. body: JSON.stringify({
  3770. id: name,
  3771. name,
  3772. local_address: local,
  3773. remote_address: remote,
  3774. dns_servers: dns,
  3775. use_encryption: enc,
  3776. only_one: onlyone,
  3777. comment
  3778. })
  3779. });
  3780. if (res.ok) {
  3781. showToast('Profile Saved', `PPP profile ${name} created`, 'success');
  3782. closePPPProfileModal();
  3783. loadPPPProfiles();
  3784. } else {
  3785. const err = await res.json();
  3786. showToast('Error', err.message, 'error');
  3787. }
  3788. } catch (err) {
  3789. showToast('Error', err.message, 'error');
  3790. }
  3791. }
  3792. async function deletePPPProfile(name) {
  3793. if (!confirm(`Delete PPP profile ${name}?`)) return;
  3794. try {
  3795. const res = await fetch(`${API_BASE}/vpn/ppp/profiles/${encodeURIComponent(name)}`, { method: 'DELETE' });
  3796. if (res.ok) {
  3797. showToast('Deleted', 'Profile removed', 'success');
  3798. loadPPPProfiles();
  3799. } else {
  3800. const err = await res.json();
  3801. showToast('Error', err.message, 'error');
  3802. }
  3803. } catch (err) {
  3804. showToast('Error', err.message, 'error');
  3805. }
  3806. }
  3807. // Server Config submissions
  3808. async function savePPPoEServerConfig(e) {
  3809. e.preventDefault();
  3810. const enabled = document.getElementById('pppoe-server-enabled').checked;
  3811. const name = document.getElementById('pppoe-server-name').value.trim();
  3812. const iface = document.getElementById('pppoe-server-iface').value;
  3813. const profile = document.getElementById('pppoe-server-profile').value;
  3814. const mtu = parseInt(document.getElementById('pppoe-server-mtu').value) || 1480;
  3815. const onesession = document.getElementById('pppoe-server-onesession').checked;
  3816. try {
  3817. const res = await fetch(`${API_BASE}/vpn/servers/pppoe`, {
  3818. method: 'POST',
  3819. headers: { 'Content-Type': 'application/json' },
  3820. body: JSON.stringify({
  3821. enabled,
  3822. service_name: name,
  3823. interface: iface,
  3824. default_profile: profile,
  3825. max_mtu: mtu,
  3826. max_mru: mtu,
  3827. one_session_per_host: onesession
  3828. })
  3829. });
  3830. if (res.ok) {
  3831. showToast('PPPoE Server', enabled ? 'PPPoE Server started' : 'PPPoE Server stopped', 'success');
  3832. loadPPPServers();
  3833. fetchData(false);
  3834. } else {
  3835. const err = await res.json();
  3836. showToast('Error', err.message, 'error');
  3837. }
  3838. } catch (err) {
  3839. showToast('Error', err.message, 'error');
  3840. }
  3841. }
  3842. async function savePPTPServerConfig(e) {
  3843. e.preventDefault();
  3844. const enabled = document.getElementById('pptp-server-enabled').checked;
  3845. const port = parseInt(document.getElementById('pptp-server-port').value) || 1723;
  3846. const profile = document.getElementById('pptp-server-profile').value;
  3847. const mppe = document.getElementById('pptp-server-mppe').checked;
  3848. try {
  3849. const res = await fetch(`${API_BASE}/vpn/servers/pptp`, {
  3850. method: 'POST',
  3851. headers: { 'Content-Type': 'application/json' },
  3852. body: JSON.stringify({
  3853. enabled,
  3854. port,
  3855. default_profile: profile,
  3856. require_mppe: mppe
  3857. })
  3858. });
  3859. if (res.ok) {
  3860. showToast('PPTP Server', enabled ? 'PPTP Server started' : 'PPTP Server stopped', 'success');
  3861. loadPPPServers();
  3862. fetchData(false);
  3863. } else {
  3864. const err = await res.json();
  3865. showToast('Error', err.message, 'error');
  3866. }
  3867. } catch (err) {
  3868. showToast('Error', err.message, 'error');
  3869. }
  3870. }
  3871. async function saveL2TPServerConfig(e) {
  3872. e.preventDefault();
  3873. const enabled = document.getElementById('l2tp-server-enabled').checked;
  3874. const port = parseInt(document.getElementById('l2tp-server-port').value) || 1701;
  3875. const profile = document.getElementById('l2tp-server-profile').value;
  3876. const useipsec = document.getElementById('l2tp-server-useipsec').value;
  3877. const psk = document.getElementById('l2tp-server-ipsecsecret').value.trim();
  3878. try {
  3879. const res = await fetch(`${API_BASE}/vpn/servers/l2tp`, {
  3880. method: 'POST',
  3881. headers: { 'Content-Type': 'application/json' },
  3882. body: JSON.stringify({
  3883. enabled,
  3884. port,
  3885. default_profile: profile,
  3886. use_ipsec: useipsec,
  3887. ipsec_secret: psk
  3888. })
  3889. });
  3890. if (res.ok) {
  3891. showToast('L2TP Server', enabled ? 'L2TP Server started' : 'L2TP Server stopped', 'success');
  3892. loadPPPServers();
  3893. fetchData(false);
  3894. } else {
  3895. const err = await res.json();
  3896. showToast('Error', err.message, 'error');
  3897. }
  3898. } catch (err) {
  3899. showToast('Error', err.message, 'error');
  3900. }
  3901. }
  3902. // IPSec Server Modal
  3903. function openIPSecServerModal() {
  3904. loadPPPServers();
  3905. document.getElementById('ipsec-server-modal').classList.remove('hidden');
  3906. }
  3907. function closeIPSecServerModal() {
  3908. document.getElementById('ipsec-server-modal').classList.add('hidden');
  3909. }
  3910. async function submitSaveIPSecServer(e) {
  3911. e.preventDefault();
  3912. const enabled = document.getElementById('modal-ipsec-server-enabled').checked;
  3913. const psk = document.getElementById('modal-ipsec-server-psk').value.trim();
  3914. const pool = document.getElementById('modal-ipsec-server-pool').value.trim();
  3915. const dns = document.getElementById('modal-ipsec-server-dns').value.trim();
  3916. const subnet = document.getElementById('modal-ipsec-server-subnet').value.trim();
  3917. try {
  3918. const res = await fetch(`${API_BASE}/vpn/servers/ipsec`, {
  3919. method: 'POST',
  3920. headers: { 'Content-Type': 'application/json' },
  3921. body: JSON.stringify({
  3922. enabled,
  3923. preshared_key: psk,
  3924. pool_address: pool,
  3925. dns_servers: dns,
  3926. local_subnet: subnet
  3927. })
  3928. });
  3929. if (res.ok) {
  3930. showToast('IPSec Server', enabled ? 'IKEv2 Roadwarrior responder active' : 'IPSec Server stopped', 'success');
  3931. closeIPSecServerModal();
  3932. loadPPPServers();
  3933. fetchData(false);
  3934. } else {
  3935. const err = await res.json();
  3936. showToast('Error', err.message, 'error');
  3937. }
  3938. } catch (err) {
  3939. showToast('Error', err.message, 'error');
  3940. }
  3941. }
  3942. // WireGuard Client Config Viewer
  3943. let currentWGClientConf = '';
  3944. async function openWGClientConfModal(iface, clientIP) {
  3945. try {
  3946. const res = await fetch(`${API_BASE}/vpn/wireguard/client-config`, {
  3947. method: 'POST',
  3948. headers: { 'Content-Type': 'application/json' },
  3949. body: JSON.stringify({
  3950. interface: iface,
  3951. address: clientIP || '10.10.0.2/32',
  3952. dns: '1.1.1.1, 8.8.8.8'
  3953. })
  3954. });
  3955. if (res.ok) {
  3956. const data = await res.json();
  3957. currentWGClientConf = data.config;
  3958. document.getElementById('wg-client-conf-text').value = currentWGClientConf;
  3959. document.getElementById('wg-client-conf-modal').classList.remove('hidden');
  3960. } else {
  3961. const err = await res.json();
  3962. showToast('Error', err.message, 'error');
  3963. }
  3964. } catch (err) {
  3965. showToast('Error', err.message, 'error');
  3966. }
  3967. }
  3968. function closeWGClientConfModal() {
  3969. document.getElementById('wg-client-conf-modal').classList.add('hidden');
  3970. }
  3971. function copyWGClientConf() {
  3972. if (!currentWGClientConf) return;
  3973. copyToClipboard(currentWGClientConf, 'WireGuard Client Profile');
  3974. }
  3975. function downloadWGClientConf() {
  3976. if (!currentWGClientConf) return;
  3977. const blob = new Blob([currentWGClientConf], { type: 'text/plain;charset=utf-8' });
  3978. const a = document.createElement('a');
  3979. a.href = URL.createObjectURL(blob);
  3980. a.download = 'wireguard-client.conf';
  3981. document.body.appendChild(a);
  3982. a.click();
  3983. document.body.removeChild(a);
  3984. showToast('Downloaded', 'wireguard-client.conf saved', 'success');
  3985. }
  3986. // =========================================================================
  3987. // DYNAMIC ROUTING (FRRouting BGP & OSPFv2)
  3988. // =========================================================================
  3989. state.activeDynSubTab = 'bgp-peers';
  3990. state.bgpInstance = null;
  3991. state.bgpPeers = [];
  3992. state.bgpNets = [];
  3993. state.bgpRoutes = [];
  3994. state.ospfInstance = null;
  3995. state.ospfInterfaces = [];
  3996. state.ospfAreas = [];
  3997. state.ospfNeighbors = [];
  3998. state.ospfRoutes = [];
  3999. function switchDynSubTab(subTab) {
  4000. state.activeDynSubTab = subTab;
  4001. const tabs = ['bgp-peers', 'bgp-nets', 'bgp-routes', 'ospf-ifaces', 'ospf-areas', 'ospf-nbrs', 'ospf-routes'];
  4002. tabs.forEach(t => {
  4003. const el = document.getElementById(`dyn-subtab-${t}`);
  4004. const btn = document.getElementById(`dyn-subtab-btn-${t}`);
  4005. if (el) el.classList.toggle('hidden', t !== subTab);
  4006. if (btn) {
  4007. if (t === subTab) {
  4008. btn.className = `px-4 py-2.5 text-xs font-bold border-b-2 ${t.startsWith('bgp') ? 'border-purple-500' : 'border-indigo-500'} text-white transition flex items-center gap-2 whitespace-nowrap`;
  4009. } else {
  4010. btn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition flex items-center gap-2 whitespace-nowrap';
  4011. }
  4012. }
  4013. });
  4014. }
  4015. async function loadDynamicRouting(showToastMsg = true) {
  4016. try {
  4017. const [sumRes, bgpInstRes, bgpPeersRes, bgpNetsRes, bgpRoutesRes, ospfInstRes, ospfIfacesRes, ospfAreasRes, ospfNbrsRes, ospfRoutesRes] = await Promise.all([
  4018. fetch(`${API_BASE}/routing/dynamic/summary`),
  4019. fetch(`${API_BASE}/routing/bgp/instance`),
  4020. fetch(`${API_BASE}/routing/bgp/peers`),
  4021. fetch(`${API_BASE}/routing/bgp/networks`),
  4022. fetch(`${API_BASE}/routing/bgp/routes`),
  4023. fetch(`${API_BASE}/routing/ospf/instance`),
  4024. fetch(`${API_BASE}/routing/ospf/interfaces`),
  4025. fetch(`${API_BASE}/routing/ospf/areas`),
  4026. fetch(`${API_BASE}/routing/ospf/neighbors`),
  4027. fetch(`${API_BASE}/routing/ospf/routes`)
  4028. ]);
  4029. if (sumRes.ok) state.dynSummary = await sumRes.json();
  4030. if (bgpInstRes.ok) state.bgpInstance = await bgpInstRes.json();
  4031. if (bgpPeersRes.ok) state.bgpPeers = await bgpPeersRes.json();
  4032. if (bgpNetsRes.ok) state.bgpNets = await bgpNetsRes.json();
  4033. if (bgpRoutesRes.ok) state.bgpRoutes = await bgpRoutesRes.json();
  4034. if (ospfInstRes.ok) state.ospfInstance = await ospfInstRes.json();
  4035. if (ospfIfacesRes.ok) state.ospfInterfaces = await ospfIfacesRes.json();
  4036. if (ospfAreasRes.ok) state.ospfAreas = await ospfAreasRes.json();
  4037. if (ospfNbrsRes.ok) state.ospfNeighbors = await ospfNbrsRes.json();
  4038. if (ospfRoutesRes.ok) state.ospfRoutes = await ospfRoutesRes.json();
  4039. renderBgpStatusPill();
  4040. renderBgpPeers();
  4041. renderBgpNetworks();
  4042. renderBgpRoutes();
  4043. renderOspfStatusPill();
  4044. renderOspfInterfaces();
  4045. renderOspfAreas();
  4046. renderOspfNeighbors();
  4047. renderOspfRoutes();
  4048. updateBadges();
  4049. } catch (err) {
  4050. console.error('Failed to load dynamic routing:', err);
  4051. if (showToastMsg) showToast('Error', 'Failed to load dynamic routing telemetry', 'error');
  4052. }
  4053. }
  4054. function renderBgpStatusPill() {
  4055. const pill = document.getElementById('bgp-live-status-pill');
  4056. if (!pill) return;
  4057. const inst = state.bgpInstance;
  4058. if (!inst || !inst.enabled) {
  4059. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-slate-800 text-slate-400 border border-slate-700';
  4060. pill.innerText = 'BGP DISABLED';
  4061. } else if (inst.running) {
  4062. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-purple-950 text-purple-300 border border-purple-800/60 font-semibold';
  4063. pill.innerText = `BGP ACTIVE (AS ${inst.as})`;
  4064. } else {
  4065. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-amber-950 text-amber-300 border border-amber-800/60 font-semibold';
  4066. pill.innerText = 'BGP STARTING...';
  4067. }
  4068. }
  4069. function renderBgpPeers() {
  4070. const tbody = document.getElementById('bgp-peers-table-body');
  4071. const empty = document.getElementById('bgp-peers-empty');
  4072. const countBadge = document.getElementById('bgp-peers-count-badge');
  4073. const navBadge = document.getElementById('dyn-badge-bgp-peers');
  4074. const peers = state.bgpPeers || [];
  4075. if (countBadge) countBadge.innerText = `${peers.length} Peers`;
  4076. if (navBadge) navBadge.innerText = peers.length;
  4077. if (peers.length === 0) {
  4078. tbody.innerHTML = '';
  4079. empty.classList.remove('hidden');
  4080. return;
  4081. }
  4082. empty.classList.add('hidden');
  4083. tbody.innerHTML = peers.map(p => {
  4084. let flagA = !p.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  4085. let flagE = p.state === 'Established' ? '<span class="text-emerald-400 font-bold ml-1" title="Established">E</span>' : '';
  4086. let flagX = p.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
  4087. let stateBadge = '';
  4088. if (p.disabled) {
  4089. stateBadge = '<span class="px-2 py-0.5 rounded-full text-[10px] font-sans font-medium bg-slate-800 text-slate-400 border border-slate-700">Disabled</span>';
  4090. } else if (p.state === 'Established') {
  4091. stateBadge = '<span class="px-2 py-0.5 rounded-full text-[10px] font-sans font-medium bg-emerald-500/10 text-emerald-400 border border-emerald-500/20">Established</span>';
  4092. } else if (p.state === 'Connect' || p.state === 'Active') {
  4093. stateBadge = `<span class="px-2 py-0.5 rounded-full text-[10px] font-sans font-medium bg-amber-500/10 text-amber-400 border border-amber-500/20">${p.state}</span>`;
  4094. } else {
  4095. stateBadge = `<span class="px-2 py-0.5 rounded-full text-[10px] font-sans font-medium bg-slate-800 text-slate-400 border border-slate-700">${p.state || 'Idle'}</span>`;
  4096. }
  4097. return `
  4098. <tr class="hover:bg-slate-800/40 transition">
  4099. <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagE}${flagX}</td>
  4100. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(p.name)}</td>
  4101. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(p.remote_address)}</td>
  4102. <td class="py-2.5 px-3 font-bold text-slate-200">AS ${p.remote_as}</td>
  4103. <td class="py-2.5 px-3">${stateBadge}</td>
  4104. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(p.uptime || '-')}</td>
  4105. <td class="py-2.5 px-3 text-slate-300">
  4106. <span class="text-emerald-400 font-bold">↓ ${p.prefix_received || 0}</span> /
  4107. <span class="text-blue-400 font-bold">↑ ${p.prefix_sent || 0}</span>
  4108. </td>
  4109. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(p.comment || '')}</td>
  4110. <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
  4111. <button onclick="toggleBgpPeerState('${p.id}', ${!p.disabled})" class="px-2 py-1 rounded text-[11px] ${p.disabled ? 'bg-emerald-950 hover:bg-emerald-900 text-emerald-400 border border-emerald-800/50' : 'bg-slate-800 hover:bg-slate-700 text-slate-300 border border-slate-700'}">
  4112. ${p.disabled ? 'Enable' : 'Disable'}
  4113. </button>
  4114. <button onclick="openEditBgpPeerModal('${p.id}')" class="px-2 py-1 rounded text-[11px] bg-slate-800 hover:bg-slate-700 text-purple-300 border border-slate-700">
  4115. Edit
  4116. </button>
  4117. <button onclick="deleteBgpPeer('${p.id}')" class="px-2 py-1 rounded text-[11px] bg-rose-950/60 hover:bg-rose-900 text-rose-300 border border-rose-900/50">
  4118. Delete
  4119. </button>
  4120. </td>
  4121. </tr>
  4122. `;
  4123. }).join('');
  4124. }
  4125. function renderBgpNetworks() {
  4126. const tbody = document.getElementById('bgp-nets-table-body');
  4127. const empty = document.getElementById('bgp-nets-empty');
  4128. const countBadge = document.getElementById('bgp-nets-count-badge');
  4129. const navBadge = document.getElementById('dyn-badge-bgp-nets');
  4130. const nets = state.bgpNets || [];
  4131. if (countBadge) countBadge.innerText = `${nets.length} Networks`;
  4132. if (navBadge) navBadge.innerText = nets.length;
  4133. if (nets.length === 0) {
  4134. tbody.innerHTML = '';
  4135. empty.classList.remove('hidden');
  4136. return;
  4137. }
  4138. empty.classList.add('hidden');
  4139. tbody.innerHTML = nets.map(n => `
  4140. <tr class="hover:bg-slate-800/40 transition">
  4141. <td class="py-2.5 px-3 font-semibold text-purple-300 font-mono">${escapeHtml(n.network)}</td>
  4142. <td class="py-2.5 px-3">
  4143. ${n.disabled
  4144. ? '<span class="px-2 py-0.5 rounded-full text-[10px] bg-slate-800 text-slate-400 border border-slate-700">Disabled</span>'
  4145. : '<span class="px-2 py-0.5 rounded-full text-[10px] bg-emerald-500/10 text-emerald-400 border border-emerald-500/20">Announcing</span>'}
  4146. </td>
  4147. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(n.comment || '')}</td>
  4148. <td class="py-2.5 px-3 text-right space-x-1 font-sans">
  4149. <button onclick="deleteBgpNetwork('${n.id}')" class="px-2 py-1 rounded text-[11px] bg-rose-950/60 hover:bg-rose-900 text-rose-300 border border-rose-900/50">
  4150. Delete
  4151. </button>
  4152. </td>
  4153. </tr>
  4154. `).join('');
  4155. }
  4156. function renderBgpRoutes() {
  4157. const tbody = document.getElementById('bgp-routes-table-body');
  4158. const empty = document.getElementById('bgp-routes-empty');
  4159. const countBadge = document.getElementById('bgp-routes-count-badge');
  4160. const navBadge = document.getElementById('dyn-badge-bgp-routes');
  4161. const routes = state.bgpRoutes || [];
  4162. if (countBadge) countBadge.innerText = `${routes.length} Routes`;
  4163. if (navBadge) navBadge.innerText = routes.length;
  4164. if (routes.length === 0) {
  4165. tbody.innerHTML = '';
  4166. empty.classList.remove('hidden');
  4167. return;
  4168. }
  4169. empty.classList.add('hidden');
  4170. tbody.innerHTML = routes.map(r => `
  4171. <tr class="hover:bg-slate-800/40 transition">
  4172. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.prefix)}</td>
  4173. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(r.next_hop || '-')}</td>
  4174. <td class="py-2.5 px-3 text-slate-300">${r.metric}</td>
  4175. <td class="py-2.5 px-3 text-slate-300">${r.weight}</td>
  4176. <td class="py-2.5 px-3 text-amber-300">${escapeHtml(r.path || 'i')}</td>
  4177. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.origin || 'IGP')}</td>
  4178. </tr>
  4179. `).join('');
  4180. }
  4181. function renderOspfStatusPill() {
  4182. const pill = document.getElementById('ospf-live-status-pill');
  4183. if (!pill) return;
  4184. const inst = state.ospfInstance;
  4185. if (!inst || !inst.enabled) {
  4186. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-slate-800 text-slate-400 border border-slate-700';
  4187. pill.innerText = 'OSPF DISABLED';
  4188. } else if (inst.running) {
  4189. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-indigo-950 text-indigo-300 border border-indigo-800/60 font-semibold';
  4190. pill.innerText = `OSPF ACTIVE (ID: ${inst.router_id || 'Auto'})`;
  4191. } else {
  4192. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-amber-950 text-amber-300 border border-amber-800/60 font-semibold';
  4193. pill.innerText = 'OSPF STARTING...';
  4194. }
  4195. }
  4196. function renderOspfInterfaces() {
  4197. const tbody = document.getElementById('ospf-ifaces-table-body');
  4198. const empty = document.getElementById('ospf-ifaces-empty');
  4199. const countBadge = document.getElementById('ospf-ifaces-count-badge');
  4200. const navBadge = document.getElementById('dyn-badge-ospf-ifaces');
  4201. const ifaces = state.ospfInterfaces || [];
  4202. if (countBadge) countBadge.innerText = `${ifaces.length} Interfaces`;
  4203. if (navBadge) navBadge.innerText = ifaces.length;
  4204. if (ifaces.length === 0) {
  4205. tbody.innerHTML = '';
  4206. empty.classList.remove('hidden');
  4207. return;
  4208. }
  4209. empty.classList.add('hidden');
  4210. tbody.innerHTML = ifaces.map(i => {
  4211. let flagA = !i.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  4212. let flagP = i.passive ? '<span class="text-amber-400 font-bold ml-1" title="Passive">P</span>' : '';
  4213. let flagX = i.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
  4214. return `
  4215. <tr class="hover:bg-slate-800/40 transition">
  4216. <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagP}${flagX}</td>
  4217. <td class="py-2.5 px-3 font-semibold text-white font-mono">${escapeHtml(i.network)}</td>
  4218. <td class="py-2.5 px-3 text-indigo-300 font-bold">Area ${escapeHtml(i.area)}</td>
  4219. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(i.interface || 'Any')}</td>
  4220. <td class="py-2.5 px-3 text-slate-300">${i.cost}</td>
  4221. <td class="py-2.5 px-3 text-slate-300">${i.priority}</td>
  4222. <td class="py-2.5 px-3 text-slate-400">${i.hello_interval}s / ${i.dead_interval}s</td>
  4223. <td class="py-2.5 px-3 text-slate-300 uppercase">${escapeHtml(i.auth_type || 'none')}</td>
  4224. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(i.comment || '')}</td>
  4225. <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
  4226. <button onclick="toggleOspfInterfaceState('${i.id}', ${!i.disabled})" class="px-2 py-1 rounded text-[11px] ${i.disabled ? 'bg-emerald-950 hover:bg-emerald-900 text-emerald-400 border border-emerald-800/50' : 'bg-slate-800 hover:bg-slate-700 text-slate-300 border border-slate-700'}">
  4227. ${i.disabled ? 'Enable' : 'Disable'}
  4228. </button>
  4229. <button onclick="openEditOspfInterfaceModal('${i.id}')" class="px-2 py-1 rounded text-[11px] bg-slate-800 hover:bg-slate-700 text-indigo-300 border border-slate-700">
  4230. Edit
  4231. </button>
  4232. <button onclick="deleteOspfInterface('${i.id}')" class="px-2 py-1 rounded text-[11px] bg-rose-950/60 hover:bg-rose-900 text-rose-300 border border-rose-900/50">
  4233. Delete
  4234. </button>
  4235. </td>
  4236. </tr>
  4237. `;
  4238. }).join('');
  4239. }
  4240. function renderOspfAreas() {
  4241. const tbody = document.getElementById('ospf-areas-table-body');
  4242. const countBadge = document.getElementById('ospf-areas-count-badge');
  4243. const navBadge = document.getElementById('dyn-badge-ospf-areas');
  4244. const areas = state.ospfAreas || [];
  4245. if (countBadge) countBadge.innerText = `${areas.length} Areas`;
  4246. if (navBadge) navBadge.innerText = areas.length;
  4247. tbody.innerHTML = areas.map(a => `
  4248. <tr class="hover:bg-slate-800/40 transition">
  4249. <td class="py-2.5 px-3 font-semibold text-white font-mono">${escapeHtml(a.name)}</td>
  4250. <td class="py-2.5 px-3 font-bold text-indigo-300">${escapeHtml(a.area_id)}</td>
  4251. <td class="py-2.5 px-3 text-slate-300 uppercase">${escapeHtml(a.area_type || 'default')}</td>
  4252. <td class="py-2.5 px-3 text-slate-400 font-sans">${escapeHtml(a.comment || '')}</td>
  4253. <td class="py-2.5 px-3 text-right font-sans">
  4254. <button onclick="deleteOspfArea('${a.id}')" class="px-2 py-1 rounded text-[11px] bg-rose-950/60 hover:bg-rose-900 text-rose-300 border border-rose-900/50">
  4255. Delete
  4256. </button>
  4257. </td>
  4258. </tr>
  4259. `).join('');
  4260. }
  4261. function renderOspfNeighbors() {
  4262. const tbody = document.getElementById('ospf-nbrs-table-body');
  4263. const empty = document.getElementById('ospf-nbrs-empty');
  4264. const countBadge = document.getElementById('ospf-nbrs-count-badge');
  4265. const navBadge = document.getElementById('dyn-badge-ospf-nbrs');
  4266. const nbrs = state.ospfNeighbors || [];
  4267. if (countBadge) countBadge.innerText = `${nbrs.length} Neighbors`;
  4268. if (navBadge) navBadge.innerText = nbrs.length;
  4269. if (nbrs.length === 0) {
  4270. tbody.innerHTML = '';
  4271. empty.classList.remove('hidden');
  4272. return;
  4273. }
  4274. empty.classList.add('hidden');
  4275. tbody.innerHTML = nbrs.map(n => {
  4276. let stateBadge = '';
  4277. if (n.state && (n.state.startsWith('Full') || n.state.includes('DR') || n.state.includes('Backup'))) {
  4278. stateBadge = `<span class="px-2 py-0.5 rounded-full text-[10px] font-sans font-medium bg-emerald-500/10 text-emerald-400 border border-emerald-500/20">${escapeHtml(n.state)}</span>`;
  4279. } else {
  4280. stateBadge = `<span class="px-2 py-0.5 rounded-full text-[10px] font-sans font-medium bg-amber-500/10 text-amber-400 border border-amber-500/20">${escapeHtml(n.state || 'Unknown')}</span>`;
  4281. }
  4282. return `
  4283. <tr class="hover:bg-slate-800/40 transition">
  4284. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(n.neighbor_id)}</td>
  4285. <td class="py-2.5 px-3 text-indigo-300 font-bold">${escapeHtml(n.address)}</td>
  4286. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(n.interface)}</td>
  4287. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(n.area || '0.0.0.0')}</td>
  4288. <td class="py-2.5 px-3">${stateBadge}</td>
  4289. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(n.dead_timer || '-')}</td>
  4290. </tr>
  4291. `;
  4292. }).join('');
  4293. }
  4294. function renderOspfRoutes() {
  4295. const tbody = document.getElementById('ospf-routes-table-body');
  4296. const empty = document.getElementById('ospf-routes-empty');
  4297. const countBadge = document.getElementById('ospf-routes-count-badge');
  4298. const navBadge = document.getElementById('dyn-badge-ospf-routes');
  4299. const routes = state.ospfRoutes || [];
  4300. if (countBadge) countBadge.innerText = `${routes.length} Routes`;
  4301. if (navBadge) navBadge.innerText = routes.length;
  4302. if (routes.length === 0) {
  4303. tbody.innerHTML = '';
  4304. empty.classList.remove('hidden');
  4305. return;
  4306. }
  4307. empty.classList.add('hidden');
  4308. tbody.innerHTML = routes.map(r => `
  4309. <tr class="hover:bg-slate-800/40 transition">
  4310. <td class="py-2.5 px-3 font-semibold text-white font-mono">${escapeHtml(r.prefix)}</td>
  4311. <td class="py-2.5 px-3 text-slate-300">${escapeHtml(r.route_type || 'Network')}</td>
  4312. <td class="py-2.5 px-3 text-slate-300">${r.cost}</td>
  4313. <td class="py-2.5 px-3 text-indigo-300 font-bold">Area ${escapeHtml(r.area || '0.0.0.0')}</td>
  4314. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(r.next_hop || r.interface || '-')}</td>
  4315. </tr>
  4316. `).join('');
  4317. }
  4318. // BGP Modals & Actions
  4319. function openBgpInstanceModal() {
  4320. const inst = state.bgpInstance || { enabled: false, as: 65001, router_id: '192.168.131.56', hold_time: 180, keepalive_time: 60 };
  4321. document.getElementById('modal-bgp-enabled').checked = !!inst.enabled;
  4322. document.getElementById('modal-bgp-as').value = inst.as || 65001;
  4323. document.getElementById('modal-bgp-router-id').value = inst.router_id || '';
  4324. document.getElementById('modal-bgp-keepalive').value = inst.keepalive_time || 60;
  4325. document.getElementById('modal-bgp-holdtime').value = inst.hold_time || 180;
  4326. document.getElementById('modal-bgp-redist-conn').checked = !!inst.redistribute_connected;
  4327. document.getElementById('modal-bgp-redist-static').checked = !!inst.redistribute_static;
  4328. document.getElementById('modal-bgp-redist-ospf').checked = !!inst.redistribute_ospf;
  4329. document.getElementById('bgp-instance-modal').classList.remove('hidden');
  4330. }
  4331. function closeBgpInstanceModal() {
  4332. document.getElementById('bgp-instance-modal').classList.add('hidden');
  4333. }
  4334. async function submitBgpInstance(e) {
  4335. e.preventDefault();
  4336. const payload = {
  4337. enabled: document.getElementById('modal-bgp-enabled').checked,
  4338. as: parseInt(document.getElementById('modal-bgp-as').value, 10),
  4339. router_id: document.getElementById('modal-bgp-router-id').value.trim(),
  4340. keepalive_time: parseInt(document.getElementById('modal-bgp-keepalive').value, 10),
  4341. hold_time: parseInt(document.getElementById('modal-bgp-holdtime').value, 10),
  4342. redistribute_connected: document.getElementById('modal-bgp-redist-conn').checked,
  4343. redistribute_static: document.getElementById('modal-bgp-redist-static').checked,
  4344. redistribute_ospf: document.getElementById('modal-bgp-redist-ospf').checked
  4345. };
  4346. try {
  4347. const res = await fetch(`${API_BASE}/routing/bgp/instance`, {
  4348. method: 'POST',
  4349. headers: { 'Content-Type': 'application/json' },
  4350. body: JSON.stringify(payload)
  4351. });
  4352. if (res.ok) {
  4353. closeBgpInstanceModal();
  4354. showToast('Success', 'BGP instance configuration updated', 'success');
  4355. loadDynamicRouting();
  4356. } else {
  4357. const err = await res.json();
  4358. showToast('Error', err.error || 'Failed to update BGP instance', 'error');
  4359. }
  4360. } catch (err) {
  4361. showToast('Error', err.message, 'error');
  4362. }
  4363. }
  4364. function openAddBgpPeerModal() {
  4365. document.getElementById('bgp-peer-form').reset();
  4366. document.getElementById('modal-bgp-peer-id').value = '';
  4367. document.getElementById('bgp-peer-modal-title').innerText = 'Add BGP Peer Connection';
  4368. document.getElementById('modal-bgp-peer-nexthop-self').checked = true;
  4369. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  4370. }
  4371. function openEditBgpPeerModal(id) {
  4372. const p = (state.bgpPeers || []).find(item => item.id === id);
  4373. if (!p) return;
  4374. document.getElementById('modal-bgp-peer-id').value = p.id;
  4375. document.getElementById('modal-bgp-peer-name').value = p.name || '';
  4376. document.getElementById('modal-bgp-peer-remote-addr').value = p.remote_address || '';
  4377. document.getElementById('modal-bgp-peer-remote-as').value = p.remote_as || '';
  4378. document.getElementById('modal-bgp-peer-local-addr').value = p.local_address || '';
  4379. document.getElementById('modal-bgp-peer-password').value = p.password || '';
  4380. document.getElementById('modal-bgp-peer-multihop').checked = !!p.multihop;
  4381. document.getElementById('modal-bgp-peer-nexthop-self').checked = !!p.nexthop_self;
  4382. document.getElementById('modal-bgp-peer-passive').checked = !!p.passive;
  4383. document.getElementById('modal-bgp-peer-disabled').checked = !!p.disabled;
  4384. document.getElementById('modal-bgp-peer-comment').value = p.comment || '';
  4385. document.getElementById('bgp-peer-modal-title').innerText = 'Edit BGP Peer Connection';
  4386. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  4387. }
  4388. function closeBgpPeerModal() {
  4389. document.getElementById('bgp-peer-modal').classList.add('hidden');
  4390. }
  4391. async function submitBgpPeer(e) {
  4392. e.preventDefault();
  4393. const payload = {
  4394. id: document.getElementById('modal-bgp-peer-id').value,
  4395. name: document.getElementById('modal-bgp-peer-name').value.trim(),
  4396. remote_address: document.getElementById('modal-bgp-peer-remote-addr').value.trim(),
  4397. remote_as: parseInt(document.getElementById('modal-bgp-peer-remote-as').value, 10),
  4398. local_address: document.getElementById('modal-bgp-peer-local-addr').value.trim(),
  4399. password: document.getElementById('modal-bgp-peer-password').value,
  4400. multihop: document.getElementById('modal-bgp-peer-multihop').checked,
  4401. nexthop_self: document.getElementById('modal-bgp-peer-nexthop-self').checked,
  4402. passive: document.getElementById('modal-bgp-peer-passive').checked,
  4403. disabled: document.getElementById('modal-bgp-peer-disabled').checked,
  4404. comment: document.getElementById('modal-bgp-peer-comment').value.trim()
  4405. };
  4406. try {
  4407. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  4408. method: 'POST',
  4409. headers: { 'Content-Type': 'application/json' },
  4410. body: JSON.stringify(payload)
  4411. });
  4412. if (res.ok) {
  4413. closeBgpPeerModal();
  4414. showToast('Success', 'BGP Peer saved', 'success');
  4415. loadDynamicRouting();
  4416. } else {
  4417. const err = await res.json();
  4418. showToast('Error', err.error || 'Failed to save peer', 'error');
  4419. }
  4420. } catch (err) {
  4421. showToast('Error', err.message, 'error');
  4422. }
  4423. }
  4424. async function deleteBgpPeer(id) {
  4425. if (!confirm('Are you sure you want to delete this BGP peer connection?')) return;
  4426. try {
  4427. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4428. if (res.ok) {
  4429. showToast('Deleted', 'BGP peer removed', 'success');
  4430. loadDynamicRouting();
  4431. }
  4432. } catch (err) {
  4433. showToast('Error', err.message, 'error');
  4434. }
  4435. }
  4436. async function toggleBgpPeerState(id, disabled) {
  4437. try {
  4438. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}/state`, {
  4439. method: 'POST',
  4440. headers: { 'Content-Type': 'application/json' },
  4441. body: JSON.stringify({ disabled })
  4442. });
  4443. if (res.ok) {
  4444. showToast('Updated', `Peer ${disabled ? 'disabled' : 'enabled'}`, 'success');
  4445. loadDynamicRouting();
  4446. }
  4447. } catch (err) {
  4448. showToast('Error', err.message, 'error');
  4449. }
  4450. }
  4451. function openAddBgpNetworkModal() {
  4452. document.getElementById('bgp-network-form').reset();
  4453. document.getElementById('modal-bgp-net-id').value = '';
  4454. document.getElementById('bgp-network-modal').classList.remove('hidden');
  4455. }
  4456. function closeBgpNetworkModal() {
  4457. document.getElementById('bgp-network-modal').classList.add('hidden');
  4458. }
  4459. async function submitBgpNetwork(e) {
  4460. e.preventDefault();
  4461. const payload = {
  4462. id: document.getElementById('modal-bgp-net-id').value,
  4463. network: document.getElementById('modal-bgp-net-cidr').value.trim(),
  4464. comment: document.getElementById('modal-bgp-net-comment').value.trim(),
  4465. disabled: document.getElementById('modal-bgp-net-disabled').checked
  4466. };
  4467. try {
  4468. const res = await fetch(`${API_BASE}/routing/bgp/networks`, {
  4469. method: 'POST',
  4470. headers: { 'Content-Type': 'application/json' },
  4471. body: JSON.stringify(payload)
  4472. });
  4473. if (res.ok) {
  4474. closeBgpNetworkModal();
  4475. showToast('Success', 'BGP network advertisement saved', 'success');
  4476. loadDynamicRouting();
  4477. } else {
  4478. const err = await res.json();
  4479. showToast('Error', err.error || 'Failed to save network', 'error');
  4480. }
  4481. } catch (err) {
  4482. showToast('Error', err.message, 'error');
  4483. }
  4484. }
  4485. async function deleteBgpNetwork(id) {
  4486. if (!confirm('Are you sure you want to stop announcing this network?')) return;
  4487. try {
  4488. const res = await fetch(`${API_BASE}/routing/bgp/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4489. if (res.ok) {
  4490. showToast('Deleted', 'Network advertisement removed', 'success');
  4491. loadDynamicRouting();
  4492. }
  4493. } catch (err) {
  4494. showToast('Error', err.message, 'error');
  4495. }
  4496. }
  4497. // OSPF Modals & Actions
  4498. function openOspfInstanceModal() {
  4499. const inst = state.ospfInstance || { enabled: false, router_id: '192.168.131.56', default_metric: 10 };
  4500. document.getElementById('modal-ospf-enabled').checked = !!inst.enabled;
  4501. document.getElementById('modal-ospf-router-id').value = inst.router_id || '';
  4502. document.getElementById('modal-ospf-metric').value = inst.default_metric || 10;
  4503. document.getElementById('modal-ospf-redist-conn').checked = !!inst.redistribute_connected;
  4504. document.getElementById('modal-ospf-redist-static').checked = !!inst.redistribute_static;
  4505. document.getElementById('modal-ospf-redist-bgp').checked = !!inst.redistribute_bgp;
  4506. document.getElementById('ospf-instance-modal').classList.remove('hidden');
  4507. }
  4508. function closeOspfInstanceModal() {
  4509. document.getElementById('ospf-instance-modal').classList.add('hidden');
  4510. }
  4511. async function submitOspfInstance(e) {
  4512. e.preventDefault();
  4513. const payload = {
  4514. enabled: document.getElementById('modal-ospf-enabled').checked,
  4515. router_id: document.getElementById('modal-ospf-router-id').value.trim(),
  4516. default_metric: parseInt(document.getElementById('modal-ospf-metric').value, 10),
  4517. redistribute_connected: document.getElementById('modal-ospf-redist-conn').checked,
  4518. redistribute_static: document.getElementById('modal-ospf-redist-static').checked,
  4519. redistribute_bgp: document.getElementById('modal-ospf-redist-bgp').checked
  4520. };
  4521. try {
  4522. const res = await fetch(`${API_BASE}/routing/ospf/instance`, {
  4523. method: 'POST',
  4524. headers: { 'Content-Type': 'application/json' },
  4525. body: JSON.stringify(payload)
  4526. });
  4527. if (res.ok) {
  4528. closeOspfInstanceModal();
  4529. showToast('Success', 'OSPF instance configuration updated', 'success');
  4530. loadDynamicRouting();
  4531. } else {
  4532. const err = await res.json();
  4533. showToast('Error', err.error || 'Failed to update OSPF instance', 'error');
  4534. }
  4535. } catch (err) {
  4536. showToast('Error', err.message, 'error');
  4537. }
  4538. }
  4539. function openAddOspfAreaModal() {
  4540. document.getElementById('ospf-area-form').reset();
  4541. document.getElementById('modal-ospf-area-id').value = '';
  4542. document.getElementById('modal-ospf-area-areaid').value = '0.0.0.0';
  4543. document.getElementById('ospf-area-modal').classList.remove('hidden');
  4544. }
  4545. function closeOspfAreaModal() {
  4546. document.getElementById('ospf-area-modal').classList.add('hidden');
  4547. }
  4548. async function submitOspfArea(e) {
  4549. e.preventDefault();
  4550. const payload = {
  4551. id: document.getElementById('modal-ospf-area-id').value,
  4552. name: document.getElementById('modal-ospf-area-name').value.trim(),
  4553. area_id: document.getElementById('modal-ospf-area-areaid').value.trim(),
  4554. area_type: document.getElementById('modal-ospf-area-type').value,
  4555. comment: document.getElementById('modal-ospf-area-comment').value.trim()
  4556. };
  4557. try {
  4558. const res = await fetch(`${API_BASE}/routing/ospf/areas`, {
  4559. method: 'POST',
  4560. headers: { 'Content-Type': 'application/json' },
  4561. body: JSON.stringify(payload)
  4562. });
  4563. if (res.ok) {
  4564. closeOspfAreaModal();
  4565. showToast('Success', 'OSPF area saved', 'success');
  4566. loadDynamicRouting();
  4567. } else {
  4568. const err = await res.json();
  4569. showToast('Error', err.error || 'Failed to save area', 'error');
  4570. }
  4571. } catch (err) {
  4572. showToast('Error', err.message, 'error');
  4573. }
  4574. }
  4575. async function deleteOspfArea(id) {
  4576. if (!confirm('Are you sure you want to delete this OSPF area?')) return;
  4577. try {
  4578. const res = await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4579. if (res.ok) {
  4580. showToast('Deleted', 'OSPF area removed', 'success');
  4581. loadDynamicRouting();
  4582. }
  4583. } catch (err) {
  4584. showToast('Error', err.message, 'error');
  4585. }
  4586. }
  4587. function populateOspfInterfaceDevices() {
  4588. const select = document.getElementById('modal-ospf-iface-device');
  4589. if (!select) return;
  4590. const current = select.value;
  4591. select.innerHTML = '<option value="">Any matching interface</option>';
  4592. (state.interfaces || []).forEach(iface => {
  4593. select.innerHTML += `<option value="${escapeHtml(iface.name)}">${escapeHtml(iface.name)} (${iface.type})</option>`;
  4594. });
  4595. if (current) select.value = current;
  4596. }
  4597. function openAddOspfInterfaceModal() {
  4598. document.getElementById('ospf-interface-form').reset();
  4599. document.getElementById('modal-ospf-iface-id').value = '';
  4600. document.getElementById('modal-ospf-iface-area').value = '0.0.0.0';
  4601. document.getElementById('modal-ospf-iface-cost').value = '10';
  4602. document.getElementById('modal-ospf-iface-priority').value = '1';
  4603. document.getElementById('modal-ospf-iface-hello').value = '10';
  4604. document.getElementById('modal-ospf-iface-dead').value = '40';
  4605. document.getElementById('ospf-interface-modal-title').innerText = 'Add OSPF Interface';
  4606. populateOspfInterfaceDevices();
  4607. document.getElementById('ospf-interface-modal').classList.remove('hidden');
  4608. }
  4609. function openEditOspfInterfaceModal(id) {
  4610. const item = (state.ospfInterfaces || []).find(i => i.id === id);
  4611. if (!item) return;
  4612. populateOspfInterfaceDevices();
  4613. document.getElementById('modal-ospf-iface-id').value = item.id;
  4614. document.getElementById('modal-ospf-iface-net').value = item.network || '';
  4615. document.getElementById('modal-ospf-iface-area').value = item.area || '0.0.0.0';
  4616. document.getElementById('modal-ospf-iface-device').value = item.interface || '';
  4617. document.getElementById('modal-ospf-iface-cost').value = item.cost || 10;
  4618. document.getElementById('modal-ospf-iface-priority').value = item.priority || 1;
  4619. document.getElementById('modal-ospf-iface-hello').value = item.hello_interval || 10;
  4620. document.getElementById('modal-ospf-iface-dead').value = item.dead_interval || 40;
  4621. document.getElementById('modal-ospf-iface-auth-type').value = item.auth_type || 'none';
  4622. document.getElementById('modal-ospf-iface-auth-key').value = item.auth_key || '';
  4623. document.getElementById('modal-ospf-iface-passive').checked = !!item.passive;
  4624. document.getElementById('modal-ospf-iface-disabled').checked = !!item.disabled;
  4625. document.getElementById('modal-ospf-iface-comment').value = item.comment || '';
  4626. document.getElementById('ospf-interface-modal-title').innerText = 'Edit OSPF Interface';
  4627. document.getElementById('ospf-interface-modal').classList.remove('hidden');
  4628. }
  4629. function closeOspfInterfaceModal() {
  4630. document.getElementById('ospf-interface-modal').classList.add('hidden');
  4631. }
  4632. async function submitOspfInterface(e) {
  4633. e.preventDefault();
  4634. const payload = {
  4635. id: document.getElementById('modal-ospf-iface-id').value,
  4636. network: document.getElementById('modal-ospf-iface-net').value.trim(),
  4637. area: document.getElementById('modal-ospf-iface-area').value.trim(),
  4638. interface: document.getElementById('modal-ospf-iface-device').value,
  4639. cost: parseInt(document.getElementById('modal-ospf-iface-cost').value, 10),
  4640. priority: parseInt(document.getElementById('modal-ospf-iface-priority').value, 10),
  4641. hello_interval: parseInt(document.getElementById('modal-ospf-iface-hello').value, 10),
  4642. dead_interval: parseInt(document.getElementById('modal-ospf-iface-dead').value, 10),
  4643. auth_type: document.getElementById('modal-ospf-iface-auth-type').value,
  4644. auth_key: document.getElementById('modal-ospf-iface-auth-key').value,
  4645. passive: document.getElementById('modal-ospf-iface-passive').checked,
  4646. disabled: document.getElementById('modal-ospf-iface-disabled').checked,
  4647. comment: document.getElementById('modal-ospf-iface-comment').value.trim()
  4648. };
  4649. try {
  4650. const res = await fetch(`${API_BASE}/routing/ospf/interfaces`, {
  4651. method: 'POST',
  4652. headers: { 'Content-Type': 'application/json' },
  4653. body: JSON.stringify(payload)
  4654. });
  4655. if (res.ok) {
  4656. closeOspfInterfaceModal();
  4657. showToast('Success', 'OSPF interface template saved', 'success');
  4658. loadDynamicRouting();
  4659. } else {
  4660. const err = await res.json();
  4661. showToast('Error', err.error || 'Failed to save interface', 'error');
  4662. }
  4663. } catch (err) {
  4664. showToast('Error', err.message, 'error');
  4665. }
  4666. }
  4667. async function deleteOspfInterface(id) {
  4668. if (!confirm('Are you sure you want to delete this OSPF interface?')) return;
  4669. try {
  4670. const res = await fetch(`${API_BASE}/routing/ospf/interfaces/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4671. if (res.ok) {
  4672. showToast('Deleted', 'OSPF interface removed', 'success');
  4673. loadDynamicRouting();
  4674. }
  4675. } catch (err) {
  4676. showToast('Error', err.message, 'error');
  4677. }
  4678. }
  4679. async function toggleOspfInterfaceState(id, disabled) {
  4680. try {
  4681. const res = await fetch(`${API_BASE}/routing/ospf/interfaces/${encodeURIComponent(id)}/state`, {
  4682. method: 'POST',
  4683. headers: { 'Content-Type': 'application/json' },
  4684. body: JSON.stringify({ disabled })
  4685. });
  4686. if (res.ok) {
  4687. showToast('Updated', `Interface ${disabled ? 'disabled' : 'enabled'}`, 'success');
  4688. loadDynamicRouting();
  4689. }
  4690. } catch (err) {
  4691. showToast('Error', err.message, 'error');
  4692. }
  4693. }