hfs 0.49.0-alpha2 → 0.49.0-alpha4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/commands.js CHANGED
@@ -57,14 +57,7 @@ const commands = {
57
57
  },
58
58
  'create-admin': {
59
59
  params: '<password> [<username>=admin]',
60
- async cb(password, username = 'admin') {
61
- if ((0, perm_1.getAccount)(username))
62
- throw `user ${username} already exists`;
63
- const acc = (0, perm_1.addAccount)(username, { admin: true });
64
- await (0, perm_1.updateAccount)(acc, acc => {
65
- acc.password = password;
66
- });
67
- }
60
+ cb: perm_1.createAdmin
68
61
  },
69
62
  'change-password': {
70
63
  params: '<user> <password>',
@@ -105,8 +98,8 @@ const commands = {
105
98
  }
106
99
  },
107
100
  update: {
108
- params: '',
109
- cb: () => (0, update_1.update)()
101
+ params: '[<version>=latest]',
102
+ cb: update_1.update
110
103
  },
111
104
  'check-update': {
112
105
  params: '',
package/src/config.js CHANGED
@@ -4,7 +4,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  return (mod && mod.__esModule) ? mod : { "default": mod };
5
5
  };
6
6
  Object.defineProperty(exports, "__esModule", { value: true });
7
- exports.saveConfigAsap = exports.setConfig = exports.getWholeConfig = exports.getConfig = exports.configKeyExists = exports.defineConfig = exports.currentVersion = exports.versionToScalar = void 0;
7
+ exports.configFile = exports.saveConfigAsap = exports.setConfig = exports.getWholeConfig = exports.getConfig = exports.configKeyExists = exports.defineConfig = exports.currentVersion = exports.versionToScalar = void 0;
8
8
  const events_1 = __importDefault(require("events"));
9
9
  const const_1 = require("./const");
10
10
  const watchLoad_1 = require("./watchLoad");
@@ -70,12 +70,12 @@ function defineConfig(k, defaultValue, compiler) {
70
70
  cb(getConfig(k), { k, was: defaultValue, defaultValue, version: configVersion.compiled() });
71
71
  const eventName = CONFIG_CHANGE_EVENT_PREFIX + k;
72
72
  return (0, misc_1.onOff)(cfgEvents, {
73
- [eventName]() {
73
+ [eventName](v, was, version) {
74
74
  if (stack.includes(cb))
75
75
  return; // avoid infinite loop in case a subscriber changes the value
76
- stack.push(cb); // @ts-ignore arguments
76
+ stack.push(cb);
77
77
  try {
78
- return cb.apply(this, arguments);
78
+ return cb(v, { k, was, version, defaultValue });
79
79
  }
80
80
  finally {
81
81
  stack.pop();
@@ -177,13 +177,16 @@ const saveDebounced = (0, misc_1.debounceAsync)(async () => {
177
177
  const aWeekAgo = Date.now() - misc_1.DAY * 7;
178
178
  if (await (0, promises_1.stat)(bak).then(x => aWeekAgo > Number(x.mtime || x.ctime), () => true))
179
179
  await (0, promises_1.copyFile)(filePath, bak).catch(() => { }); // ignore errors
180
- await save(yaml_1.default.stringify({ ...state, version: const_1.VERSION }, { lineWidth: 1000 }))
180
+ await exports.configFile.save(stringify({ ...state, version: const_1.VERSION }))
181
181
  .catch(err => console.error('Failed at saving config file, please ensure it is writable.', String(err)));
182
182
  });
183
183
  const saveConfigAsap = () => void (saveDebounced());
184
184
  exports.saveConfigAsap = saveConfigAsap;
185
+ function stringify(obj) {
186
+ return yaml_1.default.stringify(obj, { lineWidth: 1000 });
187
+ }
185
188
  console.log("config", filePath);
186
- const { save } = (0, watchLoad_1.watchLoad)(filePath, text => setConfig(yaml_1.default.parse(text) || {}, false), {
189
+ exports.configFile = (0, watchLoad_1.watchLoad)(filePath, text => setConfig(yaml_1.default.parse(text, { uniqueKeys: false }) || {}, false), {
187
190
  failedOnFirstAttempt() {
188
191
  console.log("No config file, using defaults");
189
192
  setConfig({}, false);
package/src/const.js CHANGED
@@ -23,53 +23,30 @@ var __importStar = (this && this.__importStar) || function (mod) {
23
23
  __setModuleDefault(result, mod);
24
24
  return result;
25
25
  };
26
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
27
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
28
+ };
26
29
  var __importDefault = (this && this.__importDefault) || function (mod) {
27
30
  return (mod && mod.__esModule) ? mod : { "default": mod };
28
31
  };
29
32
  Object.defineProperty(exports, "__esModule", { value: true });
30
- exports.APP_PATH = exports.IS_BINARY = exports.IS_MAC = exports.IS_WINDOWS = exports.HTTP_SERVICE_UNAVAILABLE = exports.HTTP_SERVER_ERROR = exports.HTTP_FAILED_DEPENDENCY = exports.HTTP_FOOL = exports.HTTP_RANGE_NOT_SATISFIABLE = exports.HTTP_PAYLOAD_TOO_LARGE = exports.HTTP_CONFLICT = exports.HTTP_NOT_ACCEPTABLE = exports.HTTP_METHOD_NOT_ALLOWED = exports.HTTP_NOT_FOUND = exports.HTTP_FORBIDDEN = exports.HTTP_UNAUTHORIZED = exports.HTTP_BAD_REQUEST = exports.HTTP_NOT_MODIFIED = exports.HTTP_TEMPORARY_REDIRECT = exports.HTTP_MOVED_PERMANENTLY = exports.HTTP_PARTIAL_CONTENT = exports.HTTP_NO_CONTENT = exports.HTTP_OK = exports.PLUGINS_PUB_URI = exports.API_URI = exports.ADMIN_URI = exports.FRONTEND_URI = exports.SPECIAL_URI = exports.HFS_REPO_BRANCH = exports.HFS_REPO = exports.COMPATIBLE_API_VERSION = exports.API_VERSION = exports.RUNNING_BETA = exports.VERSION = exports.BUILD_TIMESTAMP = exports.HFS_STARTED = exports.ORIGINAL_CWD = exports.DEV = exports.argv = void 0;
33
+ exports.APP_PATH = exports.IS_BINARY = exports.IS_MAC = exports.IS_WINDOWS = exports.HFS_REPO_BRANCH = exports.RUNNING_BETA = exports.VERSION = exports.BUILD_TIMESTAMP = exports.HFS_STARTED = exports.ORIGINAL_CWD = exports.DEV = exports.argv = void 0;
31
34
  const minimist_1 = __importDefault(require("minimist"));
32
35
  const fs = __importStar(require("fs"));
33
36
  const os_1 = require("os");
34
37
  const fs_1 = require("fs");
35
38
  const path_1 = require("path");
39
+ __exportStar(require("./cross-const"), exports);
36
40
  exports.argv = (0, minimist_1.default)(process.argv.slice(2));
37
41
  exports.DEV = process.env.DEV || exports.argv.dev ? 'DEV' : '';
38
42
  exports.ORIGINAL_CWD = process.cwd();
39
43
  exports.HFS_STARTED = new Date();
40
44
  const PKG_PATH = (0, path_1.join)(__dirname, '..', 'package.json');
41
- exports.BUILD_TIMESTAMP = "2023-10-04T19:41:32.601Z";
45
+ exports.BUILD_TIMESTAMP = "2023-10-18T21:04:49.738Z";
42
46
  const pkg = JSON.parse(fs.readFileSync(PKG_PATH, 'utf8'));
43
47
  exports.VERSION = pkg.version;
44
48
  exports.RUNNING_BETA = exports.VERSION.includes('-');
45
- exports.API_VERSION = 8.4;
46
- exports.COMPATIBLE_API_VERSION = 1; // while changes in the api are not breaking, this number stays the same, otherwise it is made equal to API_VERSION
47
- exports.HFS_REPO = 'rejetto/hfs';
48
49
  exports.HFS_REPO_BRANCH = exports.RUNNING_BETA ? 'next' : 'main';
49
- exports.SPECIAL_URI = '/~/';
50
- exports.FRONTEND_URI = exports.SPECIAL_URI + 'frontend/';
51
- exports.ADMIN_URI = exports.SPECIAL_URI + 'admin/';
52
- exports.API_URI = exports.SPECIAL_URI + 'api/';
53
- exports.PLUGINS_PUB_URI = exports.SPECIAL_URI + 'plugins/';
54
- exports.HTTP_OK = 200;
55
- exports.HTTP_NO_CONTENT = 204;
56
- exports.HTTP_PARTIAL_CONTENT = 206;
57
- exports.HTTP_MOVED_PERMANENTLY = 301;
58
- exports.HTTP_TEMPORARY_REDIRECT = 302;
59
- exports.HTTP_NOT_MODIFIED = 304;
60
- exports.HTTP_BAD_REQUEST = 400;
61
- exports.HTTP_UNAUTHORIZED = 401;
62
- exports.HTTP_FORBIDDEN = 403;
63
- exports.HTTP_NOT_FOUND = 404;
64
- exports.HTTP_METHOD_NOT_ALLOWED = 405;
65
- exports.HTTP_NOT_ACCEPTABLE = 406;
66
- exports.HTTP_CONFLICT = 409;
67
- exports.HTTP_PAYLOAD_TOO_LARGE = 413;
68
- exports.HTTP_RANGE_NOT_SATISFIABLE = 416;
69
- exports.HTTP_FOOL = 418;
70
- exports.HTTP_FAILED_DEPENDENCY = 424;
71
- exports.HTTP_SERVER_ERROR = 500;
72
- exports.HTTP_SERVICE_UNAVAILABLE = 503;
73
50
  exports.IS_WINDOWS = process.platform === 'win32';
74
51
  exports.IS_MAC = process.platform === 'darwin';
75
52
  exports.IS_BINARY = !(0, path_1.basename)(process.execPath).includes('node'); // this won't be node if pkg was used
@@ -84,7 +61,6 @@ console.log(`License https://www.gnu.org/licenses/gpl-3.0.txt`);
84
61
  console.log('started', exports.HFS_STARTED.toLocaleString(), exports.DEV);
85
62
  console.log('version', exports.VERSION || '-');
86
63
  console.log('build', exports.BUILD_TIMESTAMP || '-');
87
- console.log('pid', process.pid);
88
64
  const winExe = exports.IS_WINDOWS && process.execPath.match(/(?<!node)\.exe$/i);
89
65
  if (exports.argv.cwd)
90
66
  process.chdir(exports.argv.cwd);
@@ -101,3 +77,4 @@ else if (!winExe) { // still considering whether to use this behavior with Windo
101
77
  }
102
78
  console.log('cwd', process.cwd());
103
79
  console.log('node', process.version);
80
+ console.log('pid', process.pid);
@@ -0,0 +1,31 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.HTTP_SERVICE_UNAVAILABLE = exports.HTTP_SERVER_ERROR = exports.HTTP_FAILED_DEPENDENCY = exports.HTTP_FOOL = exports.HTTP_RANGE_NOT_SATISFIABLE = exports.HTTP_PAYLOAD_TOO_LARGE = exports.HTTP_PRECONDITION_FAILED = exports.HTTP_CONFLICT = exports.HTTP_NOT_ACCEPTABLE = exports.HTTP_METHOD_NOT_ALLOWED = exports.HTTP_NOT_FOUND = exports.HTTP_FORBIDDEN = exports.HTTP_UNAUTHORIZED = exports.HTTP_BAD_REQUEST = exports.HTTP_NOT_MODIFIED = exports.HTTP_TEMPORARY_REDIRECT = exports.HTTP_MOVED_PERMANENTLY = exports.HTTP_PARTIAL_CONTENT = exports.HTTP_NO_CONTENT = exports.HTTP_OK = exports.PLUGINS_PUB_URI = exports.API_URI = exports.ADMIN_URI = exports.FRONTEND_URI = exports.SPECIAL_URI = exports.HFS_REPO = exports.COMPATIBLE_API_VERSION = exports.API_VERSION = void 0;
4
+ exports.API_VERSION = 8.4;
5
+ exports.COMPATIBLE_API_VERSION = 1; // while changes in the api are not breaking, this number stays the same, otherwise it is made equal to API_VERSION
6
+ exports.HFS_REPO = 'rejetto/hfs';
7
+ exports.SPECIAL_URI = '/~/';
8
+ exports.FRONTEND_URI = exports.SPECIAL_URI + 'frontend/';
9
+ exports.ADMIN_URI = exports.SPECIAL_URI + 'admin/';
10
+ exports.API_URI = exports.SPECIAL_URI + 'api/';
11
+ exports.PLUGINS_PUB_URI = exports.SPECIAL_URI + 'plugins/';
12
+ exports.HTTP_OK = 200;
13
+ exports.HTTP_NO_CONTENT = 204;
14
+ exports.HTTP_PARTIAL_CONTENT = 206;
15
+ exports.HTTP_MOVED_PERMANENTLY = 301;
16
+ exports.HTTP_TEMPORARY_REDIRECT = 302;
17
+ exports.HTTP_NOT_MODIFIED = 304;
18
+ exports.HTTP_BAD_REQUEST = 400;
19
+ exports.HTTP_UNAUTHORIZED = 401;
20
+ exports.HTTP_FORBIDDEN = 403;
21
+ exports.HTTP_NOT_FOUND = 404;
22
+ exports.HTTP_METHOD_NOT_ALLOWED = 405;
23
+ exports.HTTP_NOT_ACCEPTABLE = 406;
24
+ exports.HTTP_CONFLICT = 409;
25
+ exports.HTTP_PRECONDITION_FAILED = 412;
26
+ exports.HTTP_PAYLOAD_TOO_LARGE = 413;
27
+ exports.HTTP_RANGE_NOT_SATISFIABLE = 416;
28
+ exports.HTTP_FOOL = 418;
29
+ exports.HTTP_FAILED_DEPENDENCY = 424;
30
+ exports.HTTP_SERVER_ERROR = 500;
31
+ exports.HTTP_SERVICE_UNAVAILABLE = 503;
package/src/cross.js CHANGED
@@ -1,4 +1,18 @@
1
1
  "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
2
16
  var __importDefault = (this && this.__importDefault) || function (mod) {
3
17
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
18
  };
@@ -8,6 +22,7 @@ exports.promiseBestEffort = exports.escapeHTML = exports.ipForUrl = exports.ipLo
8
22
  // This file is part of HFS - Copyright 2021-2023, Massimo Melina <a@rejetto.com> - License https://www.gnu.org/licenses/gpl-3.0.txt
9
23
  // all content here is shared between client and server
10
24
  const lodash_1 = __importDefault(require("lodash"));
25
+ __exportStar(require("./cross-const"), exports);
11
26
  exports.REPO_URL = 'https://github.com/rejetto/hfs/';
12
27
  exports.WIKI_URL = exports.REPO_URL + 'wiki/';
13
28
  exports.MINUTE = 60000;
@@ -50,15 +65,15 @@ function wait(ms, val) {
50
65
  }
51
66
  exports.wait = wait;
52
67
  function haveTimeout(ms, job, error) {
53
- return Promise.race([job, wait(ms).then(() => { throw error; })]);
68
+ return Promise.race([job, wait(ms).then(() => { throw error || Error('timeout'); })]);
54
69
  }
55
70
  exports.haveTimeout = haveTimeout;
56
71
  function objSameKeys(src, newValue) {
57
72
  return Object.fromEntries(Object.entries(src).map(([k, v]) => [k, newValue(v, k)]));
58
73
  }
59
74
  exports.objSameKeys = objSameKeys;
60
- function enforceFinal(sub, s) {
61
- return !s || s.endsWith(sub) ? s : s + sub;
75
+ function enforceFinal(sub, s, evenEmpty = false) {
76
+ return !evenEmpty && !s || s.endsWith(sub) ? s : s + sub;
62
77
  }
63
78
  exports.enforceFinal = enforceFinal;
64
79
  function truthy(value) {
@@ -49,7 +49,7 @@ exports.frontEndApis = {
49
49
  list.ready(); // on chrome109 EventSource doesn't emit 'open' until something is sent
50
50
  return list.events(ctx, {
51
51
  [NOTIFICATION_PREFIX + channel](name, data) {
52
- list.custom({ name, data });
52
+ list.custom(name, data);
53
53
  }
54
54
  });
55
55
  },
package/src/index.js CHANGED
@@ -25,13 +25,15 @@ const assert_1 = require("assert");
25
25
  const lodash_1 = __importDefault(require("lodash"));
26
26
  const misc_1 = require("./misc");
27
27
  const koa_session_1 = __importDefault(require("koa-session"));
28
- const api_net_1 = require("./api.net");
28
+ const selfCheck_1 = require("./selfCheck");
29
+ const acme_1 = require("./acme");
29
30
  (0, assert_1.ok)(lodash_1.default.intersection(Object.keys(frontEndApis_1.frontEndApis), Object.keys(adminApis_1.adminApis)).length === 0); // they share same endpoints, don't clash
30
31
  process.title = 'HFS ' + const_1.VERSION;
31
32
  const keys = ((_a = process.env.COOKIE_SIGN_KEYS) === null || _a === void 0 ? void 0 : _a.split(',')) || [(0, misc_1.randomId)(30)];
32
33
  exports.app = new koa_1.default({ keys });
33
34
  exports.app.use(middlewares_1.someSecurity)
34
- .use(api_net_1.acmeMiddleware)
35
+ .use(selfCheck_1.selfCheckMiddleware)
36
+ .use(acme_1.acmeMiddleware)
35
37
  .use((0, koa_session_1.default)({ key: 'hfs_$id', signed: true, rolling: true, sameSite: 'lax' }, exports.app))
36
38
  .use(middlewares_1.prepareState)
37
39
  .use(middlewares_1.gzipper)
@@ -56,7 +58,7 @@ function errorHandler(err) {
56
58
  }
57
59
  process.on('uncaughtException', err => {
58
60
  if (err.syscall !== 'watch')
59
- console.error(err);
61
+ console.error("uncaught:", err);
60
62
  });
61
63
  (0, config_1.defineConfig)('proxies', 0).sub(n => {
62
64
  exports.app.proxy = n > 0;
package/src/listen.js CHANGED
@@ -27,7 +27,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
27
27
  return (mod && mod.__esModule) ? mod : { "default": mod };
28
28
  };
29
29
  Object.defineProperty(exports, "__esModule", { value: true });
30
- exports.getUrls = exports.getIps = exports.getServerStatus = exports.stopServer = exports.startServer = exports.httpsPortCfg = exports.privateKey = exports.cert = exports.getCertObject = exports.openAdmin = exports.portCfg = exports.getHttpsWorkingPort = void 0;
30
+ exports.getUrls = exports.getIps = exports.getServerStatus = exports.stopServer = exports.startServer = exports.httpsPortCfg = exports.privateKey = exports.cert = exports.getCertObject = exports.openAdmin = exports.portCfg = exports.getHttpsWorkingPort = exports.getBaseUrlOrDefault = exports.baseUrl = void 0;
31
31
  const http = __importStar(require("http"));
32
32
  const config_1 = require("./config");
33
33
  const index_1 = require("./index");
@@ -42,12 +42,17 @@ const find_process_1 = __importDefault(require("find-process"));
42
42
  const adminApis_1 = require("./adminApis");
43
43
  const lodash_1 = __importDefault(require("lodash"));
44
44
  const crypto_1 = require("crypto");
45
- const api_net_1 = require("./api.net");
46
45
  const events_1 = __importDefault(require("./events"));
47
46
  const net_1 = require("net");
47
+ const nat_1 = require("./nat");
48
48
  let httpSrv;
49
49
  let httpsSrv;
50
50
  const openBrowserAtStart = (0, config_1.defineConfig)('open_browser_at_start', !const_1.DEV);
51
+ exports.baseUrl = (0, config_1.defineConfig)('base_url', '');
52
+ function getBaseUrlOrDefault() {
53
+ return exports.baseUrl.get() || nat_1.defaultBaseUrl.get();
54
+ }
55
+ exports.getBaseUrlOrDefault = getBaseUrlOrDefault;
51
56
  function getHttpsWorkingPort() {
52
57
  var _a;
53
58
  return (httpsSrv === null || httpsSrv === void 0 ? void 0 : httpsSrv.listening) && ((_a = httpsSrv.address()) === null || _a === void 0 ? void 0 : _a.port);
@@ -96,8 +101,10 @@ function getCertObject() {
96
101
  }
97
102
  exports.getCertObject = getCertObject;
98
103
  const considerHttps = (0, misc_1.debounceAsync)(async () => {
99
- var _a, _b, _c;
104
+ var _a, _b, _c, _d, _e;
100
105
  stopServer(httpsSrv).then();
106
+ nat_1.defaultBaseUrl.proto = 'http';
107
+ nat_1.defaultBaseUrl.port = (_a = getCurrentPort(httpSrv)) !== null && _a !== void 0 ? _a : 0;
101
108
  let port = exports.httpsPortCfg.get();
102
109
  try {
103
110
  while (!index_1.app)
@@ -107,7 +114,7 @@ const considerHttps = (0, misc_1.debounceAsync)(async () => {
107
114
  const cert = getCertObject();
108
115
  if (!cert)
109
116
  return;
110
- const cn = (_a = cert.subject) === null || _a === void 0 ? void 0 : _a.CN;
117
+ const cn = (_b = cert.subject) === null || _b === void 0 ? void 0 : _b.CN;
111
118
  if (cn)
112
119
  console.log("certificate loaded for", cn);
113
120
  const now = new Date();
@@ -115,10 +122,10 @@ const considerHttps = (0, misc_1.debounceAsync)(async () => {
115
122
  : new Date(cert.validTo) < now ? "certificate expired"
116
123
  : undefined;
117
124
  const namesForOutput = { cert: 'certificate', private_key: 'private key' };
118
- const missing = (_b = httpsNeeds.find(x => !x.get())) === null || _b === void 0 ? void 0 : _b.key();
125
+ const missing = (_c = httpsNeeds.find(x => !x.get())) === null || _c === void 0 ? void 0 : _c.key();
119
126
  if (missing)
120
127
  return httpsSrv.error = "missing " + namesForOutput[missing];
121
- const cantRead = (_c = httpsNeeds.find(x => !httpsOptions[x.key()])) === null || _c === void 0 ? void 0 : _c.key();
128
+ const cantRead = (_d = httpsNeeds.find(x => !httpsOptions[x.key()])) === null || _d === void 0 ? void 0 : _d.key();
122
129
  if (cantRead)
123
130
  return httpsSrv.error = "cannot read " + namesForOutput[cantRead];
124
131
  }
@@ -134,6 +141,8 @@ const considerHttps = (0, misc_1.debounceAsync)(async () => {
134
141
  httpsSrv.on('connection', connections_1.newConnection);
135
142
  printUrls(httpsSrv.name);
136
143
  events_1.default.emit('https ready');
144
+ nat_1.defaultBaseUrl.proto = 'https';
145
+ nat_1.defaultBaseUrl.port = (_e = getCurrentPort(httpsSrv)) !== null && _e !== void 0 ? _e : 0;
137
146
  });
138
147
  exports.cert = (0, config_1.defineConfig)('cert', '');
139
148
  exports.privateKey = (0, config_1.defineConfig)('private_key', '');
@@ -212,7 +221,7 @@ function startServer(srv, { port, host }) {
212
221
  }
213
222
  console.error(srv.name, srv.error);
214
223
  const k = (srv === httpSrv ? exports.portCfg : exports.httpsPortCfg).key();
215
- console.log(` >> try specifying a different port, enter this command: config ${k} 8011`);
224
+ console.log(` >> try specifying a different port, enter this command: config ${k} 1080`);
216
225
  resolve(0);
217
226
  }
218
227
  });
@@ -234,19 +243,22 @@ function stopServer(srv) {
234
243
  });
235
244
  }
236
245
  exports.stopServer = stopServer;
246
+ function getCurrentPort(srv) {
247
+ var _a;
248
+ return (_a = srv === null || srv === void 0 ? void 0 : srv.address()) === null || _a === void 0 ? void 0 : _a.port;
249
+ }
237
250
  async function getServerStatus() {
238
251
  return {
239
252
  http: await serverStatus(httpSrv, exports.portCfg.get()),
240
253
  https: await serverStatus(httpsSrv, exports.httpsPortCfg.get()),
241
254
  };
242
255
  async function serverStatus(srv, configuredPort) {
243
- var _a;
244
256
  const busy = await (srv === null || srv === void 0 ? void 0 : srv.busy);
245
257
  await (0, misc_1.wait)(0); // simple trick to wait for also .error to be updated. If this trickery becomes necessary elsewhere, then we should make also error a Promise.
246
258
  return {
247
259
  ...lodash_1.default.pick(srv, ['listening', 'error']),
248
260
  busy,
249
- port: ((_a = srv === null || srv === void 0 ? void 0 : srv.address()) === null || _a === void 0 ? void 0 : _a.port) || configuredPort,
261
+ port: getCurrentPort(srv) || configuredPort,
250
262
  configuredPort,
251
263
  srv,
252
264
  };
@@ -258,11 +270,13 @@ async function getIps(external = true) {
258
270
  const ips = (0, misc_1.onlyTruthy)(Object.entries((0, os_1.networkInterfaces)()).map(([name, nets]) => nets && !ignore.test(name)
259
271
  && v4first((0, misc_1.onlyTruthy)(nets.map(net => !net.internal && net.address)))[0] // for each interface we consider only 1 address
260
272
  )).flat();
261
- const e = external && api_net_1.externalIp;
273
+ const e = external && nat_1.defaultBaseUrl.externalIp;
262
274
  if (e && !ips.includes(e))
263
275
  ips.unshift(e);
264
- return v4first(ips)
276
+ const ret = v4first(ips)
265
277
  .filter((x, i, a) => a.length > 1 || !x.startsWith('169.254')); // 169.254 = dhcp failure on the interface, but keep it if it's our only one
278
+ nat_1.defaultBaseUrl.localIp = ret[0] || '';
279
+ return ret;
266
280
  function v4first(a) {
267
281
  return lodash_1.default.sortBy(a, net_1.isIPv6); // works because `false` comes first
268
282
  }
@@ -4,7 +4,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  return (mod && mod.__esModule) ? mod : { "default": mod };
5
5
  };
6
6
  Object.defineProperty(exports, "__esModule", { value: true });
7
- exports.paramsDecoder = exports.prepareState = exports.getProxyDetected = exports.someSecurity = exports.baseUrl = exports.sendErrorPage = exports.serveGuiAndSharedFiles = exports.headRequests = exports.gzipper = exports.sessionDuration = void 0;
7
+ exports.paramsDecoder = exports.prepareState = exports.getProxyDetected = exports.someSecurity = exports.sendErrorPage = exports.serveGuiAndSharedFiles = exports.headRequests = exports.gzipper = exports.sessionDuration = void 0;
8
8
  const koa_compress_1 = __importDefault(require("koa-compress"));
9
9
  const const_1 = require("./const");
10
10
  const const_2 = require("./const");
@@ -62,6 +62,7 @@ const serveFrontendPrefixed = (0, koa_mount_1.default)(const_2.FRONTEND_URI.slic
62
62
  const serveAdminFiles = (0, serveGuiFiles_1.serveGuiFiles)(process.env.ADMIN_PROXY, const_1.ADMIN_URI);
63
63
  const serveAdminPrefixed = (0, koa_mount_1.default)(const_1.ADMIN_URI.slice(0, -1), serveAdminFiles);
64
64
  const serveGuiAndSharedFiles = async (ctx, next) => {
65
+ var _a;
65
66
  const { path } = ctx;
66
67
  // dynamic import on frontend|admin (used for non-https login) while developing (vite4) is not producing a relative path
67
68
  if (const_1.DEV && path.startsWith('/node_modules/')) {
@@ -103,7 +104,7 @@ const serveGuiAndSharedFiles = async (ctx, next) => {
103
104
  return (0, serveFile_1.serveFile)(ctx, adminApis_1.favicon.get());
104
105
  let node = await (0, vfs_1.urlToNode)(path, ctx);
105
106
  if ((node === null || node === void 0 ? void 0 : node.default) && (path.endsWith('/') || !node.default.match(/\.html?$/i))) // final/ needed on browser to make resource urls correctly
106
- node = await (0, vfs_1.urlToNode)(node.default, ctx, node);
107
+ node = (_a = await (0, vfs_1.urlToNode)(node.default, ctx, node)) !== null && _a !== void 0 ? _a : node;
107
108
  if (!node)
108
109
  return sendErrorPage(ctx, const_1.HTTP_NOT_FOUND);
109
110
  if (ctx.method === 'POST') { // curl -F upload=@file url/
@@ -164,13 +165,12 @@ const errorMessages = {
164
165
  [const_1.HTTP_UNAUTHORIZED]: "Unauthorized",
165
166
  [const_1.HTTP_FORBIDDEN]: "Forbidden",
166
167
  };
167
- exports.baseUrl = (0, config_1.defineConfig)('base_url', '');
168
168
  async function sendFolderList(node, ctx) {
169
169
  let { depth = 0, folders, prepend } = ctx.query;
170
170
  ctx.type = 'text';
171
171
  if (prepend === undefined || prepend === '*') { // * = force auto-detection even if we have baseUrl set
172
172
  const { URL } = ctx;
173
- const base = prepend === undefined && exports.baseUrl.get()
173
+ const base = prepend === undefined && listen_1.baseUrl.get()
174
174
  || URL.protocol + '//' + URL.host + ctx.state.revProxyPath;
175
175
  prepend = base + ctx.originalUrl.split('?')[0];
176
176
  }
package/src/misc.js CHANGED
@@ -106,7 +106,7 @@ function parseAddress(s) {
106
106
  return new node_net_1.SocketAddress({ address: s, family: (0, net_1.isIPv6)(s) ? 'ipv6' : 'ipv4' });
107
107
  }
108
108
  function makeMatcher(mask, emptyMaskReturns = false) {
109
- return mask ? (0, micromatch_1.matcher)(mask.replace(/^(!)?/, '$1(') + ')') // adding () will allow us to use the pipe at root level
109
+ return mask ? (0, micromatch_1.matcher)(mask.replace(/^(!)?/, '$1(') + ')', { nocase: true }) // adding () will allow us to use the pipe at root level
110
110
  : () => emptyMaskReturns;
111
111
  }
112
112
  exports.makeMatcher = makeMatcher;
package/src/nat.js ADDED
@@ -0,0 +1,101 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.getNatInfo = exports.upnpClient = exports.getBaseUrlOrDefault = exports.defaultBaseUrl = void 0;
7
+ const valtio_1 = require("valtio");
8
+ const nat_upnp_ts_1 = require("nat-upnp-ts");
9
+ const debounceAsync_1 = require("./debounceAsync");
10
+ const cross_1 = require("./cross");
11
+ const github_1 = require("./github");
12
+ const lodash_1 = __importDefault(require("lodash"));
13
+ const util_http_1 = require("./util-http");
14
+ const promises_1 = require("dns/promises");
15
+ const net_1 = require("net");
16
+ const listen_1 = require("./listen");
17
+ const child_process_1 = require("child_process");
18
+ const const_1 = require("./const");
19
+ exports.defaultBaseUrl = (0, valtio_1.proxy)({
20
+ proto: 'http',
21
+ publicIps: [],
22
+ externalIp: '',
23
+ localIp: '',
24
+ port: 0,
25
+ get() {
26
+ const defPort = this.proto === 'https' ? 443 : 80;
27
+ return `${this.proto}://${this.publicIps[0] || this.externalIp || this.localIp}${!this.port || this.port === defPort ? '' : ':' + this.port}`;
28
+ }
29
+ });
30
+ function getBaseUrlOrDefault() {
31
+ return listen_1.baseUrl.get() || exports.defaultBaseUrl.get();
32
+ }
33
+ exports.getBaseUrlOrDefault = getBaseUrlOrDefault;
34
+ exports.upnpClient = new nat_upnp_ts_1.Client({ timeout: 4000 });
35
+ const originalMethod = exports.upnpClient.getGateway;
36
+ // other client methods call getGateway too, so this will ensure they reuse this same result
37
+ exports.upnpClient.getGateway = (0, debounceAsync_1.debounceAsync)(() => originalMethod.apply(exports.upnpClient), 0, { retain: cross_1.HOUR, retainFailure: 30000 });
38
+ exports.upnpClient.getGateway().catch(() => { });
39
+ // poll external ip
40
+ (0, cross_1.repeat)(10 * cross_1.MINUTE, () => exports.upnpClient.getPublicIp().then(v => {
41
+ if (v === exports.defaultBaseUrl.externalIp)
42
+ return;
43
+ getPublicIps.clearRetain();
44
+ return exports.defaultBaseUrl.externalIp = v;
45
+ }));
46
+ const getPublicIps = (0, debounceAsync_1.debounceAsync)(async () => {
47
+ const res = await (0, github_1.getProjectInfo)();
48
+ const groupedByVersion = Object.values(lodash_1.default.groupBy(res.publicIpServices, x => { var _a; return (_a = x.v) !== null && _a !== void 0 ? _a : 4; }));
49
+ const ips = await (0, cross_1.promiseBestEffort)(groupedByVersion.map(singleVersion => Promise.any(singleVersion.map(async (svc) => {
50
+ if (typeof svc === 'string')
51
+ svc = { type: 'http', url: svc };
52
+ console.debug("trying ip service", svc.url || svc.name);
53
+ if (svc.type === 'http')
54
+ return (0, util_http_1.httpString)(svc.url);
55
+ if (svc.type !== 'dns')
56
+ throw "unsupported";
57
+ const resolver = new promises_1.Resolver({ timeout: 2000 });
58
+ resolver.setServers(svc.ips);
59
+ return resolver.resolve(svc.name, svc.dnsRecord);
60
+ }).map(async (ret) => {
61
+ const validIps = (0, cross_1.wantArray)(await ret).map(x => x.trim()).filter(net_1.isIP);
62
+ if (!validIps.length)
63
+ throw "no good";
64
+ return validIps;
65
+ }))));
66
+ return lodash_1.default.uniq(ips.flat());
67
+ }, 0, { retain: 10 * cross_1.MINUTE });
68
+ exports.getNatInfo = (0, debounceAsync_1.debounceAsync)(async () => {
69
+ var _a, _b, _c, _d;
70
+ const gettingIps = getPublicIps(); // don't wait, do it in parallel
71
+ const res = await exports.upnpClient.getGateway().catch(() => null);
72
+ const status = await (0, listen_1.getServerStatus)();
73
+ const mappings = res && await (0, cross_1.haveTimeout)(5000, exports.upnpClient.getMappings()).catch(() => null);
74
+ console.debug('mappings found', mappings === null || mappings === void 0 ? void 0 : mappings.map(x => x.description));
75
+ const gatewayIp = res ? new URL(res.gateway.description).hostname : await findGateway().catch(() => undefined);
76
+ const localIp = (res === null || res === void 0 ? void 0 : res.address) || (await (0, listen_1.getIps)())[0];
77
+ const internalPort = ((_a = status === null || status === void 0 ? void 0 : status.https) === null || _a === void 0 ? void 0 : _a.listening) && status.https.port || ((_b = status === null || status === void 0 ? void 0 : status.http) === null || _b === void 0 ? void 0 : _b.listening) && status.http.port || undefined;
78
+ const mapped = lodash_1.default.find(mappings, x => x.private.host === localIp && x.private.port === internalPort);
79
+ const externalPort = mapped === null || mapped === void 0 ? void 0 : mapped.public.port;
80
+ exports.defaultBaseUrl.port = externalPort || internalPort || 0;
81
+ return {
82
+ upnp: Boolean(res),
83
+ localIp,
84
+ gatewayIp,
85
+ publicIps: exports.defaultBaseUrl.publicIps = await gettingIps,
86
+ externalIp: exports.defaultBaseUrl.externalIp,
87
+ mapped,
88
+ internalPort,
89
+ externalPort,
90
+ proto: ((_c = status === null || status === void 0 ? void 0 : status.https) === null || _c === void 0 ? void 0 : _c.listening) ? 'https' : ((_d = status === null || status === void 0 ? void 0 : status.http) === null || _d === void 0 ? void 0 : _d.listening) ? 'http' : '',
91
+ };
92
+ });
93
+ function findGateway() {
94
+ return new Promise((resolve, reject) => (0, child_process_1.exec)(const_1.IS_WINDOWS || const_1.IS_MAC ? 'netstat -rn' : 'route -n', (err, out) => {
95
+ var _a;
96
+ if (err)
97
+ return reject(err);
98
+ const re = const_1.IS_WINDOWS ? /(?:0\.0\.0\.0 +){2}([\d.]+)/ : const_1.IS_MAC ? /default +([\d.]+)/ : /^0\.0\.0\.0 +([\d.]+)/;
99
+ resolve((_a = re.exec(out)) === null || _a === void 0 ? void 0 : _a[1]);
100
+ }));
101
+ }
package/src/perm.js CHANGED
@@ -4,7 +4,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  return (mod && mod.__esModule) ? mod : { "default": mod };
5
5
  };
6
6
  Object.defineProperty(exports, "__esModule", { value: true });
7
- exports.accountCanLoginAdmin = exports.accountCanLogin = exports.accountHasPassword = exports.getFromAccount = exports.delAccount = exports.setAccount = exports.addAccount = exports.renameAccount = exports.normalizeUsername = exports.accountsConfig = exports.updateAccount = exports.allowClearTextLogin = exports.saveSrpInfo = exports.getAccount = exports.expandUsername = exports.getCurrentUsername = void 0;
7
+ exports.accountCanLoginAdmin = exports.accountCanLogin = exports.accountHasPassword = exports.getFromAccount = exports.delAccount = exports.setAccount = exports.addAccount = exports.renameAccount = exports.normalizeUsername = exports.accountsConfig = exports.updateAccount = exports.createAdmin = exports.allowClearTextLogin = exports.saveSrpInfo = exports.getAccount = exports.expandUsername = exports.getCurrentUsername = void 0;
8
8
  const lodash_1 = __importDefault(require("lodash"));
9
9
  const crypt_1 = require("./crypt");
10
10
  const misc_1 = require("./misc");
@@ -43,6 +43,21 @@ function saveSrpInfo(account, salt, verifier) {
43
43
  }
44
44
  exports.saveSrpInfo = saveSrpInfo;
45
45
  exports.allowClearTextLogin = (0, config_1.defineConfig)('allow_clear_text_login', false);
46
+ const createAdminConfig = (0, config_1.defineConfig)('create-admin', '');
47
+ createAdminConfig.sub(v => {
48
+ if (!v)
49
+ return;
50
+ createAdmin(v);
51
+ createAdminConfig.set('');
52
+ });
53
+ function createAdmin(pass, username = 'admin') {
54
+ const acc = addAccount(username, { admin: true });
55
+ if (!acc)
56
+ return console.log("cannot create, already exists");
57
+ updateAccount(acc, acc => { acc.password = pass; });
58
+ console.log("account admin created");
59
+ }
60
+ exports.createAdmin = createAdmin;
46
61
  const srp6aNimbusRoutines = new tssrp6a_1.SRPRoutines(new tssrp6a_1.SRPParameters());
47
62
  async function updateAccount(account, changer) {
48
63
  const was = JSON.stringify(account);
package/src/plugins.js CHANGED
@@ -35,6 +35,7 @@ const const_1 = require("./const");
35
35
  const Const = __importStar(require("./const"));
36
36
  const misc_1 = require("./misc");
37
37
  const config_1 = require("./config");
38
+ const vfs_1 = require("./vfs");
38
39
  const serveFile_1 = require("./serveFile");
39
40
  const events_1 = __importDefault(require("./events"));
40
41
  const promises_1 = require("fs/promises");
@@ -153,7 +154,7 @@ const pluginsMiddleware = async (ctx, next) => {
153
154
  const a = path.substring(const_1.PLUGINS_PUB_URI.length).split('/');
154
155
  const name = a.shift();
155
156
  if (plugins.hasOwnProperty(name)) // do it only if the plugin is loaded
156
- await (0, serveFile_1.serveFile)(ctx, plugins[name].folder + '/public/' + a.join('/'), 'auto');
157
+ await (0, serveFile_1.serveFile)(ctx, plugins[name].folder + '/public/' + a.join('/'), vfs_1.MIME_AUTO);
157
158
  return;
158
159
  }
159
160
  await next();
@@ -0,0 +1,60 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.selfCheck = exports.selfCheckMiddleware = void 0;
7
+ const cross_const_1 = require("./cross-const");
8
+ const github_1 = require("./github");
9
+ const net_1 = require("net");
10
+ const lodash_1 = __importDefault(require("lodash"));
11
+ const cross_1 = require("./cross");
12
+ const util_http_1 = require("./util-http");
13
+ let selfCheckMiddlewareEnabled = false;
14
+ const CHECK_URL = cross_const_1.SPECIAL_URI + 'self-check';
15
+ const selfCheckMiddleware = (ctx, next) => {
16
+ if (!selfCheckMiddlewareEnabled || !ctx.url.startsWith(CHECK_URL))
17
+ return next();
18
+ ctx.body = 'HFS';
19
+ };
20
+ exports.selfCheckMiddleware = selfCheckMiddleware;
21
+ async function selfCheck(url) {
22
+ var _a;
23
+ const prjInfo = await (0, github_1.getProjectInfo)();
24
+ console.log(`checking server ${url}`);
25
+ selfCheckMiddlewareEnabled = true;
26
+ try {
27
+ const parsed = new URL(url);
28
+ const family = !(0, net_1.isIP)(parsed.hostname) ? undefined : (0, net_1.isIPv6)(parsed.hostname) ? 6 : 4;
29
+ for (const services of lodash_1.default.chunk(lodash_1.default.shuffle(prjInfo.selfCheckServices), 2)) {
30
+ try {
31
+ return await Promise.any(services.map(async (svc) => {
32
+ if (!svc.url || svc.type)
33
+ throw 'unsupported ' + svc.type; // only default type supported for now
34
+ let { url: serviceUrl, body, regexpSuccess, regexpFailure, ...rest } = svc;
35
+ const service = new URL(serviceUrl).hostname;
36
+ console.log('trying external service', service);
37
+ body = applySymbols(body);
38
+ serviceUrl = applySymbols(serviceUrl);
39
+ const res = await (0, cross_1.haveTimeout)(10000, (0, util_http_1.httpString)(serviceUrl, { family, ...rest, body }));
40
+ const success = new RegExp(regexpSuccess).test(res);
41
+ const failure = new RegExp(regexpFailure).test(res);
42
+ if (success === failure)
43
+ throw 'inconsistent: ' + service + ': ' + res; // this result cannot be trusted
44
+ console.debug(service, 'responded', success);
45
+ return { success, service, url };
46
+ }));
47
+ }
48
+ catch (e) {
49
+ console.debug(((_a = e === null || e === void 0 ? void 0 : e.errors) === null || _a === void 0 ? void 0 : _a.map(String)) || (e === null || e === void 0 ? void 0 : e.cause) || String(e));
50
+ }
51
+ }
52
+ function applySymbols(s) {
53
+ return s === null || s === void 0 ? void 0 : s.replace('$IP', parsed.hostname).replace('$PORT', parsed.port || (parsed.protocol === 'https:' ? '443' : '80')).replace('$URL', url.replace(/\/$/, '') + CHECK_URL);
54
+ }
55
+ }
56
+ finally {
57
+ selfCheckMiddlewareEnabled = false;
58
+ }
59
+ }
60
+ exports.selfCheck = selfCheck;