app.js 234 KB

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