upstreams.html 26 KB

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