app.js 235 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630
  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. } catch (err) {
  2011. console.error('Failed to load firewall:', err);
  2012. }
  2013. }
  2014. // ----------------- Filter Rules -----------------
  2015. function renderFilterRules() {
  2016. const chainFilter = document.getElementById('filter-filter-chain')?.value || '';
  2017. const tbody = document.getElementById('filter-table-body');
  2018. const empty = document.getElementById('filter-empty');
  2019. if (!tbody) return;
  2020. tbody.innerHTML = '';
  2021. const rules = (state.filterRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  2022. document.getElementById('filter-count-badge').innerText = `${rules.length} Rules`;
  2023. if (rules.length === 0) {
  2024. empty?.classList.remove('hidden');
  2025. return;
  2026. }
  2027. empty?.classList.add('hidden');
  2028. rules.forEach((r, idx) => {
  2029. const tr = document.createElement('tr');
  2030. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  2031. const ports = [r.src_port ? 's:' + r.src_port : '', r.dst_port ? 'd:' + r.dst_port : ''].filter(Boolean).join(' ');
  2032. const ifaces = [r.in_interface ? 'in:' + r.in_interface : '', r.out_interface ? 'out:' + r.out_interface : ''].filter(Boolean).join(' ');
  2033. tr.innerHTML = `
  2034. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  2035. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  2036. <td class="py-2.5 px-3 font-bold text-white">${r.chain}</td>
  2037. <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>
  2038. <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>
  2039. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}</td>
  2040. <td class="py-2.5 px-3 text-amber-400">${ports || '-'}</td>
  2041. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  2042. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  2043. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  2044. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  2045. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  2046. </td>
  2047. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  2048. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  2049. <button onclick="moveFilterRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  2050. <button onclick="moveFilterRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  2051. <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>
  2052. <button onclick="openEditFilterModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2053. <button onclick="deleteFilterRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2054. </td>
  2055. `;
  2056. tbody.appendChild(tr);
  2057. });
  2058. }
  2059. function populateInterfaceSelect(selectId, currentVal = '') {
  2060. const sel = document.getElementById(selectId);
  2061. if (!sel) return;
  2062. sel.innerHTML = '<option value="">(Any Interface)</option>';
  2063. (state.interfaces || []).forEach(i => {
  2064. const opt = document.createElement('option');
  2065. opt.value = i.name;
  2066. opt.innerText = `${i.name} (${i.role || i.type})`;
  2067. if (i.name === currentVal) opt.selected = true;
  2068. sel.appendChild(opt);
  2069. });
  2070. }
  2071. function populateAddressListSelect(selectId, currentVal = '') {
  2072. const sel = document.getElementById(selectId);
  2073. if (!sel) return;
  2074. sel.innerHTML = '<option value="">(None)</option>';
  2075. const cleanVal = currentVal.startsWith('!') ? currentVal.substring(1) : currentVal;
  2076. // 1. Custom Address Lists
  2077. const customNames = Array.from(new Set((state.addressLists || []).map(a => a.name))).sort();
  2078. if (customNames.length > 0) {
  2079. const optgroup = document.createElement('optgroup');
  2080. optgroup.label = 'Custom Address Lists';
  2081. customNames.forEach(name => {
  2082. const count = (state.addressLists || []).filter(a => a.name === name).length;
  2083. const opt = document.createElement('option');
  2084. opt.value = name;
  2085. opt.innerText = `${name} (${count} entries)`;
  2086. if (name === cleanVal) opt.selected = true;
  2087. optgroup.appendChild(opt);
  2088. });
  2089. sel.appendChild(optgroup);
  2090. }
  2091. // 2. Enabled Geo-Location Countries
  2092. const geoCountries = (state.geoCountries || []).filter(c => c.enabled);
  2093. if (geoCountries.length > 0) {
  2094. const optgroup = document.createElement('optgroup');
  2095. optgroup.label = '🌍 Geo-Location Countries';
  2096. geoCountries.forEach(c => {
  2097. const val = `geo:${c.code}`;
  2098. const opt = document.createElement('option');
  2099. opt.value = val;
  2100. opt.innerText = `${c.name} (${c.code}) - ${c.subnet_count.toLocaleString()} subnets`;
  2101. if (val === cleanVal || `geo_${c.code}` === cleanVal) opt.selected = true;
  2102. optgroup.appendChild(opt);
  2103. });
  2104. sel.appendChild(optgroup);
  2105. }
  2106. // Fallback: If cleanVal is set but not in list, add it as custom option
  2107. if (cleanVal && !sel.querySelector(`option[value="${cleanVal}"]`)) {
  2108. const opt = document.createElement('option');
  2109. opt.value = cleanVal;
  2110. opt.innerText = cleanVal;
  2111. opt.selected = true;
  2112. sel.appendChild(opt);
  2113. }
  2114. }
  2115. function openAddFilterModal() {
  2116. document.getElementById('filter-modal-title').innerText = 'Add Firewall Filter Rule';
  2117. document.getElementById('filter-modal-id').value = '';
  2118. document.getElementById('filter-modal-chain').value = 'forward';
  2119. document.getElementById('filter-modal-action').value = 'accept';
  2120. document.getElementById('filter-modal-proto').value = 'all';
  2121. document.getElementById('filter-modal-src').value = '';
  2122. document.getElementById('filter-modal-dst').value = '';
  2123. document.getElementById('filter-modal-sport').value = '';
  2124. document.getElementById('filter-modal-dport').value = '';
  2125. document.getElementById('filter-modal-connmark').value = '';
  2126. document.getElementById('filter-modal-comment').value = '';
  2127. document.getElementById('filter-modal-disabled').checked = false;
  2128. document.getElementById('filter-modal-cs-established').checked = false;
  2129. document.getElementById('filter-modal-cs-related').checked = false;
  2130. document.getElementById('filter-modal-cs-new').checked = false;
  2131. document.getElementById('filter-modal-cs-invalid').checked = false;
  2132. populateInterfaceSelect('filter-modal-iniface');
  2133. populateInterfaceSelect('filter-modal-outiface');
  2134. populateAddressListSelect('filter-modal-srclist');
  2135. populateAddressListSelect('filter-modal-dstlist');
  2136. toggleFilterActionFields();
  2137. document.getElementById('filter-modal').classList.remove('hidden');
  2138. }
  2139. function openEditFilterModal(id) {
  2140. const r = (state.filterRules || []).find(rule => rule.id === id);
  2141. if (!r) return;
  2142. document.getElementById('filter-modal-title').innerText = `Edit Filter Rule (#${r.order})`;
  2143. document.getElementById('filter-modal-id').value = r.id;
  2144. document.getElementById('filter-modal-chain').value = r.chain || 'forward';
  2145. document.getElementById('filter-modal-action').value = r.action || 'accept';
  2146. document.getElementById('filter-modal-proto').value = r.protocol || 'all';
  2147. document.getElementById('filter-modal-src').value = r.src_address || '';
  2148. document.getElementById('filter-modal-dst').value = r.dst_address || '';
  2149. document.getElementById('filter-modal-sport').value = r.src_port || '';
  2150. document.getElementById('filter-modal-dport').value = r.dst_port || '';
  2151. document.getElementById('filter-modal-connmark').value = r.connection_mark || '';
  2152. document.getElementById('filter-modal-comment').value = r.comment || '';
  2153. document.getElementById('filter-modal-disabled').checked = !!r.disabled;
  2154. const states = r.connection_state || [];
  2155. document.getElementById('filter-modal-cs-established').checked = states.includes('established');
  2156. document.getElementById('filter-modal-cs-related').checked = states.includes('related');
  2157. document.getElementById('filter-modal-cs-new').checked = states.includes('new');
  2158. document.getElementById('filter-modal-cs-invalid').checked = states.includes('invalid');
  2159. populateInterfaceSelect('filter-modal-iniface', r.in_interface);
  2160. populateInterfaceSelect('filter-modal-outiface', r.out_interface);
  2161. populateAddressListSelect('filter-modal-srclist', r.src_address_list);
  2162. populateAddressListSelect('filter-modal-dstlist', r.dst_address_list);
  2163. toggleFilterActionFields();
  2164. document.getElementById('filter-modal').classList.remove('hidden');
  2165. }
  2166. function closeFilterModal() {
  2167. document.getElementById('filter-modal').classList.add('hidden');
  2168. }
  2169. function toggleFilterActionFields() {
  2170. const act = document.getElementById('filter-modal-action').value;
  2171. const rejectBox = document.getElementById('filter-action-reject-box');
  2172. if (rejectBox) {
  2173. if (act === 'reject') rejectBox.classList.remove('hidden');
  2174. else rejectBox.classList.add('hidden');
  2175. }
  2176. }
  2177. async function submitSaveFilterRule(e) {
  2178. e.preventDefault();
  2179. const id = document.getElementById('filter-modal-id').value;
  2180. const chain = document.getElementById('filter-modal-chain').value;
  2181. const action = document.getElementById('filter-modal-action').value;
  2182. const proto = document.getElementById('filter-modal-proto').value;
  2183. const src = document.getElementById('filter-modal-src').value.trim();
  2184. const dst = document.getElementById('filter-modal-dst').value.trim();
  2185. const sport = document.getElementById('filter-modal-sport').value.trim();
  2186. const dport = document.getElementById('filter-modal-dport').value.trim();
  2187. const inIface = document.getElementById('filter-modal-iniface').value;
  2188. const outIface = document.getElementById('filter-modal-outiface').value;
  2189. const connmark = document.getElementById('filter-modal-connmark').value.trim();
  2190. const srclist = document.getElementById('filter-modal-srclist').value;
  2191. const dstlist = document.getElementById('filter-modal-dstlist').value;
  2192. const comment = document.getElementById('filter-modal-comment').value.trim();
  2193. const disabled = document.getElementById('filter-modal-disabled').checked;
  2194. const rejectWith = document.getElementById('filter-modal-rejectwith')?.value || '';
  2195. const states = [];
  2196. if (document.getElementById('filter-modal-cs-established').checked) states.push('established');
  2197. if (document.getElementById('filter-modal-cs-related').checked) states.push('related');
  2198. if (document.getElementById('filter-modal-cs-new').checked) states.push('new');
  2199. if (document.getElementById('filter-modal-cs-invalid').checked) states.push('invalid');
  2200. try {
  2201. const res = await fetch(`${API_BASE}/firewall/filter`, {
  2202. method: 'POST',
  2203. headers: { 'Content-Type': 'application/json' },
  2204. body: JSON.stringify({
  2205. id,
  2206. chain,
  2207. action,
  2208. reject_with: rejectWith,
  2209. protocol: proto,
  2210. src_address: src,
  2211. dst_address: dst,
  2212. src_port: sport,
  2213. dst_port: dport,
  2214. in_interface: inIface,
  2215. out_interface: outIface,
  2216. connection_state: states,
  2217. connection_mark: connmark,
  2218. src_address_list: srclist,
  2219. dst_address_list: dstlist,
  2220. comment,
  2221. disabled
  2222. })
  2223. });
  2224. if (res.ok) {
  2225. showToast('Filter Rule Saved', 'Rule applied successfully to firewall', 'success');
  2226. closeFilterModal();
  2227. loadFirewall(false);
  2228. } else {
  2229. const err = await res.json();
  2230. showToast('Error', err.message, 'error');
  2231. }
  2232. } catch (err) {
  2233. showToast('Error', err.message, 'error');
  2234. }
  2235. }
  2236. async function moveFilterRule(id, dir) {
  2237. try {
  2238. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/move`, {
  2239. method: 'POST',
  2240. headers: { 'Content-Type': 'application/json' },
  2241. body: JSON.stringify({ direction: dir })
  2242. });
  2243. if (res.ok) loadFirewall(false);
  2244. } catch (err) {
  2245. showToast('Error', err.message, 'error');
  2246. }
  2247. }
  2248. async function toggleFilterRuleState(id, disabled) {
  2249. try {
  2250. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/state`, {
  2251. method: 'POST',
  2252. headers: { 'Content-Type': 'application/json' },
  2253. body: JSON.stringify({ disabled })
  2254. });
  2255. if (res.ok) loadFirewall(false);
  2256. } catch (err) {
  2257. showToast('Error', err.message, 'error');
  2258. }
  2259. }
  2260. async function deleteFilterRule(id) {
  2261. if (!confirm('Are you sure you want to delete this filter rule?')) return;
  2262. try {
  2263. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}`, { method: 'DELETE' });
  2264. if (res.ok) {
  2265. showToast('Deleted', 'Filter rule removed', 'success');
  2266. loadFirewall(false);
  2267. }
  2268. } catch (err) {
  2269. showToast('Error', err.message, 'error');
  2270. }
  2271. }
  2272. // ----------------- NAT Rules -----------------
  2273. function renderNATRules() {
  2274. const chainFilter = document.getElementById('nat-filter-chain')?.value || '';
  2275. const tbody = document.getElementById('nat-table-body');
  2276. const empty = document.getElementById('nat-empty');
  2277. if (!tbody) return;
  2278. tbody.innerHTML = '';
  2279. const rules = (state.natRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  2280. document.getElementById('nat-count-badge').innerText = `${rules.length} Rules`;
  2281. if (rules.length === 0) {
  2282. empty?.classList.remove('hidden');
  2283. return;
  2284. }
  2285. empty?.classList.add('hidden');
  2286. rules.forEach((r, idx) => {
  2287. const tr = document.createElement('tr');
  2288. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  2289. const toTarget = [r.to_addresses, r.to_ports].filter(Boolean).join(':');
  2290. const ifaces = [r.out_interface ? 'out:' + r.out_interface : '', r.in_interface ? 'in:' + r.in_interface : ''].filter(Boolean).join(' ');
  2291. tr.innerHTML = `
  2292. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  2293. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  2294. <td class="py-2.5 px-3 font-bold text-amber-400">${r.chain}</td>
  2295. <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>
  2296. <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>
  2297. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}${r.dst_port ? ':' + r.dst_port : ''}</td>
  2298. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  2299. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  2300. <td class="py-2.5 px-3 font-mono font-bold text-amber-300">${toTarget || '-'}</td>
  2301. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  2302. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  2303. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  2304. </td>
  2305. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  2306. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  2307. <button onclick="moveNATRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  2308. <button onclick="moveNATRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  2309. <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>
  2310. <button onclick="openEditNATModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2311. <button onclick="deleteNATRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2312. </td>
  2313. `;
  2314. tbody.appendChild(tr);
  2315. });
  2316. }
  2317. function openAddNATModal() {
  2318. document.getElementById('nat-modal-title').innerText = 'Add NAT Rule';
  2319. document.getElementById('nat-modal-id').value = '';
  2320. document.getElementById('nat-modal-chain').value = 'srcnat';
  2321. document.getElementById('nat-modal-action').value = 'masquerade';
  2322. document.getElementById('nat-modal-toaddr').value = '';
  2323. document.getElementById('nat-modal-toport').value = '';
  2324. document.getElementById('nat-modal-proto').value = 'all';
  2325. document.getElementById('nat-modal-src').value = '';
  2326. document.getElementById('nat-modal-dst').value = '';
  2327. document.getElementById('nat-modal-dport').value = '';
  2328. document.getElementById('nat-modal-comment').value = '';
  2329. document.getElementById('nat-modal-disabled').checked = false;
  2330. populateInterfaceSelect('nat-modal-iniface');
  2331. populateInterfaceSelect('nat-modal-outiface');
  2332. populateAddressListSelect('nat-modal-srclist');
  2333. populateAddressListSelect('nat-modal-dstlist');
  2334. const srcInvEl = document.getElementById('nat-modal-srclist-inv');
  2335. if (srcInvEl) srcInvEl.checked = false;
  2336. const dstInvEl = document.getElementById('nat-modal-dstlist-inv');
  2337. if (dstInvEl) dstInvEl.checked = false;
  2338. toggleNATActionFields();
  2339. document.getElementById('nat-modal').classList.remove('hidden');
  2340. }
  2341. function openEditNATModal(id) {
  2342. const r = (state.natRules || []).find(rule => rule.id === id);
  2343. if (!r) return;
  2344. document.getElementById('nat-modal-title').innerText = `Edit NAT Rule (#${r.order})`;
  2345. document.getElementById('nat-modal-id').value = r.id;
  2346. document.getElementById('nat-modal-chain').value = r.chain || 'srcnat';
  2347. document.getElementById('nat-modal-action').value = r.action || 'masquerade';
  2348. document.getElementById('nat-modal-toaddr').value = r.to_addresses || '';
  2349. document.getElementById('nat-modal-toport').value = r.to_ports || '';
  2350. document.getElementById('nat-modal-proto').value = r.protocol || 'all';
  2351. document.getElementById('nat-modal-src').value = r.src_address || '';
  2352. document.getElementById('nat-modal-dst').value = r.dst_address || '';
  2353. document.getElementById('nat-modal-dport').value = r.dst_port || '';
  2354. document.getElementById('nat-modal-comment').value = r.comment || '';
  2355. document.getElementById('nat-modal-disabled').checked = !!r.disabled;
  2356. populateInterfaceSelect('nat-modal-iniface', r.in_interface);
  2357. populateInterfaceSelect('nat-modal-outiface', r.out_interface);
  2358. const srcInv = (r.src_address_list || '').startsWith('!');
  2359. const dstInv = (r.dst_address_list || '').startsWith('!');
  2360. const srcInvEl = document.getElementById('nat-modal-srclist-inv');
  2361. if (srcInvEl) srcInvEl.checked = srcInv;
  2362. const dstInvEl = document.getElementById('nat-modal-dstlist-inv');
  2363. if (dstInvEl) dstInvEl.checked = dstInv;
  2364. populateAddressListSelect('nat-modal-srclist', r.src_address_list || '');
  2365. populateAddressListSelect('nat-modal-dstlist', r.dst_address_list || '');
  2366. toggleNATActionFields();
  2367. document.getElementById('nat-modal').classList.remove('hidden');
  2368. }
  2369. function closeNATModal() {
  2370. document.getElementById('nat-modal').classList.add('hidden');
  2371. }
  2372. function toggleNATChainFields() {
  2373. const ch = document.getElementById('nat-modal-chain').value;
  2374. const actSel = document.getElementById('nat-modal-action');
  2375. if (ch === 'srcnat' && actSel.value === 'dst-nat') {
  2376. actSel.value = 'masquerade';
  2377. } else if (ch === 'dstnat' && actSel.value === 'masquerade') {
  2378. actSel.value = 'dst-nat';
  2379. }
  2380. toggleNATActionFields();
  2381. }
  2382. function toggleNATActionFields() {
  2383. const act = document.getElementById('nat-modal-action').value;
  2384. const toBox = document.getElementById('nat-action-to-box');
  2385. if (toBox) {
  2386. if (act === 'masquerade' || act === 'accept') toBox.classList.add('hidden');
  2387. else toBox.classList.remove('hidden');
  2388. }
  2389. }
  2390. async function submitSaveNATRule(e) {
  2391. e.preventDefault();
  2392. const id = document.getElementById('nat-modal-id').value;
  2393. const chain = document.getElementById('nat-modal-chain').value;
  2394. const action = document.getElementById('nat-modal-action').value;
  2395. const toaddr = document.getElementById('nat-modal-toaddr').value.trim();
  2396. const toport = document.getElementById('nat-modal-toport').value.trim();
  2397. const proto = document.getElementById('nat-modal-proto').value;
  2398. const src = document.getElementById('nat-modal-src').value.trim();
  2399. const dst = document.getElementById('nat-modal-dst').value.trim();
  2400. const dport = document.getElementById('nat-modal-dport').value.trim();
  2401. const inIface = document.getElementById('nat-modal-iniface').value;
  2402. const outIface = document.getElementById('nat-modal-outiface').value;
  2403. let srclist = document.getElementById('nat-modal-srclist')?.value || '';
  2404. if (srclist && document.getElementById('nat-modal-srclist-inv')?.checked) {
  2405. srclist = '!' + srclist.replace(/^!/, '');
  2406. }
  2407. let dstlist = document.getElementById('nat-modal-dstlist')?.value || '';
  2408. if (dstlist && document.getElementById('nat-modal-dstlist-inv')?.checked) {
  2409. dstlist = '!' + dstlist.replace(/^!/, '');
  2410. }
  2411. const comment = document.getElementById('nat-modal-comment').value.trim();
  2412. const disabled = document.getElementById('nat-modal-disabled').checked;
  2413. try {
  2414. const res = await fetch(`${API_BASE}/firewall/nat`, {
  2415. method: 'POST',
  2416. headers: { 'Content-Type': 'application/json' },
  2417. body: JSON.stringify({
  2418. id,
  2419. chain,
  2420. action,
  2421. to_addresses: toaddr,
  2422. to_ports: toport,
  2423. protocol: proto,
  2424. src_address: src,
  2425. dst_address: dst,
  2426. dst_port: dport,
  2427. in_interface: inIface,
  2428. out_interface: outIface,
  2429. src_address_list: srclist,
  2430. dst_address_list: dstlist,
  2431. comment,
  2432. disabled
  2433. })
  2434. });
  2435. id,
  2436. chain,
  2437. action,
  2438. to_addresses: toaddr,
  2439. to_ports: toport,
  2440. protocol: proto,
  2441. src_address: src,
  2442. dst_address: dst,
  2443. dst_port: dport,
  2444. in_interface: inIface,
  2445. out_interface: outIface,
  2446. comment,
  2447. disabled
  2448. })
  2449. });
  2450. if (res.ok) {
  2451. showToast('NAT Rule Saved', 'NAT mapping updated', 'success');
  2452. closeNATModal();
  2453. loadFirewall(false);
  2454. }
  2455. } catch (err) {
  2456. showToast('Error', err.message, 'error');
  2457. }
  2458. }
  2459. async function moveNATRule(id, dir) {
  2460. try {
  2461. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/move`, {
  2462. method: 'POST',
  2463. headers: { 'Content-Type': 'application/json' },
  2464. body: JSON.stringify({ direction: dir })
  2465. });
  2466. if (res.ok) loadFirewall(false);
  2467. } catch (err) {
  2468. showToast('Error', err.message, 'error');
  2469. }
  2470. }
  2471. async function toggleNATRuleState(id, disabled) {
  2472. try {
  2473. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/state`, {
  2474. method: 'POST',
  2475. headers: { 'Content-Type': 'application/json' },
  2476. body: JSON.stringify({ disabled })
  2477. });
  2478. if (res.ok) loadFirewall(false);
  2479. } catch (err) {
  2480. showToast('Error', err.message, 'error');
  2481. }
  2482. }
  2483. async function deleteNATRule(id) {
  2484. if (!confirm('Are you sure you want to delete this NAT rule?')) return;
  2485. try {
  2486. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}`, { method: 'DELETE' });
  2487. if (res.ok) {
  2488. showToast('Deleted', 'NAT rule removed', 'success');
  2489. loadFirewall(false);
  2490. }
  2491. } catch (err) {
  2492. showToast('Error', err.message, 'error');
  2493. }
  2494. }
  2495. // ----------------- Mangle Rules -----------------
  2496. function renderMangleRules() {
  2497. const chainFilter = document.getElementById('mangle-filter-chain')?.value || '';
  2498. const tbody = document.getElementById('mangle-table-body');
  2499. const empty = document.getElementById('mangle-empty');
  2500. if (!tbody) return;
  2501. tbody.innerHTML = '';
  2502. const rules = (state.mangleRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  2503. document.getElementById('mangle-count-badge').innerText = `${rules.length} Rules`;
  2504. if (rules.length === 0) {
  2505. empty?.classList.remove('hidden');
  2506. return;
  2507. }
  2508. empty?.classList.add('hidden');
  2509. rules.forEach((r, idx) => {
  2510. const tr = document.createElement('tr');
  2511. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  2512. const markVal = r.new_connection_mark || r.new_routing_mark || r.new_packet_mark || r.new_mss || (r.new_dscp ? 'DSCP:' + r.new_dscp : '');
  2513. tr.innerHTML = `
  2514. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  2515. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  2516. <td class="py-2.5 px-3 font-bold text-purple-400">${r.chain}</td>
  2517. <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>
  2518. <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>
  2519. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  2520. <td class="py-2.5 px-3 font-mono font-bold text-cyan-300">${markVal || '-'}</td>
  2521. <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>
  2522. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  2523. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  2524. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  2525. </td>
  2526. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  2527. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  2528. <button onclick="moveMangleRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  2529. <button onclick="moveMangleRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  2530. <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>
  2531. <button onclick="openEditMangleModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2532. <button onclick="deleteMangleRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2533. </td>
  2534. `;
  2535. tbody.appendChild(tr);
  2536. });
  2537. }
  2538. function openAddMangleModal() {
  2539. document.getElementById('mangle-modal-title').innerText = 'Add Mangle Rule';
  2540. document.getElementById('mangle-modal-id').value = '';
  2541. document.getElementById('mangle-modal-chain').value = 'prerouting';
  2542. document.getElementById('mangle-modal-action').value = 'mark-connection';
  2543. document.getElementById('mangle-modal-newmark').value = '';
  2544. document.getElementById('mangle-modal-passthrough').checked = true;
  2545. document.getElementById('mangle-modal-src').value = '';
  2546. document.getElementById('mangle-modal-dst').value = '';
  2547. document.getElementById('mangle-modal-connmark').value = '';
  2548. document.getElementById('mangle-modal-comment').value = '';
  2549. document.getElementById('mangle-modal-disabled').checked = false;
  2550. populateInterfaceSelect('mangle-modal-iniface');
  2551. populateAddressListSelect('mangle-modal-srclist');
  2552. populateAddressListSelect('mangle-modal-dstlist');
  2553. const srcInvEl = document.getElementById('mangle-modal-srclist-inv');
  2554. if (srcInvEl) srcInvEl.checked = false;
  2555. const dstInvEl = document.getElementById('mangle-modal-dstlist-inv');
  2556. if (dstInvEl) dstInvEl.checked = false;
  2557. document.getElementById('mangle-modal').classList.remove('hidden');
  2558. }
  2559. function openEditMangleModal(id) {
  2560. const r = (state.mangleRules || []).find(rule => rule.id === id);
  2561. if (!r) return;
  2562. document.getElementById('mangle-modal-title').innerText = `Edit Mangle Rule (#${r.order})`;
  2563. document.getElementById('mangle-modal-id').value = r.id;
  2564. document.getElementById('mangle-modal-chain').value = r.chain || 'prerouting';
  2565. document.getElementById('mangle-modal-action').value = r.action || 'mark-connection';
  2566. document.getElementById('mangle-modal-newmark').value = r.new_connection_mark || r.new_routing_mark || r.new_packet_mark || r.new_mss || '';
  2567. document.getElementById('mangle-modal-passthrough').checked = r.passthrough ?? true;
  2568. document.getElementById('mangle-modal-src').value = r.src_address || '';
  2569. document.getElementById('mangle-modal-dst').value = r.dst_address || '';
  2570. document.getElementById('mangle-modal-connmark').value = r.connection_mark || '';
  2571. document.getElementById('mangle-modal-comment').value = r.comment || '';
  2572. document.getElementById('mangle-modal-disabled').checked = !!r.disabled;
  2573. populateInterfaceSelect('mangle-modal-iniface', r.in_interface);
  2574. const srcInv = (r.src_address_list || '').startsWith('!');
  2575. const dstInv = (r.dst_address_list || '').startsWith('!');
  2576. const srcInvEl = document.getElementById('mangle-modal-srclist-inv');
  2577. if (srcInvEl) srcInvEl.checked = srcInv;
  2578. const dstInvEl = document.getElementById('mangle-modal-dstlist-inv');
  2579. if (dstInvEl) dstInvEl.checked = dstInv;
  2580. populateAddressListSelect('mangle-modal-srclist', r.src_address_list || '');
  2581. populateAddressListSelect('mangle-modal-dstlist', r.dst_address_list || '');
  2582. document.getElementById('mangle-modal').classList.remove('hidden');
  2583. }
  2584. function closeMangleModal() {
  2585. document.getElementById('mangle-modal').classList.add('hidden');
  2586. }
  2587. function toggleMangleActionFields() {
  2588. // Handled smoothly by single dynamic input
  2589. }
  2590. async function submitSaveMangleRule(e) {
  2591. e.preventDefault();
  2592. const id = document.getElementById('mangle-modal-id').value;
  2593. const chain = document.getElementById('mangle-modal-chain').value;
  2594. const action = document.getElementById('mangle-modal-action').value;
  2595. const newmark = document.getElementById('mangle-modal-newmark').value.trim();
  2596. const passthrough = document.getElementById('mangle-modal-passthrough').checked;
  2597. const src = document.getElementById('mangle-modal-src').value.trim();
  2598. const dst = document.getElementById('mangle-modal-dst').value.trim();
  2599. const inIface = document.getElementById('mangle-modal-iniface').value;
  2600. let srclist = document.getElementById('mangle-modal-srclist')?.value || '';
  2601. if (srclist && document.getElementById('mangle-modal-srclist-inv')?.checked) {
  2602. srclist = '!' + srclist.replace(/^!/, '');
  2603. }
  2604. let dstlist = document.getElementById('mangle-modal-dstlist')?.value || '';
  2605. if (dstlist && document.getElementById('mangle-modal-dstlist-inv')?.checked) {
  2606. dstlist = '!' + dstlist.replace(/^!/, '');
  2607. }
  2608. const connmark = document.getElementById('mangle-modal-connmark').value.trim();
  2609. const comment = document.getElementById('mangle-modal-comment').value.trim();
  2610. const disabled = document.getElementById('mangle-modal-disabled').checked;
  2611. const payload = {
  2612. id,
  2613. chain,
  2614. action,
  2615. passthrough,
  2616. src_address: src,
  2617. dst_address: dst,
  2618. in_interface: inIface,
  2619. src_address_list: srclist,
  2620. dst_address_list: dstlist,
  2621. connection_mark: connmark,
  2622. comment,
  2623. disabled
  2624. };
  2625. if (action === 'mark-connection') payload.new_connection_mark = newmark;
  2626. else if (action === 'mark-routing') payload.new_routing_mark = newmark;
  2627. else if (action === 'mark-packet') payload.new_packet_mark = newmark;
  2628. else if (action === 'change-mss') payload.new_mss = newmark || 'clamp-to-pmtu';
  2629. try {
  2630. const res = await fetch(`${API_BASE}/firewall/mangle`, {
  2631. method: 'POST',
  2632. headers: { 'Content-Type': 'application/json' },
  2633. body: JSON.stringify(payload)
  2634. });
  2635. if (res.ok) {
  2636. showToast('Mangle Rule Saved', 'Marking rule applied', 'success');
  2637. closeMangleModal();
  2638. loadFirewall(false);
  2639. }
  2640. } catch (err) {
  2641. showToast('Error', err.message, 'error');
  2642. }
  2643. }
  2644. async function moveMangleRule(id, dir) {
  2645. try {
  2646. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/move`, {
  2647. method: 'POST',
  2648. headers: { 'Content-Type': 'application/json' },
  2649. body: JSON.stringify({ direction: dir })
  2650. });
  2651. if (res.ok) loadFirewall(false);
  2652. } catch (err) {
  2653. showToast('Error', err.message, 'error');
  2654. }
  2655. }
  2656. async function toggleMangleRuleState(id, disabled) {
  2657. try {
  2658. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/state`, {
  2659. method: 'POST',
  2660. headers: { 'Content-Type': 'application/json' },
  2661. body: JSON.stringify({ disabled })
  2662. });
  2663. if (res.ok) loadFirewall(false);
  2664. } catch (err) {
  2665. showToast('Error', err.message, 'error');
  2666. }
  2667. }
  2668. async function deleteMangleRule(id) {
  2669. if (!confirm('Are you sure you want to delete this mangle rule?')) return;
  2670. try {
  2671. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}`, { method: 'DELETE' });
  2672. if (res.ok) {
  2673. showToast('Deleted', 'Mangle rule removed', 'success');
  2674. loadFirewall(false);
  2675. }
  2676. } catch (err) {
  2677. showToast('Error', err.message, 'error');
  2678. }
  2679. }
  2680. // ----------------- Address Lists -----------------
  2681. function renderAddressLists() {
  2682. const filterList = document.getElementById('addrlist-filter-name')?.value || '';
  2683. const tbody = document.getElementById('addrlist-table-body');
  2684. const empty = document.getElementById('addrlist-empty');
  2685. if (!tbody) return;
  2686. tbody.innerHTML = '';
  2687. const entries = (state.addressLists || []).filter(e => !filterList || e.name === filterList);
  2688. document.getElementById('addrlist-count-badge').innerText = `${entries.length} Entries`;
  2689. // Update filter select
  2690. const sel = document.getElementById('addrlist-filter-name');
  2691. if (sel) {
  2692. const cur = sel.value;
  2693. sel.innerHTML = '<option value="">All Lists</option>';
  2694. const set = new Set((state.addressLists || []).map(a => a.name));
  2695. set.forEach(n => {
  2696. const opt = document.createElement('option');
  2697. opt.value = n;
  2698. opt.innerText = n;
  2699. if (n === cur) opt.selected = true;
  2700. sel.appendChild(opt);
  2701. });
  2702. }
  2703. if (entries.length === 0) {
  2704. empty?.classList.remove('hidden');
  2705. return;
  2706. }
  2707. empty?.classList.add('hidden');
  2708. entries.forEach((e, idx) => {
  2709. const tr = document.createElement('tr');
  2710. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${e.disabled ? 'opacity-50' : ''}`;
  2711. tr.setAttribute('ondblclick', `openEditAddrListModal('${e.id}')`);
  2712. tr.innerHTML = `
  2713. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  2714. <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>
  2715. <td class="py-2.5 px-3 font-bold text-white font-mono">${e.name}</td>
  2716. <td class="py-2.5 px-3 font-mono font-bold text-emerald-400">${e.address}</td>
  2717. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[150px]">${e.comment || '-'}</td>
  2718. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  2719. <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>
  2720. <button onclick="openEditAddrListModal('${e.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-medium">Edit</button>
  2721. <button onclick="deleteAddrList('${e.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2722. </td>
  2723. `;
  2724. tbody.appendChild(tr);
  2725. });
  2726. }
  2727. function openAddAddrListModal() {
  2728. document.getElementById('addrlist-modal-title').innerText = 'Add Address List Entry';
  2729. document.getElementById('addrlist-modal-id').value = '';
  2730. document.getElementById('addrlist-modal-name').value = '';
  2731. document.getElementById('addrlist-modal-addr').value = '';
  2732. document.getElementById('addrlist-modal-comment').value = '';
  2733. document.getElementById('addrlist-modal-disabled').checked = false;
  2734. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  2735. if (submitBtn) submitBtn.innerText = 'Add to List';
  2736. document.getElementById('addrlist-modal').classList.remove('hidden');
  2737. }
  2738. function openEditAddrListModal(id) {
  2739. const e = (state.addressLists || []).find(item => item.id === id);
  2740. if (!e) return;
  2741. document.getElementById('addrlist-modal-title').innerText = `Edit Address List Entry: ${e.name}`;
  2742. document.getElementById('addrlist-modal-id').value = e.id;
  2743. document.getElementById('addrlist-modal-name').value = e.name;
  2744. document.getElementById('addrlist-modal-addr').value = e.address;
  2745. document.getElementById('addrlist-modal-comment').value = e.comment || '';
  2746. document.getElementById('addrlist-modal-disabled').checked = !!e.disabled;
  2747. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  2748. if (submitBtn) submitBtn.innerText = 'Save Changes';
  2749. document.getElementById('addrlist-modal').classList.remove('hidden');
  2750. }
  2751. function closeAddrListModal() {
  2752. document.getElementById('addrlist-modal').classList.add('hidden');
  2753. }
  2754. async function submitSaveAddrList(e) {
  2755. e.preventDefault();
  2756. const id = document.getElementById('addrlist-modal-id').value;
  2757. const name = document.getElementById('addrlist-modal-name').value.trim();
  2758. const addr = document.getElementById('addrlist-modal-addr').value.trim();
  2759. const comment = document.getElementById('addrlist-modal-comment').value.trim();
  2760. const disabled = document.getElementById('addrlist-modal-disabled').checked;
  2761. try {
  2762. const res = await fetch(`${API_BASE}/firewall/address-lists`, {
  2763. method: 'POST',
  2764. headers: { 'Content-Type': 'application/json' },
  2765. body: JSON.stringify({ id, name, address: addr, comment, disabled })
  2766. });
  2767. if (res.ok) {
  2768. showToast('Address List Item Saved', `Saved ${addr} in ${name}`, 'success');
  2769. closeAddrListModal();
  2770. loadFirewall(false);
  2771. } else {
  2772. const err = await res.json();
  2773. showToast('Error', err.message || 'Failed to save address list', 'error');
  2774. }
  2775. } catch (err) {
  2776. showToast('Error', err.message, 'error');
  2777. }
  2778. }
  2779. async function toggleAddrListState(id, disabled) {
  2780. try {
  2781. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}/state`, {
  2782. method: 'POST',
  2783. headers: { 'Content-Type': 'application/json' },
  2784. body: JSON.stringify({ disabled })
  2785. });
  2786. if (res.ok) {
  2787. loadFirewall(false);
  2788. }
  2789. } catch (err) {
  2790. showToast('Error', err.message, 'error');
  2791. }
  2792. }
  2793. async function deleteAddrList(id) {
  2794. if (!confirm('Are you sure you want to delete this address list item?')) return;
  2795. try {
  2796. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  2797. if (res.ok) {
  2798. showToast('Deleted', 'Address list item removed', 'info');
  2799. loadFirewall(false);
  2800. }
  2801. } catch (err) {
  2802. showToast('Error', err.message, 'error');
  2803. }
  2804. }
  2805. // ----------------- Geo-Location IP Management -----------------
  2806. async function loadGeoIP() {
  2807. try {
  2808. const [statusRes, countriesRes] = await Promise.all([
  2809. fetch(`${API_BASE}/firewall/geoip/status`),
  2810. fetch(`${API_BASE}/firewall/geoip/countries`)
  2811. ]);
  2812. if (statusRes.ok) state.geoStatus = await statusRes.json();
  2813. if (countriesRes.ok) state.geoCountries = await countriesRes.json();
  2814. updateGeoHeader();
  2815. renderGeoCountries();
  2816. } catch (err) {
  2817. console.error('Failed to load GeoIP:', err);
  2818. }
  2819. }
  2820. function updateGeoHeader() {
  2821. const s = state.geoStatus || {};
  2822. const statusBadge = document.getElementById('geo-status-badge');
  2823. if (statusBadge) {
  2824. statusBadge.innerText = s.auto_update ? 'Auto-Update ON' : 'Auto-Update OFF';
  2825. statusBadge.className = s.auto_update
  2826. ? 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-emerald-500/20 text-emerald-300 border border-emerald-500/30'
  2827. : 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 text-slate-400';
  2828. }
  2829. const intervalLabel = document.getElementById('geo-interval-label');
  2830. if (intervalLabel) {
  2831. intervalLabel.innerText = `Every ${s.interval_hours || 24}h`;
  2832. }
  2833. const activeCountEl = document.getElementById('geo-stat-active-countries');
  2834. if (activeCountEl) activeCountEl.innerText = (s.enabled_count || 0).toLocaleString();
  2835. const totalSubnetsEl = document.getElementById('geo-stat-total-subnets');
  2836. if (totalSubnetsEl) totalSubnetsEl.innerText = (s.total_subnets || 0).toLocaleString();
  2837. const lastSyncEl = document.getElementById('geo-stat-last-sync');
  2838. if (lastSyncEl) {
  2839. if (s.last_updated && !s.last_updated.startsWith('0001')) {
  2840. const d = new Date(s.last_updated);
  2841. lastSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  2842. } else {
  2843. lastSyncEl.innerText = 'Never (Sync Pending)';
  2844. }
  2845. }
  2846. const nextSyncEl = document.getElementById('geo-stat-next-sync');
  2847. if (nextSyncEl) {
  2848. if (s.next_update && !s.next_update.startsWith('0001')) {
  2849. const d = new Date(s.next_update);
  2850. nextSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  2851. } else {
  2852. nextSyncEl.innerText = '-';
  2853. }
  2854. }
  2855. const badge = document.getElementById('fw-badge-geo');
  2856. if (badge) badge.innerText = s.enabled_count || 0;
  2857. }
  2858. function renderGeoCountries() {
  2859. const tbody = document.getElementById('geo-table-body');
  2860. const empty = document.getElementById('geo-empty');
  2861. if (!tbody) return;
  2862. tbody.innerHTML = '';
  2863. const q = (document.getElementById('geo-search-input')?.value || '').trim().toLowerCase();
  2864. const continent = document.getElementById('geo-continent-filter')?.value || '';
  2865. const enabledOnly = document.getElementById('geo-filter-enabled-only')?.checked;
  2866. const countries = (state.geoCountries || []).filter(c => {
  2867. if (enabledOnly && !c.enabled) return false;
  2868. if (continent && c.continent !== continent) return false;
  2869. if (q) {
  2870. const matchCode = c.code.toLowerCase().includes(q);
  2871. const matchName = c.name.toLowerCase().includes(q);
  2872. if (!matchCode && !matchName) return false;
  2873. }
  2874. return true;
  2875. });
  2876. if (countries.length === 0) {
  2877. empty?.classList.remove('hidden');
  2878. return;
  2879. }
  2880. empty?.classList.add('hidden');
  2881. countries.forEach(c => {
  2882. const tr = document.createElement('tr');
  2883. tr.className = `hover:bg-slate-800/40 transition text-xs ${c.enabled ? 'bg-emerald-950/10' : ''}`;
  2884. tr.innerHTML = `
  2885. <td class="py-2.5 px-3 text-center">
  2886. <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'}">
  2887. ${c.code}
  2888. </span>
  2889. </td>
  2890. <td class="py-2.5 px-3 font-bold text-white">${c.name}</td>
  2891. <td class="py-2.5 px-3 text-slate-400">${c.continent}</td>
  2892. <td class="py-2.5 px-3 font-mono ${c.subnet_count > 0 ? 'text-emerald-400 font-bold' : 'text-slate-500'}">
  2893. ${c.subnet_count > 0 ? c.subnet_count.toLocaleString() + ' CIDRs' : 'Not Cached'}
  2894. </td>
  2895. <td class="py-2.5 px-3 font-mono text-purple-300">${c.ipset_name}</td>
  2896. <td class="py-2.5 px-3">
  2897. ${c.enabled
  2898. ? '<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>'
  2899. : '<span class="px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 text-slate-500">DISABLED</span>'}
  2900. </td>
  2901. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  2902. ${c.enabled
  2903. ? `<button onclick="toggleGeoCountry('${c.code}', false)" class="text-xs text-rose-400 hover:underline font-semibold">Disable</button>`
  2904. : `<button onclick="toggleGeoCountry('${c.code}', true)" class="text-xs text-emerald-400 hover:underline font-semibold">Enable</button>`}
  2905. <button onclick="updateGeoCountry('${c.code}')" class="text-xs text-cyan-400 hover:text-cyan-300" title="Re-download latest country IP blocks">Sync</button>
  2906. <button onclick="viewGeoSubnets('${c.code}', '${c.name.replace(/'/g, "\\'")}')" class="text-xs text-slate-400 hover:text-white" title="Preview Subnet Ranges">View</button>
  2907. </td>
  2908. `;
  2909. tbody.appendChild(tr);
  2910. });
  2911. }
  2912. async function toggleGeoCountry(code, enabled) {
  2913. try {
  2914. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/toggle`, {
  2915. method: 'POST',
  2916. headers: { 'Content-Type': 'application/json' },
  2917. body: JSON.stringify({ enabled })
  2918. });
  2919. if (res.ok) {
  2920. showToast(enabled ? 'Country Enabled' : 'Country Disabled', `${code} ${enabled ? 'active in firewall' : 'removed from firewall'}`, 'success');
  2921. loadGeoIP();
  2922. } else {
  2923. const err = await res.json();
  2924. showToast('Error', err.message || 'Failed to toggle country', 'error');
  2925. }
  2926. } catch (err) {
  2927. showToast('Error', err.message, 'error');
  2928. }
  2929. }
  2930. async function updateGeoCountry(code) {
  2931. try {
  2932. showToast('Syncing Country', `Downloading latest IP blocks for ${code}...`, 'info');
  2933. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/update`, { method: 'POST' });
  2934. if (res.ok) {
  2935. const data = await res.json();
  2936. showToast('Synced', `Loaded ${data.subnets} CIDR blocks for ${code}`, 'success');
  2937. loadGeoIP();
  2938. } else {
  2939. const err = await res.json();
  2940. showToast('Sync Error', err.message || 'Failed to sync country', 'error');
  2941. }
  2942. } catch (err) {
  2943. showToast('Error', err.message, 'error');
  2944. }
  2945. }
  2946. async function triggerGeoUpdateNow() {
  2947. const spinner = document.getElementById('geo-update-spinner');
  2948. if (spinner) spinner.classList.remove('hidden');
  2949. try {
  2950. const res = await fetch(`${API_BASE}/firewall/geoip/update-now`, { method: 'POST' });
  2951. if (res.ok) {
  2952. showToast('Update Started', 'Updating all active GeoIP country zones in background...', 'info');
  2953. setTimeout(() => {
  2954. loadGeoIP();
  2955. if (spinner) spinner.classList.add('hidden');
  2956. }, 2500);
  2957. } else {
  2958. const err = await res.json();
  2959. showToast('Notice', err.message || 'Update in progress', 'info');
  2960. if (spinner) spinner.classList.add('hidden');
  2961. }
  2962. } catch (err) {
  2963. showToast('Error', err.message, 'error');
  2964. if (spinner) spinner.classList.add('hidden');
  2965. }
  2966. }
  2967. async function applyGeoPreset(preset) {
  2968. try {
  2969. const res = await fetch(`${API_BASE}/firewall/geoip/batch-toggle`, {
  2970. method: 'POST',
  2971. headers: { 'Content-Type': 'application/json' },
  2972. body: JSON.stringify({ preset, enabled: preset !== 'NONE' })
  2973. });
  2974. if (res.ok) {
  2975. showToast('Preset Applied', `Preset ${preset} updated in firewall`, 'success');
  2976. loadGeoIP();
  2977. }
  2978. } catch (err) {
  2979. showToast('Error', err.message, 'error');
  2980. }
  2981. }
  2982. function openGeoIntervalModal() {
  2983. const s = state.geoStatus || {};
  2984. document.getElementById('geo-cfg-autoupdate').checked = s.auto_update !== false;
  2985. const sel = document.getElementById('geo-cfg-interval');
  2986. const customBox = document.getElementById('geo-cfg-custom-box');
  2987. const customHoursInput = document.getElementById('geo-cfg-custom-hours');
  2988. const curHours = s.interval_hours || 24;
  2989. const matchOption = Array.from(sel.options).find(o => parseInt(o.value, 10) === curHours);
  2990. if (matchOption) {
  2991. sel.value = String(curHours);
  2992. customBox.classList.add('hidden');
  2993. } else {
  2994. sel.value = 'custom';
  2995. customHoursInput.value = curHours;
  2996. customBox.classList.remove('hidden');
  2997. }
  2998. document.getElementById('geo-interval-modal').classList.remove('hidden');
  2999. }
  3000. function closeGeoIntervalModal() {
  3001. document.getElementById('geo-interval-modal').classList.add('hidden');
  3002. }
  3003. function toggleCustomGeoInterval() {
  3004. const val = document.getElementById('geo-cfg-interval').value;
  3005. const customBox = document.getElementById('geo-cfg-custom-box');
  3006. if (val === 'custom') {
  3007. customBox.classList.remove('hidden');
  3008. } else {
  3009. customBox.classList.add('hidden');
  3010. }
  3011. }
  3012. async function submitGeoIntervalSettings(e) {
  3013. e.preventDefault();
  3014. const autoUpdate = document.getElementById('geo-cfg-autoupdate').checked;
  3015. const intervalVal = document.getElementById('geo-cfg-interval').value;
  3016. let hours = 24;
  3017. if (intervalVal === 'custom') {
  3018. hours = parseInt(document.getElementById('geo-cfg-custom-hours').value, 10) || 24;
  3019. } else {
  3020. hours = parseInt(intervalVal, 10) || 24;
  3021. }
  3022. try {
  3023. const res = await fetch(`${API_BASE}/firewall/geoip/config`, {
  3024. method: 'POST',
  3025. headers: { 'Content-Type': 'application/json' },
  3026. body: JSON.stringify({ auto_update: autoUpdate, interval_hours: hours })
  3027. });
  3028. if (res.ok) {
  3029. showToast('Schedule Saved', `Auto-update set to every ${hours} hours`, 'success');
  3030. closeGeoIntervalModal();
  3031. loadGeoIP();
  3032. } else {
  3033. const err = await res.json();
  3034. showToast('Error', err.message || 'Failed to save schedule', 'error');
  3035. }
  3036. } catch (err) {
  3037. showToast('Error', err.message, 'error');
  3038. }
  3039. }
  3040. async function viewGeoSubnets(code, name) {
  3041. document.getElementById('geo-subnets-title').innerText = `${name} (${code}) Subnets`;
  3042. document.getElementById('geo-subnets-subtitle').innerText = `Kernel IPSet: mk_geo_${code}`;
  3043. const listEl = document.getElementById('geo-subnets-list');
  3044. listEl.innerHTML = '<span class="text-slate-500">Loading subnets...</span>';
  3045. document.getElementById('geo-subnets-modal').classList.remove('hidden');
  3046. try {
  3047. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/subnets`);
  3048. if (res.ok) {
  3049. const data = await res.json();
  3050. const subnets = data.subnets || [];
  3051. if (subnets.length === 0) {
  3052. listEl.innerHTML = '<span class="text-slate-500">No cached subnets found. Click Sync to download this zone.</span>';
  3053. } else {
  3054. listEl.innerHTML = subnets.map(s => `<div>${s}</div>`).join('');
  3055. }
  3056. } else {
  3057. listEl.innerHTML = '<span class="text-rose-400">Failed to load subnets.</span>';
  3058. }
  3059. } catch (err) {
  3060. listEl.innerHTML = `<span class="text-rose-400">Error: ${err.message}</span>`;
  3061. }
  3062. }
  3063. function closeGeoSubnetsModal() {
  3064. document.getElementById('geo-subnets-modal').classList.add('hidden');
  3065. }
  3066. // ----------------- Active Connections Tracking -----------------
  3067. async function loadConnections() {
  3068. try {
  3069. const res = await fetch(`${API_BASE}/firewall/connections`);
  3070. const data = await res.json();
  3071. state.connections = Array.isArray(data) ? data : [];
  3072. document.getElementById('fw-badge-connections').innerText = state.connections.length;
  3073. document.getElementById('conns-count-badge').innerText = `${state.connections.length} Flows`;
  3074. renderConnections();
  3075. } catch (err) {
  3076. console.error('Failed to load connections:', err);
  3077. }
  3078. }
  3079. function renderConnections() {
  3080. const search = (document.getElementById('conns-search-input')?.value || '').toLowerCase();
  3081. const protoFilter = document.getElementById('conns-filter-proto')?.value || '';
  3082. const tbody = document.getElementById('conns-table-body');
  3083. const empty = document.getElementById('conns-empty');
  3084. if (!tbody) return;
  3085. tbody.innerHTML = '';
  3086. const conns = (state.connections || []).filter(c => {
  3087. if (protoFilter && c.protocol !== protoFilter) return false;
  3088. if (search) {
  3089. const line = `${c.protocol} ${c.src_address} ${c.dst_address} ${c.src_port} ${c.dst_port} ${c.tcp_state} ${c.connection_mark}`.toLowerCase();
  3090. if (!line.includes(search)) return false;
  3091. }
  3092. return true;
  3093. });
  3094. if (conns.length === 0) {
  3095. empty?.classList.remove('hidden');
  3096. return;
  3097. }
  3098. empty?.classList.add('hidden');
  3099. conns.slice(0, 150).forEach(c => {
  3100. const tr = document.createElement('tr');
  3101. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  3102. let stateColor = 'text-slate-400';
  3103. if (c.tcp_state === 'ESTABLISHED') stateColor = 'text-emerald-400 font-bold';
  3104. else if (c.tcp_state === 'TIME_WAIT' || c.tcp_state === 'SYN_SENT') stateColor = 'text-amber-400';
  3105. tr.innerHTML = `
  3106. <td class="py-2.5 px-3 font-bold text-cyan-400">${c.protocol}</td>
  3107. <td class="py-2.5 px-3 font-mono text-white">${c.src_address}:${c.src_port}</td>
  3108. <td class="py-2.5 px-3 font-mono text-white">${c.dst_address}:${c.dst_port}</td>
  3109. <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>
  3110. <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>
  3111. <td class="py-2.5 px-3 font-mono ${stateColor}">${c.tcp_state}</td>
  3112. <td class="py-2.5 px-3 font-mono text-purple-300">${c.connection_mark || '-'}</td>
  3113. <td class="py-2.5 px-3 text-slate-500">${c.timeout ? c.timeout + 's' : '-'}</td>
  3114. <td class="py-2.5 px-3 text-right font-sans">
  3115. <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>
  3116. </td>
  3117. `;
  3118. tbody.appendChild(tr);
  3119. });
  3120. }
  3121. async function killConnection(protocol, src, sport, dst, dport) {
  3122. try {
  3123. const res = await fetch(`${API_BASE}/firewall/connections/kill`, {
  3124. method: 'POST',
  3125. headers: { 'Content-Type': 'application/json' },
  3126. body: JSON.stringify({ protocol, src, sport, dst, dport })
  3127. });
  3128. if (res.ok) {
  3129. showToast('Terminated', `Killed flow ${src}:${sport} -> ${dst}:${dport}`, 'info');
  3130. loadConnections();
  3131. }
  3132. } catch (err) {
  3133. showToast('Error', err.message, 'error');
  3134. }
  3135. }
  3136. async function resetFirewallCounters() {
  3137. if (!confirm('Reset all firewall packet and byte counters to zero?')) return;
  3138. try {
  3139. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  3140. if (res.ok) {
  3141. showToast('Counters Reset', 'All rules counters reset to 0', 'success');
  3142. loadFirewall(false);
  3143. }
  3144. } catch (err) {
  3145. showToast('Error', err.message, 'error');
  3146. }
  3147. }
  3148. // ======================== MIKROTIK ROUTING & POLICY (/ip route) ========================
  3149. function switchRoutesSubTab(tab) {
  3150. state.routesSubTab = tab;
  3151. const tabs = ['routes', 'rules', 'tables'];
  3152. tabs.forEach(t => {
  3153. const panel = document.getElementById(`routes-subtab-${t}`);
  3154. const btn = document.getElementById(`routes-subtab-btn-${t}`);
  3155. if (panel) {
  3156. if (t === tab) panel.classList.remove('hidden');
  3157. else panel.classList.add('hidden');
  3158. }
  3159. if (btn) {
  3160. if (t === tab) {
  3161. 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';
  3162. } else {
  3163. 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';
  3164. }
  3165. }
  3166. });
  3167. }
  3168. async function loadRoutes() {
  3169. try {
  3170. const [routesRes, rulesRes, tablesRes] = await Promise.all([
  3171. fetch(`${API_BASE}/routes`),
  3172. fetch(`${API_BASE}/routing/rules`),
  3173. fetch(`${API_BASE}/routing/tables`)
  3174. ]);
  3175. if (routesRes.ok) state.routes = await routesRes.json();
  3176. if (rulesRes.ok) state.policyRules = await rulesRes.json();
  3177. if (tablesRes.ok) state.routingTables = await tablesRes.json();
  3178. const bRoutes = document.getElementById('routes-badge-routes');
  3179. if (bRoutes) bRoutes.innerText = (state.routes || []).length;
  3180. const bRules = document.getElementById('routes-badge-rules');
  3181. if (bRules) bRules.innerText = (state.policyRules || []).length;
  3182. const bTables = document.getElementById('routes-badge-tables');
  3183. if (bTables) bTables.innerText = (state.routingTables || []).length;
  3184. const bRoutesCount = document.getElementById('badge-routes-count');
  3185. if (bRoutesCount) bRoutesCount.innerText = (state.routes || []).length;
  3186. renderRoutesList();
  3187. renderPolicyRules();
  3188. renderRoutingTables();
  3189. } catch (err) {
  3190. console.error('Failed to load routing:', err);
  3191. }
  3192. }
  3193. function renderRoutesList() {
  3194. const tableFilter = document.getElementById('routes-filter-table')?.value || '';
  3195. const tbody = document.getElementById('routes-table-body');
  3196. const empty = document.getElementById('routes-empty');
  3197. if (!tbody) return;
  3198. tbody.innerHTML = '';
  3199. // Update table filter select
  3200. const sel = document.getElementById('routes-filter-table');
  3201. if (sel) {
  3202. const cur = sel.value;
  3203. sel.innerHTML = '<option value="">All Tables</option>';
  3204. (state.routingTables || []).forEach(t => {
  3205. const opt = document.createElement('option');
  3206. opt.value = t.name;
  3207. opt.innerText = t.name;
  3208. if (t.name === cur) opt.selected = true;
  3209. sel.appendChild(opt);
  3210. });
  3211. }
  3212. const routes = (state.routes || []).filter(r => !tableFilter || r.routing_table === tableFilter);
  3213. document.getElementById('routes-count-badge').innerText = `${routes.length} Routes`;
  3214. if (routes.length === 0) {
  3215. empty?.classList.remove('hidden');
  3216. return;
  3217. }
  3218. empty?.classList.add('hidden');
  3219. routes.forEach(r => {
  3220. const tr = document.createElement('tr');
  3221. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${r.disabled ? 'opacity-50' : ''}`;
  3222. tr.setAttribute('ondblclick', `openEditRouteModal('${r.id}')`);
  3223. // MikroTik Flags string: D=Dynamic, A=Active, C=Connect, S=Static, X=Disabled
  3224. let flags = '';
  3225. if (r.dynamic) flags += 'D';
  3226. if (r.active) flags += 'A';
  3227. if (r.connect) flags += 'C';
  3228. if (r.static) flags += 'S';
  3229. if (r.disabled) flags += 'X';
  3230. const isDefault = r.dst_address === 'default' || r.dst_address === '0.0.0.0/0';
  3231. tr.innerHTML = `
  3232. <td class="py-2.5 px-3 text-center">
  3233. <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'}">
  3234. ${flags || '-'}
  3235. </span>
  3236. </td>
  3237. <td class="py-2.5 px-3 font-bold ${isDefault ? 'text-cyan-300' : 'text-white'}">${r.dst_address}</td>
  3238. <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>
  3239. <td class="py-2.5 px-3 text-slate-400 font-mono">${(r.distance !== undefined && r.distance !== null) ? r.distance : 0}</td>
  3240. <td class="py-2.5 px-3 font-mono font-semibold text-purple-300">${r.routing_table || 'main'}</td>
  3241. <td class="py-2.5 px-3 text-emerald-400 font-mono">${r.interface || '-'}</td>
  3242. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]">${r.comment || '-'}</td>
  3243. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  3244. ${r.static ? `
  3245. <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>
  3246. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  3247. <button onclick="deleteRoute('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  3248. ` : `
  3249. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">View</button>
  3250. `}
  3251. </td>
  3252. `;
  3253. tbody.appendChild(tr);
  3254. });
  3255. }
  3256. function openAddRouteModal() {
  3257. document.getElementById('route-modal-title').innerText = 'Add Static Route';
  3258. document.getElementById('route-modal-id').value = '';
  3259. document.getElementById('route-modal-old-dst').value = '';
  3260. document.getElementById('route-modal-old-gw').value = '';
  3261. document.getElementById('route-modal-old-distance').value = '';
  3262. document.getElementById('route-modal-old-table').value = '';
  3263. document.getElementById('route-modal-old-iface').value = '';
  3264. const dstInput = document.getElementById('route-modal-dst');
  3265. const gwInput = document.getElementById('route-modal-gw');
  3266. const distInput = document.getElementById('route-modal-distance');
  3267. const ifaceSelect = document.getElementById('route-modal-iface');
  3268. const tableSelect = document.getElementById('route-modal-table');
  3269. const commentInput = document.getElementById('route-modal-comment');
  3270. const disCheck = document.getElementById('route-modal-disabled');
  3271. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  3272. dstInput.disabled = false;
  3273. dstInput.value = '0.0.0.0/0';
  3274. gwInput.disabled = false;
  3275. gwInput.value = '';
  3276. distInput.disabled = false;
  3277. distInput.value = '1';
  3278. ifaceSelect.disabled = false;
  3279. tableSelect.disabled = false;
  3280. commentInput.disabled = false;
  3281. commentInput.value = '';
  3282. disCheck.disabled = false;
  3283. disCheck.checked = false;
  3284. if (saveBtn) saveBtn.classList.remove('hidden');
  3285. populateInterfaceSelect('route-modal-iface');
  3286. // Populate tables
  3287. tableSelect.innerHTML = '';
  3288. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  3289. const opt = document.createElement('option');
  3290. opt.value = t.name;
  3291. opt.innerText = t.name;
  3292. if (t.name === 'main') opt.selected = true;
  3293. tableSelect.appendChild(opt);
  3294. });
  3295. document.getElementById('route-modal').classList.remove('hidden');
  3296. }
  3297. function openEditRouteModal(id) {
  3298. const r = (state.routes || []).find(route => route.id === id);
  3299. if (!r) return;
  3300. const isStatic = !!r.static;
  3301. document.getElementById('route-modal-title').innerText = isStatic
  3302. ? `Edit Route: ${r.dst_address}`
  3303. : `Route Properties (Read Only): ${r.dst_address}`;
  3304. document.getElementById('route-modal-id').value = r.id;
  3305. document.getElementById('route-modal-old-dst').value = r.dst_address || '';
  3306. document.getElementById('route-modal-old-gw').value = r.gateway || '';
  3307. document.getElementById('route-modal-old-distance').value = (r.distance !== undefined && r.distance !== null) ? r.distance : '';
  3308. document.getElementById('route-modal-old-table').value = r.routing_table || 'main';
  3309. document.getElementById('route-modal-old-iface').value = r.interface || '';
  3310. const dstInput = document.getElementById('route-modal-dst');
  3311. const gwInput = document.getElementById('route-modal-gw');
  3312. const distInput = document.getElementById('route-modal-distance');
  3313. const ifaceSelect = document.getElementById('route-modal-iface');
  3314. const tableSelect = document.getElementById('route-modal-table');
  3315. const commentInput = document.getElementById('route-modal-comment');
  3316. const disCheck = document.getElementById('route-modal-disabled');
  3317. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  3318. dstInput.value = r.dst_address;
  3319. gwInput.value = r.gateway || '';
  3320. distInput.value = (r.distance !== undefined && r.distance !== null) ? r.distance : 1;
  3321. commentInput.value = r.comment || '';
  3322. disCheck.checked = !!r.disabled;
  3323. dstInput.disabled = !isStatic;
  3324. gwInput.disabled = !isStatic;
  3325. distInput.disabled = !isStatic;
  3326. ifaceSelect.disabled = !isStatic;
  3327. tableSelect.disabled = !isStatic;
  3328. commentInput.disabled = !isStatic;
  3329. disCheck.disabled = !isStatic;
  3330. if (saveBtn) {
  3331. if (isStatic) {
  3332. saveBtn.classList.remove('hidden');
  3333. } else {
  3334. saveBtn.classList.add('hidden');
  3335. }
  3336. }
  3337. populateInterfaceSelect('route-modal-iface', r.interface);
  3338. tableSelect.innerHTML = '';
  3339. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  3340. const opt = document.createElement('option');
  3341. opt.value = t.name;
  3342. opt.innerText = t.name;
  3343. if (t.name === (r.routing_table || 'main')) opt.selected = true;
  3344. tableSelect.appendChild(opt);
  3345. });
  3346. document.getElementById('route-modal').classList.remove('hidden');
  3347. }
  3348. function closeRouteModal() {
  3349. document.getElementById('route-modal').classList.add('hidden');
  3350. }
  3351. async function submitSaveRoute(e) {
  3352. e.preventDefault();
  3353. const id = document.getElementById('route-modal-id').value;
  3354. const oldDst = document.getElementById('route-modal-old-dst')?.value || '';
  3355. const oldGw = document.getElementById('route-modal-old-gw')?.value || '';
  3356. const oldDistStr = document.getElementById('route-modal-old-distance')?.value;
  3357. const oldTable = document.getElementById('route-modal-old-table')?.value || '';
  3358. const oldIface = document.getElementById('route-modal-old-iface')?.value || '';
  3359. const dst = document.getElementById('route-modal-dst').value.trim();
  3360. const gw = document.getElementById('route-modal-gw').value.trim();
  3361. const table = document.getElementById('route-modal-table').value;
  3362. const distance = parseInt(document.getElementById('route-modal-distance').value, 10) || 0;
  3363. const iface = document.getElementById('route-modal-iface').value;
  3364. const comment = document.getElementById('route-modal-comment').value.trim();
  3365. const disabled = document.getElementById('route-modal-disabled').checked;
  3366. if (!dst) {
  3367. showToast('Error', 'Destination address is required', 'error');
  3368. return;
  3369. }
  3370. if (!gw && !iface) {
  3371. showToast('Error', 'Either Gateway IP or Interface must be specified', 'error');
  3372. return;
  3373. }
  3374. const payload = {
  3375. id,
  3376. old_dst_address: oldDst,
  3377. old_gateway: oldGw,
  3378. old_routing_table: oldTable,
  3379. old_interface: oldIface,
  3380. dst_address: dst,
  3381. gateway: gw || iface,
  3382. routing_table: table,
  3383. distance,
  3384. interface: iface,
  3385. comment,
  3386. disabled
  3387. };
  3388. if (oldDistStr !== undefined && oldDistStr !== '') {
  3389. payload.old_distance = parseInt(oldDistStr, 10);
  3390. }
  3391. try {
  3392. const res = await fetch(`${API_BASE}/routes`, {
  3393. method: 'POST',
  3394. headers: { 'Content-Type': 'application/json' },
  3395. body: JSON.stringify(payload)
  3396. });
  3397. if (res.ok) {
  3398. showToast('Route Saved', `Route to ${dst} installed`, 'success');
  3399. closeRouteModal();
  3400. loadRoutes();
  3401. } else {
  3402. const err = await res.json();
  3403. showToast('Error', err.message || 'Failed to save route', 'error');
  3404. }
  3405. } catch (err) {
  3406. showToast('Error', err.message, 'error');
  3407. }
  3408. }
  3409. async function toggleRouteState(id, disabled) {
  3410. try {
  3411. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}/state`, {
  3412. method: 'POST',
  3413. headers: { 'Content-Type': 'application/json' },
  3414. body: JSON.stringify({ disabled })
  3415. });
  3416. if (res.ok) loadRoutes();
  3417. } catch (err) {
  3418. showToast('Error', err.message, 'error');
  3419. }
  3420. }
  3421. async function deleteRoute(id) {
  3422. if (!confirm('Are you sure you want to delete this route?')) return;
  3423. try {
  3424. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}`, { method: 'DELETE' });
  3425. if (res.ok) {
  3426. showToast('Deleted', 'Route removed', 'success');
  3427. loadRoutes();
  3428. }
  3429. } catch (err) {
  3430. showToast('Error', err.message, 'error');
  3431. }
  3432. }
  3433. // ----------------- Policy Rules (/ip route rule) -----------------
  3434. function renderPolicyRules() {
  3435. const tbody = document.getElementById('rules-table-body');
  3436. const empty = document.getElementById('rules-empty');
  3437. if (!tbody) return;
  3438. tbody.innerHTML = '';
  3439. const rules = state.policyRules || [];
  3440. document.getElementById('rules-count-badge').innerText = `${rules.length} Rules`;
  3441. if (rules.length === 0) {
  3442. empty?.classList.remove('hidden');
  3443. return;
  3444. }
  3445. empty?.classList.add('hidden');
  3446. rules.forEach(pr => {
  3447. const tr = document.createElement('tr');
  3448. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  3449. tr.innerHTML = `
  3450. <td class="py-2.5 px-3 font-mono text-cyan-400 font-bold">${pr.priority}</td>
  3451. <td class="py-2.5 px-3 font-mono text-white">${pr.src_address || '<span class="text-slate-600">all</span>'}</td>
  3452. <td class="py-2.5 px-3 font-mono text-white">${pr.dst_address || '<span class="text-slate-600">all</span>'}</td>
  3453. <td class="py-2.5 px-3 font-mono font-bold text-purple-300">${pr.routing_mark || '<span class="text-slate-600">-</span>'}</td>
  3454. <td class="py-2.5 px-3 font-mono font-bold text-amber-300">${pr.table}</td>
  3455. <td class="py-2.5 px-3 font-mono text-slate-300">${pr.action}</td>
  3456. <td class="py-2.5 px-3 text-right font-sans">
  3457. ${pr.priority < 32766 && pr.priority > 0 ? `
  3458. <button onclick="deletePolicyRule('${pr.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  3459. ` : `<span class="text-slate-600 text-[10px]">Default</span>`}
  3460. </td>
  3461. `;
  3462. tbody.appendChild(tr);
  3463. });
  3464. }
  3465. function openAddPolicyRuleModal() {
  3466. document.getElementById('prule-modal-pref').value = (state.policyRules || []).length * 10 + 1000;
  3467. document.getElementById('prule-modal-mark').value = '';
  3468. document.getElementById('prule-modal-src').value = '';
  3469. document.getElementById('prule-modal-dst').value = '';
  3470. const sel = document.getElementById('prule-modal-table');
  3471. sel.innerHTML = '';
  3472. (state.routingTables || []).forEach(t => {
  3473. const opt = document.createElement('option');
  3474. opt.value = t.name;
  3475. opt.innerText = t.name;
  3476. sel.appendChild(opt);
  3477. });
  3478. document.getElementById('prule-modal').classList.remove('hidden');
  3479. }
  3480. function closePolicyRuleModal() {
  3481. document.getElementById('prule-modal').classList.add('hidden');
  3482. }
  3483. async function submitSavePolicyRule(e) {
  3484. e.preventDefault();
  3485. const pref = parseInt(document.getElementById('prule-modal-pref').value, 10) || 1000;
  3486. const mark = document.getElementById('prule-modal-mark').value.trim();
  3487. const src = document.getElementById('prule-modal-src').value.trim();
  3488. const dst = document.getElementById('prule-modal-dst').value.trim();
  3489. const table = document.getElementById('prule-modal-table').value;
  3490. const action = document.getElementById('prule-modal-action').value;
  3491. try {
  3492. const res = await fetch(`${API_BASE}/routing/rules`, {
  3493. method: 'POST',
  3494. headers: { 'Content-Type': 'application/json' },
  3495. body: JSON.stringify({ priority: pref, routing_mark: mark, src_address: src, dst_address: dst, table, action })
  3496. });
  3497. if (res.ok) {
  3498. showToast('Rule Added', `Policy rule installed for table ${table}`, 'success');
  3499. closePolicyRuleModal();
  3500. loadRoutes();
  3501. } else {
  3502. const err = await res.json();
  3503. showToast('Error', err.message, 'error');
  3504. }
  3505. } catch (err) {
  3506. showToast('Error', err.message, 'error');
  3507. }
  3508. }
  3509. async function deletePolicyRule(id) {
  3510. if (!confirm('Are you sure you want to remove this policy rule?')) return;
  3511. try {
  3512. const res = await fetch(`${API_BASE}/routing/rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  3513. if (res.ok) {
  3514. showToast('Rule Removed', 'Policy rule deleted', 'success');
  3515. loadRoutes();
  3516. }
  3517. } catch (err) {
  3518. showToast('Error', err.message, 'error');
  3519. }
  3520. }
  3521. // ----------------- Routing Tables -----------------
  3522. function renderRoutingTables() {
  3523. const tbody = document.getElementById('tables-table-body');
  3524. if (!tbody) return;
  3525. tbody.innerHTML = '';
  3526. (state.routingTables || []).forEach(t => {
  3527. const tr = document.createElement('tr');
  3528. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  3529. tr.innerHTML = `
  3530. <td class="py-2.5 px-3 text-cyan-400 font-bold">${t.table_id}</td>
  3531. <td class="py-2.5 px-3 font-bold text-white">${t.name}</td>
  3532. <td class="py-2.5 px-3 text-slate-400 italic">${t.comment || '-'}</td>
  3533. `;
  3534. tbody.appendChild(tr);
  3535. });
  3536. }
  3537. function openAddTableModal() {
  3538. document.getElementById('table-modal-name').value = '';
  3539. document.getElementById('table-modal-id').value = '';
  3540. document.getElementById('table-modal-comment').value = '';
  3541. document.getElementById('table-modal').classList.remove('hidden');
  3542. }
  3543. function closeTableModal() {
  3544. document.getElementById('table-modal').classList.add('hidden');
  3545. }
  3546. async function submitSaveTable(e) {
  3547. e.preventDefault();
  3548. const name = document.getElementById('table-modal-name').value.trim();
  3549. const id = parseInt(document.getElementById('table-modal-id').value, 10) || 0;
  3550. const comment = document.getElementById('table-modal-comment').value.trim();
  3551. try {
  3552. const res = await fetch(`${API_BASE}/routing/tables`, {
  3553. method: 'POST',
  3554. headers: { 'Content-Type': 'application/json' },
  3555. body: JSON.stringify({ name, table_id: id, comment })
  3556. });
  3557. if (res.ok) {
  3558. showToast('Table Created', `Routing table ${name} registered`, 'success');
  3559. closeTableModal();
  3560. loadRoutes();
  3561. } else {
  3562. const err = await res.json();
  3563. showToast('Error', err.message, 'error');
  3564. }
  3565. } catch (err) {
  3566. showToast('Error', err.message, 'error');
  3567. }
  3568. }
  3569. async function loadDebianConfig() {
  3570. const view = document.getElementById('debian-config-view');
  3571. view.innerText = 'Generating live configuration...';
  3572. try {
  3573. const res = await fetch(`${API_BASE}/debian/config`);
  3574. const data = await res.json();
  3575. view.innerText = data.content || '# Empty config';
  3576. } catch (err) {
  3577. view.innerText = 'Failed to generate Debian network config.';
  3578. }
  3579. }
  3580. async function saveDebianConfig() {
  3581. try {
  3582. const res = await fetch(`${API_BASE}/debian/apply`, { method: 'POST' });
  3583. const data = await res.json();
  3584. if (res.ok) {
  3585. showToast('Configuration Saved', data.message || 'Saved to /etc/network/interfaces.d/vlans.cfg', 'success');
  3586. loadDebianConfig();
  3587. }
  3588. } catch (err) {
  3589. showToast('Error', err.message, 'error');
  3590. }
  3591. }
  3592. function showToast(title, message, type = 'info') {
  3593. const container = document.getElementById('toast-container');
  3594. const toast = document.createElement('div');
  3595. const borderColors = {
  3596. success: 'border-emerald-500/40 bg-slate-900/95 text-emerald-400',
  3597. error: 'border-rose-500/40 bg-slate-900/95 text-rose-400',
  3598. info: 'border-cyan-500/40 bg-slate-900/95 text-cyan-400'
  3599. };
  3600. 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}`;
  3601. toast.innerHTML = `
  3602. <div class="flex-1">
  3603. <div class="font-bold text-xs text-white">${title}</div>
  3604. <div class="text-[11px] text-slate-300 mt-0.5 leading-relaxed font-sans">${message}</div>
  3605. </div>
  3606. `;
  3607. container.appendChild(toast);
  3608. requestAnimationFrame(() => toast.classList.remove('translate-y-2', 'opacity-0'));
  3609. setTimeout(() => {
  3610. toast.classList.add('opacity-0', 'translate-y-2');
  3611. setTimeout(() => toast.remove(), 300);
  3612. }, 4000);
  3613. }
  3614. function formatTraffic(bytesPerSec) {
  3615. if (bytesPerSec < 1024) return `${Math.round(bytesPerSec)} B/s`;
  3616. const kb = bytesPerSec / 1024;
  3617. if (kb < 1024) return `${kb.toFixed(1)} KB/s`;
  3618. const mb = kb / 1024;
  3619. return `${mb.toFixed(2)} MB/s`;
  3620. }
  3621. function toggleSidebar() {
  3622. const sb = document.getElementById('sidebar');
  3623. sb.classList.toggle('-translate-x-full');
  3624. }
  3625. // ======================== EoIP (Ethernet over IP) ========================
  3626. async function loadEoIP(populate = true) {
  3627. try {
  3628. const res = await fetch(`${API_BASE}/vpn/eoip`);
  3629. const data = await res.json();
  3630. state.eoipTunnels = Array.isArray(data) ? data : [];
  3631. const badge = document.getElementById('eoip-count-badge');
  3632. if (badge) badge.innerText = `${state.eoipTunnels.length} Tunnels`;
  3633. const sideBadge = document.getElementById('badge-eoip-count');
  3634. if (sideBadge) sideBadge.innerText = state.eoipTunnels.length;
  3635. renderEoIPTunnels();
  3636. } catch (err) {
  3637. console.error('Failed to load EoIP:', err);
  3638. }
  3639. }
  3640. function renderEoIPTunnels() {
  3641. const tbody = document.getElementById('eoip-table-body');
  3642. const empty = document.getElementById('eoip-empty');
  3643. if (!tbody) return;
  3644. tbody.innerHTML = '';
  3645. const tunnels = state.eoipTunnels || [];
  3646. if (tunnels.length === 0) {
  3647. empty?.classList.remove('hidden');
  3648. return;
  3649. }
  3650. empty?.classList.add('hidden');
  3651. tunnels.forEach(t => {
  3652. const tr = document.createElement('tr');
  3653. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  3654. tr.innerHTML = `
  3655. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.running, t.disabled)}</td>
  3656. <td class="py-2.5 px-3 font-bold text-white font-mono">${t.name}</td>
  3657. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${t.tunnel_id}</td>
  3658. <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>
  3659. <td class="py-2.5 px-3 text-cyan-300 font-mono">${t.remote_address}</td>
  3660. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.local_address || '(any)'}</td>
  3661. <td class="py-2.5 px-3 text-slate-300 font-mono text-[11px]">${t.mac_address || '-'}</td>
  3662. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.mtu || 1500}</td>
  3663. <td class="py-2.5 px-3 font-mono text-[11px]">
  3664. <span class="text-emerald-400">↓ ${t.rx_human || '0 B'}</span>
  3665. <span class="text-cyan-400 ml-1">↑ ${t.tx_human || '0 B'}</span>
  3666. </td>
  3667. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${t.comment || ''}">${t.comment || '-'}</td>
  3668. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  3669. <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>
  3670. <button onclick="openEditEoIPModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  3671. <button onclick="deleteEoIP('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  3672. </td>
  3673. `;
  3674. tbody.appendChild(tr);
  3675. });
  3676. }
  3677. function openAddEoIPModal() {
  3678. document.getElementById('eoip-modal-title').innerText = 'Add EoIP Tunnel';
  3679. document.getElementById('eoip-modal-id').value = '';
  3680. document.getElementById('eoip-modal-name').value = `eoip-tunnel${(state.eoipTunnels || []).length + 1}`;
  3681. document.getElementById('eoip-modal-tunnelid').value = (state.eoipTunnels || []).length + 10;
  3682. document.getElementById('eoip-modal-remote').value = '';
  3683. document.getElementById('eoip-modal-ip').value = '';
  3684. document.getElementById('eoip-modal-local').value = '';
  3685. document.getElementById('eoip-modal-mac').value = '';
  3686. document.getElementById('eoip-modal-mtu').value = '1500';
  3687. document.getElementById('eoip-modal-comment').value = '';
  3688. document.getElementById('eoip-modal-clampmss').checked = true;
  3689. document.getElementById('eoip-modal-disabled').checked = false;
  3690. document.getElementById('eoip-modal').classList.remove('hidden');
  3691. }
  3692. function openEditEoIPModal(id) {
  3693. const t = (state.eoipTunnels || []).find(tun => tun.id === id);
  3694. if (!t) return;
  3695. document.getElementById('eoip-modal-title').innerText = `Edit EoIP Tunnel (${t.name})`;
  3696. document.getElementById('eoip-modal-id').value = t.id;
  3697. document.getElementById('eoip-modal-name').value = t.name;
  3698. document.getElementById('eoip-modal-tunnelid').value = t.tunnel_id;
  3699. document.getElementById('eoip-modal-remote').value = t.remote_address;
  3700. document.getElementById('eoip-modal-ip').value = t.ip_address || '';
  3701. document.getElementById('eoip-modal-local').value = t.local_address || '';
  3702. document.getElementById('eoip-modal-mac').value = t.mac_address || '';
  3703. document.getElementById('eoip-modal-mtu').value = t.mtu || 1500;
  3704. document.getElementById('eoip-modal-comment').value = t.comment || '';
  3705. document.getElementById('eoip-modal-clampmss').checked = !!t.clamp_mss;
  3706. document.getElementById('eoip-modal-disabled').checked = !!t.disabled;
  3707. document.getElementById('eoip-modal').classList.remove('hidden');
  3708. }
  3709. function closeEoIPModal() {
  3710. document.getElementById('eoip-modal').classList.add('hidden');
  3711. }
  3712. async function submitSaveEoIP(e) {
  3713. e.preventDefault();
  3714. const id = document.getElementById('eoip-modal-id').value;
  3715. const name = document.getElementById('eoip-modal-name').value.trim();
  3716. const tunnelId = parseInt(document.getElementById('eoip-modal-tunnelid').value);
  3717. const remote = document.getElementById('eoip-modal-remote').value.trim();
  3718. const ipAddress = document.getElementById('eoip-modal-ip').value.trim();
  3719. const local = document.getElementById('eoip-modal-local').value.trim();
  3720. const mac = document.getElementById('eoip-modal-mac').value.trim();
  3721. const mtu = parseInt(document.getElementById('eoip-modal-mtu').value) || 1500;
  3722. const comment = document.getElementById('eoip-modal-comment').value.trim();
  3723. const clampMss = document.getElementById('eoip-modal-clampmss').checked;
  3724. const disabled = document.getElementById('eoip-modal-disabled').checked;
  3725. try {
  3726. const res = await fetch(`${API_BASE}/vpn/eoip`, {
  3727. method: 'POST',
  3728. headers: { 'Content-Type': 'application/json' },
  3729. body: JSON.stringify({
  3730. id,
  3731. name,
  3732. tunnel_id: tunnelId,
  3733. remote_address: remote,
  3734. ip_address: ipAddress,
  3735. local_address: local,
  3736. mac_address: mac,
  3737. mtu,
  3738. clamp_mss: clampMss,
  3739. comment,
  3740. disabled
  3741. })
  3742. });
  3743. if (res.ok) {
  3744. showToast('EoIP Saved', `Tunnel ${name} configured successfully`, 'success');
  3745. closeEoIPModal();
  3746. loadEoIP(false);
  3747. fetchData(false);
  3748. } else {
  3749. const err = await res.json();
  3750. showToast('Error', err.message, 'error');
  3751. }
  3752. } catch (err) {
  3753. showToast('Error', err.message, 'error');
  3754. }
  3755. }
  3756. async function toggleEoIPState(id, disabled) {
  3757. try {
  3758. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}/state`, {
  3759. method: 'POST',
  3760. headers: { 'Content-Type': 'application/json' },
  3761. body: JSON.stringify({ disabled })
  3762. });
  3763. if (res.ok) {
  3764. showToast(disabled ? 'Disabled' : 'Enabled', 'EoIP tunnel state updated', 'info');
  3765. loadEoIP(false);
  3766. fetchData(false);
  3767. }
  3768. } catch (err) {
  3769. showToast('Error', err.message, 'error');
  3770. }
  3771. }
  3772. async function deleteEoIP(id) {
  3773. if (!confirm('Are you sure you want to delete this EoIP tunnel?')) return;
  3774. try {
  3775. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}`, { method: 'DELETE' });
  3776. if (res.ok) {
  3777. showToast('Deleted', 'EoIP tunnel removed', 'success');
  3778. loadEoIP(false);
  3779. fetchData(false);
  3780. }
  3781. } catch (err) {
  3782. showToast('Error', err.message, 'error');
  3783. }
  3784. }
  3785. // ======================== PPP Central Hub & Servers ========================
  3786. function switchPPPSubTab(tab) {
  3787. state.pppSubTab = tab;
  3788. const tabs = ['secrets', 'profiles', 'pppoe', 'pptp', 'l2tp', 'active'];
  3789. tabs.forEach(t => {
  3790. const panel = document.getElementById(`ppp-subtab-${t}`);
  3791. const btn = document.getElementById(`ppp-subtab-btn-${t}`);
  3792. if (panel) {
  3793. if (t === tab) panel.classList.remove('hidden');
  3794. else panel.classList.add('hidden');
  3795. }
  3796. if (btn) {
  3797. if (t === tab) {
  3798. 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';
  3799. } else {
  3800. 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';
  3801. }
  3802. }
  3803. });
  3804. const addBtn = document.getElementById('ppp-primary-add-btn');
  3805. if (addBtn) {
  3806. if (tab === 'secrets') addBtn.innerHTML = '<span>+ Add User (Secret)</span>';
  3807. else if (tab === 'profiles') addBtn.innerHTML = '<span>+ Add Profile</span>';
  3808. else if (tab === 'active') addBtn.innerHTML = '<span>Refresh Sessions</span>';
  3809. else addBtn.innerHTML = '<span>Save Config</span>';
  3810. }
  3811. if (tab === 'active') loadPPPSessions();
  3812. }
  3813. function openCurrentPPPModal() {
  3814. if (state.pppSubTab === 'secrets') openAddPPPSecretModal();
  3815. else if (state.pppSubTab === 'profiles') openAddPPPProfileModal();
  3816. else if (state.pppSubTab === 'active') loadPPPSessions();
  3817. else if (state.pppSubTab === 'pppoe') document.querySelector('#ppp-subtab-pppoe form')?.requestSubmit();
  3818. else if (state.pppSubTab === 'pptp') document.querySelector('#ppp-subtab-pptp form')?.requestSubmit();
  3819. else if (state.pppSubTab === 'l2tp') document.querySelector('#ppp-subtab-l2tp form')?.requestSubmit();
  3820. }
  3821. async function loadPPP(populateDropdowns = true) {
  3822. await Promise.all([
  3823. loadPPPSecrets(),
  3824. loadPPPProfiles(),
  3825. loadPPPServers(),
  3826. loadPPPSessions()
  3827. ]);
  3828. }
  3829. async function loadPPPSecrets() {
  3830. try {
  3831. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`);
  3832. const data = await res.json();
  3833. state.pppSecrets = Array.isArray(data) ? data : [];
  3834. const b = document.getElementById('ppp-badge-secrets');
  3835. if (b) b.innerText = state.pppSecrets.length;
  3836. const b2 = document.getElementById('secrets-count-badge');
  3837. if (b2) b2.innerText = `${state.pppSecrets.length} Users`;
  3838. renderPPPSecrets();
  3839. } catch (err) {
  3840. console.error('Failed to load PPP secrets:', err);
  3841. }
  3842. }
  3843. function renderPPPSecrets() {
  3844. const tbody = document.getElementById('secrets-table-body');
  3845. const empty = document.getElementById('secrets-empty');
  3846. if (!tbody) return;
  3847. tbody.innerHTML = '';
  3848. const secrets = state.pppSecrets || [];
  3849. if (secrets.length === 0) {
  3850. empty?.classList.remove('hidden');
  3851. return;
  3852. }
  3853. empty?.classList.add('hidden');
  3854. secrets.forEach(s => {
  3855. const tr = document.createElement('tr');
  3856. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  3857. tr.innerHTML = `
  3858. <td class="py-2.5 px-3 text-center">${renderRuleFlag(s.disabled, !!s.comment)}</td>
  3859. <td class="py-2.5 px-3 font-bold text-white font-mono">${s.name}</td>
  3860. <td class="py-2.5 px-3 text-purple-300 font-mono font-semibold">${s.service}</td>
  3861. <td class="py-2.5 px-3 text-amber-300 font-mono">${s.profile}</td>
  3862. <td class="py-2.5 px-3 text-slate-400 font-mono">${s.local_address || '(profile)'}</td>
  3863. <td class="py-2.5 px-3 text-cyan-400 font-mono font-bold">${s.remote_address || '(profile)'}</td>
  3864. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]">${s.comment || '-'}</td>
  3865. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  3866. <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>
  3867. <button onclick="openEditPPPSecretModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  3868. <button onclick="deletePPPSecret('${s.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  3869. </td>
  3870. `;
  3871. tbody.appendChild(tr);
  3872. });
  3873. }
  3874. async function loadPPPProfiles() {
  3875. try {
  3876. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  3877. const data = await res.json();
  3878. state.pppProfiles = Array.isArray(data) ? data : [];
  3879. const b = document.getElementById('ppp-badge-profiles');
  3880. if (b) b.innerText = state.pppProfiles.length;
  3881. const b2 = document.getElementById('profiles-count-badge');
  3882. if (b2) b2.innerText = `${state.pppProfiles.length} Profiles`;
  3883. // Populate profile selects across modals
  3884. const selects = ['secret-modal-profile', 'pppoe-server-profile', 'pptp-server-profile', 'l2tp-server-profile'];
  3885. selects.forEach(sid => {
  3886. const el = document.getElementById(sid);
  3887. if (!el) return;
  3888. const cur = el.value;
  3889. el.innerHTML = '';
  3890. state.pppProfiles.forEach(p => {
  3891. const opt = document.createElement('option');
  3892. opt.value = p.name;
  3893. opt.innerText = `${p.name} (${p.remote_address})`;
  3894. if (p.name === cur) opt.selected = true;
  3895. el.appendChild(opt);
  3896. });
  3897. });
  3898. renderPPPProfiles();
  3899. } catch (err) {
  3900. console.error('Failed to load PPP profiles:', err);
  3901. }
  3902. }
  3903. function renderPPPProfiles() {
  3904. const tbody = document.getElementById('profiles-table-body');
  3905. if (!tbody) return;
  3906. tbody.innerHTML = '';
  3907. (state.pppProfiles || []).forEach(p => {
  3908. const isDefault = p.name.startsWith('default');
  3909. const tr = document.createElement('tr');
  3910. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  3911. tr.innerHTML = `
  3912. <td class="py-2.5 px-3 font-bold text-white">${p.name}</td>
  3913. <td class="py-2.5 px-3 text-slate-300">${p.local_address}</td>
  3914. <td class="py-2.5 px-3 text-cyan-400 font-bold">${p.remote_address}</td>
  3915. <td class="py-2.5 px-3 text-slate-400">${p.dns_servers || '-'}</td>
  3916. <td class="py-2.5 px-3 text-purple-300 font-semibold">${p.use_encryption}</td>
  3917. <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>
  3918. <td class="py-2.5 px-3 text-slate-400 italic">${p.comment || '-'}</td>
  3919. <td class="py-2.5 px-3 text-right font-sans whitespace-nowrap">
  3920. ${!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>`}
  3921. </td>
  3922. `;
  3923. tbody.appendChild(tr);
  3924. });
  3925. }
  3926. async function loadPPPServers() {
  3927. try {
  3928. const [pppoeRes, pptpRes, l2tpRes, ipsecRes] = await Promise.all([
  3929. fetch(`${API_BASE}/vpn/servers/pppoe`),
  3930. fetch(`${API_BASE}/vpn/servers/pptp`),
  3931. fetch(`${API_BASE}/vpn/servers/l2tp`),
  3932. fetch(`${API_BASE}/vpn/servers/ipsec`)
  3933. ]);
  3934. if (pppoeRes.ok) {
  3935. state.pppoeServer = await pppoeRes.json();
  3936. const s = state.pppoeServer;
  3937. document.getElementById('pppoe-server-enabled').checked = !!s.enabled;
  3938. document.getElementById('pppoe-server-name').value = s.service_name || 'proxmox-pppoe';
  3939. populateInterfaceSelect('pppoe-server-iface', s.interface || 'eth0');
  3940. document.getElementById('pppoe-server-profile').value = s.default_profile || 'default';
  3941. document.getElementById('pppoe-server-mtu').value = s.max_mtu || 1480;
  3942. document.getElementById('pppoe-server-onesession').checked = !!s.one_session_per_host;
  3943. const pill = document.getElementById('pppoe-server-status-pill');
  3944. if (pill) {
  3945. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  3946. 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';
  3947. }
  3948. setDotBadge('ppp-badge-pppoe-state', s.running);
  3949. }
  3950. if (pptpRes.ok) {
  3951. state.pptpServer = await pptpRes.json();
  3952. const s = state.pptpServer;
  3953. document.getElementById('pptp-server-enabled').checked = !!s.enabled;
  3954. document.getElementById('pptp-server-port').value = s.port || 1723;
  3955. document.getElementById('pptp-server-profile').value = s.default_profile || 'default-encryption';
  3956. document.getElementById('pptp-server-mppe').checked = s.require_mppe !== false;
  3957. const pill = document.getElementById('pptp-server-status-pill');
  3958. if (pill) {
  3959. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  3960. 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';
  3961. }
  3962. setDotBadge('ppp-badge-pptp-state', s.running);
  3963. }
  3964. if (l2tpRes.ok) {
  3965. state.l2tpServer = await l2tpRes.json();
  3966. const s = state.l2tpServer;
  3967. document.getElementById('l2tp-server-enabled').checked = !!s.enabled;
  3968. document.getElementById('l2tp-server-port').value = s.port || 1701;
  3969. document.getElementById('l2tp-server-profile').value = s.default_profile || 'default';
  3970. document.getElementById('l2tp-server-useipsec').value = s.use_ipsec || 'no';
  3971. document.getElementById('l2tp-server-ipsecsecret').value = s.ipsec_secret || '';
  3972. const pill = document.getElementById('l2tp-server-status-pill');
  3973. if (pill) {
  3974. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  3975. 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';
  3976. }
  3977. setDotBadge('ppp-badge-l2tp-state', s.running);
  3978. }
  3979. if (ipsecRes.ok) {
  3980. state.ipsecServer = await ipsecRes.json();
  3981. const s = state.ipsecServer;
  3982. const modalEn = document.getElementById('modal-ipsec-server-enabled');
  3983. if (modalEn) modalEn.checked = !!s.enabled;
  3984. const modalPsk = document.getElementById('modal-ipsec-server-psk');
  3985. if (modalPsk) modalPsk.value = s.preshared_key || '';
  3986. const modalPool = document.getElementById('modal-ipsec-server-pool');
  3987. if (modalPool) modalPool.value = s.pool_address || '10.10.30.0/24';
  3988. const modalDns = document.getElementById('modal-ipsec-server-dns');
  3989. if (modalDns) modalDns.value = s.dns_servers || '1.1.1.1,8.8.8.8';
  3990. const modalSubnet = document.getElementById('modal-ipsec-server-subnet');
  3991. if (modalSubnet) modalSubnet.value = s.local_subnet || '0.0.0.0/0';
  3992. const pill = document.getElementById('modal-ipsec-server-status');
  3993. if (pill) {
  3994. pill.innerText = s.running ? 'ACTIVE RESPONDER' : 'STOPPED';
  3995. 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';
  3996. }
  3997. }
  3998. } catch (err) {
  3999. console.error('Failed to load VPN servers:', err);
  4000. }
  4001. }
  4002. async function loadPPPSessions() {
  4003. try {
  4004. const res = await fetch(`${API_BASE}/vpn/ppp/active`);
  4005. const data = await res.json();
  4006. state.pppActiveSessions = Array.isArray(data) ? data : [];
  4007. const b = document.getElementById('ppp-badge-active');
  4008. if (b) b.innerText = state.pppActiveSessions.length;
  4009. const sideB = document.getElementById('badge-ppp-sessions');
  4010. if (sideB) sideB.innerText = state.pppActiveSessions.length;
  4011. renderPPPSessions();
  4012. } catch (err) {
  4013. console.error('Failed to load active PPP sessions:', err);
  4014. }
  4015. }
  4016. function renderPPPSessions() {
  4017. const tbody = document.getElementById('active-ppp-table-body');
  4018. const empty = document.getElementById('active-ppp-empty');
  4019. if (!tbody) return;
  4020. tbody.innerHTML = '';
  4021. const list = state.pppActiveSessions || [];
  4022. if (list.length === 0) {
  4023. empty?.classList.remove('hidden');
  4024. return;
  4025. }
  4026. empty?.classList.add('hidden');
  4027. list.forEach(s => {
  4028. const tr = document.createElement('tr');
  4029. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  4030. tr.innerHTML = `
  4031. <td class="py-2.5 px-3 font-bold text-white">${s.interface}</td>
  4032. <td class="py-2.5 px-3 font-semibold text-violet-300">${s.username}</td>
  4033. <td class="py-2.5 px-3 text-cyan-400 uppercase">${s.service}</td>
  4034. <td class="py-2.5 px-3 text-emerald-400 font-bold">${s.address || '-'}</td>
  4035. <td class="py-2.5 px-3 text-slate-400">${s.uptime}</td>
  4036. <td class="py-2.5 px-3 text-[11px]">
  4037. <span class="text-emerald-400">↓ ${s.rx_human || '0 B'}</span>
  4038. <span class="text-cyan-400 ml-1">↑ ${s.tx_human || '0 B'}</span>
  4039. </td>
  4040. <td class="py-2.5 px-3 text-right font-sans">
  4041. <button onclick="disconnectPPPSession('${s.interface}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  4042. </td>
  4043. `;
  4044. tbody.appendChild(tr);
  4045. });
  4046. }
  4047. async function disconnectPPPSession(iface) {
  4048. if (!confirm(`Disconnect session ${iface}?`)) return;
  4049. try {
  4050. const res = await fetch(`${API_BASE}/vpn/ppp/active/${encodeURIComponent(iface)}`, { method: 'DELETE' });
  4051. if (res.ok) {
  4052. showToast('Disconnected', `Session ${iface} terminated`, 'info');
  4053. loadPPPSessions();
  4054. }
  4055. } catch (err) {
  4056. showToast('Error', err.message, 'error');
  4057. }
  4058. }
  4059. // PPP Secret Modal handlers
  4060. function openAddPPPSecretModal() {
  4061. document.getElementById('secret-modal-title').innerText = 'Add PPP Secret';
  4062. document.getElementById('secret-modal-id').value = '';
  4063. document.getElementById('secret-modal-name').value = '';
  4064. document.getElementById('secret-modal-password').value = '';
  4065. document.getElementById('secret-modal-service').value = 'any';
  4066. document.getElementById('secret-modal-profile').value = 'default';
  4067. document.getElementById('secret-modal-local').value = '';
  4068. document.getElementById('secret-modal-remote').value = '';
  4069. document.getElementById('secret-modal-comment').value = '';
  4070. document.getElementById('secret-modal-disabled').checked = false;
  4071. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  4072. }
  4073. function openEditPPPSecretModal(id) {
  4074. const s = (state.pppSecrets || []).find(sec => sec.id === id);
  4075. if (!s) return;
  4076. document.getElementById('secret-modal-title').innerText = `Edit PPP Secret (${s.name})`;
  4077. document.getElementById('secret-modal-id').value = s.id;
  4078. document.getElementById('secret-modal-name').value = s.name;
  4079. document.getElementById('secret-modal-password').value = s.password;
  4080. document.getElementById('secret-modal-service').value = s.service || 'any';
  4081. document.getElementById('secret-modal-profile').value = s.profile || 'default';
  4082. document.getElementById('secret-modal-local').value = s.local_address || '';
  4083. document.getElementById('secret-modal-remote').value = s.remote_address || '';
  4084. document.getElementById('secret-modal-comment').value = s.comment || '';
  4085. document.getElementById('secret-modal-disabled').checked = !!s.disabled;
  4086. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  4087. }
  4088. function closePPPSecretModal() {
  4089. document.getElementById('ppp-secret-modal').classList.add('hidden');
  4090. }
  4091. async function submitSavePPPSecret(e) {
  4092. e.preventDefault();
  4093. const id = document.getElementById('secret-modal-id').value;
  4094. const name = document.getElementById('secret-modal-name').value.trim();
  4095. const password = document.getElementById('secret-modal-password').value.trim();
  4096. const service = document.getElementById('secret-modal-service').value;
  4097. const profile = document.getElementById('secret-modal-profile').value;
  4098. const local = document.getElementById('secret-modal-local').value.trim();
  4099. const remote = document.getElementById('secret-modal-remote').value.trim();
  4100. const comment = document.getElementById('secret-modal-comment').value.trim();
  4101. const disabled = document.getElementById('secret-modal-disabled').checked;
  4102. try {
  4103. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`, {
  4104. method: 'POST',
  4105. headers: { 'Content-Type': 'application/json' },
  4106. body: JSON.stringify({
  4107. id,
  4108. name,
  4109. password,
  4110. service,
  4111. profile,
  4112. local_address: local,
  4113. remote_address: remote,
  4114. comment,
  4115. disabled
  4116. })
  4117. });
  4118. if (res.ok) {
  4119. showToast('Secret Saved', `User ${name} saved to PPP database`, 'success');
  4120. closePPPSecretModal();
  4121. loadPPPSecrets();
  4122. } else {
  4123. const err = await res.json();
  4124. showToast('Error', err.message, 'error');
  4125. }
  4126. } catch (err) {
  4127. showToast('Error', err.message, 'error');
  4128. }
  4129. }
  4130. async function togglePPPSecretState(id, disabled) {
  4131. try {
  4132. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}/state`, {
  4133. method: 'POST',
  4134. headers: { 'Content-Type': 'application/json' },
  4135. body: JSON.stringify({ disabled })
  4136. });
  4137. if (res.ok) {
  4138. showToast(disabled ? 'Disabled' : 'Enabled', 'Secret user state updated', 'info');
  4139. loadPPPSecrets();
  4140. }
  4141. } catch (err) {
  4142. showToast('Error', err.message, 'error');
  4143. }
  4144. }
  4145. async function deletePPPSecret(id) {
  4146. if (!confirm('Are you sure you want to delete this secret account?')) return;
  4147. try {
  4148. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4149. if (res.ok) {
  4150. showToast('Deleted', 'Secret account removed', 'success');
  4151. loadPPPSecrets();
  4152. }
  4153. } catch (err) {
  4154. showToast('Error', err.message, 'error');
  4155. }
  4156. }
  4157. // PPP Profile Modal handlers
  4158. function openAddPPPProfileModal() {
  4159. document.getElementById('profile-modal-name').value = '';
  4160. document.getElementById('profile-modal-local').value = '10.10.10.1';
  4161. document.getElementById('profile-modal-remote').value = '10.10.10.10-10.10.10.50';
  4162. document.getElementById('profile-modal-dns').value = '1.1.1.1,8.8.8.8';
  4163. document.getElementById('profile-modal-encryption').value = 'required';
  4164. document.getElementById('profile-modal-onlyone').checked = true;
  4165. document.getElementById('profile-modal-comment').value = '';
  4166. document.getElementById('ppp-profile-modal').classList.remove('hidden');
  4167. }
  4168. function closePPPProfileModal() {
  4169. document.getElementById('ppp-profile-modal').classList.add('hidden');
  4170. }
  4171. async function submitSavePPPProfile(e) {
  4172. e.preventDefault();
  4173. const name = document.getElementById('profile-modal-name').value.trim();
  4174. const local = document.getElementById('profile-modal-local').value.trim();
  4175. const remote = document.getElementById('profile-modal-remote').value.trim();
  4176. const dns = document.getElementById('profile-modal-dns').value.trim();
  4177. const enc = document.getElementById('profile-modal-encryption').value;
  4178. const onlyone = document.getElementById('profile-modal-onlyone').checked;
  4179. const comment = document.getElementById('profile-modal-comment').value.trim();
  4180. try {
  4181. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`, {
  4182. method: 'POST',
  4183. headers: { 'Content-Type': 'application/json' },
  4184. body: JSON.stringify({
  4185. id: name,
  4186. name,
  4187. local_address: local,
  4188. remote_address: remote,
  4189. dns_servers: dns,
  4190. use_encryption: enc,
  4191. only_one: onlyone,
  4192. comment
  4193. })
  4194. });
  4195. if (res.ok) {
  4196. showToast('Profile Saved', `PPP profile ${name} created`, 'success');
  4197. closePPPProfileModal();
  4198. loadPPPProfiles();
  4199. } else {
  4200. const err = await res.json();
  4201. showToast('Error', err.message, 'error');
  4202. }
  4203. } catch (err) {
  4204. showToast('Error', err.message, 'error');
  4205. }
  4206. }
  4207. async function deletePPPProfile(name) {
  4208. if (!confirm(`Delete PPP profile ${name}?`)) return;
  4209. try {
  4210. const res = await fetch(`${API_BASE}/vpn/ppp/profiles/${encodeURIComponent(name)}`, { method: 'DELETE' });
  4211. if (res.ok) {
  4212. showToast('Deleted', 'Profile removed', 'success');
  4213. loadPPPProfiles();
  4214. } else {
  4215. const err = await res.json();
  4216. showToast('Error', err.message, 'error');
  4217. }
  4218. } catch (err) {
  4219. showToast('Error', err.message, 'error');
  4220. }
  4221. }
  4222. // Server Config submissions
  4223. async function savePPPoEServerConfig(e) {
  4224. e.preventDefault();
  4225. const enabled = document.getElementById('pppoe-server-enabled').checked;
  4226. const name = document.getElementById('pppoe-server-name').value.trim();
  4227. const iface = document.getElementById('pppoe-server-iface').value;
  4228. const profile = document.getElementById('pppoe-server-profile').value;
  4229. const mtu = parseInt(document.getElementById('pppoe-server-mtu').value) || 1480;
  4230. const onesession = document.getElementById('pppoe-server-onesession').checked;
  4231. try {
  4232. const res = await fetch(`${API_BASE}/vpn/servers/pppoe`, {
  4233. method: 'POST',
  4234. headers: { 'Content-Type': 'application/json' },
  4235. body: JSON.stringify({
  4236. enabled,
  4237. service_name: name,
  4238. interface: iface,
  4239. default_profile: profile,
  4240. max_mtu: mtu,
  4241. max_mru: mtu,
  4242. one_session_per_host: onesession
  4243. })
  4244. });
  4245. if (res.ok) {
  4246. showToast('PPPoE Server', enabled ? 'PPPoE Server started' : 'PPPoE Server stopped', 'success');
  4247. loadPPPServers();
  4248. fetchData(false);
  4249. } else {
  4250. const err = await res.json();
  4251. showToast('Error', err.message, 'error');
  4252. }
  4253. } catch (err) {
  4254. showToast('Error', err.message, 'error');
  4255. }
  4256. }
  4257. async function savePPTPServerConfig(e) {
  4258. e.preventDefault();
  4259. const enabled = document.getElementById('pptp-server-enabled').checked;
  4260. const port = parseInt(document.getElementById('pptp-server-port').value) || 1723;
  4261. const profile = document.getElementById('pptp-server-profile').value;
  4262. const mppe = document.getElementById('pptp-server-mppe').checked;
  4263. try {
  4264. const res = await fetch(`${API_BASE}/vpn/servers/pptp`, {
  4265. method: 'POST',
  4266. headers: { 'Content-Type': 'application/json' },
  4267. body: JSON.stringify({
  4268. enabled,
  4269. port,
  4270. default_profile: profile,
  4271. require_mppe: mppe
  4272. })
  4273. });
  4274. if (res.ok) {
  4275. showToast('PPTP Server', enabled ? 'PPTP Server started' : 'PPTP Server stopped', 'success');
  4276. loadPPPServers();
  4277. fetchData(false);
  4278. } else {
  4279. const err = await res.json();
  4280. showToast('Error', err.message, 'error');
  4281. }
  4282. } catch (err) {
  4283. showToast('Error', err.message, 'error');
  4284. }
  4285. }
  4286. async function saveL2TPServerConfig(e) {
  4287. e.preventDefault();
  4288. const enabled = document.getElementById('l2tp-server-enabled').checked;
  4289. const port = parseInt(document.getElementById('l2tp-server-port').value) || 1701;
  4290. const profile = document.getElementById('l2tp-server-profile').value;
  4291. const useipsec = document.getElementById('l2tp-server-useipsec').value;
  4292. const psk = document.getElementById('l2tp-server-ipsecsecret').value.trim();
  4293. try {
  4294. const res = await fetch(`${API_BASE}/vpn/servers/l2tp`, {
  4295. method: 'POST',
  4296. headers: { 'Content-Type': 'application/json' },
  4297. body: JSON.stringify({
  4298. enabled,
  4299. port,
  4300. default_profile: profile,
  4301. use_ipsec: useipsec,
  4302. ipsec_secret: psk
  4303. })
  4304. });
  4305. if (res.ok) {
  4306. showToast('L2TP Server', enabled ? 'L2TP Server started' : 'L2TP Server stopped', 'success');
  4307. loadPPPServers();
  4308. fetchData(false);
  4309. } else {
  4310. const err = await res.json();
  4311. showToast('Error', err.message, 'error');
  4312. }
  4313. } catch (err) {
  4314. showToast('Error', err.message, 'error');
  4315. }
  4316. }
  4317. // IPSec Server Modal
  4318. function openIPSecServerModal() {
  4319. loadPPPServers();
  4320. document.getElementById('ipsec-server-modal').classList.remove('hidden');
  4321. }
  4322. function closeIPSecServerModal() {
  4323. document.getElementById('ipsec-server-modal').classList.add('hidden');
  4324. }
  4325. async function submitSaveIPSecServer(e) {
  4326. e.preventDefault();
  4327. const enabled = document.getElementById('modal-ipsec-server-enabled').checked;
  4328. const psk = document.getElementById('modal-ipsec-server-psk').value.trim();
  4329. const pool = document.getElementById('modal-ipsec-server-pool').value.trim();
  4330. const dns = document.getElementById('modal-ipsec-server-dns').value.trim();
  4331. const subnet = document.getElementById('modal-ipsec-server-subnet').value.trim();
  4332. try {
  4333. const res = await fetch(`${API_BASE}/vpn/servers/ipsec`, {
  4334. method: 'POST',
  4335. headers: { 'Content-Type': 'application/json' },
  4336. body: JSON.stringify({
  4337. enabled,
  4338. preshared_key: psk,
  4339. pool_address: pool,
  4340. dns_servers: dns,
  4341. local_subnet: subnet
  4342. })
  4343. });
  4344. if (res.ok) {
  4345. showToast('IPSec Server', enabled ? 'IKEv2 Roadwarrior responder active' : 'IPSec Server stopped', 'success');
  4346. closeIPSecServerModal();
  4347. loadPPPServers();
  4348. fetchData(false);
  4349. } else {
  4350. const err = await res.json();
  4351. showToast('Error', err.message, 'error');
  4352. }
  4353. } catch (err) {
  4354. showToast('Error', err.message, 'error');
  4355. }
  4356. }
  4357. // WireGuard Client Config Viewer
  4358. let currentWGClientConf = '';
  4359. async function openWGClientConfModal(iface, clientIP) {
  4360. try {
  4361. const res = await fetch(`${API_BASE}/vpn/wireguard/client-config`, {
  4362. method: 'POST',
  4363. headers: { 'Content-Type': 'application/json' },
  4364. body: JSON.stringify({
  4365. interface: iface,
  4366. address: clientIP || '10.10.0.2/32',
  4367. dns: '1.1.1.1, 8.8.8.8'
  4368. })
  4369. });
  4370. if (res.ok) {
  4371. const data = await res.json();
  4372. currentWGClientConf = data.config;
  4373. document.getElementById('wg-client-conf-text').value = currentWGClientConf;
  4374. document.getElementById('wg-client-conf-modal').classList.remove('hidden');
  4375. } else {
  4376. const err = await res.json();
  4377. showToast('Error', err.message, 'error');
  4378. }
  4379. } catch (err) {
  4380. showToast('Error', err.message, 'error');
  4381. }
  4382. }
  4383. function closeWGClientConfModal() {
  4384. document.getElementById('wg-client-conf-modal').classList.add('hidden');
  4385. }
  4386. function copyWGClientConf() {
  4387. if (!currentWGClientConf) return;
  4388. copyToClipboard(currentWGClientConf, 'WireGuard Client Profile');
  4389. }
  4390. function downloadWGClientConf() {
  4391. if (!currentWGClientConf) return;
  4392. const blob = new Blob([currentWGClientConf], { type: 'text/plain;charset=utf-8' });
  4393. const a = document.createElement('a');
  4394. a.href = URL.createObjectURL(blob);
  4395. a.download = 'wireguard-client.conf';
  4396. document.body.appendChild(a);
  4397. a.click();
  4398. document.body.removeChild(a);
  4399. showToast('Downloaded', 'wireguard-client.conf saved', 'success');
  4400. }
  4401. // =========================================================================
  4402. // DYNAMIC ROUTING (FRRouting BGP & OSPFv2)
  4403. // =========================================================================
  4404. state.activeDynSubTab = 'bgp-peers';
  4405. state.bgpInstance = null;
  4406. state.bgpPeers = [];
  4407. state.bgpNets = [];
  4408. state.bgpRoutes = [];
  4409. state.ospfInstance = null;
  4410. state.ospfInterfaces = [];
  4411. state.ospfAreas = [];
  4412. state.ospfNeighbors = [];
  4413. state.ospfRoutes = [];
  4414. function switchDynSubTab(subTab) {
  4415. state.activeDynSubTab = subTab;
  4416. const tabs = ['bgp-peers', 'bgp-nets', 'bgp-routes', 'ospf-ifaces', 'ospf-areas', 'ospf-nbrs', 'ospf-routes'];
  4417. tabs.forEach(t => {
  4418. const el = document.getElementById(`dyn-subtab-${t}`);
  4419. const btn = document.getElementById(`dyn-subtab-btn-${t}`);
  4420. if (el) el.classList.toggle('hidden', t !== subTab);
  4421. if (btn) {
  4422. if (t === subTab) {
  4423. 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`;
  4424. } else {
  4425. 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';
  4426. }
  4427. }
  4428. });
  4429. }
  4430. async function loadDynamicRouting(showToastMsg = true) {
  4431. try {
  4432. const [sumRes, bgpInstRes, bgpPeersRes, bgpNetsRes, bgpRoutesRes, ospfInstRes, ospfIfacesRes, ospfAreasRes, ospfNbrsRes, ospfRoutesRes] = await Promise.all([
  4433. fetch(`${API_BASE}/routing/dynamic/summary`),
  4434. fetch(`${API_BASE}/routing/bgp/instance`),
  4435. fetch(`${API_BASE}/routing/bgp/peers`),
  4436. fetch(`${API_BASE}/routing/bgp/networks`),
  4437. fetch(`${API_BASE}/routing/bgp/routes`),
  4438. fetch(`${API_BASE}/routing/ospf/instance`),
  4439. fetch(`${API_BASE}/routing/ospf/interfaces`),
  4440. fetch(`${API_BASE}/routing/ospf/areas`),
  4441. fetch(`${API_BASE}/routing/ospf/neighbors`),
  4442. fetch(`${API_BASE}/routing/ospf/routes`)
  4443. ]);
  4444. if (sumRes.ok) state.dynSummary = await sumRes.json();
  4445. if (bgpInstRes.ok) state.bgpInstance = await bgpInstRes.json();
  4446. if (bgpPeersRes.ok) state.bgpPeers = await bgpPeersRes.json();
  4447. if (bgpNetsRes.ok) state.bgpNets = await bgpNetsRes.json();
  4448. if (bgpRoutesRes.ok) state.bgpRoutes = await bgpRoutesRes.json();
  4449. if (ospfInstRes.ok) state.ospfInstance = await ospfInstRes.json();
  4450. if (ospfIfacesRes.ok) state.ospfInterfaces = await ospfIfacesRes.json();
  4451. if (ospfAreasRes.ok) state.ospfAreas = await ospfAreasRes.json();
  4452. if (ospfNbrsRes.ok) state.ospfNeighbors = await ospfNbrsRes.json();
  4453. if (ospfRoutesRes.ok) state.ospfRoutes = await ospfRoutesRes.json();
  4454. renderBgpStatusPill();
  4455. renderBgpPeers();
  4456. renderBgpNetworks();
  4457. renderBgpRoutes();
  4458. renderOspfStatusPill();
  4459. renderOspfInterfaces();
  4460. renderOspfAreas();
  4461. renderOspfNeighbors();
  4462. renderOspfRoutes();
  4463. updateBadges();
  4464. } catch (err) {
  4465. console.error('Failed to load dynamic routing:', err);
  4466. if (showToastMsg) showToast('Error', 'Failed to load dynamic routing telemetry', 'error');
  4467. }
  4468. }
  4469. function renderBgpStatusPill() {
  4470. const pill = document.getElementById('bgp-live-status-pill');
  4471. if (!pill) return;
  4472. const inst = state.bgpInstance;
  4473. if (!inst || !inst.enabled) {
  4474. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-slate-800 text-slate-400 border border-slate-700';
  4475. pill.innerText = 'BGP DISABLED';
  4476. } else if (inst.running) {
  4477. 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';
  4478. pill.innerText = `BGP ACTIVE (AS ${inst.as})`;
  4479. } else {
  4480. 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';
  4481. pill.innerText = 'BGP STARTING...';
  4482. }
  4483. }
  4484. function renderBgpPeers() {
  4485. const tbody = document.getElementById('bgp-peers-table-body');
  4486. const empty = document.getElementById('bgp-peers-empty');
  4487. const countBadge = document.getElementById('bgp-peers-count-badge');
  4488. const navBadge = document.getElementById('dyn-badge-bgp-peers');
  4489. const peers = state.bgpPeers || [];
  4490. if (countBadge) countBadge.innerText = `${peers.length} Peers`;
  4491. if (navBadge) navBadge.innerText = peers.length;
  4492. if (peers.length === 0) {
  4493. tbody.innerHTML = '';
  4494. empty.classList.remove('hidden');
  4495. return;
  4496. }
  4497. empty.classList.add('hidden');
  4498. tbody.innerHTML = peers.map(p => {
  4499. let flagA = !p.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  4500. let flagE = p.state === 'Established' ? '<span class="text-emerald-400 font-bold ml-1" title="Established">E</span>' : '';
  4501. let flagX = p.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
  4502. let stateBadge = '';
  4503. if (p.disabled) {
  4504. 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>';
  4505. } else if (p.state === 'Established') {
  4506. 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>';
  4507. } else if (p.state === 'Connect' || p.state === 'Active') {
  4508. 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>`;
  4509. } else {
  4510. 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>`;
  4511. }
  4512. return `
  4513. <tr class="hover:bg-slate-800/40 transition">
  4514. <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagE}${flagX}</td>
  4515. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(p.name)}</td>
  4516. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(p.remote_address)}</td>
  4517. <td class="py-2.5 px-3 font-bold text-slate-200">AS ${p.remote_as}</td>
  4518. <td class="py-2.5 px-3">${stateBadge}</td>
  4519. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(p.uptime || '-')}</td>
  4520. <td class="py-2.5 px-3 text-slate-300">
  4521. <span class="text-emerald-400 font-bold">↓ ${p.prefix_received || 0}</span> /
  4522. <span class="text-blue-400 font-bold">↑ ${p.prefix_sent || 0}</span>
  4523. </td>
  4524. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(p.comment || '')}</td>
  4525. <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
  4526. <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'}">
  4527. ${p.disabled ? 'Enable' : 'Disable'}
  4528. </button>
  4529. <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">
  4530. Edit
  4531. </button>
  4532. <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">
  4533. Delete
  4534. </button>
  4535. </td>
  4536. </tr>
  4537. `;
  4538. }).join('');
  4539. }
  4540. function renderBgpNetworks() {
  4541. const tbody = document.getElementById('bgp-nets-table-body');
  4542. const empty = document.getElementById('bgp-nets-empty');
  4543. const countBadge = document.getElementById('bgp-nets-count-badge');
  4544. const navBadge = document.getElementById('dyn-badge-bgp-nets');
  4545. const nets = state.bgpNets || [];
  4546. if (countBadge) countBadge.innerText = `${nets.length} Networks`;
  4547. if (navBadge) navBadge.innerText = nets.length;
  4548. if (nets.length === 0) {
  4549. tbody.innerHTML = '';
  4550. empty.classList.remove('hidden');
  4551. return;
  4552. }
  4553. empty.classList.add('hidden');
  4554. tbody.innerHTML = nets.map(n => `
  4555. <tr class="hover:bg-slate-800/40 transition">
  4556. <td class="py-2.5 px-3 font-semibold text-purple-300 font-mono">${escapeHtml(n.network)}</td>
  4557. <td class="py-2.5 px-3">
  4558. ${n.disabled
  4559. ? '<span class="px-2 py-0.5 rounded-full text-[10px] bg-slate-800 text-slate-400 border border-slate-700">Disabled</span>'
  4560. : '<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>'}
  4561. </td>
  4562. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(n.comment || '')}</td>
  4563. <td class="py-2.5 px-3 text-right space-x-1 font-sans">
  4564. <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">
  4565. Delete
  4566. </button>
  4567. </td>
  4568. </tr>
  4569. `).join('');
  4570. }
  4571. function renderBgpRoutes() {
  4572. const tbody = document.getElementById('bgp-routes-table-body');
  4573. const empty = document.getElementById('bgp-routes-empty');
  4574. const countBadge = document.getElementById('bgp-routes-count-badge');
  4575. const navBadge = document.getElementById('dyn-badge-bgp-routes');
  4576. const routes = state.bgpRoutes || [];
  4577. if (countBadge) countBadge.innerText = `${routes.length} Routes`;
  4578. if (navBadge) navBadge.innerText = routes.length;
  4579. if (routes.length === 0) {
  4580. tbody.innerHTML = '';
  4581. empty.classList.remove('hidden');
  4582. return;
  4583. }
  4584. empty.classList.add('hidden');
  4585. tbody.innerHTML = routes.map(r => `
  4586. <tr class="hover:bg-slate-800/40 transition">
  4587. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.prefix)}</td>
  4588. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(r.next_hop || '-')}</td>
  4589. <td class="py-2.5 px-3 text-slate-300">${r.metric}</td>
  4590. <td class="py-2.5 px-3 text-slate-300">${r.weight}</td>
  4591. <td class="py-2.5 px-3 text-amber-300">${escapeHtml(r.path || 'i')}</td>
  4592. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.origin || 'IGP')}</td>
  4593. </tr>
  4594. `).join('');
  4595. }
  4596. function renderOspfStatusPill() {
  4597. const pill = document.getElementById('ospf-live-status-pill');
  4598. if (!pill) return;
  4599. const inst = state.ospfInstance;
  4600. if (!inst || !inst.enabled) {
  4601. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-slate-800 text-slate-400 border border-slate-700';
  4602. pill.innerText = 'OSPF DISABLED';
  4603. } else if (inst.running) {
  4604. 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';
  4605. pill.innerText = `OSPF ACTIVE (ID: ${inst.router_id || 'Auto'})`;
  4606. } else {
  4607. 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';
  4608. pill.innerText = 'OSPF STARTING...';
  4609. }
  4610. }
  4611. function renderOspfInterfaces() {
  4612. const tbody = document.getElementById('ospf-ifaces-table-body');
  4613. const empty = document.getElementById('ospf-ifaces-empty');
  4614. const countBadge = document.getElementById('ospf-ifaces-count-badge');
  4615. const navBadge = document.getElementById('dyn-badge-ospf-ifaces');
  4616. const ifaces = state.ospfInterfaces || [];
  4617. if (countBadge) countBadge.innerText = `${ifaces.length} Interfaces`;
  4618. if (navBadge) navBadge.innerText = ifaces.length;
  4619. if (ifaces.length === 0) {
  4620. tbody.innerHTML = '';
  4621. empty.classList.remove('hidden');
  4622. return;
  4623. }
  4624. empty.classList.add('hidden');
  4625. tbody.innerHTML = ifaces.map(i => {
  4626. let flagA = !i.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  4627. let flagP = i.passive ? '<span class="text-amber-400 font-bold ml-1" title="Passive">P</span>' : '';
  4628. let flagX = i.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
  4629. return `
  4630. <tr class="hover:bg-slate-800/40 transition">
  4631. <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagP}${flagX}</td>
  4632. <td class="py-2.5 px-3 font-semibold text-white font-mono">${escapeHtml(i.network)}</td>
  4633. <td class="py-2.5 px-3 text-indigo-300 font-bold">Area ${escapeHtml(i.area)}</td>
  4634. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(i.interface || 'Any')}</td>
  4635. <td class="py-2.5 px-3 text-slate-300">${i.cost}</td>
  4636. <td class="py-2.5 px-3 text-slate-300">${i.priority}</td>
  4637. <td class="py-2.5 px-3 text-slate-400">${i.hello_interval}s / ${i.dead_interval}s</td>
  4638. <td class="py-2.5 px-3 text-slate-300 uppercase">${escapeHtml(i.auth_type || 'none')}</td>
  4639. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(i.comment || '')}</td>
  4640. <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
  4641. <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'}">
  4642. ${i.disabled ? 'Enable' : 'Disable'}
  4643. </button>
  4644. <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">
  4645. Edit
  4646. </button>
  4647. <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">
  4648. Delete
  4649. </button>
  4650. </td>
  4651. </tr>
  4652. `;
  4653. }).join('');
  4654. }
  4655. function renderOspfAreas() {
  4656. const tbody = document.getElementById('ospf-areas-table-body');
  4657. const countBadge = document.getElementById('ospf-areas-count-badge');
  4658. const navBadge = document.getElementById('dyn-badge-ospf-areas');
  4659. const areas = state.ospfAreas || [];
  4660. if (countBadge) countBadge.innerText = `${areas.length} Areas`;
  4661. if (navBadge) navBadge.innerText = areas.length;
  4662. tbody.innerHTML = areas.map(a => `
  4663. <tr class="hover:bg-slate-800/40 transition">
  4664. <td class="py-2.5 px-3 font-semibold text-white font-mono">${escapeHtml(a.name)}</td>
  4665. <td class="py-2.5 px-3 font-bold text-indigo-300">${escapeHtml(a.area_id)}</td>
  4666. <td class="py-2.5 px-3 text-slate-300 uppercase">${escapeHtml(a.area_type || 'default')}</td>
  4667. <td class="py-2.5 px-3 text-slate-400 font-sans">${escapeHtml(a.comment || '')}</td>
  4668. <td class="py-2.5 px-3 text-right font-sans">
  4669. <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">
  4670. Delete
  4671. </button>
  4672. </td>
  4673. </tr>
  4674. `).join('');
  4675. }
  4676. function renderOspfNeighbors() {
  4677. const tbody = document.getElementById('ospf-nbrs-table-body');
  4678. const empty = document.getElementById('ospf-nbrs-empty');
  4679. const countBadge = document.getElementById('ospf-nbrs-count-badge');
  4680. const navBadge = document.getElementById('dyn-badge-ospf-nbrs');
  4681. const nbrs = state.ospfNeighbors || [];
  4682. if (countBadge) countBadge.innerText = `${nbrs.length} Neighbors`;
  4683. if (navBadge) navBadge.innerText = nbrs.length;
  4684. if (nbrs.length === 0) {
  4685. tbody.innerHTML = '';
  4686. empty.classList.remove('hidden');
  4687. return;
  4688. }
  4689. empty.classList.add('hidden');
  4690. tbody.innerHTML = nbrs.map(n => {
  4691. let stateBadge = '';
  4692. if (n.state && (n.state.startsWith('Full') || n.state.includes('DR') || n.state.includes('Backup'))) {
  4693. 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>`;
  4694. } else {
  4695. 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>`;
  4696. }
  4697. return `
  4698. <tr class="hover:bg-slate-800/40 transition">
  4699. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(n.neighbor_id)}</td>
  4700. <td class="py-2.5 px-3 text-indigo-300 font-bold">${escapeHtml(n.address)}</td>
  4701. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(n.interface)}</td>
  4702. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(n.area || '0.0.0.0')}</td>
  4703. <td class="py-2.5 px-3">${stateBadge}</td>
  4704. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(n.dead_timer || '-')}</td>
  4705. </tr>
  4706. `;
  4707. }).join('');
  4708. }
  4709. function renderOspfRoutes() {
  4710. const tbody = document.getElementById('ospf-routes-table-body');
  4711. const empty = document.getElementById('ospf-routes-empty');
  4712. const countBadge = document.getElementById('ospf-routes-count-badge');
  4713. const navBadge = document.getElementById('dyn-badge-ospf-routes');
  4714. const routes = state.ospfRoutes || [];
  4715. if (countBadge) countBadge.innerText = `${routes.length} Routes`;
  4716. if (navBadge) navBadge.innerText = routes.length;
  4717. if (routes.length === 0) {
  4718. tbody.innerHTML = '';
  4719. empty.classList.remove('hidden');
  4720. return;
  4721. }
  4722. empty.classList.add('hidden');
  4723. tbody.innerHTML = routes.map(r => `
  4724. <tr class="hover:bg-slate-800/40 transition">
  4725. <td class="py-2.5 px-3 font-semibold text-white font-mono">${escapeHtml(r.prefix)}</td>
  4726. <td class="py-2.5 px-3 text-slate-300">${escapeHtml(r.route_type || 'Network')}</td>
  4727. <td class="py-2.5 px-3 text-slate-300">${r.cost}</td>
  4728. <td class="py-2.5 px-3 text-indigo-300 font-bold">Area ${escapeHtml(r.area || '0.0.0.0')}</td>
  4729. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(r.next_hop || r.interface || '-')}</td>
  4730. </tr>
  4731. `).join('');
  4732. }
  4733. // BGP Modals & Actions
  4734. function openBgpInstanceModal() {
  4735. const inst = state.bgpInstance || { enabled: false, as: 65001, router_id: '192.168.131.56', hold_time: 180, keepalive_time: 60 };
  4736. document.getElementById('modal-bgp-enabled').checked = !!inst.enabled;
  4737. document.getElementById('modal-bgp-as').value = inst.as || 65001;
  4738. document.getElementById('modal-bgp-router-id').value = inst.router_id || '';
  4739. document.getElementById('modal-bgp-keepalive').value = inst.keepalive_time || 60;
  4740. document.getElementById('modal-bgp-holdtime').value = inst.hold_time || 180;
  4741. document.getElementById('modal-bgp-redist-conn').checked = !!inst.redistribute_connected;
  4742. document.getElementById('modal-bgp-redist-static').checked = !!inst.redistribute_static;
  4743. document.getElementById('modal-bgp-redist-ospf').checked = !!inst.redistribute_ospf;
  4744. document.getElementById('bgp-instance-modal').classList.remove('hidden');
  4745. }
  4746. function closeBgpInstanceModal() {
  4747. document.getElementById('bgp-instance-modal').classList.add('hidden');
  4748. }
  4749. async function submitBgpInstance(e) {
  4750. e.preventDefault();
  4751. const payload = {
  4752. enabled: document.getElementById('modal-bgp-enabled').checked,
  4753. as: parseInt(document.getElementById('modal-bgp-as').value, 10),
  4754. router_id: document.getElementById('modal-bgp-router-id').value.trim(),
  4755. keepalive_time: parseInt(document.getElementById('modal-bgp-keepalive').value, 10),
  4756. hold_time: parseInt(document.getElementById('modal-bgp-holdtime').value, 10),
  4757. redistribute_connected: document.getElementById('modal-bgp-redist-conn').checked,
  4758. redistribute_static: document.getElementById('modal-bgp-redist-static').checked,
  4759. redistribute_ospf: document.getElementById('modal-bgp-redist-ospf').checked
  4760. };
  4761. try {
  4762. const res = await fetch(`${API_BASE}/routing/bgp/instance`, {
  4763. method: 'POST',
  4764. headers: { 'Content-Type': 'application/json' },
  4765. body: JSON.stringify(payload)
  4766. });
  4767. if (res.ok) {
  4768. closeBgpInstanceModal();
  4769. showToast('Success', 'BGP instance configuration updated', 'success');
  4770. loadDynamicRouting();
  4771. } else {
  4772. const err = await res.json();
  4773. showToast('Error', err.error || 'Failed to update BGP instance', 'error');
  4774. }
  4775. } catch (err) {
  4776. showToast('Error', err.message, 'error');
  4777. }
  4778. }
  4779. function openAddBgpPeerModal() {
  4780. document.getElementById('bgp-peer-form').reset();
  4781. document.getElementById('modal-bgp-peer-id').value = '';
  4782. document.getElementById('bgp-peer-modal-title').innerText = 'Add BGP Peer Connection';
  4783. document.getElementById('modal-bgp-peer-nexthop-self').checked = true;
  4784. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  4785. }
  4786. function openEditBgpPeerModal(id) {
  4787. const p = (state.bgpPeers || []).find(item => item.id === id);
  4788. if (!p) return;
  4789. document.getElementById('modal-bgp-peer-id').value = p.id;
  4790. document.getElementById('modal-bgp-peer-name').value = p.name || '';
  4791. document.getElementById('modal-bgp-peer-remote-addr').value = p.remote_address || '';
  4792. document.getElementById('modal-bgp-peer-remote-as').value = p.remote_as || '';
  4793. document.getElementById('modal-bgp-peer-local-addr').value = p.local_address || '';
  4794. document.getElementById('modal-bgp-peer-password').value = p.password || '';
  4795. document.getElementById('modal-bgp-peer-multihop').checked = !!p.multihop;
  4796. document.getElementById('modal-bgp-peer-nexthop-self').checked = !!p.nexthop_self;
  4797. document.getElementById('modal-bgp-peer-passive').checked = !!p.passive;
  4798. document.getElementById('modal-bgp-peer-disabled').checked = !!p.disabled;
  4799. document.getElementById('modal-bgp-peer-comment').value = p.comment || '';
  4800. document.getElementById('bgp-peer-modal-title').innerText = 'Edit BGP Peer Connection';
  4801. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  4802. }
  4803. function closeBgpPeerModal() {
  4804. document.getElementById('bgp-peer-modal').classList.add('hidden');
  4805. }
  4806. async function submitBgpPeer(e) {
  4807. e.preventDefault();
  4808. const payload = {
  4809. id: document.getElementById('modal-bgp-peer-id').value,
  4810. name: document.getElementById('modal-bgp-peer-name').value.trim(),
  4811. remote_address: document.getElementById('modal-bgp-peer-remote-addr').value.trim(),
  4812. remote_as: parseInt(document.getElementById('modal-bgp-peer-remote-as').value, 10),
  4813. local_address: document.getElementById('modal-bgp-peer-local-addr').value.trim(),
  4814. password: document.getElementById('modal-bgp-peer-password').value,
  4815. multihop: document.getElementById('modal-bgp-peer-multihop').checked,
  4816. nexthop_self: document.getElementById('modal-bgp-peer-nexthop-self').checked,
  4817. passive: document.getElementById('modal-bgp-peer-passive').checked,
  4818. disabled: document.getElementById('modal-bgp-peer-disabled').checked,
  4819. comment: document.getElementById('modal-bgp-peer-comment').value.trim()
  4820. };
  4821. try {
  4822. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  4823. method: 'POST',
  4824. headers: { 'Content-Type': 'application/json' },
  4825. body: JSON.stringify(payload)
  4826. });
  4827. if (res.ok) {
  4828. closeBgpPeerModal();
  4829. showToast('Success', 'BGP Peer saved', 'success');
  4830. loadDynamicRouting();
  4831. } else {
  4832. const err = await res.json();
  4833. showToast('Error', err.error || 'Failed to save peer', 'error');
  4834. }
  4835. } catch (err) {
  4836. showToast('Error', err.message, 'error');
  4837. }
  4838. }
  4839. async function deleteBgpPeer(id) {
  4840. if (!confirm('Are you sure you want to delete this BGP peer connection?')) return;
  4841. try {
  4842. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4843. if (res.ok) {
  4844. showToast('Deleted', 'BGP peer removed', 'success');
  4845. loadDynamicRouting();
  4846. }
  4847. } catch (err) {
  4848. showToast('Error', err.message, 'error');
  4849. }
  4850. }
  4851. async function toggleBgpPeerState(id, disabled) {
  4852. try {
  4853. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}/state`, {
  4854. method: 'POST',
  4855. headers: { 'Content-Type': 'application/json' },
  4856. body: JSON.stringify({ disabled })
  4857. });
  4858. if (res.ok) {
  4859. showToast('Updated', `Peer ${disabled ? 'disabled' : 'enabled'}`, 'success');
  4860. loadDynamicRouting();
  4861. }
  4862. } catch (err) {
  4863. showToast('Error', err.message, 'error');
  4864. }
  4865. }
  4866. function openAddBgpNetworkModal() {
  4867. document.getElementById('bgp-network-form').reset();
  4868. document.getElementById('modal-bgp-net-id').value = '';
  4869. document.getElementById('bgp-network-modal').classList.remove('hidden');
  4870. }
  4871. function closeBgpNetworkModal() {
  4872. document.getElementById('bgp-network-modal').classList.add('hidden');
  4873. }
  4874. async function submitBgpNetwork(e) {
  4875. e.preventDefault();
  4876. const payload = {
  4877. id: document.getElementById('modal-bgp-net-id').value,
  4878. network: document.getElementById('modal-bgp-net-cidr').value.trim(),
  4879. comment: document.getElementById('modal-bgp-net-comment').value.trim(),
  4880. disabled: document.getElementById('modal-bgp-net-disabled').checked
  4881. };
  4882. try {
  4883. const res = await fetch(`${API_BASE}/routing/bgp/networks`, {
  4884. method: 'POST',
  4885. headers: { 'Content-Type': 'application/json' },
  4886. body: JSON.stringify(payload)
  4887. });
  4888. if (res.ok) {
  4889. closeBgpNetworkModal();
  4890. showToast('Success', 'BGP network advertisement saved', 'success');
  4891. loadDynamicRouting();
  4892. } else {
  4893. const err = await res.json();
  4894. showToast('Error', err.error || 'Failed to save network', 'error');
  4895. }
  4896. } catch (err) {
  4897. showToast('Error', err.message, 'error');
  4898. }
  4899. }
  4900. async function deleteBgpNetwork(id) {
  4901. if (!confirm('Are you sure you want to stop announcing this network?')) return;
  4902. try {
  4903. const res = await fetch(`${API_BASE}/routing/bgp/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4904. if (res.ok) {
  4905. showToast('Deleted', 'Network advertisement removed', 'success');
  4906. loadDynamicRouting();
  4907. }
  4908. } catch (err) {
  4909. showToast('Error', err.message, 'error');
  4910. }
  4911. }
  4912. // OSPF Modals & Actions
  4913. function openOspfInstanceModal() {
  4914. const inst = state.ospfInstance || { enabled: false, router_id: '192.168.131.56', default_metric: 10 };
  4915. document.getElementById('modal-ospf-enabled').checked = !!inst.enabled;
  4916. document.getElementById('modal-ospf-router-id').value = inst.router_id || '';
  4917. document.getElementById('modal-ospf-metric').value = inst.default_metric || 10;
  4918. document.getElementById('modal-ospf-redist-conn').checked = !!inst.redistribute_connected;
  4919. document.getElementById('modal-ospf-redist-static').checked = !!inst.redistribute_static;
  4920. document.getElementById('modal-ospf-redist-bgp').checked = !!inst.redistribute_bgp;
  4921. document.getElementById('ospf-instance-modal').classList.remove('hidden');
  4922. }
  4923. function closeOspfInstanceModal() {
  4924. document.getElementById('ospf-instance-modal').classList.add('hidden');
  4925. }
  4926. async function submitOspfInstance(e) {
  4927. e.preventDefault();
  4928. const payload = {
  4929. enabled: document.getElementById('modal-ospf-enabled').checked,
  4930. router_id: document.getElementById('modal-ospf-router-id').value.trim(),
  4931. default_metric: parseInt(document.getElementById('modal-ospf-metric').value, 10),
  4932. redistribute_connected: document.getElementById('modal-ospf-redist-conn').checked,
  4933. redistribute_static: document.getElementById('modal-ospf-redist-static').checked,
  4934. redistribute_bgp: document.getElementById('modal-ospf-redist-bgp').checked
  4935. };
  4936. try {
  4937. const res = await fetch(`${API_BASE}/routing/ospf/instance`, {
  4938. method: 'POST',
  4939. headers: { 'Content-Type': 'application/json' },
  4940. body: JSON.stringify(payload)
  4941. });
  4942. if (res.ok) {
  4943. closeOspfInstanceModal();
  4944. showToast('Success', 'OSPF instance configuration updated', 'success');
  4945. loadDynamicRouting();
  4946. } else {
  4947. const err = await res.json();
  4948. showToast('Error', err.error || 'Failed to update OSPF instance', 'error');
  4949. }
  4950. } catch (err) {
  4951. showToast('Error', err.message, 'error');
  4952. }
  4953. }
  4954. function openAddOspfAreaModal() {
  4955. document.getElementById('ospf-area-form').reset();
  4956. document.getElementById('modal-ospf-area-id').value = '';
  4957. document.getElementById('modal-ospf-area-areaid').value = '0.0.0.0';
  4958. document.getElementById('ospf-area-modal').classList.remove('hidden');
  4959. }
  4960. function closeOspfAreaModal() {
  4961. document.getElementById('ospf-area-modal').classList.add('hidden');
  4962. }
  4963. async function submitOspfArea(e) {
  4964. e.preventDefault();
  4965. const payload = {
  4966. id: document.getElementById('modal-ospf-area-id').value,
  4967. name: document.getElementById('modal-ospf-area-name').value.trim(),
  4968. area_id: document.getElementById('modal-ospf-area-areaid').value.trim(),
  4969. area_type: document.getElementById('modal-ospf-area-type').value,
  4970. comment: document.getElementById('modal-ospf-area-comment').value.trim()
  4971. };
  4972. try {
  4973. const res = await fetch(`${API_BASE}/routing/ospf/areas`, {
  4974. method: 'POST',
  4975. headers: { 'Content-Type': 'application/json' },
  4976. body: JSON.stringify(payload)
  4977. });
  4978. if (res.ok) {
  4979. closeOspfAreaModal();
  4980. showToast('Success', 'OSPF area saved', 'success');
  4981. loadDynamicRouting();
  4982. } else {
  4983. const err = await res.json();
  4984. showToast('Error', err.error || 'Failed to save area', 'error');
  4985. }
  4986. } catch (err) {
  4987. showToast('Error', err.message, 'error');
  4988. }
  4989. }
  4990. async function deleteOspfArea(id) {
  4991. if (!confirm('Are you sure you want to delete this OSPF area?')) return;
  4992. try {
  4993. const res = await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4994. if (res.ok) {
  4995. showToast('Deleted', 'OSPF area removed', 'success');
  4996. loadDynamicRouting();
  4997. }
  4998. } catch (err) {
  4999. showToast('Error', err.message, 'error');
  5000. }
  5001. }
  5002. function populateOspfInterfaceDevices() {
  5003. const select = document.getElementById('modal-ospf-iface-device');
  5004. if (!select) return;
  5005. const current = select.value;
  5006. select.innerHTML = '<option value="">Any matching interface</option>';
  5007. (state.interfaces || []).forEach(iface => {
  5008. select.innerHTML += `<option value="${escapeHtml(iface.name)}">${escapeHtml(iface.name)} (${iface.type})</option>`;
  5009. });
  5010. if (current) select.value = current;
  5011. }
  5012. function openAddOspfInterfaceModal() {
  5013. document.getElementById('ospf-interface-form').reset();
  5014. document.getElementById('modal-ospf-iface-id').value = '';
  5015. document.getElementById('modal-ospf-iface-area').value = '0.0.0.0';
  5016. document.getElementById('modal-ospf-iface-cost').value = '10';
  5017. document.getElementById('modal-ospf-iface-priority').value = '1';
  5018. document.getElementById('modal-ospf-iface-hello').value = '10';
  5019. document.getElementById('modal-ospf-iface-dead').value = '40';
  5020. document.getElementById('ospf-interface-modal-title').innerText = 'Add OSPF Interface';
  5021. populateOspfInterfaceDevices();
  5022. document.getElementById('ospf-interface-modal').classList.remove('hidden');
  5023. }
  5024. function openEditOspfInterfaceModal(id) {
  5025. const item = (state.ospfInterfaces || []).find(i => i.id === id);
  5026. if (!item) return;
  5027. populateOspfInterfaceDevices();
  5028. document.getElementById('modal-ospf-iface-id').value = item.id;
  5029. document.getElementById('modal-ospf-iface-net').value = item.network || '';
  5030. document.getElementById('modal-ospf-iface-area').value = item.area || '0.0.0.0';
  5031. document.getElementById('modal-ospf-iface-device').value = item.interface || '';
  5032. document.getElementById('modal-ospf-iface-cost').value = item.cost || 10;
  5033. document.getElementById('modal-ospf-iface-priority').value = item.priority || 1;
  5034. document.getElementById('modal-ospf-iface-hello').value = item.hello_interval || 10;
  5035. document.getElementById('modal-ospf-iface-dead').value = item.dead_interval || 40;
  5036. document.getElementById('modal-ospf-iface-auth-type').value = item.auth_type || 'none';
  5037. document.getElementById('modal-ospf-iface-auth-key').value = item.auth_key || '';
  5038. document.getElementById('modal-ospf-iface-passive').checked = !!item.passive;
  5039. document.getElementById('modal-ospf-iface-disabled').checked = !!item.disabled;
  5040. document.getElementById('modal-ospf-iface-comment').value = item.comment || '';
  5041. document.getElementById('ospf-interface-modal-title').innerText = 'Edit OSPF Interface';
  5042. document.getElementById('ospf-interface-modal').classList.remove('hidden');
  5043. }
  5044. function closeOspfInterfaceModal() {
  5045. document.getElementById('ospf-interface-modal').classList.add('hidden');
  5046. }
  5047. async function submitOspfInterface(e) {
  5048. e.preventDefault();
  5049. const payload = {
  5050. id: document.getElementById('modal-ospf-iface-id').value,
  5051. network: document.getElementById('modal-ospf-iface-net').value.trim(),
  5052. area: document.getElementById('modal-ospf-iface-area').value.trim(),
  5053. interface: document.getElementById('modal-ospf-iface-device').value,
  5054. cost: parseInt(document.getElementById('modal-ospf-iface-cost').value, 10),
  5055. priority: parseInt(document.getElementById('modal-ospf-iface-priority').value, 10),
  5056. hello_interval: parseInt(document.getElementById('modal-ospf-iface-hello').value, 10),
  5057. dead_interval: parseInt(document.getElementById('modal-ospf-iface-dead').value, 10),
  5058. auth_type: document.getElementById('modal-ospf-iface-auth-type').value,
  5059. auth_key: document.getElementById('modal-ospf-iface-auth-key').value,
  5060. passive: document.getElementById('modal-ospf-iface-passive').checked,
  5061. disabled: document.getElementById('modal-ospf-iface-disabled').checked,
  5062. comment: document.getElementById('modal-ospf-iface-comment').value.trim()
  5063. };
  5064. try {
  5065. const res = await fetch(`${API_BASE}/routing/ospf/interfaces`, {
  5066. method: 'POST',
  5067. headers: { 'Content-Type': 'application/json' },
  5068. body: JSON.stringify(payload)
  5069. });
  5070. if (res.ok) {
  5071. closeOspfInterfaceModal();
  5072. showToast('Success', 'OSPF interface template saved', 'success');
  5073. loadDynamicRouting();
  5074. } else {
  5075. const err = await res.json();
  5076. showToast('Error', err.error || 'Failed to save interface', 'error');
  5077. }
  5078. } catch (err) {
  5079. showToast('Error', err.message, 'error');
  5080. }
  5081. }
  5082. async function deleteOspfInterface(id) {
  5083. if (!confirm('Are you sure you want to delete this OSPF interface?')) return;
  5084. try {
  5085. const res = await fetch(`${API_BASE}/routing/ospf/interfaces/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5086. if (res.ok) {
  5087. showToast('Deleted', 'OSPF interface removed', 'success');
  5088. loadDynamicRouting();
  5089. }
  5090. } catch (err) {
  5091. showToast('Error', err.message, 'error');
  5092. }
  5093. }
  5094. async function toggleOspfInterfaceState(id, disabled) {
  5095. try {
  5096. const res = await fetch(`${API_BASE}/routing/ospf/interfaces/${encodeURIComponent(id)}/state`, {
  5097. method: 'POST',
  5098. headers: { 'Content-Type': 'application/json' },
  5099. body: JSON.stringify({ disabled })
  5100. });
  5101. if (res.ok) {
  5102. showToast('Updated', `Interface ${disabled ? 'disabled' : 'enabled'}`, 'success');
  5103. loadDynamicRouting();
  5104. }
  5105. } catch (err) {
  5106. showToast('Error', err.message, 'error');
  5107. }
  5108. }