hfs 0.53.0 → 0.54.0-alpha1

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.
@@ -1,4 +1,4 @@
1
- System.register(["./index-legacy-5MEl9EM8.js"],(function(h,t){"use strict";var i,s;return{setters:[function(h){i=h.g,s=h.c}],execute:function(){function t(h,t){for(var i=function(){var i=t[s];if("string"!=typeof i&&!Array.isArray(i)){var r=function(t){if("default"!==t&&!(t in h)){var s=Object.getOwnPropertyDescriptor(i,t);s&&Object.defineProperty(h,t,s.get?s:{enumerable:!0,get:function(){return i[t]}})}};for(var e in i)r(e)}},s=0;s<t.length;s++)i();return Object.freeze(Object.defineProperty(h,Symbol.toStringTag,{value:"Module"}))}var r={exports:{}};
1
+ System.register(["./index-legacy-C5quHzqa.js"],(function(h,t){"use strict";var i,s;return{setters:[function(h){i=h.g,s=h.c}],execute:function(){function t(h,t){for(var i=function(){var i=t[s];if("string"!=typeof i&&!Array.isArray(i)){var r=function(t){if("default"!==t&&!(t in h)){var s=Object.getOwnPropertyDescriptor(i,t);s&&Object.defineProperty(h,t,s.get?s:{enumerable:!0,get:function(){return i[t]}})}};for(var e in i)r(e)}},s=0;s<t.length;s++)i();return Object.freeze(Object.defineProperty(h,Symbol.toStringTag,{value:"Module"}))}var r={exports:{}};
2
2
  /*
3
3
  * [js-sha512]{@link https://github.com/emn178/js-sha512}
4
4
  *
@@ -9,6 +9,6 @@
9
9
  <body>
10
10
  <div id="root">Wait for loading or <a href="?get=basic">use basic interface now</a></div>
11
11
  <script crossorigin id="vite-legacy-polyfill" src="/assets/polyfills-legacy-31b7nyOi.js"></script>
12
- <script crossorigin id="vite-legacy-entry" data-src="/assets/index-legacy-5MEl9EM8.js">System.import(document.getElementById('vite-legacy-entry').getAttribute('data-src'))</script>
12
+ <script crossorigin id="vite-legacy-entry" data-src="/assets/index-legacy-C5quHzqa.js">System.import(document.getElementById('vite-legacy-entry').getAttribute('data-src'))</script>
13
13
  </body>
14
14
  </html>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "hfs",
3
- "version": "0.53.0",
3
+ "version": "0.54.0-alpha1",
4
4
  "description": "HTTP File Server",
5
5
  "keywords": [
6
6
  "file server",
@@ -16,21 +16,6 @@ exports.configDialog = {
16
16
 
17
17
  exports.init = async api => {
18
18
  const db = await api.openDb('counters.kv', { defaultPutDelay: 5_000, maxPutDelay: 30_000 })
19
-
20
- try { // load legacy file
21
- const countersFile = 'counters.yaml'
22
- const yaml = api.require('yaml')
23
- const { readFile, unlink } = api.require('fs/promises')
24
- const data = await readFile(countersFile, 'utf8')
25
- for (const [k,v] of Object.entries(yaml.parse(data)))
26
- db.put(uri2key(k), v)
27
- await unlink(countersFile)
28
- api.log("data converted")
29
- }
30
- catch(err) {
31
- if (err.code !== 'ENOENT')
32
- api.log(err)
33
- }
34
19
  return {
35
20
  frontend_js: 'main.js',
36
21
  frontend_css: 'style.css',
package/src/acme.js CHANGED
@@ -113,7 +113,7 @@ exports.makeCert = (0, debounceAsync_1.debounceAsync)(async (domain, email, altN
113
113
  await promises_1.default.writeFile(KEY_FILE, res.key);
114
114
  listen_1.cert.set(CERT_FILE); // update config
115
115
  listen_1.privateKey.set(KEY_FILE);
116
- }, 0);
116
+ });
117
117
  const acmeDomain = (0, config_1.defineConfig)('acme_domain', '');
118
118
  const acmeEmail = (0, config_1.defineConfig)('acme_email', '');
119
119
  const acmeRenew = (0, config_1.defineConfig)('acme_renew', false); // handle config changes
@@ -133,4 +133,4 @@ const renewCert = (0, debounceAsync_1.debounceAsync)(async () => {
133
133
  return console.log("certificate still good");
134
134
  await (0, exports.makeCert)(domain, acmeEmail.get(), altNames)
135
135
  .catch(e => console.log("error renewing certificate: ", String(e.message || e)));
136
- }, 0, { retain: misc_1.DAY, retainFailure: misc_1.HOUR });
136
+ }, { retain: misc_1.DAY, retainFailure: misc_1.HOUR });
package/src/adminApis.js CHANGED
@@ -32,6 +32,8 @@ const geo_1 = require("./geo");
32
32
  const roots_1 = require("./roots");
33
33
  const SendList_1 = require("./SendList");
34
34
  const ddns_1 = require("./ddns");
35
+ const block_1 = require("./block");
36
+ const github_1 = require("./github");
35
37
  exports.adminApis = {
36
38
  ...api_vfs_1.default,
37
39
  ...api_accounts_1.default,
@@ -71,6 +73,10 @@ exports.adminApis = {
71
73
  async check_update() {
72
74
  return { options: await (0, update_1.getUpdates)() };
73
75
  },
76
+ async wait_project_info() {
77
+ await (0, github_1.getProjectInfo)();
78
+ return {};
79
+ },
74
80
  async ip_country({ ips }) {
75
81
  const res = await Promise.allSettled(ips.map(geo_1.ip2country));
76
82
  return {
@@ -107,6 +113,8 @@ exports.adminApis = {
107
113
  baseUrl: await (0, listen_1.getBaseUrlOrDefault)(),
108
114
  roots: roots_1.roots.get(),
109
115
  updatePossible: !await (0, update_1.updateSupported)() ? false : (await (0, update_1.localUpdateAvailable)()) ? 'local' : true,
116
+ autoCheckUpdateResult: update_1.autoCheckUpdateResult.get(),
117
+ alerts: github_1.alerts.get(),
110
118
  proxyDetected: (0, middlewares_1.getProxyDetected)(),
111
119
  frpDetected: exports.localhostAdmin.get() && !(0, middlewares_1.getProxyDetected)()
112
120
  && (0, connections_1.getConnections)().every(misc_1.isLocalHost)
@@ -121,9 +129,18 @@ exports.adminApis = {
121
129
  await (0, promises_1.writeFile)(files.cert, cert);
122
130
  return files;
123
131
  },
132
+ async add_block({ merge, ip, expire, comment }) {
133
+ (0, misc_1.apiAssertTypes)({
134
+ string: { ip },
135
+ string_undefined: { comment, expire },
136
+ object_undefined: { merge },
137
+ });
138
+ (0, block_1.addBlock)({ ip, expire, comment }, merge);
139
+ return {};
140
+ }
124
141
  };
125
- for (const [k, was] of Object.entries(exports.adminApis))
126
- exports.adminApis[k] = (params, ctx) => {
142
+ for (const [k, was] of (0, misc_1.typedEntries)(exports.adminApis))
143
+ exports.adminApis[k] = ((params, ctx) => {
127
144
  if (!allowAdmin(ctx))
128
145
  return new apiMiddleware_1.ApiError(const_1.HTTP_FORBIDDEN);
129
146
  if (ctxAdminAccess(ctx))
@@ -132,7 +149,7 @@ for (const [k, was] of Object.entries(exports.adminApis))
132
149
  return ctx.headers.accept === 'text/event-stream'
133
150
  ? new SendList_1.SendListReadable({ doAtStart: x => x.error(const_1.HTTP_UNAUTHORIZED, true, props) })
134
151
  : new apiMiddleware_1.ApiError(const_1.HTTP_UNAUTHORIZED, props);
135
- };
152
+ });
136
153
  exports.localhostAdmin = (0, config_1.defineConfig)('localhost_admin', true);
137
154
  exports.adminNet = (0, config_1.defineConfig)('admin_net', '', v => (0, misc_1.makeNetMatcher)(v, true));
138
155
  exports.favicon = (0, config_1.defineConfig)('favicon', '');
@@ -14,7 +14,8 @@ const connections_1 = require("./connections");
14
14
  const adminApis_1 = require("./adminApis");
15
15
  const upload_1 = require("./upload");
16
16
  const SendList_1 = require("./SendList");
17
- const get_file_list = async ({ uri = '/', offset, limit, search, c, onlyFolders, admin }, ctx) => {
17
+ const get_file_list = async ({ uri = '/', offset, limit, search, wild, c, onlyFolders, admin }, ctx) => {
18
+ var _a;
18
19
  const node = await (0, vfs_1.urlToNode)(uri, ctx);
19
20
  const list = ctx.get('accept') === 'text/event-stream' ? new SendList_1.SendListReadable() : undefined;
20
21
  if (!node)
@@ -29,17 +30,19 @@ const get_file_list = async ({ uri = '/', offset, limit, search, c, onlyFolders,
29
30
  return fail();
30
31
  offset = Number(offset);
31
32
  limit = Number(limit);
32
- const filter = (0, misc_1.pattern2filter)(String(search || ''));
33
+ search = String(search || '').toLocaleLowerCase();
34
+ const filter = wild === 'no' ? (s) => s.includes(search)
35
+ : (0, misc_1.pattern2filter)(search);
33
36
  const walker = (0, vfs_1.walkNode)(node, { ctx: admin ? undefined : ctx, onlyFolders, depth: search ? Infinity : 0 });
34
37
  const onDirEntryHandlers = (0, plugins_1.mapPlugins)(plug => plug.onDirEntry);
35
38
  const can_upload = admin || (0, vfs_1.hasPermission)(node, 'can_upload', ctx);
36
- const fakeChild = await (0, vfs_1.applyParentToChild)(undefined, node); // can we delete children
39
+ const fakeChild = await (0, vfs_1.applyParentToChild)({ source: 'x' }, node); // can we delete children
37
40
  const can_delete = admin || (0, vfs_1.hasPermission)(fakeChild, 'can_delete', ctx);
38
- const can_archive = admin || (0, vfs_1.hasPermission)(node, 'can_archive', ctx);
41
+ const can_archive = admin || (0, vfs_1.hasPermission)(fakeChild, 'can_archive', ctx);
39
42
  const can_comment = can_upload && (0, comments_1.areCommentsEnabled)();
40
43
  const can_overwrite = can_upload && (can_delete || !upload_1.dontOverwriteUploading.get());
41
- const comment = await (0, comments_1.getCommentFor)(node.source);
42
- const props = { can_archive, can_upload, can_delete, can_overwrite, can_comment, comment, accept: node.accept };
44
+ const comment = (_a = node.comment) !== null && _a !== void 0 ? _a : await (0, comments_1.getCommentFor)(node.source);
45
+ const props = { can_archive, can_upload, can_delete, can_overwrite, can_comment, comment, accept: node.accept, icon: getNodeIcon(node) };
43
46
  ctx.state.browsing = uri.replace(/\/{2,}/g, '/');
44
47
  (0, connections_1.updateConnectionForCtx)(ctx);
45
48
  if (!list)
@@ -94,7 +97,12 @@ const get_file_list = async ({ uri = '/', offset, limit, search, c, onlyFolders,
94
97
  break;
95
98
  }
96
99
  }
100
+ function getNodeIcon(node) {
101
+ var _a;
102
+ return ((_a = node.icon) === null || _a === void 0 ? void 0 : _a.includes('.')) || node.icon; // true = specific for this file, otherwise is a SYS_ICONS
103
+ }
97
104
  async function nodeToDirEntry(ctx, node) {
105
+ var _a;
98
106
  const { source, url } = node;
99
107
  const name = (0, vfs_1.getNodeName)(node);
100
108
  if (url)
@@ -117,11 +125,12 @@ const get_file_list = async ({ uri = '/', offset, limit, search, c, onlyFolders,
117
125
  m: !st || Math.abs(+st.mtime - +st.ctime) < 1000 ? undefined : st.mtime,
118
126
  s: isFolder ? undefined : st === null || st === void 0 ? void 0 : st.size,
119
127
  p: (pr + pl + pd + pa) || undefined,
120
- comment: await (0, comments_1.getCommentFor)(source),
128
+ comment: (_a = node.comment) !== null && _a !== void 0 ? _a : await (0, comments_1.getCommentFor)(source),
129
+ icon: getNodeIcon(node),
121
130
  web: await (0, vfs_1.hasDefaultFile)(node, ctx) ? true : undefined,
122
131
  };
123
132
  }
124
- catch (_a) {
133
+ catch (_b) {
125
134
  return null;
126
135
  }
127
136
  function filesInsideCould(n = node) {
@@ -71,7 +71,7 @@ exports.default = {
71
71
  ...s.browsing ? { op: 'browsing', path: decodeURIComponent(s.browsing) }
72
72
  : s.uploadPath ? { op: 'upload', path: decodeURIComponent(s.uploadPath) }
73
73
  : {
74
- op: !s.considerAsGui && s.op || undefined,
74
+ op: !s.considerAsGui && (ctx.state.archive || ctx.state.vfsNode) ? 'download' : undefined,
75
75
  path: (0, misc_1.try_)(() => decodeURIComponent(ctx.originalUrl), () => ctx.originalUrl),
76
76
  },
77
77
  opProgress: lodash_1.default.isNumber(s.opProgress) ? lodash_1.default.round(s.opProgress, 3) : undefined,
@@ -43,6 +43,8 @@ const apis = {
43
43
  if (online.version !== disk.version) { // not just newer one, in case a version was retired
44
44
  online.id = disk.id; // id is installation-dependant, and online cannot know
45
45
  online.repo = serialize(disk).repo; // show the user the current repo we are getting this update from, not a possibly-changed future one
46
+ if (online.version < disk.version)
47
+ online.downgrade = true;
46
48
  list.add(online);
47
49
  }
48
50
  }
package/src/api.vfs.js CHANGED
@@ -21,7 +21,7 @@ async function urlToNodeOriginal(uri) {
21
21
  const n = await (0, vfs_1.urlToNode)(uri);
22
22
  return (n === null || n === void 0 ? void 0 : n.isTemp) ? n.original : n;
23
23
  }
24
- const ALLOWED_KEYS = ['name', 'source', 'masks', 'default', 'accept', 'rename', 'mime', 'url', 'target', ...misc_1.PERM_KEYS];
24
+ const ALLOWED_KEYS = ['name', 'source', 'masks', 'default', 'accept', 'rename', 'mime', 'url', 'target', 'comment', 'icon', ...misc_1.PERM_KEYS];
25
25
  const apis = {
26
26
  async get_vfs() {
27
27
  return { root: await recur() };
@@ -188,7 +188,9 @@ const apis = {
188
188
  try {
189
189
  const matching = (0, misc_1.makeMatcher)(fileMask);
190
190
  path = (0, misc_1.isWindowsDrive)(path) ? path + '\\' : (0, path_1.resolve)(path || '/');
191
- for await (const [name, isDir] of (0, misc_1.dirStream)(path)) {
191
+ for await (const entry of (0, misc_1.dirStream)(path)) {
192
+ const { path: name } = entry;
193
+ const isDir = entry.isDirectory();
192
194
  if (ctx.req.aborted)
193
195
  return;
194
196
  if (!isDir)
package/src/block.js CHANGED
@@ -1,10 +1,14 @@
1
1
  "use strict";
2
2
  // This file is part of HFS - Copyright 2021-2023, Massimo Melina <a@rejetto.com> - License https://www.gnu.org/licenses/gpl-3.0.txt
3
+ var __importDefault = (this && this.__importDefault) || function (mod) {
4
+ return (mod && mod.__esModule) ? mod : { "default": mod };
5
+ };
3
6
  Object.defineProperty(exports, "__esModule", { value: true });
4
- exports.applyBlock = exports.block = void 0;
7
+ exports.addBlock = exports.applyBlock = exports.block = void 0;
5
8
  const config_1 = require("./config");
6
9
  const connections_1 = require("./connections");
7
10
  const misc_1 = require("./misc");
11
+ const lodash_1 = __importDefault(require("lodash"));
8
12
  exports.block = (0, config_1.defineConfig)('block', [], rules => {
9
13
  const now = new Date();
10
14
  const ret = !Array.isArray(rules) ? []
@@ -31,3 +35,11 @@ setInterval(() => {
31
35
  console.log("blocking rules:", n, "expired");
32
36
  exports.block.set(next);
33
37
  }, misc_1.MINUTE / 2);
38
+ function addBlock(rule, merge) {
39
+ exports.block.set(was => {
40
+ const found = merge && lodash_1.default.findIndex(was, merge);
41
+ return found ? was.map((x, i) => i === found ? { ...x, ...rule, ip: `${x.ip}|${rule.ip}` } : x)
42
+ : [...was, { ...merge, ...rule }];
43
+ });
44
+ }
45
+ exports.addBlock = addBlock;
package/src/const.js CHANGED
@@ -37,7 +37,7 @@ const os_1 = require("os");
37
37
  const fs_1 = require("fs");
38
38
  const path_1 = require("path");
39
39
  __exportStar(require("./cross-const"), exports);
40
- exports.API_VERSION = 8.891;
40
+ exports.API_VERSION = 8.9;
41
41
  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
42
42
  exports.HFS_REPO = 'rejetto/hfs';
43
43
  exports.argv = (0, minimist_1.default)(process.argv.slice(2));
@@ -45,7 +45,7 @@ exports.DEV = process.env.DEV || exports.argv.dev ? 'DEV' : '';
45
45
  exports.ORIGINAL_CWD = process.cwd();
46
46
  exports.HFS_STARTED = new Date();
47
47
  const PKG_PATH = (0, path_1.join)(__dirname, '..', 'package.json');
48
- exports.BUILD_TIMESTAMP = "2024-07-19T14:05:43.478Z";
48
+ exports.BUILD_TIMESTAMP = "2024-07-21T21:45:23.266Z";
49
49
  const pkg = JSON.parse(fs.readFileSync(PKG_PATH, 'utf8'));
50
50
  exports.VERSION = pkg.version;
51
51
  exports.RUNNING_BETA = exports.VERSION.includes('-');
@@ -83,5 +83,5 @@ console.log('cwd', process.cwd());
83
83
  if (exports.APP_PATH !== process.cwd())
84
84
  console.log('app', exports.APP_PATH);
85
85
  console.log('node', process.version);
86
- console.log('platform', process.platform, process.arch);
86
+ console.log('platform', process.platform);
87
87
  console.log('pid', process.pid);
package/src/cross.js CHANGED
@@ -18,7 +18,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
18
18
  };
19
19
  Object.defineProperty(exports, "__esModule", { value: true });
20
20
  exports.objRenameKey = exports.randomId = exports.getOrSet = exports.waitFor = exports.newObj = exports.findDefined = exports.isOrderedEqual = exports.swap = exports.tryJson = exports.dirname = exports.basename = exports.pendingPromise = exports._dbg = exports._log = exports.wantArray = exports.formatPerc = exports.with_ = exports.try_ = exports.setHidden = exports.onlyTruthy = exports.truthy = exports.splitAt = exports.strinsert = exports.removeStarting = exports.enforceStarting = exports.enforceFinal = exports.objSameKeys = exports.haveTimeout = exports.wait = exports.join = exports.prefix = exports.formatSpeed = exports.formatBytes = exports.isWhoObject = exports.PERM_KEYS = exports.defaultPerms = exports.WHO_ANY_ACCOUNT = exports.WHO_NO_ONE = exports.WHO_ANYONE = exports.LIST = exports.CFG = exports.THEME_OPTIONS = exports.SORT_BY_OPTIONS = exports.FRONTEND_OPTIONS = exports.MAX_TILE_SIZE = exports.DAY = exports.HOUR = exports.MINUTE = exports.WIKI_URL = exports.REPO_URL = void 0;
21
- exports.shortenAgent = exports.safeDecodeURIComponent = exports.callable = exports.mapFilter = exports.inCommon = exports.replace = exports.matches = exports.makeMatcher = exports.runAt = exports.pathEncode = exports.promiseBestEffort = exports.escapeHTML = exports.ipForUrl = exports.isIpLan = exports.isIpLocalHost = exports.xlate = exports.isEqualLax = exports.isTimestampString = exports.isWindowsDrive = exports.isIP = exports.isPrimitive = exports.formatTimestamp = exports.repeat = exports.asyncGeneratorToArray = exports.filterMapGenerator = exports.throw_ = exports.hasProp = exports.typedEntries = exports.typedKeys = void 0;
21
+ exports.shortenAgent = exports.popKey = exports.safeDecodeURIComponent = exports.callable = exports.mapFilter = exports.inCommon = exports.replace = exports.matches = exports.makeMatcher = exports.runAt = exports.pathEncode = exports.promiseBestEffort = exports.escapeHTML = exports.ipForUrl = exports.isIpLan = exports.isIpLocalHost = exports.xlate = exports.isEqualLax = exports.isTimestampString = exports.isWindowsDrive = exports.isIP = exports.isPrimitive = exports.formatTimestamp = exports.repeat = exports.asyncGeneratorToArray = exports.filterMapGenerator = exports.throw_ = exports.hasProp = exports.typedEntries = exports.typedKeys = void 0;
22
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
23
23
  // all content here is shared between client and server
24
24
  const lodash_1 = __importDefault(require("lodash"));
@@ -456,6 +456,14 @@ function safeDecodeURIComponent(s) {
456
456
  }
457
457
  }
458
458
  exports.safeDecodeURIComponent = safeDecodeURIComponent;
459
+ function popKey(o, k) {
460
+ if (!o)
461
+ return;
462
+ const x = o[k];
463
+ delete o[k];
464
+ return x;
465
+ }
466
+ exports.popKey = popKey;
459
467
  function shortenAgent(agent) {
460
468
  var _a;
461
469
  return lodash_1.default.findKey(BROWSERS, re => re.test(agent))
@@ -5,10 +5,8 @@ exports.singleWorkerFromBatchWorker = exports.debounceAsync = void 0;
5
5
  // like lodash.debounce, but also avoids async invocations to overlap
6
6
  function debounceAsync(
7
7
  // the function you want to not call too often, too soon
8
- callback,
9
- // time to wait after invocation of the debounced function. If you call again while waiting, the timer starts again.
10
- wait = 100, options = {}) {
11
- const { leading = false, maxWait = Infinity, cancelable = false, retain = 0, retainFailure } = options;
8
+ callback, options = {}) {
9
+ const { wait = 0, leading = false, maxWait = Infinity, cancelable = false, retain = 0, retainFailure } = options;
12
10
  let started = 0; // latest callback invocation
13
11
  let runningCallback; // latest callback invocation result
14
12
  let latestDebouncer; // latest wrapper invocation
@@ -76,7 +74,7 @@ function singleWorkerFromBatchWorker(batchWorker, { maxWait = Infinity } = {}) {
76
74
  const ret = batchWorker(batch);
77
75
  batch = []; // this is reset as batchWorker starts, but without waiting
78
76
  return ret;
79
- }, 100, { maxWait });
77
+ }, { wait: 100, maxWait });
80
78
  return (...args) => {
81
79
  const idx = batch.push(args) - 1;
82
80
  return debounced().then((x) => x[idx]);
@@ -0,0 +1,97 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DirentFromStats = exports.createDirStream = void 0;
4
+ const makeQ_1 = require("./makeQ");
5
+ const promises_1 = require("fs/promises");
6
+ const path_1 = require("path");
7
+ const stream_1 = require("stream");
8
+ const cross_1 = require("./cross");
9
+ const node_fs_1 = require("node:fs");
10
+ const dirQ = (0, makeQ_1.makeQ)(3);
11
+ function createDirStream(startPath, depth = 0) {
12
+ let stopped = false;
13
+ let started = false;
14
+ const stream = new stream_1.Readable({
15
+ objectMode: true,
16
+ read() {
17
+ if (started)
18
+ return;
19
+ started = true;
20
+ dirQ.add(() => readDir('', depth)
21
+ .then(res => {
22
+ Promise.resolve(res === null || res === void 0 ? void 0 : res.branchDone).then(() => {
23
+ stream.push(null);
24
+ });
25
+ }));
26
+ }
27
+ });
28
+ stream.on('close', () => stopped = true);
29
+ return Object.assign(stream, {
30
+ stop() {
31
+ stopped = true;
32
+ if (!dirQ.isWorking())
33
+ stream.push(null);
34
+ },
35
+ });
36
+ async function readDir(path, depth) {
37
+ if (stopped)
38
+ return;
39
+ const base = (0, path_1.join)(startPath, path);
40
+ const dir = await (0, promises_1.opendir)(base);
41
+ const subDirsDone = [];
42
+ let last = undefined;
43
+ for await (let entry of dir) {
44
+ last = entry;
45
+ if (stopped) {
46
+ await dir.close().catch(() => { }); // only necessary for early exit
47
+ break;
48
+ }
49
+ const stats = entry.isSymbolicLink() && await (0, promises_1.stat)((0, path_1.join)(base, entry.name));
50
+ if (stats)
51
+ entry = new DirentFromStats(entry.name, stats);
52
+ entry.path = (0, path_1.join)(path, entry.name);
53
+ const expanded = entry;
54
+ if (stats)
55
+ expanded.stats = stats;
56
+ if (depth > 0 && entry.isDirectory()) {
57
+ const branchDone = (0, cross_1.pendingPromise)(); // per-job
58
+ const job = () => readDir(entry.path, depth - 1) // recur
59
+ .then(x => x, () => { }) // mute errors
60
+ .then(res => {
61
+ Promise.resolve(res === null || res === void 0 ? void 0 : res.branchDone).then(() => branchDone.resolve());
62
+ });
63
+ dirQ.add(job); // this won't start until next tick
64
+ subDirsDone.push(branchDone);
65
+ //Object.assign(entry, { branchDone }) // we return this pendingPromise because the job has not even started
66
+ //branchDone.then(() => console.log(entry.path))
67
+ }
68
+ stream.push(entry);
69
+ }
70
+ const branchDone = Promise.allSettled(subDirsDone).then(() => { });
71
+ if (last)
72
+ last.closingBranch = branchDone.then(() => path);
73
+ // don't return the promise directly, as this job ends here, but communicate to caller the promise for the whole branch
74
+ return { branchDone };
75
+ }
76
+ }
77
+ exports.createDirStream = createDirStream;
78
+ const kStats = Symbol('stats');
79
+ // Adapting an internal class in Node.js to mimic the behavior of `Dirent` when creating it manually from `Stats`.
80
+ // https://github.com/nodejs/node/blob/a4cf6b204f0b160480153dc293ae748bf15225f9/lib/internal/fs/utils.js#L199C1-L213
81
+ class DirentFromStats extends node_fs_1.Dirent {
82
+ constructor(name, stats) {
83
+ // @ts-expect-error The constructor has parameters, but they are not represented in types.
84
+ // https://github.com/nodejs/node/blob/a4cf6b204f0b160480153dc293ae748bf15225f9/lib/internal/fs/utils.js#L164
85
+ super(name, null);
86
+ this[kStats] = stats;
87
+ }
88
+ }
89
+ exports.DirentFromStats = DirentFromStats;
90
+ for (const key of Reflect.ownKeys(node_fs_1.Dirent.prototype)) {
91
+ const name = key;
92
+ if (name === 'constructor')
93
+ continue;
94
+ DirentFromStats.prototype[name] = function () {
95
+ return this[kStats][name]();
96
+ };
97
+ }
package/src/github.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.getProjectInfo = exports.searchPlugins = exports.getFolder2repo = exports.readOnlineCompatiblePlugin = exports.readOnlinePlugin = exports.readGithubFile = exports.getRepoInfo = exports.downloadPlugin = void 0;
7
+ exports.getProjectInfo = exports.alerts = exports.searchPlugins = exports.getFolder2repo = exports.readOnlineCompatiblePlugin = exports.readOnlinePlugin = exports.readGithubFile = exports.getRepoInfo = exports.downloadPlugin = void 0;
8
8
  const events_1 = __importDefault(require("./events"));
9
9
  const misc_1 = require("./misc");
10
10
  const plugins_1 = require("./plugins");
@@ -14,6 +14,7 @@ const const_1 = require("./const");
14
14
  const promises_1 = require("fs/promises");
15
15
  const path_1 = require("path");
16
16
  const fs_1 = require("fs");
17
+ const persistence_1 = require("./persistence");
17
18
  const DIST_ROOT = 'dist';
18
19
  const downloading = {};
19
20
  function downloadProgress(id, status) {
@@ -218,10 +219,27 @@ async function searchPlugins(text = '', { skipRepos = [''] } = {}) {
218
219
  }));
219
220
  }
220
221
  exports.searchPlugins = searchPlugins;
222
+ exports.alerts = persistence_1.storedMap.singleSync('alerts', []);
221
223
  // centralized hosted information, to be used as little as possible
222
224
  const FN = 'central.json';
223
225
  let builtIn = JSON.parse((0, fs_1.readFileSync)((0, path_1.join)(__dirname, '..', FN), 'utf8'));
224
226
  exports.getProjectInfo = (0, misc_1.debounceAsync)(() => readGithubFile(`${const_1.HFS_REPO}/${const_1.HFS_REPO_BRANCH}/${FN}`)
225
227
  .then(JSON.parse, () => null)
226
- .then(x => Object.assign({ ...builtIn }, const_1.DEV ? null : x)), // fall back to built-in
227
- 0, { retain: misc_1.DAY, retainFailure: 60000 });
228
+ .then(o => {
229
+ o = Object.assign({ ...builtIn }, const_1.DEV ? null : o); // fall back to built-in
230
+ // merge byVersions info in the main object, but collect alerts separately, to preserve multiple instances
231
+ const allAlerts = [o.alert];
232
+ for (const [ver, more] of Object.entries((0, misc_1.popKey)(o, 'byVersion') || {}))
233
+ if (const_1.VERSION.match(new RegExp(ver))) {
234
+ allAlerts.push(more.alert);
235
+ Object.assign(o, more);
236
+ }
237
+ lodash_1.default.remove(allAlerts, x => !x);
238
+ exports.alerts.set(was => {
239
+ if (!lodash_1.default.isEqual(was, allAlerts))
240
+ for (const a of allAlerts)
241
+ console.log("ALERT:", a);
242
+ return allAlerts;
243
+ });
244
+ return o;
245
+ }), { retain: misc_1.DAY, retainFailure: 60000 });
package/src/listen.js CHANGED
@@ -184,6 +184,13 @@ for (const cfg of httpsNeeds) {
184
184
  exports.httpsPortCfg = (0, config_1.defineConfig)('https_port', const_1.PORT_DISABLED);
185
185
  exports.httpsPortCfg.sub(considerHttps);
186
186
  listenInterface.sub(considerHttps);
187
+ function renderHost(host) {
188
+ return (0, misc_1.xlate)(host, {
189
+ '0.0.0.0': "any IPv4",
190
+ '::': "any IPv6",
191
+ '': "any network",
192
+ });
193
+ }
187
194
  function startServer(srv, { port, host }) {
188
195
  return new Promise(async (resolve) => {
189
196
  if (!srv)
@@ -195,7 +202,7 @@ function startServer(srv, { port, host }) {
195
202
  srv.on('checkContinue', (req, res) => srv.emit('request', req, res));
196
203
  port = await listen(host);
197
204
  if (port)
198
- console.log(srv.name, "serving on", host || "any network", ':', port);
205
+ console.log(srv.name, "serving on", renderHost(host || ''), ':', port);
199
206
  resolve(port);
200
207
  }
201
208
  catch (e) {
@@ -283,7 +290,8 @@ exports.getServerStatus = getServerStatus;
283
290
  const ignore = /^(lo|.*loopback.*|virtualbox.*|.*\(wsl\).*|llw\d|awdl\d|utun\d|anpi\d)$/i; // avoid giving too much information
284
291
  const isLinkLocal = (0, misc_1.makeNetMatcher)('169.254.0.0/16|FE80::/16');
285
292
  async function getIps(external = true) {
286
- const ips = (0, misc_1.onlyTruthy)(Object.entries((0, os_1.networkInterfaces)()).flatMap(([name, nets]) => nets && !ignore.test(name) && nets.map(net => !net.internal && net.address)));
293
+ const only = { '0.0.0.0': 'IPv4', '::': 'IPv6' }[listenInterface.get()] || '';
294
+ const ips = (0, misc_1.onlyTruthy)(Object.entries((0, os_1.networkInterfaces)()).flatMap(([name, nets]) => nets && !ignore.test(name) && nets.map(net => !net.internal && (!only || only === net.family) && net.address)));
287
295
  const e = external && nat_1.defaultBaseUrl.externalIp;
288
296
  if (e && !ips.includes(e))
289
297
  ips.push(e);
@@ -298,7 +306,7 @@ async function getIps(external = true) {
298
306
  exports.getIps = getIps;
299
307
  async function getUrls() {
300
308
  const on = listenInterface.get();
301
- const ips = on ? [on] : await getIps();
309
+ const ips = on === renderHost(on) ? [on] : await getIps();
302
310
  return Object.fromEntries((0, misc_1.onlyTruthy)([httpSrv, httpsSrv].map(srv => {
303
311
  var _a;
304
312
  if (!(srv === null || srv === void 0 ? void 0 : srv.listening))
package/src/log.js CHANGED
@@ -141,7 +141,7 @@ const logMw = async (ctx, next) => {
141
141
  const length = (_c = ctx.state.length) !== null && _c !== void 0 ? _c : ctx.length;
142
142
  const uri = ctx.originalUrl;
143
143
  ctx.logExtra(ctx.state.includesLastByte && ctx.vfsNode && ctx.res.finished && { dl: 1 }
144
- || ctx.state.op === 'upload' && { size: ctx.state.opTotal, ul: ctx.state.uploads });
144
+ || ctx.state.uploadPath && { size: ctx.state.opTotal, ul: ctx.state.uploads });
145
145
  if (conn === null || conn === void 0 ? void 0 : conn.country)
146
146
  ctx.logExtra({ country: conn.country });
147
147
  if (logUA.get())
package/src/makeQ.js ADDED
@@ -0,0 +1,31 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.makeQ = void 0;
4
+ function makeQ(parallelization = 1) {
5
+ const running = new Set();
6
+ const queued = [];
7
+ return {
8
+ add(toAdd) {
9
+ queued.push(toAdd);
10
+ setTimeout(startNextIfPossible); // avoid nesting/stacking of jobs
11
+ },
12
+ isWorking() { return running.size > 0; },
13
+ isFree() { return running.size < parallelization; },
14
+ };
15
+ function startNextIfPossible() {
16
+ while (running.size < parallelization) {
17
+ const job = queued.shift();
18
+ if (!job)
19
+ break; // finished
20
+ const working = job(); // start the job
21
+ if (!working)
22
+ continue; // it was canceled
23
+ running.add(working);
24
+ working.then(() => {
25
+ running.delete(working);
26
+ startNextIfPossible();
27
+ });
28
+ }
29
+ }
30
+ }
31
+ exports.makeQ = makeQ;
package/src/nat.js CHANGED
@@ -32,7 +32,7 @@ exports.defaultBaseUrl = (0, valtio_1.proxy)({
32
32
  exports.upnpClient = new nat_upnp_rejetto_1.Client({ timeout: 4000 });
33
33
  const originalMethod = exports.upnpClient.getGateway;
34
34
  // other client methods call getGateway too, so this will ensure they reuse this same result
35
- exports.upnpClient.getGateway = (0, debounceAsync_1.debounceAsync)(() => originalMethod.apply(exports.upnpClient), 0, { retain: cross_1.HOUR, retainFailure: 30000 });
35
+ exports.upnpClient.getGateway = (0, debounceAsync_1.debounceAsync)(() => originalMethod.apply(exports.upnpClient), { retain: cross_1.HOUR, retainFailure: 30000 });
36
36
  exports.upnpClient.getGateway().then(res => {
37
37
  console.debug('upnp', res.gateway.description);
38
38
  }, e => console.debug('upnp failed:', e.message || String(e)));
@@ -64,16 +64,16 @@ exports.getPublicIps = (0, debounceAsync_1.debounceAsync)(async () => {
64
64
  return validIps;
65
65
  }))));
66
66
  return exports.defaultBaseUrl.publicIps = lodash_1.default.uniq(ips.flat());
67
- }, 0, { retain: 10 * cross_1.MINUTE });
67
+ }, { retain: 10 * cross_1.MINUTE });
68
68
  exports.getNatInfo = (0, debounceAsync_1.debounceAsync)(async () => {
69
69
  var _a, _b, _c, _d;
70
+ const gatewayIpPromise = findGateway().catch(() => undefined);
70
71
  const res = await (0, cross_1.haveTimeout)(10000, exports.upnpClient.getGateway()).catch(() => null);
71
72
  const status = await (0, listen_1.getServerStatus)();
72
73
  const mappings = res && await (0, cross_1.haveTimeout)(5000, exports.upnpClient.getMappings()).catch(() => null);
73
74
  console.debug('mappings found', mappings === null || mappings === void 0 ? void 0 : mappings.map(x => x.description));
74
- const gatewayIp = res && (0, cross_1.try_)(() => new URL(res.gateway.description).hostname, () => { var _a; return console.debug('unexpected upnp gw', (_a = res.gateway) === null || _a === void 0 ? void 0 : _a.description); })
75
- || await findGateway().catch(() => undefined);
76
75
  const localIps = await (0, listen_1.getIps)(false);
76
+ const gatewayIp = await gatewayIpPromise;
77
77
  const localIp = (res === null || res === void 0 ? void 0 : res.address) || gatewayIp ? lodash_1.default.maxBy(localIps, x => (0, cross_1.inCommon)(x, gatewayIp)) : localIps[0];
78
78
  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;
79
79
  const mapped = lodash_1.default.find(mappings, x => x.private.host === localIp && x.private.port === internalPort);
package/src/perm.js CHANGED
@@ -47,7 +47,7 @@ createAdminConfig.sub(v => {
47
47
  });
48
48
  async function createAdmin(password, username = 'admin') {
49
49
  const acc = await addAccount(username, { admin: true, password }, true);
50
- console.log(acc ? "account admin created" : "something went wrong");
50
+ console.log(acc ? "account admin set" : "something went wrong");
51
51
  }
52
52
  exports.createAdmin = createAdmin;
53
53
  const srp6aNimbusRoutines = new tssrp6a_1.SRPRoutines(new tssrp6a_1.SRPParameters());
@@ -8,7 +8,8 @@ exports.storedMap = new kvstorage_1.KvStorage({
8
8
  defaultPutDelay: 5000,
9
9
  maxPutDelay: misc_1.MINUTE,
10
10
  maxPutDelayCreate: 1000,
11
- rewriteLater: true
11
+ rewriteLater: true,
12
+ bucketThreshold: 10000,
12
13
  });
13
14
  exports.storedMap.open('data.kv');
14
15
  (0, first_1.onProcessExit)(() => exports.storedMap.flush());