upstreams.html 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <!-- Notes: This should be open in its original path-->
  5. <meta charset="utf-8">
  6. <meta name="zoraxy.csrf.Token" content="{{.csrfToken}}">
  7. <link rel="stylesheet" href="../script/semantic/semantic.min.css">
  8. <script src="../script/jquery-3.6.0.min.js"></script>
  9. <script src="../script/semantic/semantic.min.js"></script>
  10. <script src="../script/utils.js"></script>
  11. <style>
  12. .upstreamActions{
  13. position: absolute;
  14. top: 0.6em;
  15. right: 0.6em;
  16. }
  17. .upstreamLink{
  18. max-width: 220px;
  19. display: inline-block;
  20. word-break: break-all;
  21. }
  22. .upstreamEntry .ui.toggle.checkbox input:checked ~ label::before{
  23. background-color: #00ca52 !important;
  24. }
  25. #activateNewUpstream.ui.toggle.checkbox input:checked ~ label::before{
  26. background-color: #00ca52 !important;
  27. }
  28. #upstreamTable{
  29. max-height: 480px;
  30. border-radius: 0.3em;
  31. padding: 0.3em;
  32. overflow-y: auto;
  33. }
  34. .upstreamEntry.inactive{
  35. background-color: #f3f3f3 !important;
  36. }
  37. .upstreamEntry{
  38. border-radius: 0.4em !important;
  39. border: 1px solid rgb(233, 233, 233) !important;
  40. }
  41. @media (max-width: 499px) {
  42. .upstreamActions{
  43. position: relative;
  44. margin-top: 1em;
  45. margin-left: 0.4em;
  46. margin-bottom: 0.4em;
  47. }
  48. }
  49. </style>
  50. </head>
  51. <body>
  52. <br>
  53. <div class="ui container">
  54. <div class="ui header">
  55. <div class="content">
  56. Upstreams / Load Balance
  57. <div class="sub header epname"></div>
  58. </div>
  59. </div>
  60. <div class="ui divider"></div>
  61. <div class="ui small pointing secondary menu">
  62. <a class="item active narrowpadding" data-tab="upstreamlist">Upstreams</a>
  63. <a class="item narrowpadding" data-tab="newupstream">Add Upstream</a>
  64. </div>
  65. <div class="ui tab basic segment active" data-tab="upstreamlist">
  66. <!-- A list of current existing upstream on this reverse proxy-->
  67. <div id="upstreamTable">
  68. <div class="ui segment">
  69. <a><i class="ui loading spinner icon"></i> Loading</a>
  70. </div>
  71. </div>
  72. <div class="ui message">
  73. <i class="ui blue info circle icon"></i> Weighted random will be used for load-balancing. Set weight to 0 for fallback only.
  74. </div>
  75. </div>
  76. <div class="ui tab basic segment" data-tab="newupstream">
  77. <!-- Web Form to create a new upstream -->
  78. <h4 class="ui header">
  79. <i class="green add icon"></i>
  80. <div class="content">
  81. Add Upstream Server
  82. <div class="sub header">Create new load balance or fallback upstream origin</div>
  83. </div>
  84. </h4>
  85. <p style="margin-bottom: 0.4em;">Target IP address with port</p>
  86. <div class="ui fluid small input">
  87. <input type="text" id="originURL" onchange="cleanProxyTargetValue(this);"><br>
  88. </div>
  89. <small>E.g. 192.168.0.101:8000 or example.com</small>
  90. <br><br>
  91. <div id="activateNewUpstream" class="ui toggle checkbox" style="display:inline-block;">
  92. <input type="checkbox" id="activateNewUpstreamCheckbox" style="margin-top: 0.4em;" checked>
  93. <label>Activate<br>
  94. <small>Enable this upstream for load balancing</small></label>
  95. </div><br>
  96. <div class="ui checkbox" style="margin-top: 1.2em;">
  97. <input type="checkbox" id="requireTLS">
  98. <label>Require TLS<br>
  99. <small>Proxy target require HTTPS connection</small></label>
  100. </div><br>
  101. <div class="ui checkbox" style="margin-top: 0.6em;">
  102. <input type="checkbox" id="skipTlsVerification">
  103. <label>Skip Verification<br>
  104. <small>Check this if proxy target is using self signed certificates</small></label>
  105. </div><br>
  106. <div class="ui checkbox" style="margin-top: 0.4em;">
  107. <input type="checkbox" id="SkipWebSocketOriginCheck" checked>
  108. <label>Skip WebSocket Origin Check<br>
  109. <small>Check this to allow cross-origin websocket requests</small></label>
  110. </div>
  111. <br><br>
  112. <button class="ui basic button" onclick="addNewUpstream();"><i class="ui green circle add icon"></i> Create</button>
  113. </div>
  114. <div class="ui divider"></div>
  115. <div class="field" >
  116. <button class="ui basic button" style="float: right;" onclick="closeThisWrapper();">Close</button>
  117. </div>
  118. </div>
  119. <br><br><br><br>
  120. </div>
  121. <script>
  122. let origins = [];
  123. let editingEndpoint = {};
  124. $('.menu .item').tab();
  125. function initOriginList(){
  126. $.ajax({
  127. url: "/api/proxy/upstream/list",
  128. method: "GET",
  129. data: {
  130. "type":"host",
  131. "ep": editingEndpoint.ep
  132. },
  133. success: function(data){
  134. if (data.error != undefined){
  135. //This endpoint not exists?
  136. alert(data.error);
  137. return;
  138. }else{
  139. $("#upstreamTable").html("");
  140. if (data.ActiveOrigins.length == 0){
  141. //There is no upstream for this proxy rule
  142. $("#upstreamTable").append(`<tr>
  143. <td colspan="2"><b><i class="ui yellow exclamation triangle icon"></i> No Active Upstream Origin</b><br>
  144. This HTTP proxy rule will always return Error 521 when requested. To fix this, add or enable a upstream origin to this proxy endpoint.
  145. <div class="ui divider"></div>
  146. </td>
  147. </tr>`);
  148. }
  149. data.ActiveOrigins.forEach(upstream => {
  150. renderUpstreamEntryToTable(upstream, true);
  151. });
  152. data.InactiveOrigins.forEach(upstream => {
  153. renderUpstreamEntryToTable(upstream, false);
  154. });
  155. let totalUpstreams = data.ActiveOrigins.length + data.InactiveOrigins.length;
  156. if (totalUpstreams == 1){
  157. $(".lowPriorityButton").addClass('disabled');
  158. }
  159. if (parent && parent.document.getElementById("httpProxyList") != null){
  160. //Also update the parent display
  161. let element = $(parent.document.getElementById("httpProxyList")).find(".upstreamList.editing");
  162. let upstreams = "";
  163. data.ActiveOrigins.forEach(upstream => {
  164. //Check if the upstreams require TLS connections
  165. let tlsIcon = "";
  166. if (upstream.RequireTLS){
  167. tlsIcon = `<i class="green lock icon" title="TLS Mode"></i>`;
  168. if (upstream.SkipCertValidations){
  169. tlsIcon = `<i class="yellow lock icon" title="TLS/SSL mode without verification"></i>`
  170. }
  171. }
  172. let upstreamLink = `${upstream.RequireTLS?"https://":"http://"}${upstream.OriginIpOrDomain}`;
  173. upstreams += `<a href="${upstreamLink}" target="_blank">${upstream.OriginIpOrDomain} ${tlsIcon}</a><br>`;
  174. });
  175. if (data.ActiveOrigins.length == 0){
  176. upstreams = `<i class="ui yellow exclamation triangle icon"></i> No Active Upstream Origin<br>`
  177. }
  178. $(element).html(upstreams);
  179. }
  180. $(".ui.checkbox").checkbox();
  181. }
  182. }
  183. })
  184. }
  185. function renderUpstreamEntryToTable(upstream, isActive){
  186. function newUID(){return"00000000-0000-4000-8000-000000000000".replace(/0/g,function(){return(0|Math.random()*16).toString(16)})};
  187. let tlsIcon = "";
  188. if (upstream.RequireTLS){
  189. tlsIcon = `<i class="green lock icon" title="TLS Mode"></i>`;
  190. if (upstream.SkipCertValidations){
  191. tlsIcon = `<i class="yellow lock icon" title="TLS/SSL mode without verification"></i>`
  192. }
  193. }
  194. //Priority Arrows
  195. let downArrowClass = "";
  196. if (upstream.Weight == 0 ){
  197. //Cannot go any lower
  198. downArrowClass = "disabled";
  199. }
  200. let url = `${upstream.RequireTLS?"https://":"http://"}${upstream.OriginIpOrDomain}`
  201. let payload = encodeURIComponent(JSON.stringify(upstream));
  202. let domUID = newUID();
  203. $("#upstreamTable").append(`<div class="ui upstreamEntry ${isActive?"":"inactive"} basic segment" data-domid="${domUID}" data-payload="${payload}" data-priority="${upstream.Priority}">
  204. <h4 class="ui header">
  205. <div class="ui toggle checkbox" style="display:inline-block;">
  206. <input type="checkbox" class="enableState" name="enabled" style="margin-top: 0.4em;" onchange="saveUpstreamUpdate('${domUID}');" ${isActive?"checked":""}>
  207. <label></label>
  208. </div>
  209. <div class="content">
  210. <a href="${url}" target="_blank" class="upstreamLink">${upstream.OriginIpOrDomain} ${tlsIcon}</a>
  211. <div class="sub header">${isActive?(upstream.Weight==0?"Fallback Only":"Active"):"Inactive"} | Weight: ${upstream.Weight}x </div>
  212. </div>
  213. </h4>
  214. <div class="advanceOptions" style="display:none;">
  215. <div class="upstreamOriginField">
  216. <p>New upstream origin IP address or domain</p>
  217. <div class="ui small fluid input" style="margin-top: -0.6em;">
  218. <input type="text" class="newOrigin" value="${upstream.OriginIpOrDomain}" onchange="handleAutoOriginClean('${domUID}');">
  219. </div>
  220. <small>e.g. 192.168.0.101:8000 or example.com</small>
  221. </div>
  222. <div class="ui divider"></div>
  223. <div class="ui checkbox">
  224. <input type="checkbox" class="reqTLSCheckbox" ${upstream.RequireTLS?"checked":""}>
  225. <label>Require TLS<br>
  226. <small>Proxy target require HTTPS connection</small></label>
  227. </div><br>
  228. <div class="ui checkbox" style="margin-top: 0.6em;">
  229. <input type="checkbox" class="skipVerificationCheckbox" ${upstream.SkipCertValidations?"checked":""}>
  230. <label>Skip Verification<br>
  231. <small>Check this if proxy target is using self signed certificates</small></label>
  232. </div><br>
  233. <div class="ui checkbox" style="margin-top: 0.4em;">
  234. <input type="checkbox" class="SkipWebSocketOriginCheck" ${upstream.SkipWebSocketOriginCheck?"checked":""}>
  235. <label>Skip WebSocket Origin Check<br>
  236. <small>Check this to allow cross-origin websocket requests</small></label>
  237. </div><br>
  238. </div>
  239. <div class="upstreamActions">
  240. <!-- Change Priority -->
  241. <button class="ui basic circular icon button highPriorityButton" title="Increase Weight" onclick="increaseUpstreamWeight('${domUID}');"><i class="ui arrow up icon"></i></button>
  242. <button class="ui basic circular icon button lowPriorityButton ${downArrowClass}" title="Reduce Weight" onclick="decreaseUpstreamWeight('${domUID}');"><i class="ui arrow down icon"></i></button>
  243. <button class="ui basic circular icon editbtn button" onclick="handleUpstreamOriginEdit('${domUID}');" title="Edit Upstream Destination"><i class="ui grey edit icon"></i></button>
  244. <button style="display:none;" class="ui basic circular icon trashbtn button" onclick="removeUpstream('${domUID}');" title="Remove Upstream"><i class="ui red trash icon"></i></button>
  245. <button style="display:none;" class="ui basic circular icon savebtn button" onclick="saveUpstreamUpdate('${domUID}');" title="Save Changes"><i class="ui green save icon"></i></button>
  246. <button style="display:none;" class="ui basic circular icon cancelbtn button" onclick="initOriginList();" title="Cancel"><i class="ui grey times icon"></i></button>
  247. </div>
  248. </div>`);
  249. }
  250. /* New Upstream Origin Functions */
  251. //Clearn the proxy target value, make sure user do not enter http:// or https://
  252. //and auto select TLS checkbox if https:// exists
  253. function cleanProxyTargetValue(input){
  254. let targetDomain = $(input).val().trim();
  255. if (targetDomain.startsWith("http://")){
  256. targetDomain = targetDomain.substr(7);
  257. $(input).val(targetDomain);
  258. $("#requireTLS").parent().checkbox("set unchecked");
  259. }else if (targetDomain.startsWith("https://")){
  260. targetDomain = targetDomain.substr(8);
  261. $(input).val(targetDomain);
  262. $("#requireTLS").parent().checkbox("set checked");
  263. }else{
  264. //URL does not contains https or http protocol tag
  265. //sniff header
  266. $.cjax({
  267. url: "/api/proxy/tlscheck",
  268. method: "POST",
  269. data: {url: targetDomain},
  270. success: function(data){
  271. if (data.error != undefined){
  272. }else if (data == "https"){
  273. $("#requireTLS").parent().checkbox("set checked");
  274. }else if (data == "http"){
  275. $("#requireTLS").parent().checkbox("set unchecked");
  276. }
  277. }
  278. })
  279. }
  280. }
  281. //Add a new upstream to this http proxy rule
  282. function addNewUpstream(){
  283. let origin = $("#originURL").val().trim();
  284. let requireTLS = $("#requireTLS")[0].checked;
  285. let skipVerification = $("#skipTlsVerification")[0].checked;
  286. let skipWebSocketOriginCheck = $("#SkipWebSocketOriginCheck")[0].checked;
  287. let activateLoadbalancer = $("#activateNewUpstreamCheckbox")[0].checked;
  288. if (origin == ""){
  289. parent.msgbox("Upstream origin cannot be empty", false);
  290. return;
  291. }
  292. $.cjax({
  293. url: "/api/proxy/upstream/add",
  294. method: "POST",
  295. data:{
  296. "ep": editingEndpoint.ep,
  297. "origin": origin,
  298. "tls": requireTLS,
  299. "tlsval": skipVerification,
  300. "bpwsorg":skipWebSocketOriginCheck,
  301. "active": activateLoadbalancer,
  302. },
  303. success: function(data){
  304. if (data.error != undefined){
  305. parent.msgbox(data.error, false);
  306. }else{
  307. parent.msgbox("New upstream origin added");
  308. initOriginList();
  309. $("#originURL").val("");
  310. }
  311. }
  312. })
  313. }
  314. //Get a upstream setting data from DOM element
  315. function getUpstreamSettingFromDOM(upstream){
  316. //Get the original setting from DOM payload
  317. let originalSettings = $(upstream).attr("data-payload");
  318. originalSettings = JSON.parse(decodeURIComponent(originalSettings));
  319. //Get the updated settings if any
  320. let requireTLS = $(upstream).find(".reqTLSCheckbox")[0].checked;
  321. let skipTLSVerification = $(upstream).find(".skipVerificationCheckbox")[0].checked;
  322. let skipWebSocketOriginCheck = $(upstream).find(".SkipWebSocketOriginCheck")[0].checked;
  323. //Update the original setting with new one just applied
  324. originalSettings.OriginIpOrDomain = $(upstream).find(".newOrigin").val();
  325. originalSettings.RequireTLS = requireTLS;
  326. originalSettings.SkipCertValidations = skipTLSVerification;
  327. originalSettings.SkipWebSocketOriginCheck = skipWebSocketOriginCheck;
  328. //console.log(originalSettings);
  329. return originalSettings;
  330. }
  331. //Handle setting change on upstream config
  332. function saveUpstreamUpdate(upstreamDomID){
  333. let targetDOM = $(`.upstreamEntry[data-domid=${upstreamDomID}]`);
  334. let originalSettings = $(targetDOM).attr("data-payload");
  335. originalSettings = JSON.parse(decodeURIComponent(originalSettings));
  336. let newConfig = getUpstreamSettingFromDOM(targetDOM);
  337. let isActive = $(targetDOM).find(".enableState")[0].checked;
  338. console.log(newConfig);
  339. $.cjax({
  340. url: "/api/proxy/upstream/update",
  341. method: "POST",
  342. data: {
  343. ep: editingEndpoint.ep,
  344. origin: originalSettings.OriginIpOrDomain, //Original ip or domain as key
  345. payload: JSON.stringify(newConfig),
  346. active: isActive,
  347. },
  348. success: function(data){
  349. if (data.error != undefined){
  350. parent.msgbox(data.error, false);
  351. }else{
  352. parent.msgbox("Upstream setting updated");
  353. initOriginList();
  354. }
  355. }
  356. })
  357. }
  358. //Edit the upstream origin of this upstream entry
  359. function handleUpstreamOriginEdit(upstreamDomID){
  360. let targetDOM = $(`.upstreamEntry[data-domid=${upstreamDomID}]`);
  361. let originalSettings = getUpstreamSettingsFromDomID(upstreamDomID);
  362. let originIP = originalSettings.OriginIpOrDomain;
  363. //Change the UI to edit mode
  364. $(".editbtn").hide();
  365. $(".lowPriorityButton").hide();
  366. $(".highPriorityButton").hide();
  367. $(targetDOM).find(".trashbtn").show();
  368. $(targetDOM).find(".savebtn").show();
  369. $(targetDOM).find(".cancelbtn").show();
  370. $(targetDOM).find(".advanceOptions").show();
  371. }
  372. //Check if the entered URL contains http or https
  373. function handleAutoOriginClean(domid){
  374. let targetDOM = $(`.upstreamEntry[data-domid=${domid}]`);
  375. let targetTLSCheckbox = $(targetDOM).find(".reqTLSCheckbox");
  376. let targetDomain = $(targetDOM).find(".newOrigin").val().trim();
  377. if (targetDomain.startsWith("http://")){
  378. targetDomain = targetDomain.substr(7);
  379. $(input).val(targetDomain);
  380. $(targetTLSCheckbox).parent().checkbox("set unchecked");
  381. }else if (targetDomain.startsWith("https://")){
  382. targetDomain = targetDomain.substr(8);
  383. $(input).val(targetDomain);
  384. $(targetTLSCheckbox).parent().checkbox("set checked");
  385. }else{
  386. //URL does not contains https or http protocol tag
  387. //sniff header
  388. $.cjax({
  389. url: "/api/proxy/tlscheck",
  390. method: "POST",
  391. data: {url: targetDomain},
  392. success: function(data){
  393. if (data.error != undefined){
  394. }else if (data == "https"){
  395. $(targetTLSCheckbox).parent().checkbox("set checked");
  396. }else if (data == "http"){
  397. $(targetTLSCheckbox).parent().checkbox("set unchecked");
  398. }
  399. }
  400. })
  401. }
  402. }
  403. function getUpstreamSettingsFromDomID(domid){
  404. let targetDOM = $(`.upstreamEntry[data-domid=${domid}]`);
  405. if (targetDOM.length == 0){
  406. return undefined;
  407. }
  408. let upstreamSettings = $(targetDOM).attr("data-payload");
  409. upstreamSettings = JSON.parse(decodeURIComponent(upstreamSettings));
  410. return upstreamSettings;
  411. }
  412. function increaseUpstreamWeight(domid){
  413. let upstreamSetting = getUpstreamSettingsFromDomID(domid);
  414. let originIP = upstreamSetting.OriginIpOrDomain;
  415. let currentWeight = upstreamSetting.Weight;
  416. setUpstreamWeight(originIP, currentWeight+1);
  417. }
  418. function decreaseUpstreamWeight(domid){
  419. let upstreamSetting = getUpstreamSettingsFromDomID(domid);
  420. let originIP = upstreamSetting.OriginIpOrDomain;
  421. let currentWeight = upstreamSetting.Weight;
  422. setUpstreamWeight(originIP, currentWeight-1);
  423. }
  424. //Set a weight of a upstream
  425. function setUpstreamWeight(originIP, newWeight){
  426. $.cjax({
  427. url: "/api/proxy/upstream/setPriority",
  428. method: "POST",
  429. data: {
  430. ep: editingEndpoint.ep,
  431. origin: originIP,
  432. weight: newWeight,
  433. },
  434. success: function(data){
  435. if (data.error != undefined){
  436. parent.msgbox(data.error, false);
  437. }else{
  438. parent.msgbox("Upstream Weight Updated");
  439. initOriginList();
  440. }
  441. }
  442. })
  443. }
  444. //Handle removal of an upstream
  445. function removeUpstream(domid){
  446. let targetDOM = $(`.upstreamEntry[data-domid=${domid}]`);
  447. let originalSettings = $(targetDOM).attr("data-payload");
  448. originalSettings = JSON.parse(decodeURIComponent(originalSettings));
  449. let UpstreamKey = originalSettings.OriginIpOrDomain;
  450. if (!confirm("Confirm removing " + UpstreamKey + " from upstream?")){
  451. return;
  452. }
  453. //Remove the upstream
  454. $.cjax({
  455. url: "/api/proxy/upstream/remove",
  456. method: "POST",
  457. data: {
  458. ep: editingEndpoint.ep,
  459. origin: originalSettings.OriginIpOrDomain, //Original ip or domain as key
  460. },
  461. success: function(data){
  462. if (data.error != undefined){
  463. parent.msgbox(data.error, false);
  464. }else{
  465. parent.msgbox("Upstream deleted");
  466. initOriginList();
  467. }
  468. }
  469. })
  470. }
  471. if (window.location.hash.length > 1){
  472. let payloadHash = window.location.hash.substr(1);
  473. try{
  474. payloadHash = JSON.parse(decodeURIComponent(payloadHash));
  475. $(".epname").text(payloadHash.ep);
  476. editingEndpoint = payloadHash;
  477. initOriginList();
  478. }catch(ex){
  479. console.log("Unable to load endpoint data from hash")
  480. }
  481. }
  482. function closeThisWrapper(){
  483. parent.hideSideWrapper(true);
  484. }
  485. </script>
  486. </body>
  487. </html>