utils.html 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  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. <!-- System Information -->
  111. <div class="ui divider"></div>
  112. <div id="zoraxyinfo">
  113. <h3 class="ui header">
  114. System Information
  115. </h3>
  116. <p>Basic information about this zoraxy host</p>
  117. <table class="ui very basic collapsing celled table">
  118. <tbody>
  119. <tr>
  120. <td>Host UUID</td>
  121. <td class="uuid"></td>
  122. </tr>
  123. <tr>
  124. <td>Version</td>
  125. <td class="version"></td>
  126. </tr>
  127. <tr>
  128. <td>Build</td>
  129. <td class="development"></td>
  130. </tr>
  131. <tr>
  132. <td>Running Since</td>
  133. <td class="boottime"></td>
  134. </tr>
  135. <tr>
  136. <td>ZeroTier Linked</td>
  137. <td class="zt"></td>
  138. </tr>
  139. <tr>
  140. <td>Enable SSH Loopback</td>
  141. <td class="sshlb"></td>
  142. </tr>
  143. </tbody>
  144. </table>
  145. <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>
  146. </div>
  147. <br>
  148. </div>
  149. <script>
  150. /*
  151. Account Password utilities
  152. */
  153. $.get("/api/auth/userCount", function(data){
  154. if (data == 0){
  155. //Using external auth manager. Hide options
  156. $(".selfauthOnly").hide();
  157. }
  158. });
  159. $.get("/api/info/x", function(data){
  160. function timeConverter(UNIX_timestamp){
  161. var a = new Date(UNIX_timestamp * 1000);
  162. var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
  163. var year = a.getFullYear();
  164. var month = months[a.getMonth()];
  165. var date = a.getDate();
  166. var hour = a.getHours();
  167. var min = a.getMinutes();
  168. var sec = a.getSeconds();
  169. var time = date + ' ' + month + ' ' + year + ' ' + hour + ':' + min + ':' + sec ;
  170. return time;
  171. }
  172. function secondsToDhms(seconds) {
  173. seconds = Number(seconds);
  174. var d = Math.floor(seconds / (3600*24));
  175. var h = Math.floor(seconds % (3600*24) / 3600);
  176. var m = Math.floor(seconds % 3600 / 60);
  177. var s = Math.floor(seconds % 60);
  178. var dDisplay = d > 0 ? d + (d == 1 ? " day, " : " days, ") : "";
  179. var hDisplay = h > 0 ? h + (h == 1 ? " hour, " : " hours, ") : "";
  180. var mDisplay = m > 0 ? m + (m == 1 ? " minute, " : " minutes, ") : "";
  181. var sDisplay = s > 0 ? s + (s == 1 ? " second" : " seconds") : "";
  182. return dDisplay + hDisplay + mDisplay + sDisplay;
  183. }
  184. console.log(data);
  185. $("#zoraxyinfo .uuid").text(data.NodeUUID);
  186. $("#zoraxyinfo .development").text(data.Development?"Development":"Release");
  187. $("#zoraxyinfo .version").text(data.Version);
  188. $("#zoraxyinfo .boottime").text(timeConverter(data.BootTime) + ` ( ${secondsToDhms(parseInt(Date.now()/1000) - data.BootTime)} ago)`);
  189. $("#zoraxyinfo .zt").html(data.ZerotierConnected?`<i class="ui green check icon"></i> Connected`:`<i class="ui red times icon"></i> Link Error`);
  190. $("#zoraxyinfo .sshlb").html(data.EnableSshLoopback?`<i class="ui yellow exclamation triangle icon"></i> Enabled`:`Disabled`);
  191. });
  192. function changePassword() {
  193. const oldPassword = document.getElementsByName('oldPassword')[0].value;
  194. const newPassword = document.getElementsByName('newPassword')[0].value;
  195. const confirmNewPassword = document.getElementsByName('confirmNewPassword')[0].value;
  196. $.ajax({
  197. type: "POST",
  198. url: "/api/auth/changePassword",
  199. data: {
  200. oldPassword: oldPassword,
  201. newPassword: newPassword,
  202. confirmPassword: confirmNewPassword,
  203. },
  204. success: function (data) {
  205. if (data.error != undefined){
  206. alert(data.error);
  207. }else{
  208. $("#passwordChangeSuccMsg").stop().finish().slideDown("fast").delay(3000).slideUp("fast");
  209. $('[name="oldPassword"]').val('');
  210. $('[name="newPassword"]').val('');
  211. $('[name="confirmNewPassword"]').val('');
  212. }
  213. },
  214. error: function (xhr, status, error) {
  215. alert("Error changing password: " + error);
  216. },
  217. });
  218. }
  219. /*
  220. SMTP Settings
  221. */
  222. //Bind events to the form
  223. $('#email-form').submit(function(e) {
  224. e.preventDefault();
  225. var data = {
  226. hostname: $('input[name=hostname]').val(),
  227. domain: $('input[name=domain]').val(),
  228. port: parseInt($('input[name=port]').val()),
  229. username: $('input[name=username]').val(),
  230. password: $('input[name=password]').val(),
  231. senderAddr: $('input[name=senderAddr]').val(),
  232. adminAddr: $('input[name=recvAddr]').val()
  233. };
  234. var inputValid = validateSMTPInputs();
  235. if (!inputValid){
  236. msgbox("SMTP input not valid", false, 5000);
  237. return;
  238. }
  239. $.ajax({
  240. type: "POST",
  241. url: "/api/tools/smtp/set",
  242. data: data,
  243. success: function(data) {
  244. if (data.error != undefined){
  245. msgbox(data.error, false, 5000);
  246. }else{
  247. msgbox("SMTP Account Updated")
  248. }
  249. },
  250. error: function(xhr, status, error) {
  251. msgbox(xhr.responseText, false, 5000);
  252. }
  253. });
  254. });
  255. function initSMTPSettings(){
  256. $.get("/api/tools/smtp/get", function(data){
  257. $('#email-form input[name=hostname]').val(data.Hostname);
  258. $('#email-form input[name=domain]').val(data.Domain);
  259. $('#email-form input[name=port]').val(data.Port);
  260. $('#email-form input[name=username]').val(data.Username);
  261. $('#email-form input[name=senderAddr]').val(data.SenderAddr);
  262. });
  263. $.get("/api/tools/smtp/admin", function(data){
  264. $('#email-form input[name=recvAddr]').val(data);
  265. });
  266. }
  267. initSMTPSettings();
  268. function sendTestEmail(btn){
  269. $(btn).addClass("loading").addClass("disabled");
  270. $.get("/api/tools/smtp/test", function(data){
  271. if (data.error !== undefined){
  272. msgbox(data.error, false, 5000);
  273. }else{
  274. msgbox("Test Email Sent")
  275. }
  276. $(btn).removeClass("loading").removeClass("disabled");
  277. })
  278. }
  279. function validateSMTPInputs() {
  280. let isValid = true;
  281. const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; // email regex pattern
  282. const domainRegex = /^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i; // domain/subdomain regex pattern
  283. const form = $('#email-form');
  284. // validate hostname
  285. const hostname = form.find('input[name="hostname"]').val().trim();
  286. if (!domainRegex.test(hostname)) {
  287. form.find('input[name="hostname"]').parent().addClass('error');
  288. isValid = false;
  289. } else {
  290. form.find('input[name="hostname"]').parent().removeClass('error');
  291. }
  292. // validate domain
  293. const domain = form.find('input[name="domain"]').val().trim();
  294. if (!domainRegex.test(domain)) {
  295. form.find('input[name="domain"]').parent().addClass('error');
  296. isValid = false;
  297. } else {
  298. form.find('input[name="domain"]').parent().removeClass('error');
  299. }
  300. // validate username
  301. const username = form.find('input[name="username"]').val().trim();
  302. if (username === '') {
  303. form.find('input[name="username"]').parent().addClass('error');
  304. isValid = false;
  305. } else {
  306. form.find('input[name="username"]').parent().removeClass('error');
  307. }
  308. // validate password
  309. const password = form.find('input[name="password"]').val().trim();
  310. if (password === '') {
  311. form.find('input[name="password"]').parent().addClass('error');
  312. isValid = false;
  313. } else {
  314. form.find('input[name="password"]').parent().removeClass('error');
  315. }
  316. // validate sender address
  317. const senderAddr = form.find('input[name="senderAddr"]').val().trim();
  318. if (!emailRegex.test(senderAddr)) {
  319. form.find('input[name="senderAddr"]').parent().addClass('error');
  320. isValid = false;
  321. } else {
  322. form.find('input[name="senderAddr"]').parent().removeClass('error');
  323. }
  324. // validate receiver address
  325. const recvAddr = form.find('input[name="recvAddr"]').val().trim();
  326. if (!emailRegex.test(recvAddr)) {
  327. form.find('input[name="recvAddr"]').parent().addClass('error');
  328. isValid = false;
  329. } else {
  330. form.find('input[name="recvAddr"]').parent().removeClass('error');
  331. }
  332. return isValid;
  333. }
  334. /*
  335. IP Address Utilities
  336. */
  337. //events handler
  338. function convertToCIDR() {
  339. const startIp = document.getElementById('startIpInput').value.trim();
  340. const endIp = document.getElementById('endIpInput').value.trim();
  341. const cidrOutput = document.getElementById('cidrOutput');
  342. const cidr = ipRangeToCIDR(startIp, endIp);
  343. const ipRange = cidrToRange(cidr);
  344. cidrOutput.innerHTML = `CIDR: ${cidr} <br> (Cover range: ${ipRange[0]} to ${ipRange[1]})`;
  345. }
  346. // CIDR to IP Range Conversion
  347. function convertToIPRange() {
  348. const cidr = document.getElementById('cidrInput').value.trim();
  349. const ipRangeOutput = document.getElementById('ipRangeOutput');
  350. const ipRange = cidrToRange(cidr);
  351. ipRangeOutput.innerHTML = `Start IP: ${ipRange[0]}<br>End IP: ${ipRange[1]}`;
  352. }
  353. //Ip conversion function
  354. function cidrToRange(cidr) {
  355. var range = [2];
  356. cidr = cidr.split('/');
  357. var cidr_1 = parseInt(cidr[1])
  358. range[0] = long2ip((ip2long(cidr[0])) & ((-1 << (32 - cidr_1))));
  359. start = ip2long(range[0])
  360. range[1] = long2ip( start + Math.pow(2, (32 - cidr_1)) - 1);
  361. return range;
  362. }
  363. function ipRangeToCIDR(ipStart, ipEnd) {
  364. var start = ip2long(ipStart);
  365. var end = ip2long(ipEnd);
  366. var cidr = 32;
  367. while (start != end) {
  368. start >>= 1;
  369. end >>= 1;
  370. cidr--;
  371. }
  372. return ipStart + '/' + cidr;
  373. }
  374. function ip2long (argIP) {
  375. // discuss at: https://locutus.io/php/ip2long/
  376. // original by: Waldo Malqui Silva (https://waldo.malqui.info)
  377. // improved by: Victor
  378. // revised by: fearphage (https://my.opera.com/fearphage/)
  379. // revised by: Theriault (https://github.com/Theriault)
  380. // estarget: es2015
  381. // example 1: ip2long('192.0.34.166')
  382. // returns 1: 3221234342
  383. // example 2: ip2long('0.0xABCDEF')
  384. // returns 2: 11259375
  385. // example 3: ip2long('255.255.255.256')
  386. // returns 3: false
  387. let i = 0
  388. // PHP allows decimal, octal, and hexadecimal IP components.
  389. // PHP allows between 1 (e.g. 127) to 4 (e.g 127.0.0.1) components.
  390. const pattern = new RegExp([
  391. '^([1-9]\\d*|0[0-7]*|0x[\\da-f]+)',
  392. '(?:\\.([1-9]\\d*|0[0-7]*|0x[\\da-f]+))?',
  393. '(?:\\.([1-9]\\d*|0[0-7]*|0x[\\da-f]+))?',
  394. '(?:\\.([1-9]\\d*|0[0-7]*|0x[\\da-f]+))?$'
  395. ].join(''), 'i')
  396. argIP = argIP.match(pattern) // Verify argIP format.
  397. if (!argIP) {
  398. // Invalid format.
  399. return false
  400. }
  401. // Reuse argIP variable for component counter.
  402. argIP[0] = 0
  403. for (i = 1; i < 5; i += 1) {
  404. argIP[0] += !!((argIP[i] || '').length)
  405. argIP[i] = parseInt(argIP[i]) || 0
  406. }
  407. // Continue to use argIP for overflow values.
  408. // PHP does not allow any component to overflow.
  409. argIP.push(256, 256, 256, 256)
  410. // Recalculate overflow of last component supplied to make up for missing components.
  411. argIP[4 + argIP[0]] *= Math.pow(256, 4 - argIP[0])
  412. if (argIP[1] >= argIP[5] ||
  413. argIP[2] >= argIP[6] ||
  414. argIP[3] >= argIP[7] ||
  415. argIP[4] >= argIP[8]) {
  416. return false
  417. }
  418. return argIP[1] * (argIP[0] === 1 || 16777216) +
  419. argIP[2] * (argIP[0] <= 2 || 65536) +
  420. argIP[3] * (argIP[0] <= 3 || 256) +
  421. argIP[4] * 1
  422. }
  423. function long2ip (ip) {
  424. // discuss at: https://locutus.io/php/long2ip/
  425. // original by: Waldo Malqui Silva (https://fayr.us/waldo/)
  426. // example 1: long2ip( 3221234342 )
  427. // returns 1: '192.0.34.166'
  428. if (!isFinite(ip)) {
  429. return false
  430. }
  431. return [ip >>> 24 & 0xFF, ip >>> 16 & 0xFF, ip >>> 8 & 0xFF, ip & 0xFF].join('.')
  432. }
  433. </script>