hfs 0.54.0 → 0.55.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-SJb2fz1j.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-DuGmuNu8.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
  *
@@ -10,6 +10,6 @@
10
10
  <style class="removeAtBoot">@media (prefers-color-scheme: dark) { html { background-color: #000; color: #888; } }</style>
11
11
  <div id="root">Wait for loading or <a href="?get=basic">use basic interface now</a></div>
12
12
  <script crossorigin id="vite-legacy-polyfill" src="/assets/polyfills-legacy-DMrMt_pQ.js"></script>
13
- <script crossorigin id="vite-legacy-entry" data-src="/assets/index-legacy-SJb2fz1j.js">System.import(document.getElementById('vite-legacy-entry').getAttribute('data-src'))</script>
13
+ <script crossorigin id="vite-legacy-entry" data-src="/assets/index-legacy-DuGmuNu8.js">System.import(document.getElementById('vite-legacy-entry').getAttribute('data-src'))</script>
14
14
  </body>
15
15
  </html>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "hfs",
3
- "version": "0.54.0",
3
+ "version": "0.55.0-alpha1",
4
4
  "description": "HTTP File Server",
5
5
  "keywords": [
6
6
  "file server",
@@ -70,9 +70,10 @@
70
70
  ]
71
71
  },
72
72
  "dependencies": {
73
+ "@gregoranders/csv": "^0.0.13",
73
74
  "@koa/router": "^13.0.1",
74
75
  "@node-rs/crc32": "^1.10.3",
75
- "@rejetto/kvstorage": "^0.12.2",
76
+ "@rejetto/kvstorage": "^0.13.0",
76
77
  "acme-client": "^5.4.0",
77
78
  "buffer-crc32": "^1.0.0",
78
79
  "fast-glob": "^3.2.7",
@@ -82,7 +83,7 @@
82
83
  "fswin": "^3.24.829",
83
84
  "iconv-lite": "^0.6.3",
84
85
  "ip2location-nodejs": "^9.6.0",
85
- "koa": "^2.13.4",
86
+ "koa": "^2.15.3",
86
87
  "koa-compress": "^5.1.0",
87
88
  "koa-mount": "^4.0.0",
88
89
  "koa-session": "^6.2.0",
@@ -120,7 +121,7 @@
120
121
  "mocha": "^9.1.3",
121
122
  "nm-prune": "^5.0.0",
122
123
  "nodemon": "^2.0.15",
123
- "pkg": "^5.7.0",
124
+ "@yao-pkg/pkg": "^5.15.0",
124
125
  "tough-cookie": "^4.0.0",
125
126
  "ts-node": "^10.4.0"
126
127
  }
@@ -4,7 +4,7 @@
4
4
  const label = HFS.t(["download counter", "Download counter"])
5
5
  const inMenu = config.where === 'menu'
6
6
  HFS.onEvent('additionalEntryDetails', ({ entry: { hits } }) =>
7
- hits && !inMenu && `<span class="download-counter" title="${label}">${hits}</span>`)
7
+ hits && !inMenu && HFS.h('span', { className: "download-counter", title: label }, hits))
8
8
 
9
9
  HFS.onEvent('fileMenu', ({ entry, props }) => {
10
10
  if (!entry.isFolder)
@@ -1,28 +1,5 @@
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 __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
4
- if (k2 === undefined) k2 = k;
5
- var desc = Object.getOwnPropertyDescriptor(m, k);
6
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
7
- desc = { enumerable: true, get: function() { return m[k]; } };
8
- }
9
- Object.defineProperty(o, k2, desc);
10
- }) : (function(o, m, k, k2) {
11
- if (k2 === undefined) k2 = k;
12
- o[k2] = m[k];
13
- }));
14
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
15
- Object.defineProperty(o, "default", { enumerable: true, value: v });
16
- }) : function(o, v) {
17
- o["default"] = v;
18
- });
19
- var __importStar = (this && this.__importStar) || function (mod) {
20
- if (mod && mod.__esModule) return mod;
21
- var result = {};
22
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
23
- __setModuleDefault(result, mod);
24
- return result;
25
- };
26
3
  var __importDefault = (this && this.__importDefault) || function (mod) {
27
4
  return (mod && mod.__esModule) ? mod : { "default": mod };
28
5
  };
@@ -32,12 +9,12 @@ const stream_1 = require("stream");
32
9
  // @ts-ignore
33
10
  const buffer_crc32_1 = require("buffer-crc32");
34
11
  const assert_1 = __importDefault(require("assert"));
12
+ const misc_1 = require("./misc");
35
13
  const ZIP64_SIZE_LIMIT = 0xffffffff;
36
14
  const ZIP64_NUMBER_LIMIT = 0xffff;
37
- let crc32function;
38
- Promise.resolve().then(() => __importStar(require('@node-rs/crc32'))).then(lib => crc32function = lib.crc32, () => {
39
- console.log('using generic lib for crc32');
40
- crc32function = buffer_crc32_1.unsigned;
15
+ const crc32function = (0, misc_1.try_)(() => require('@node-rs/crc32').crc32, () => {
16
+ console.log('! using generic lib for crc32');
17
+ return buffer_crc32_1.unsigned;
41
18
  });
42
19
  const FLAGS = 0x0808; // bit3 = no crc in local header + bit11 = utf8
43
20
  class QuickZipStream extends stream_1.Readable {
package/src/adminApis.js CHANGED
@@ -64,6 +64,7 @@ exports.adminApis = {
64
64
  path: config_1.configFile.getPath(),
65
65
  fullPath: (0, path_1.resolve)(config_1.configFile.getPath()),
66
66
  text: config_1.configFile.getText(),
67
+ customHtml: customHtml_1.customHtml.getText(),
67
68
  };
68
69
  },
69
70
  set_config_text: ({ text }) => config_1.configFile.save(text, { reparse: true }),
@@ -88,8 +89,8 @@ exports.adminApis = {
88
89
  return {
89
90
  sections: Object.fromEntries([
90
91
  ...customHtml_1.customHtmlSections.concat((0, errorPages_1.getErrorSections)()).map(k => [k, '']),
91
- ...customHtml_1.customHtmlState.sections
92
- ])
92
+ ...customHtml_1.customHtml.sections // override entries above
93
+ ]),
93
94
  };
94
95
  },
95
96
  async set_custom_html({ sections }) {
@@ -120,6 +121,7 @@ exports.adminApis = {
120
121
  cloudflareDetected: middlewares_1.cloudflareDetected,
121
122
  ram: process.memoryUsage.rss(),
122
123
  acmeRenewError: acme_1.acmeRenewError,
124
+ blacklistedInstalledPlugins: github_1.blacklistedInstalledPlugins,
123
125
  frpDetected: exports.localhostAdmin.get() && !(0, middlewares_1.getProxyDetected)()
124
126
  && (0, connections_1.getConnections)().every(misc_1.isLocalHost)
125
127
  && await frpDebounced(),
@@ -181,6 +183,6 @@ function anyAccountCanLoginAdmin() {
181
183
  }
182
184
  exports.anyAccountCanLoginAdmin = anyAccountCanLoginAdmin;
183
185
  function allowAdmin(ctx) {
184
- return exports.adminNet.compiled()(ctx.ip);
186
+ return (0, misc_1.isLocalHost)(ctx) || exports.adminNet.compiled()(ctx.ip);
185
187
  }
186
188
  exports.allowAdmin = allowAdmin;
@@ -25,7 +25,7 @@ const get_file_list = async ({ uri = '/', offset, limit, search, wild, c, onlyFo
25
25
  return fail(const_1.HTTP_FOOL);
26
26
  if (await (0, vfs_1.hasDefaultFile)(node, ctx) || !await (0, vfs_1.nodeIsDirectory)(node)) // in case of files without permission, we are provided with the frontend, and the location is the file itself
27
27
  // so, we first check if you have a permission problem, to tell frontend to show login, otherwise we fall back to method_not_allowed, as it's proper for files.
28
- return fail((0, vfs_1.statusCodeForMissingPerm)(node, 'can_read', ctx) ? undefined : const_1.HTTP_METHOD_NOT_ALLOWED);
28
+ return fail(!admin && (0, vfs_1.statusCodeForMissingPerm)(node, 'can_read', ctx) ? undefined : const_1.HTTP_METHOD_NOT_ALLOWED);
29
29
  if (!admin && (0, vfs_1.statusCodeForMissingPerm)(node, 'can_list', ctx))
30
30
  return fail();
31
31
  offset = Number(offset);
package/src/api.log.js CHANGED
@@ -6,6 +6,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  const lodash_1 = __importDefault(require("lodash"));
7
7
  const consoleLog_1 = require("./consoleLog");
8
8
  const cross_1 = require("./cross");
9
+ const misc_1 = require("./misc");
9
10
  const events_1 = __importDefault(require("./events"));
10
11
  const log_1 = require("./log");
11
12
  const SendList_1 = require("./SendList");
@@ -27,6 +28,7 @@ exports.default = {
27
28
  return null;
28
29
  },
29
30
  get_log({ file = 'log' }, ctx) {
31
+ const files = file.split('|'); // potentially more then one
30
32
  return new SendList_1.SendListReadable({
31
33
  bufferTime: 10,
32
34
  async doAtStart(list) {
@@ -47,14 +49,34 @@ exports.default = {
47
49
  return;
48
50
  }
49
51
  // for other logs we only provide updates. Use get_log_file to download past content
50
- if (!lodash_1.default.find(log_1.loggers, { name: file }))
52
+ if (lodash_1.default.some(files, x => !lodash_1.default.find(log_1.loggers, { name: x })))
51
53
  return list.error(cross_1.HTTP_NOT_FOUND, true);
52
54
  list.ready();
53
55
  // unsubscribe when connection is interrupted
54
- ctx.res.once('close', events_1.default.on(file, x => list.add(x)));
56
+ ctx.res.once('close', events_1.default.on(files, x => list.add(x)));
55
57
  }
56
58
  });
57
59
  },
60
+ async delete_ips({ ip, ts }) {
61
+ (0, misc_1.apiAssertTypes)({ string_undefined: { ip, ts } });
62
+ if (ip) {
63
+ if (!ips_1.ips.has(ip))
64
+ throw cross_1.HTTP_NOT_FOUND;
65
+ ips_1.ips.del(ip);
66
+ return {};
67
+ }
68
+ if (ts) {
69
+ ts = new Date(ts);
70
+ let n = 0;
71
+ for await (const [k, rec] of ips_1.ips.iterator())
72
+ if (rec.ts <= ts) {
73
+ ips_1.ips.del(k);
74
+ ++n;
75
+ }
76
+ return { n };
77
+ }
78
+ throw cross_1.HTTP_BAD_REQUEST;
79
+ },
58
80
  reset_ips() {
59
81
  return ips_1.ips.clear();
60
82
  },
@@ -12,8 +12,9 @@ const auth_1 = require("./auth");
12
12
  const SendList_1 = require("./SendList");
13
13
  const persistence_1 = require("./persistence");
14
14
  exports.default = {
15
- async disconnect({ ip, port }) {
16
- const match = lodash_1.default.matches({ ip, port });
15
+ async disconnect({ ip, port, allButLocalhost }) {
16
+ const match = allButLocalhost ? ((x) => !(0, misc_1.isLocalHost)(x.ip))
17
+ : lodash_1.default.matches({ ip, port });
17
18
  const found = (0, connections_1.getConnections)().filter(c => match(getConnAddress(c)));
18
19
  for (const c of found)
19
20
  c.socket.destroy();
@@ -29,7 +29,7 @@ function apiMiddleware(apis) {
29
29
  const apiName = ctx.path;
30
30
  console.debug('API', ctx.method, apiName, { ...params });
31
31
  const noBrowser = (_a = ctx.get('user-agent')) === null || _a === void 0 ? void 0 : _a.startsWith('curl');
32
- const safe = isPost && (!noBrowser || ctx.get('x-hfs-anti-csrf')) // POST is safe because browser will enforce SameSite cookie
32
+ const safe = !noBrowser || isPost && ctx.get('x-hfs-anti-csrf') // POST is safe because browser will enforce SameSite cookie
33
33
  || apiName.startsWith('get_'); // "get_" apis are safe because they make no change
34
34
  if (!safe)
35
35
  return send(const_1.HTTP_FOOL, "missing header x-hfs-anti-csrf=1");
package/src/basicWeb.js CHANGED
@@ -43,6 +43,8 @@ function basicWeb(ctx, node) {
43
43
  return `<li>${a((0, misc_1.pathEncode)(name) + (isFolder && !await (0, vfs_1.hasDefaultFile)(el, ctx) ? force : ''), name)}\n`;
44
44
  }));
45
45
  ctx.body = stream;
46
+ stream.push(`<meta name="viewport" content="width=device-width" />`);
47
+ stream.push(`<style>body { font-size: 16pt; }</style>`);
46
48
  stream.push(`<title>${adminApis_1.title.get()}</title><body>`);
47
49
  stream.push((0, customHtml_1.getSection)('basicHeader'));
48
50
  const u = (0, auth_1.getCurrentUsername)(ctx);
package/src/config.js CHANGED
@@ -171,6 +171,10 @@ const saveDebounced = (0, misc_1.debounceAsync)(async () => {
171
171
  const aWeekAgo = Date.now() - misc_1.DAY * 7;
172
172
  if (await (0, promises_1.stat)(bak).then(x => aWeekAgo > Number(x.mtime || x.ctime), () => true))
173
173
  await (0, promises_1.copyFile)(filePath, bak).catch(() => { }); // ignore errors
174
+ if (lodash_1.default.isEmpty(state)) {
175
+ console.error('saving empty config');
176
+ debugger;
177
+ }
174
178
  await exports.configFile.save(stringify({ ...state, version: const_1.VERSION }))
175
179
  .catch(err => console.error('Failed at saving config file, please ensure it is writable.', String(err)));
176
180
  });
package/src/const.js CHANGED
@@ -37,7 +37,7 @@ const os_1 = require("os");
37
37
  const lodash_1 = __importDefault(require("lodash"));
38
38
  const path_1 = require("path");
39
39
  __exportStar(require("./cross-const"), exports);
40
- exports.API_VERSION = 9.6;
40
+ exports.API_VERSION = 10;
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));
@@ -54,7 +54,7 @@ exports.DEV = process.env.DEV || exports.argv.dev ? 'DEV' : '';
54
54
  exports.ORIGINAL_CWD = process.cwd();
55
55
  exports.HFS_STARTED = new Date();
56
56
  const PKG_PATH = (0, path_1.join)(__dirname, '..', 'package.json');
57
- exports.BUILD_TIMESTAMP = "2024-11-09T13:54:41.802Z";
57
+ exports.BUILD_TIMESTAMP = "2024-11-19T22:11:27.213Z";
58
58
  const pkg = JSON.parse(fs.readFileSync(PKG_PATH, 'utf8'));
59
59
  exports.VERSION = pkg.version;
60
60
  exports.RUNNING_BETA = exports.VERSION.includes('-');
@@ -75,6 +75,7 @@ console.log(`© Massimo Melina <a@rejetto.com> - License https://www.gnu.org/lic
75
75
  console.log('started', exports.HFS_STARTED.toLocaleString(), exports.DEV);
76
76
  console.log('version', exports.VERSION || '-');
77
77
  console.log('build', exports.BUILD_TIMESTAMP || '-');
78
+ console.debug('arguments', exports.argv);
78
79
  const winExe = exports.IS_WINDOWS && process.execPath.match(/(?<!node)\.exe$/i);
79
80
  // still considering whether to use ".hfs" with Windows users, who may be less accustomed to it
80
81
  const dir = exports.argv.cwd || useHomeDir() && (0, path_1.join)((0, os_1.homedir)(), '.hfs');
@@ -95,7 +96,7 @@ console.log('node', process.version);
95
96
  const bun = globalThis.Bun;
96
97
  if (bun)
97
98
  console.log('bun', bun.version);
98
- console.log('platform', process.platform, exports.IS_BINARY ? 'binary' : (0, path_1.basename)(process.execPath));
99
+ console.log('platform', process.platform, process.arch, exports.IS_BINARY ? 'binary' : (0, path_1.basename)(process.execPath));
99
100
  console.log('pid', process.pid);
100
101
  function useHomeDir() {
101
102
  if (!winExe)
package/src/cross.js CHANGED
@@ -17,13 +17,14 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
17
17
  return (mod && mod.__esModule) ? mod : { "default": mod };
18
18
  };
19
19
  Object.defineProperty(exports, "__esModule", { value: true });
20
- 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.stringAfter = 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.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 = exports.objRenameKey = void 0;
20
+ 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.stringAfter = 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 = exports.WEBSITE = 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.isNumeric = exports.formatTimestamp = exports.repeat = exports.asyncGeneratorToArray = exports.filterMapGenerator = exports.throw_ = exports.hasProp = exports.typedEntries = exports.typedKeys = exports.objRenameKey = exports.randomId = 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"));
25
25
  const picomatch_1 = __importDefault(require("picomatch/lib/picomatch")); // point directly to the browser-compatible source
26
26
  __exportStar(require("./cross-const"), exports);
27
+ exports.WEBSITE = 'https://rejetto.com/hfs/';
27
28
  exports.REPO_URL = 'https://github.com/rejetto/hfs/';
28
29
  exports.WIKI_URL = exports.REPO_URL + 'wiki/';
29
30
  exports.MINUTE = 60000;
@@ -337,6 +338,10 @@ function formatTimestamp(x) {
337
338
  return !x ? '' : (x instanceof Date ? x : new Date(x)).toLocaleString();
338
339
  }
339
340
  exports.formatTimestamp = formatTimestamp;
341
+ function isNumeric(x) {
342
+ return lodash_1.default.isNumber(x) || lodash_1.default.isString(x) && !isNaN(Number(x));
343
+ }
344
+ exports.isNumeric = isNumeric;
340
345
  function isPrimitive(x) {
341
346
  return !x || Object(x) !== x;
342
347
  }
@@ -505,3 +510,16 @@ const BROWSERS = {
505
510
  Xbox: /xbox/i,
506
511
  UC: /UCBrowser/i,
507
512
  };
513
+ Object.defineProperties(Object.prototype, {
514
+ _L: {
515
+ enumerable: false,
516
+ writable: true,
517
+ value(pause = false) {
518
+ const val = this instanceof Number || this instanceof String || this instanceof Boolean ? this.valueOf() : this;
519
+ if (pause)
520
+ debugger;
521
+ console.log(val);
522
+ return val;
523
+ }
524
+ }
525
+ });
package/src/customHtml.js CHANGED
@@ -3,25 +3,22 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.saveCustomHtml = exports.getAllSections = exports.getSection = exports.watchLoadCustomHtml = exports.customHtmlState = exports.customHtmlSections = void 0;
6
+ exports.saveCustomHtml = exports.getAllSections = exports.getSection = exports.watchLoadCustomHtml = exports.customHtml = exports.customHtmlSections = void 0;
7
7
  const misc_1 = require("./misc");
8
8
  const watchLoad_1 = require("./watchLoad");
9
- const vanilla_1 = require("valtio/vanilla"); // without /vanilla we trigger react dependency
10
9
  const promises_1 = require("fs/promises");
11
10
  const plugins_1 = require("./plugins");
12
11
  const lodash_1 = __importDefault(require("lodash"));
13
12
  const FILE = 'custom.html';
14
- exports.customHtmlSections = ['style', 'beforeHeader', 'afterHeader', 'afterMenuBar', 'afterList',
13
+ exports.customHtmlSections = ['style', 'script', 'beforeHeader', 'afterHeader', 'afterMenuBar', 'afterList',
15
14
  'footer', 'top', 'bottom', 'afterEntryName', 'beforeLogin', 'unauthorized', 'htmlHead', 'userPanelAfterInfo'];
16
- exports.customHtmlState = (0, vanilla_1.proxy)({
17
- sections: watchLoadCustomHtml().state
18
- });
15
+ exports.customHtml = watchLoadCustomHtml();
19
16
  function watchLoadCustomHtml(folder = '') {
20
- const state = new Map();
17
+ const sections = new Map();
21
18
  const res = (0, watchLoad_1.watchLoad)((0, misc_1.prefix)('', folder, '/') + FILE, data => {
22
19
  var _a;
23
20
  const re = /^\[([^\]]+)] *$/gm;
24
- state.clear();
21
+ sections.clear();
25
22
  if (!data)
26
23
  return;
27
24
  let name = 'top';
@@ -30,21 +27,21 @@ function watchLoadCustomHtml(folder = '') {
30
27
  const match = re.exec(data);
31
28
  const content = data.slice(last, !match ? undefined : re.lastIndex - (((_a = match === null || match === void 0 ? void 0 : match[0]) === null || _a === void 0 ? void 0 : _a.length) || 0)).trim();
32
29
  if (content)
33
- state.set(name, content);
30
+ sections.set(name, content);
34
31
  name = match === null || match === void 0 ? void 0 : match[1];
35
32
  } while (name);
36
33
  });
37
- return Object.assign(res, { state });
34
+ return Object.assign(res, { sections });
38
35
  }
39
36
  exports.watchLoadCustomHtml = watchLoadCustomHtml;
40
37
  function getSection(name) {
41
- return (exports.customHtmlState.sections.get(name) || '')
38
+ return (exports.customHtml.sections.get(name) || '')
42
39
  + (0, plugins_1.mapPlugins)(pl => pl.getData().getCustomHtml()[name]).join('\n');
43
40
  }
44
41
  exports.getSection = getSection;
45
42
  function getAllSections() {
46
43
  const keys = (0, plugins_1.mapPlugins)(pl => Object.keys(pl.getData().getCustomHtml()));
47
- keys.push(Array.from(exports.customHtmlState.sections.keys()));
44
+ keys.push(Array.from(exports.customHtml.sections.keys()));
48
45
  const all = lodash_1.default.uniq(keys.flat());
49
46
  return Object.fromEntries(all.map(x => [x, getSection(x)]));
50
47
  }
@@ -52,9 +49,9 @@ exports.getAllSections = getAllSections;
52
49
  async function saveCustomHtml(sections) {
53
50
  const text = Object.entries(sections).filter(([k, v]) => v === null || v === void 0 ? void 0 : v.trim()).map(([k, v]) => `[${k}]\n${v}\n\n`).join('');
54
51
  await (0, promises_1.writeFile)(FILE, text);
55
- exports.customHtmlState.sections.clear();
52
+ exports.customHtml.sections.clear();
56
53
  for (const [k, v] of Object.entries(sections))
57
54
  if (v)
58
- exports.customHtmlState.sections.set(k, v);
55
+ exports.customHtml.sections.set(k, v);
59
56
  }
60
57
  exports.saveCustomHtml = saveCustomHtml;
package/src/fileAttr.js CHANGED
@@ -1,27 +1,4 @@
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 __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || function (mod) {
19
- if (mod && mod.__esModule) return mod;
20
- var result = {};
21
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
- __setModuleDefault(result, mod);
23
- return result;
24
- };
25
2
  Object.defineProperty(exports, "__esModule", { value: true });
26
3
  exports.purgeFileAttr = exports.loadFileAttr = exports.storeFileAttr = void 0;
27
4
  const kvstorage_1 = require("@rejetto/kvstorage");
@@ -32,8 +9,10 @@ const cross_1 = require("./cross");
32
9
  const first_1 = require("./first");
33
10
  const promises_2 = require("node:fs/promises");
34
11
  const const_1 = require("./const");
35
- // @ts-ignore
36
- const fsx = Promise.resolve().then(() => __importStar(require('fs-x-attributes'))).then(x => ({ set: (0, util_1.promisify)(x.set), get: (0, util_1.promisify)(x.get) }), () => console.log('fs-x-attributes not available'));
12
+ const fsx = (0, cross_1.try_)(() => {
13
+ const lib = require('fs-x-attributes');
14
+ return { set: (0, util_1.promisify)(lib.set), get: (0, util_1.promisify)(lib.get) };
15
+ }, () => console.log('! fs-x-attributes not available'));
37
16
  const fileAttrDb = new kvstorage_1.KvStorage({ defaultPutDelay: 1000, maxPutDelay: 5000 });
38
17
  (0, first_1.onProcessExit)(() => fileAttrDb.flush());
39
18
  const FN = 'file-attr.kv';
@@ -43,7 +22,7 @@ const FILE_ATTR_PREFIX = 'user.hfs.'; // user. prefix to be linux compatible
43
22
  async function storeFileAttr(path, k, v) {
44
23
  var _a, _b;
45
24
  const s = await (0, promises_2.stat)(path);
46
- if (await fsx.then(x => x === null || x === void 0 ? void 0 : x.set(path, FILE_ATTR_PREFIX + k, JSON.stringify(v)).then(() => 1, () => 0))) {
25
+ if (await (fsx === null || fsx === void 0 ? void 0 : fsx.set(path, FILE_ATTR_PREFIX + k, JSON.stringify(v)).then(() => 1, () => 0))) {
47
26
  if (const_1.IS_WINDOWS)
48
27
  (0, promises_2.utimes)(path, s.atime, s.mtime); // restore timestamps, necessary only on Windows
49
28
  return true;
@@ -60,9 +39,7 @@ async function storeFileAttr(path, k, v) {
60
39
  exports.storeFileAttr = storeFileAttr;
61
40
  async function loadFileAttr(path, k) {
62
41
  var _a;
63
- return (_a = await fsx.then(x => x === null || x === void 0 ? void 0 : x.get(path, FILE_ATTR_PREFIX + k))
64
- .then((x) => x && (0, cross_1.tryJson)(String(x)), () => { })
65
- .then((x) => x !== null && x !== void 0 ? x : (fileAttrDb.isOpen() ? fileAttrDb.get(`${path}|${k}`) : null))) !== null && _a !== void 0 ? _a : undefined; // normalize, as we get null instead of undefined on windows
42
+ return (_a = await (fsx === null || fsx === void 0 ? void 0 : fsx.get(path, FILE_ATTR_PREFIX + k).then((x) => x && (0, cross_1.tryJson)(String(x)), () => { }).then((x) => x !== null && x !== void 0 ? x : (fileAttrDb.isOpen() ? fileAttrDb.get(`${path}|${k}`) : null)))) !== null && _a !== void 0 ? _a : undefined; // normalize, as we get null instead of undefined on windows
66
43
  }
67
44
  exports.loadFileAttr = loadFileAttr;
68
45
  async function purgeFileAttr() {
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.alerts = exports.searchPlugins = exports.getFolder2repo = exports.readOnlineCompatiblePlugin = exports.readOnlinePlugin = exports.readGithubFile = exports.getRepoInfo = exports.downloadPlugin = exports.downloading = void 0;
7
+ exports.getProjectInfo = exports.blacklistedInstalledPlugins = exports.alerts = exports.searchPlugins = exports.getFolder2repo = exports.readOnlineCompatiblePlugin = exports.readOnlinePlugin = exports.readGithubFile = exports.getRepoInfo = exports.downloadPlugin = exports.downloading = void 0;
8
8
  const events_1 = __importDefault(require("./events"));
9
9
  const misc_1 = require("./misc");
10
10
  const plugins_1 = require("./plugins");
@@ -38,14 +38,14 @@ async function getGithubDefaultBranch(repo) {
38
38
  return test ? 'main' : (_a = (await getRepoInfo(repo))) === null || _a === void 0 ? void 0 : _a.default_branch;
39
39
  }
40
40
  async function downloadPlugin(repo, { branch = '', overwrite = false } = {}) {
41
- var _a, _b, _c, _d;
41
+ var _a, _b, _c;
42
42
  if (typeof repo !== 'string')
43
43
  repo = repo.main;
44
44
  if (exports.downloading[repo])
45
45
  throw new apiMiddleware_1.ApiError(const_1.HTTP_CONFLICT, "already downloading");
46
- const projectInfo = await (0, exports.getProjectInfo)();
47
- if ((_a = projectInfo === null || projectInfo === void 0 ? void 0 : projectInfo.plugins_blacklist) === null || _a === void 0 ? void 0 : _a.includes(repo))
48
- throw new apiMiddleware_1.ApiError(const_1.HTTP_FORBIDDEN, "blacklisted");
46
+ const msg = await isPluginBlacklisted(repo);
47
+ if (msg)
48
+ throw new apiMiddleware_1.ApiError(const_1.HTTP_FORBIDDEN, "blacklisted: " + msg);
49
49
  console.log('downloading plugin', repo);
50
50
  downloadProgress(repo, true);
51
51
  try {
@@ -53,13 +53,13 @@ async function downloadPlugin(repo, { branch = '', overwrite = false } = {}) {
53
53
  if (repo.includes('//')) { // custom repo
54
54
  if (!pl)
55
55
  throw new apiMiddleware_1.ApiError(const_1.HTTP_BAD_REQUEST, "bad repo");
56
- const customRepo = (((_c = (_b = pl).getData) === null || _c === void 0 ? void 0 : _c.call(_b)) || pl).repo;
56
+ const customRepo = (((_b = (_a = pl).getData) === null || _b === void 0 ? void 0 : _b.call(_a)) || pl).repo;
57
57
  let url = customRepo === null || customRepo === void 0 ? void 0 : customRepo.zip;
58
58
  if (!url)
59
59
  throw new apiMiddleware_1.ApiError(const_1.HTTP_SERVER_ERROR, "bad plugin");
60
60
  if (!url.includes('//'))
61
61
  url = customRepo.web + url;
62
- return await go(url, pl === null || pl === void 0 ? void 0 : pl.id, (_d = customRepo.zipRoot) !== null && _d !== void 0 ? _d : DIST_ROOT);
62
+ return await go(url, pl === null || pl === void 0 ? void 0 : pl.id, (_c = customRepo.zipRoot) !== null && _c !== void 0 ? _c : DIST_ROOT);
63
63
  }
64
64
  branch || (branch = await getGithubDefaultBranch(repo));
65
65
  const short = repo.split('/')[1]; // second part, repo without the owner
@@ -67,7 +67,7 @@ async function downloadPlugin(repo, { branch = '', overwrite = false } = {}) {
67
67
  throw new apiMiddleware_1.ApiError(const_1.HTTP_BAD_REQUEST, "bad repo");
68
68
  const folder = overwrite && (pl === null || pl === void 0 ? void 0 : pl.id) // use existing folder
69
69
  || (getFolder2repo().hasOwnProperty(short) ? repo.replace('/', '-') // longer form only if another plugin is using short form, to avoid overwriting
70
- : short);
70
+ : short.replace(/^hfs-/, ''));
71
71
  const GITHUB_ZIP_ROOT = short + '-' + branch; // GitHub puts everything within this folder
72
72
  return await go(`https://github.com/${repo}/archive/refs/heads/${branch}.zip`, folder, GITHUB_ZIP_ROOT + '/' + DIST_ROOT);
73
73
  async function go(url, folder, zipRoot) {
@@ -207,35 +207,41 @@ async function* apiGithubPaginated(uri) {
207
207
  throw e;
208
208
  }
209
209
  }
210
+ async function isPluginBlacklisted(repo) {
211
+ return (0, exports.getProjectInfo)().then(x => { var _a, _b; return ((_b = (_a = x === null || x === void 0 ? void 0 : x.repo_blacklist) === null || _a === void 0 ? void 0 : _a[repo]) === null || _b === void 0 ? void 0 : _b.message) || ''; }, () => undefined);
212
+ }
210
213
  async function searchPlugins(text = '', { skipRepos = [''] } = {}) {
211
- const projectInfo = await (0, exports.getProjectInfo)();
212
214
  const searches = [encodeURI(text), ...text.split(' ').filter(Boolean).slice(0, 2).map(x => 'user:' + encodeURI(x))]; // first 2 words can be the author
213
215
  const list = await Promise.all(searches.map(x => (0, misc_1.asyncGeneratorToArray)(apiGithubPaginated(`search/repositories?q=topic:hfs-plugin+${x}`))))
214
216
  .then(all => all.flat()); // make it a single array
215
217
  return new misc_1.AsapStream(list.map(async (it) => {
216
- var _a, _b;
218
+ var _a;
217
219
  const repo = it.full_name;
218
- if (((_a = projectInfo === null || projectInfo === void 0 ? void 0 : projectInfo.plugins_blacklist) === null || _a === void 0 ? void 0 : _a.includes(repo)) || skipRepos.includes(repo))
220
+ if (skipRepos.includes(repo) || await isPluginBlacklisted(repo))
219
221
  return;
220
222
  const pl = await readOnlineCompatiblePlugin(repo, it.default_branch).catch(() => undefined);
221
223
  if (!pl)
222
224
  return;
223
225
  Object.assign(pl, {
224
226
  downloading: exports.downloading[repo],
225
- license: (_b = it.license) === null || _b === void 0 ? void 0 : _b.spdx_id,
227
+ license: (_a = it.license) === null || _a === void 0 ? void 0 : _a.spdx_id,
226
228
  }, lodash_1.default.pick(it, ['pushed_at', 'stargazers_count', 'default_branch']));
227
229
  return pl;
228
230
  }));
229
231
  }
230
232
  exports.searchPlugins = searchPlugins;
231
233
  exports.alerts = persistence_1.storedMap.singleSync('alerts', []);
234
+ const cachedCentralInfo = persistence_1.storedMap.singleSync('cachedCentralInfo', '');
235
+ exports.blacklistedInstalledPlugins = [];
232
236
  // centralized hosted information, to be used as little as possible
233
237
  const FN = 'central.json';
234
238
  let builtIn = JSON.parse((0, fs_1.readFileSync)((0, path_1.join)(__dirname, '..', FN), 'utf8'));
235
- exports.getProjectInfo = (0, misc_1.debounceAsync)(() => readGithubFile(`${const_1.HFS_REPO}/${const_1.HFS_REPO_BRANCH}/${FN}`)
239
+ exports.getProjectInfo = (0, misc_1.debounceAsync)(() => const_1.argv.central === false ? Promise.resolve(builtIn) : readGithubFile(`${const_1.HFS_REPO}/${const_1.HFS_REPO_BRANCH}/${FN}`)
236
240
  .then(JSON.parse, () => null)
237
241
  .then(o => {
238
- o = Object.assign({ ...builtIn }, o); // fall back to built-in
242
+ if (o)
243
+ cachedCentralInfo.set(o);
244
+ o || (o = { ...cachedCentralInfo.get() || builtIn }); // fall back to built-in
239
245
  // merge byVersions info in the main object, but collect alerts separately, to preserve multiple instances
240
246
  const allAlerts = [o.alert];
241
247
  for (const [ver, more] of Object.entries((0, misc_1.popKey)(o, 'byVersion') || {}))
@@ -250,5 +256,12 @@ exports.getProjectInfo = (0, misc_1.debounceAsync)(() => readGithubFile(`${const
250
256
  console.log("ALERT:", a);
251
257
  return allAlerts;
252
258
  });
259
+ const black = (0, misc_1.onlyTruthy)(Object.keys(o.repo_blacklist || {}).map(plugins_1.findPluginByRepo));
260
+ exports.blacklistedInstalledPlugins = (0, misc_1.onlyTruthy)(black.map(x => lodash_1.default.isString(x.repo) && x.repo));
261
+ if (black.length) {
262
+ console.log("blacklisted plugins found:", black.join(', '));
263
+ for (const p of black)
264
+ (0, plugins_1.enablePlugin)(p.id, false);
265
+ }
253
266
  return o;
254
267
  }), { retain: misc_1.DAY, retainFailure: 60000 });
@@ -155,6 +155,7 @@
155
155
  "Logged in": "Benvenuto",
156
156
  "Logged out": "Arrivederci",
157
157
  "Cancel": "Annulla",
158
- "allow_session_ip_change": "Permetti cambio IP in questa sessione"
158
+ "allow_session_ip_change": "Permetti cambio IP in questa sessione",
159
+ "focus_hint": "Scrivendo sulla tastiera cerchi tra gli elementi della lista."
159
160
  }
160
161
  }
@@ -1,7 +1,7 @@
1
1
  {
2
- "author": "Mefistofell, SanokKule",
2
+ "author": "Mefistofell, SanokKule, ItsNeverLight",
3
3
  "version": 2.6,
4
- "hfs_version": "0.53.0",
4
+ "hfs_version": "0.54.0",
5
5
  "translate": {
6
6
  "Select": "Выбор",
7
7
  "n_files": "{n,plural, one{# файл} few{# файла} many{# файлов}}",
@@ -167,6 +167,7 @@
167
167
  "Logged in": "Вход выполнен",
168
168
  "Logged out": "Выход выполнен",
169
169
  "Cancel": "Отмена",
170
- "allow_session_ip_change": "Разрешить смену IP в этой сессии"
170
+ "allow_session_ip_change": "Разрешить смену IP в этой сессии",
171
+ "focus_hint": "Набирая текст на клавиатуре, вы можете выполнять поиск и выбирать элементы из списка."
171
172
  }
172
173
  }