utils.html 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  1. <div class="standardContainer">
  2. <div class="ui basic segment">
  3. <h2>Utilities</h2>
  4. <p>You might find these tools or information helpful when setting up your gateway server</p>
  5. </div>
  6. <div class="ui divider"></div>
  7. <div class="selfauthOnly">
  8. <h3>Account Management</h3>
  9. <p>Functions to help management the current account</p>
  10. <div class="ui basic segment">
  11. <h5><i class="chevron down icon"></i> Change Password</h5>
  12. <div class="ui form">
  13. <div class="field">
  14. <label>Current Password</label>
  15. <input type="password" name="oldPassword" placeholder="Current Password">
  16. </div>
  17. <div class="field">
  18. <label>New Password</label>
  19. <input type="password" name="newPassword" placeholder="New Password">
  20. </div>
  21. <div class="field">
  22. <label>Confirm New Password</label>
  23. <input type="password" name="confirmNewPassword" placeholder="Confirm New Password">
  24. </div>
  25. <button class="ui basic button" onclick="changePassword()"><i class="ui teal key icon"></i> Change Password</button>
  26. </div>
  27. <div id="passwordChangeSuccMsg" class="ui green message" style="display:none;">
  28. <i class="ui circle checkmark green icon "></i> Password Updated
  29. </div>
  30. </div>
  31. <div class="ui divider"></div>
  32. <h3>Forget Password Email</h3>
  33. <p>The following SMTP settings help you to reset your password in case you have lost your management account.</p>
  34. <form id="email-form" class="ui form">
  35. <div class="field">
  36. <label>Sender Address</label>
  37. <input type="text" name="senderAddr" placeholder="E.g. [email protected]">
  38. </div>
  39. <div class="field">
  40. <p><i class="caret down icon"></i> Connection setup for email service provider</p>
  41. <div class="fields">
  42. <div class="twelve wide field">
  43. <label>SMTP Provider Hostname</label>
  44. <input type="text" name="hostname" placeholder="E.g. mail.gandi.net">
  45. </div>
  46. <div class="four wide field">
  47. <label>Port</label>
  48. <input type="number" name="port" placeholder="E.g. 587" value="587">
  49. </div>
  50. </div>
  51. </div>
  52. <div class="field">
  53. <p><i class="caret down icon"></i> Credentials for SMTP server authentications</p>
  54. <div class="two fields">
  55. <div class="field">
  56. <label>Sender Username</label>
  57. <input type="text" name="username" placeholder="E.g. admin">
  58. </div>
  59. <div class="field">
  60. <label>Sender Domain</label>
  61. <div class="ui labeled input">
  62. <div class="ui basic label">
  63. @
  64. </div>
  65. <input type="text" name="domain" min="1" max="65534" placeholder="E.g. arozos.com">
  66. </div>
  67. </div>
  68. </div>
  69. </div>
  70. <div class="field">
  71. <label>Sender Password</label>
  72. <input type="password" name="password" placeholder="Password of the email account">
  73. <small>Leave empty to use the old password</small>
  74. </div>
  75. <p> <i class="caret down icon"></i> Email for sending account reset link</p>
  76. <div class="field">
  77. <label>Admin / Receiver Address</label>
  78. <input type="text" name="recvAddr" placeholder="E.g. [email protected]">
  79. </div>
  80. <button class="ui basic button" type="submit"><i class="blue save icon"></i> Set SMTP Configs</button>
  81. <button class="ui basic button" onclick="event.preventDefault(); sendTestEmail(this);"><i class="teal mail icon"></i> Send Test Email</button>
  82. </form>
  83. </div>
  84. <div class="ui divider"></div>
  85. <h3> IP Address to CIDR</h3>
  86. <p>No experience with CIDR notations? Here are some tools you can use to make setting up easier.</p>
  87. <div class="ui basic segment">
  88. <h5><i class="chevron down icon"></i> IP Range to CIDR Conversion</h5>
  89. <div class="ui message">
  90. <i class="info circle icon"></i> Note that the CIDR generated here covers additional IP address before or after the given range. If you need more details settings, please use CIDR with a smaller range and add additional IPs for detail range adjustment.
  91. </div>
  92. <div class="ui input">
  93. <input type="text" placeholder="Start IP" id="startIpInput">
  94. </div>
  95. <div class="ui input">
  96. <input type="text" placeholder="End IP" id="endIpInput">
  97. </div>
  98. <br>
  99. <button style="margin-top: 0.6em;" class="ui basic button" onclick="convertToCIDR()">Convert</button>
  100. <p>Results: <div id="cidrOutput">N/A</div></p>
  101. </div>
  102. <div class="ui basic segment">
  103. <h5><i class="chevron down icon"></i> CIDR to IP Range Conversion</h5>
  104. <div class="ui action input">
  105. <input type="text" placeholder="CIDR" id="cidrInput">
  106. <button class="ui basic button" onclick="convertToIPRange()">Convert</button>
  107. </div>
  108. <p>Results: <div id="ipRangeOutput">N/A</div></p>
  109. </div>
  110. <!-- Config Tools -->
  111. <div class="ui divider"></div>
  112. <h3>System Backup & Restore</h3>
  113. <button class="ui basic button" onclick="showSideWrapper('snippet/configTools.html');">Open Config Tools</button>
  114. <!-- System Information -->
  115. <div class="ui divider"></div>
  116. <div id="zoraxyinfo">
  117. <h3 class="ui header">
  118. System Information
  119. </h3>
  120. <p>Basic information about this zoraxy host</p>
  121. <table class="ui very basic collapsing celled table">
  122. <tbody>
  123. <tr>
  124. <td>Host UUID</td>
  125. <td class="uuid"></td>
  126. </tr>
  127. <tr>
  128. <td>Version</td>
  129. <td class="version"></td>
  130. </tr>
  131. <tr>
  132. <td>Build</td>
  133. <td class="development"></td>
  134. </tr>
  135. <tr>
  136. <td>Running Since</td>
  137. <td class="boottime"></td>
  138. </tr>
  139. <tr>
  140. <td>ZeroTier Linked</td>
  141. <td class="zt"></td>
  142. </tr>
  143. <tr>
  144. <td>Enable SSH Loopback</td>
  145. <td class="sshlb"></td>
  146. </tr>
  147. </tbody>
  148. </table>
  149. <p>Zoraxy is developed by tobychui for <a href="//imuslab.com" target="_blank">imuslab</a> and open source under <a href="https://www.gnu.org/licenses/agpl-3.0.txt">AGPL</a></p>
  150. </div>
  151. <br>
  152. </div>
  153. <script>
  154. /*
  155. Account Password utilities
  156. */
  157. $.get("/api/auth/userCount", function(data){
  158. if (data == 0){
  159. //Using external auth manager. Hide options
  160. $(".selfauthOnly").hide();
  161. }
  162. });
  163. $.get("/api/info/x", function(data){
  164. function timeConverter(UNIX_timestamp){
  165. var a = new Date(UNIX_timestamp * 1000);
  166. var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
  167. var year = a.getFullYear();
  168. var month = months[a.getMonth()];
  169. var date = a.getDate();
  170. var hour = a.getHours();
  171. var min = a.getMinutes();
  172. var sec = a.getSeconds();
  173. var time = date + ' ' + month + ' ' + year + ' ' + hour + ':' + min + ':' + sec ;
  174. return time;
  175. }
  176. function secondsToDhms(seconds) {
  177. seconds = Number(seconds);
  178. var d = Math.floor(seconds / (3600*24));
  179. var h = Math.floor(seconds % (3600*24) / 3600);
  180. var m = Math.floor(seconds % 3600 / 60);
  181. var s = Math.floor(seconds % 60);
  182. var dDisplay = d > 0 ? d + (d == 1 ? " day, " : " days, ") : "";
  183. var hDisplay = h > 0 ? h + (h == 1 ? " hour, " : " hours, ") : "";
  184. var mDisplay = m > 0 ? m + (m == 1 ? " minute, " : " minutes, ") : "";
  185. var sDisplay = s > 0 ? s + (s == 1 ? " second" : " seconds") : "";
  186. return dDisplay + hDisplay + mDisplay + sDisplay;
  187. }
  188. console.log(data);
  189. $("#zoraxyinfo .uuid").text(data.NodeUUID);
  190. $("#zoraxyinfo .development").text(data.Development?"Development":"Release");
  191. $("#zoraxyinfo .version").text(data.Version);
  192. $("#zoraxyinfo .boottime").text(timeConverter(data.BootTime) + ` ( ${secondsToDhms(parseInt(Date.now()/1000) - data.BootTime)} ago)`);
  193. $("#zoraxyinfo .zt").html(data.ZerotierConnected?`<i class="ui green check icon"></i> Connected`:`<i class="ui red times icon"></i> Link Error`);
  194. $("#zoraxyinfo .sshlb").html(data.EnableSshLoopback?`<i class="ui yellow exclamation triangle icon"></i> Enabled`:`Disabled`);
  195. });
  196. function changePassword() {
  197. const oldPassword = document.getElementsByName('oldPassword')[0].value;
  198. const newPassword = document.getElementsByName('newPassword')[0].value;
  199. const confirmNewPassword = document.getElementsByName('confirmNewPassword')[0].value;
  200. $.ajax({
  201. type: "POST",
  202. url: "/api/auth/changePassword",
  203. data: {
  204. oldPassword: oldPassword,
  205. newPassword: newPassword,
  206. confirmPassword: confirmNewPassword,
  207. },
  208. success: function (data) {
  209. if (data.error != undefined){
  210. alert(data.error);
  211. }else{
  212. $("#passwordChangeSuccMsg").stop().finish().slideDown("fast").delay(3000).slideUp("fast");
  213. $('[name="oldPassword"]').val('');
  214. $('[name="newPassword"]').val('');
  215. $('[name="confirmNewPassword"]').val('');
  216. }
  217. },
  218. error: function (xhr, status, error) {
  219. alert("Error changing password: " + error);
  220. },
  221. });
  222. }
  223. /*
  224. SMTP Settings
  225. */
  226. //Bind events to the form
  227. $('#email-form').submit(function(e) {
  228. e.preventDefault();
  229. var data = {
  230. hostname: $('input[name=hostname]').val(),
  231. domain: $('input[name=domain]').val(),
  232. port: parseInt($('input[name=port]').val()),
  233. username: $('input[name=username]').val(),
  234. password: $('input[name=password]').val(),
  235. senderAddr: $('input[name=senderAddr]').val(),
  236. adminAddr: $('input[name=recvAddr]').val()
  237. };
  238. var inputValid = validateSMTPInputs();
  239. if (!inputValid){
  240. msgbox("SMTP input not valid", false, 5000);
  241. return;
  242. }
  243. $.ajax({
  244. type: "POST",
  245. url: "/api/tools/smtp/set",
  246. data: data,
  247. success: function(data) {
  248. if (data.error != undefined){
  249. msgbox(data.error, false, 5000);
  250. }else{
  251. msgbox("SMTP Account Updated")
  252. }
  253. },
  254. error: function(xhr, status, error) {
  255. msgbox(xhr.responseText, false, 5000);
  256. }
  257. });
  258. });
  259. function initSMTPSettings(){
  260. $.get("/api/tools/smtp/get", function(data){
  261. $('#email-form input[name=hostname]').val(data.Hostname);
  262. $('#email-form input[name=domain]').val(data.Domain);
  263. $('#email-form input[name=port]').val(data.Port);
  264. $('#email-form input[name=username]').val(data.Username);
  265. $('#email-form input[name=senderAddr]').val(data.SenderAddr);
  266. });
  267. $.get("/api/tools/smtp/admin", function(data){
  268. $('#email-form input[name=recvAddr]').val(data);
  269. });
  270. }
  271. initSMTPSettings();
  272. function sendTestEmail(btn){
  273. $(btn).addClass("loading").addClass("disabled");
  274. $.get("/api/tools/smtp/test", function(data){
  275. if (data.error !== undefined){
  276. msgbox(data.error, false, 5000);
  277. }else{
  278. msgbox("Test Email Sent")
  279. }
  280. $(btn).removeClass("loading").removeClass("disabled");
  281. })
  282. }
  283. function validateSMTPInputs() {
  284. let isValid = true;
  285. const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; // email regex pattern
  286. const domainRegex = /^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i; // domain/subdomain regex pattern
  287. const form = $('#email-form');
  288. // validate hostname
  289. const hostname = form.find('input[name="hostname"]').val().trim();
  290. if (!domainRegex.test(hostname)) {
  291. form.find('input[name="hostname"]').parent().addClass('error');
  292. isValid = false;
  293. } else {
  294. form.find('input[name="hostname"]').parent().removeClass('error');
  295. }
  296. // validate domain
  297. const domain = form.find('input[name="domain"]').val().trim();
  298. if (!domainRegex.test(domain)) {
  299. form.find('input[name="domain"]').parent().addClass('error');
  300. isValid = false;
  301. } else {
  302. form.find('input[name="domain"]').parent().removeClass('error');
  303. }
  304. // validate username
  305. const username = form.find('input[name="username"]').val().trim();
  306. if (username === '') {
  307. form.find('input[name="username"]').parent().addClass('error');
  308. isValid = false;
  309. } else {
  310. form.find('input[name="username"]').parent().removeClass('error');
  311. }
  312. // validate password
  313. const password = form.find('input[name="password"]').val().trim();
  314. if (password === '') {
  315. form.find('input[name="password"]').parent().addClass('error');
  316. isValid = false;
  317. } else {
  318. form.find('input[name="password"]').parent().removeClass('error');
  319. }
  320. // validate sender address
  321. const senderAddr = form.find('input[name="senderAddr"]').val().trim();
  322. if (!emailRegex.test(senderAddr)) {
  323. form.find('input[name="senderAddr"]').parent().addClass('error');
  324. isValid = false;
  325. } else {
  326. form.find('input[name="senderAddr"]').parent().removeClass('error');
  327. }
  328. // validate receiver address
  329. const recvAddr = form.find('input[name="recvAddr"]').val().trim();
  330. if (!emailRegex.test(recvAddr)) {
  331. form.find('input[name="recvAddr"]').parent().addClass('error');
  332. isValid = false;
  333. } else {
  334. form.find('input[name="recvAddr"]').parent().removeClass('error');
  335. }
  336. return isValid;
  337. }
  338. /*
  339. IP Address Utilities
  340. */
  341. //events handler
  342. function convertToCIDR() {
  343. const startIp = document.getElementById('startIpInput').value.trim();
  344. const endIp = document.getElementById('endIpInput').value.trim();
  345. const cidrOutput = document.getElementById('cidrOutput');
  346. const cidr = ipRangeToCIDR(startIp, endIp);
  347. const ipRange = cidrToRange(cidr);
  348. cidrOutput.innerHTML = `CIDR: ${cidr} <br> (Cover range: ${ipRange[0]} to ${ipRange[1]})`;
  349. }
  350. // CIDR to IP Range Conversion
  351. function convertToIPRange() {
  352. const cidr = document.getElementById('cidrInput').value.trim();
  353. const ipRangeOutput = document.getElementById('ipRangeOutput');
  354. const ipRange = cidrToRange(cidr);
  355. ipRangeOutput.innerHTML = `Start IP: ${ipRange[0]}<br>End IP: ${ipRange[1]}`;
  356. }
  357. //Ip conversion function
  358. function cidrToRange(cidr) {
  359. var range = [2];
  360. cidr = cidr.split('/');
  361. var cidr_1 = parseInt(cidr[1])
  362. range[0] = long2ip((ip2long(cidr[0])) & ((-1 << (32 - cidr_1))));
  363. start = ip2long(range[0])
  364. range[1] = long2ip( start + Math.pow(2, (32 - cidr_1)) - 1);
  365. return range;
  366. }
  367. function ipRangeToCIDR(ipStart, ipEnd) {
  368. var start = ip2long(ipStart);
  369. var end = ip2long(ipEnd);
  370. var cidr = 32;
  371. while (start != end) {
  372. start >>= 1;
  373. end >>= 1;
  374. cidr--;
  375. }
  376. return ipStart + '/' + cidr;
  377. }
  378. function ip2long (argIP) {
  379. // discuss at: https://locutus.io/php/ip2long/
  380. // original by: Waldo Malqui Silva (https://waldo.malqui.info)
  381. // improved by: Victor
  382. // revised by: fearphage (https://my.opera.com/fearphage/)
  383. // revised by: Theriault (https://github.com/Theriault)
  384. // estarget: es2015
  385. // example 1: ip2long('192.0.34.166')
  386. // returns 1: 3221234342
  387. // example 2: ip2long('0.0xABCDEF')
  388. // returns 2: 11259375
  389. // example 3: ip2long('255.255.255.256')
  390. // returns 3: false
  391. let i = 0
  392. // PHP allows decimal, octal, and hexadecimal IP components.
  393. // PHP allows between 1 (e.g. 127) to 4 (e.g 127.0.0.1) components.
  394. const pattern = new RegExp([
  395. '^([1-9]\\d*|0[0-7]*|0x[\\da-f]+)',
  396. '(?:\\.([1-9]\\d*|0[0-7]*|0x[\\da-f]+))?',
  397. '(?:\\.([1-9]\\d*|0[0-7]*|0x[\\da-f]+))?',
  398. '(?:\\.([1-9]\\d*|0[0-7]*|0x[\\da-f]+))?$'
  399. ].join(''), 'i')
  400. argIP = argIP.match(pattern) // Verify argIP format.
  401. if (!argIP) {
  402. // Invalid format.
  403. return false
  404. }
  405. // Reuse argIP variable for component counter.
  406. argIP[0] = 0
  407. for (i = 1; i < 5; i += 1) {
  408. argIP[0] += !!((argIP[i] || '').length)
  409. argIP[i] = parseInt(argIP[i]) || 0
  410. }
  411. // Continue to use argIP for overflow values.
  412. // PHP does not allow any component to overflow.
  413. argIP.push(256, 256, 256, 256)
  414. // Recalculate overflow of last component supplied to make up for missing components.
  415. argIP[4 + argIP[0]] *= Math.pow(256, 4 - argIP[0])
  416. if (argIP[1] >= argIP[5] ||
  417. argIP[2] >= argIP[6] ||
  418. argIP[3] >= argIP[7] ||
  419. argIP[4] >= argIP[8]) {
  420. return false
  421. }
  422. return argIP[1] * (argIP[0] === 1 || 16777216) +
  423. argIP[2] * (argIP[0] <= 2 || 65536) +
  424. argIP[3] * (argIP[0] <= 3 || 256) +
  425. argIP[4] * 1
  426. }
  427. function long2ip (ip) {
  428. // discuss at: https://locutus.io/php/long2ip/
  429. // original by: Waldo Malqui Silva (https://fayr.us/waldo/)
  430. // example 1: long2ip( 3221234342 )
  431. // returns 1: '192.0.34.166'
  432. if (!isFinite(ip)) {
  433. return false
  434. }
  435. return [ip >>> 24 & 0xFF, ip >>> 16 & 0xFF, ip >>> 8 & 0xFF, ip & 0xFF].join('.')
  436. }
  437. </script>