hfs 0.53.0-alpha6 → 0.53.0-beta8

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-BJteGyzW.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-DygVvUke.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
  *
@@ -11,6 +11,6 @@
11
11
  <div id="root"></div>
12
12
  <script nomodule>document.getElementById('root').innerText = "Please use a newer browser"</script>
13
13
  <script crossorigin id="vite-legacy-polyfill" src="/assets/polyfills-legacy-DMrMt_pQ.js"></script>
14
- <script crossorigin id="vite-legacy-entry" data-src="/assets/index-legacy-BJteGyzW.js">System.import(document.getElementById('vite-legacy-entry').getAttribute('data-src'))</script>
14
+ <script crossorigin id="vite-legacy-entry" data-src="/assets/index-legacy-DygVvUke.js">System.import(document.getElementById('vite-legacy-entry').getAttribute('data-src'))</script>
15
15
  </body>
16
16
  </html>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "hfs",
3
- "version": "0.53.0-alpha6",
3
+ "version": "0.53.0-beta8",
4
4
  "description": "HTTP File Server",
5
5
  "keywords": [
6
6
  "file server",
@@ -71,7 +71,7 @@
71
71
  "dependencies": {
72
72
  "@koa/router": "^12.0.1",
73
73
  "@node-rs/crc32": "^1.6.0",
74
- "@rejetto/kvstorage": "^0.4.0",
74
+ "@rejetto/kvstorage": "^0.9.3",
75
75
  "acme-client": "^5.2.0",
76
76
  "basic-auth": "^2.0.1",
77
77
  "buffer-crc32": "^0.2.13",
package/src/acme.js CHANGED
@@ -117,7 +117,7 @@ exports.makeCert = (0, debounceAsync_1.debounceAsync)(async (domain, email, altN
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
120
- events_1.default.once('https ready', () => (0, misc_1.repeat)(misc_1.HOUR, renewCert));
120
+ events_1.default.once('httpsReady', () => (0, misc_1.repeat)(misc_1.HOUR, renewCert));
121
121
  // checks if the cert is near expiration date, and if so renews it
122
122
  const renewCert = (0, debounceAsync_1.debounceAsync)(async () => {
123
123
  const [domain, ...altNames] = acmeDomain.get().split(',');
package/src/api.log.js CHANGED
@@ -10,6 +10,7 @@ const events_1 = __importDefault(require("./events"));
10
10
  const log_1 = require("./log");
11
11
  const SendList_1 = require("./SendList");
12
12
  const serveFile_1 = require("./serveFile");
13
+ const ip_1 = require("./ip");
13
14
  exports.default = {
14
15
  async get_log_file({ file = 'log', range = '' }, ctx) {
15
16
  const log = lodash_1.default.find(log_1.loggers, { name: file });
@@ -29,6 +30,12 @@ exports.default = {
29
30
  return new SendList_1.SendListReadable({
30
31
  bufferTime: 10,
31
32
  async doAtStart(list) {
33
+ if (file === 'ips') {
34
+ for await (const [k, v] of ip_1.ips.iterator())
35
+ list.add({ ip: k, ...v });
36
+ list.ready();
37
+ return;
38
+ }
32
39
  if (file === 'console') {
33
40
  for (const chunk of lodash_1.default.chunk(consoleLog_1.consoleLog, 1000)) { // avoid occupying the thread too long
34
41
  for (const x of chunk)
@@ -36,7 +43,7 @@ exports.default = {
36
43
  await (0, cross_1.wait)(0);
37
44
  }
38
45
  list.ready();
39
- events_1.default.on('console', x => list.add(x));
46
+ ctx.res.once('close', events_1.default.on('console', x => list.add(x)));
40
47
  return;
41
48
  }
42
49
  if (!lodash_1.default.find(log_1.loggers, { name: file }))
@@ -47,4 +54,7 @@ exports.default = {
47
54
  }
48
55
  });
49
56
  },
57
+ reset_ips() {
58
+ return ip_1.ips.clear();
59
+ },
50
60
  };
@@ -10,6 +10,7 @@ const misc_1 = require("./misc");
10
10
  const throttler_1 = require("./throttler");
11
11
  const auth_1 = require("./auth");
12
12
  const SendList_1 = require("./SendList");
13
+ const persistence_1 = require("./persistence");
13
14
  exports.default = {
14
15
  async disconnect({ ip, port }) {
15
16
  const match = lodash_1.default.matches({ ip, port });
@@ -85,14 +86,18 @@ exports.default = {
85
86
  yield {
86
87
  outSpeed: throttler_1.totalOutSpeed,
87
88
  inSpeed: throttler_1.totalInSpeed,
88
- got: throttler_1.totalGot,
89
- sent: throttler_1.totalSent,
89
+ sent_got: [throttler_1.totalSent.get(), throttler_1.totalGot.get()],
90
90
  connections: filtered.length,
91
91
  ips: lodash_1.default.uniqBy(filtered, x => x.ip).length,
92
92
  };
93
93
  await (0, misc_1.wait)(1000);
94
94
  }
95
95
  },
96
+ async clear_persistent({ k }) {
97
+ (0, misc_1.apiAssertTypes)({ string_array: { k } });
98
+ for (const x of (0, misc_1.wantArray)(k))
99
+ void persistence_1.storedMap.del(x);
100
+ },
96
101
  };
97
102
  function ignore(conn) {
98
103
  return false; //conn.socket && isLocalHost(conn)
@@ -61,8 +61,7 @@ const apis = {
61
61
  if ((0, plugins_1.isPluginRunning)(id))
62
62
  return { msg: 'already running' };
63
63
  await (0, plugins_1.stopPlugin)(id);
64
- await (0, plugins_1.startPlugin)(id);
65
- return {};
64
+ return (0, plugins_1.startPlugin)(id).then(() => 0, e => new apiMiddleware_1.ApiError(const_1.HTTP_SERVER_ERROR, e.message));
66
65
  },
67
66
  async stop_plugin({ id }) {
68
67
  if (!(0, plugins_1.isPluginRunning)(id))
package/src/api.vfs.js CHANGED
@@ -34,7 +34,7 @@ const apis = {
34
34
  : { size: source ? -1 : undefined };
35
35
  if (copyStats.mtime && Number(copyStats.mtime) === Number(copyStats.ctime))
36
36
  delete copyStats.mtime;
37
- const inherited = node.parent && (0, vfs_1.permsFromParent)(node.parent, node.original || node);
37
+ const inherited = node.parent && (0, vfs_1.permsFromParent)(node.parent, {});
38
38
  const byMasks = node.original && lodash_1.default.pickBy(node, (v, k) => v !== node.original[k] // something is changing me...
39
39
  && !(inherited && k in inherited) // ...and it's not inheritance...
40
40
  && misc_1.PERM_KEYS.includes(k)); // ...must be masks. Please limit this to perms
@@ -20,13 +20,15 @@ exports.ApiError = ApiError;
20
20
  const logApi = (0, config_1.defineConfig)(misc_1.CFG.log_api, true);
21
21
  function apiMiddleware(apis) {
22
22
  return async (ctx) => {
23
+ var _a;
23
24
  if (!logApi.get())
24
25
  ctx.state.dontLog = true;
25
26
  const isPost = ctx.state.params;
26
27
  const params = isPost ? ctx.state.params || {} : ctx.query;
27
28
  const apiName = ctx.path;
28
29
  console.debug('API', ctx.method, apiName, { ...params });
29
- const safe = isPost && ctx.get('x-hfs-anti-csrf') // POST is safe because browser will enforce SameSite cookie
30
+ const noBrowser = (_a = ctx.get('user-agent')) === null || _a === void 0 ? void 0 : _a.startsWith('curl');
31
+ const safe = isPost && (!noBrowser || ctx.get('x-hfs-anti-csrf')) // POST is safe because browser will enforce SameSite cookie
30
32
  || apiName.startsWith('get_'); // "get_" apis are safe because they make no change
31
33
  if (!safe)
32
34
  return send(const_1.HTTP_FOOL, "missing header x-hfs-anti-csrf=1");
package/src/commands.js CHANGED
@@ -13,6 +13,7 @@ const yaml_1 = __importDefault(require("yaml"));
13
13
  const const_1 = require("./const");
14
14
  const readline_1 = require("readline");
15
15
  const plugins_1 = require("./plugins");
16
+ const fileAttr_1 = require("./fileAttr");
16
17
  if (!const_1.argv.updating)
17
18
  try {
18
19
  /*
@@ -123,4 +124,8 @@ const commands = {
123
124
  params: '<name>',
124
125
  cb: plugins_1.stopPlugin,
125
126
  },
127
+ 'purge-file-attr': {
128
+ params: '',
129
+ cb: fileAttr_1.purgeFileAttr,
130
+ }
126
131
  };
package/src/config.js CHANGED
@@ -137,7 +137,7 @@ function setConfig(newCfg, save) {
137
137
  if (!newCfg.hasOwnProperty(k))
138
138
  apply(k, newCfg[k], true);
139
139
  started = true;
140
- events_1.default.emit('config ready');
140
+ events_1.default.emit('configReady');
141
141
  if (version !== const_1.VERSION) // be sure to save version
142
142
  (0, exports.saveConfigAsap)();
143
143
  function apply(k, newV, isDefault = false) {
package/src/consoleLog.js CHANGED
@@ -9,11 +9,12 @@ exports.consoleLog = [];
9
9
  for (const k of ['log', 'warn', 'error']) {
10
10
  const original = console[k];
11
11
  console[k] = (...args) => {
12
- const rec = { ts: new Date(), k, msg: args.join(' ') };
12
+ const ts = new Date();
13
+ const rec = { ts, k, msg: args.join(' ') };
13
14
  exports.consoleLog.push(rec);
14
15
  if (exports.consoleLog.length > 100000) // limit to avoid infinite space
15
16
  exports.consoleLog.splice(0, 1000);
16
17
  events_1.default.emit('console', rec);
17
- return original(...args);
18
+ return original(ts.toLocaleTimeString('en-uk'), ...args);
18
19
  };
19
20
  }
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.81;
40
+ exports.API_VERSION = 8.82;
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-05-22T14:13:34.416Z";
48
+ exports.BUILD_TIMESTAMP = "2024-05-30T18:05:10.175Z";
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('-');
package/src/cross.js CHANGED
@@ -43,7 +43,7 @@ exports.FRONTEND_OPTIONS = {
43
43
  exports.SORT_BY_OPTIONS = ['name', 'extension', 'size', 'time'];
44
44
  exports.THEME_OPTIONS = { auto: '', light: 'light', dark: 'dark' };
45
45
  exports.CFG = constMap(['geo_enable', 'geo_allow', 'geo_list', 'geo_allow_unknown', 'dynamic_dns_url',
46
- 'log', 'error_log', 'log_rotation', 'dont_log_net', 'log_gui', 'log_api', 'log_ua', 'log_spam',
46
+ 'log', 'error_log', 'log_rotation', 'dont_log_net', 'log_gui', 'log_api', 'log_ua', 'log_spam', 'track_ips',
47
47
  'max_downloads', 'max_downloads_per_ip', 'max_downloads_per_account', 'roots', 'force_address']);
48
48
  exports.LIST = { add: '+', remove: '-', update: '=', props: 'props', ready: 'ready', error: 'e' };
49
49
  exports.WHO_ANYONE = true;
@@ -108,11 +108,11 @@ function objSameKeys(src, newValue) {
108
108
  }
109
109
  exports.objSameKeys = objSameKeys;
110
110
  function enforceFinal(sub, s, evenEmpty = false) {
111
- return evenEmpty && !s || !s.endsWith(sub) ? s + sub : s;
111
+ return (s ? !s.endsWith(sub) : evenEmpty) ? s + sub : s;
112
112
  }
113
113
  exports.enforceFinal = enforceFinal;
114
114
  function enforceStarting(sub, s, evenEmpty = false) {
115
- return evenEmpty && !s || !s.startsWith(sub) ? sub + s : s;
115
+ return (s ? !s.startsWith(sub) : evenEmpty) ? sub + s : s;
116
116
  }
117
117
  exports.enforceStarting = enforceStarting;
118
118
  function removeStarting(sub, s) {
package/src/customHtml.js CHANGED
@@ -7,7 +7,7 @@ const vanilla_1 = require("valtio/vanilla"); // without /vanilla we trigger reac
7
7
  const promises_1 = require("fs/promises");
8
8
  const plugins_1 = require("./plugins");
9
9
  const FILE = 'custom.html';
10
- exports.customHtmlSections = ['beforeHeader', 'afterHeader', 'afterMenuBar', 'afterList',
10
+ exports.customHtmlSections = ['style', 'beforeHeader', 'afterHeader', 'afterMenuBar', 'afterList',
11
11
  'top', 'bottom', 'afterEntryName', 'beforeLogin', 'unauthorized', 'htmlHead'];
12
12
  exports.customHtmlState = (0, vanilla_1.proxy)({
13
13
  sections: watchLoadCustomHtml().state
package/src/events.js CHANGED
@@ -49,10 +49,17 @@ class BetterEventEmitter {
49
49
  if (res !== undefined)
50
50
  ret.push(res);
51
51
  }
52
- return ret;
52
+ return Object.assign(ret, {
53
+ preventDefault: () => ret.some(r => r === false)
54
+ });
53
55
  }
54
56
  emitAsync(event, ...args) {
55
- return Promise.all(this.emit(event, ...args) || []);
57
+ const ret = Promise.all(this.emit(event, ...args) || []);
58
+ return Object.assign(ret, {
59
+ async preventDefault() {
60
+ return (await ret).some((x) => x === false);
61
+ }
62
+ });
56
63
  }
57
64
  }
58
65
  exports.BetterEventEmitter = BetterEventEmitter;
@@ -0,0 +1,47 @@
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.purgeFileAttr = exports.loadFileAttr = exports.storeFileAttr = void 0;
7
+ const kvstorage_1 = require("@rejetto/kvstorage");
8
+ const fs_1 = require("fs");
9
+ const util_1 = require("util");
10
+ const promises_1 = require("fs/promises");
11
+ const cross_1 = require("./cross");
12
+ const first_1 = require("./first");
13
+ // @ts-ignore
14
+ const fs_x_attributes_1 = __importDefault(require("fs-x-attributes"));
15
+ let fileAttrDb = new kvstorage_1.KvStorage({ defaultPutDelay: 1000, maxPutDelay: 5000 });
16
+ (0, first_1.onProcessExit)(() => fileAttrDb.flush());
17
+ const FN = 'file-attr.kv';
18
+ if ((0, fs_1.existsSync)(FN))
19
+ fileAttrDb.open(FN);
20
+ const FILE_ATTR_PREFIX = 'user.hfs.'; // user. prefix to be linux compatible
21
+ function storeFileAttr(path, k, v) {
22
+ return (0, util_1.promisify)(fs_x_attributes_1.default.set)(path, FILE_ATTR_PREFIX + k, JSON.stringify(v))
23
+ .catch(async () => {
24
+ if (!fileAttrDb.isOpen())
25
+ await fileAttrDb.open(FN);
26
+ return fileAttrDb.put(`${path}|${k}`, v); // pipe should be a safe separator
27
+ }).then(() => true, (e) => {
28
+ console.error("couldn't store metadata on", path, String(e.message || e));
29
+ return false;
30
+ });
31
+ }
32
+ exports.storeFileAttr = storeFileAttr;
33
+ async function loadFileAttr(path, k) {
34
+ var _a;
35
+ return (_a = await (0, util_1.promisify)(fs_x_attributes_1.default.get)(path, FILE_ATTR_PREFIX + k)
36
+ .then((x) => x && (0, cross_1.tryJson)(String(x)), () => { })
37
+ .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
38
+ }
39
+ exports.loadFileAttr = loadFileAttr;
40
+ async function purgeFileAttr() {
41
+ let n = 0;
42
+ await Promise.all(Array.from(fileAttrDb.keys()).map(k => (0, promises_1.access)(k).catch(() => n++ && void fileAttrDb.del(k))));
43
+ if (n)
44
+ await fileAttrDb.rewrite();
45
+ console.log(`removed ${n} entrie(s)`);
46
+ }
47
+ exports.purgeFileAttr = purgeFileAttr;
package/src/first.js ADDED
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.onFirstEvent = exports.onProcessExit = void 0;
4
+ const cbs = new Set();
5
+ function onProcessExit(cb) {
6
+ cbs.add(cb);
7
+ return () => cbs.delete(cb);
8
+ }
9
+ exports.onProcessExit = onProcessExit;
10
+ onFirstEvent(process, ['exit', 'SIGQUIT', 'SIGTERM', 'SIGINT', 'SIGHUP'], signal => Promise.allSettled(Array.from(cbs).map(cb => cb(signal))).then(() => process.exit(0)));
11
+ function onFirstEvent(emitter, events, cb) {
12
+ let already = false;
13
+ for (const e of events)
14
+ emitter.once(e, (...args) => {
15
+ if (already)
16
+ return;
17
+ already = true;
18
+ cb(...args);
19
+ });
20
+ }
21
+ exports.onFirstEvent = onFirstEvent;
@@ -99,6 +99,8 @@ exports.frontEndApis = {
99
99
  if (!(0, vfs_1.hasPermission)(node, 'can_delete', ctx))
100
100
  throw new apiMiddleware_1.ApiError(const_1.HTTP_UNAUTHORIZED);
101
101
  try {
102
+ if (await events_1.default.emitAsync('deleting', { node, ctx }).preventDefault())
103
+ return null; // stop
102
104
  await (0, promises_1.rm)(node.source, { recursive: true });
103
105
  void (0, comments_1.setCommentFor)(node.source, '');
104
106
  return {};
package/src/index.js CHANGED
@@ -31,6 +31,8 @@ require("./geo");
31
31
  const geo_1 = require("./geo");
32
32
  const roots_1 = require("./roots");
33
33
  const events_1 = __importDefault(require("./events"));
34
+ const ip_1 = require("./ip");
35
+ const persistence_1 = require("./persistence");
34
36
  (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
35
37
  process.title = 'HFS ' + const_1.VERSION;
36
38
  const keys = ((_a = process.env.COOKIE_SIGN_KEYS) === null || _a === void 0 ? void 0 : _a.split(','))
@@ -42,6 +44,7 @@ exports.app.use(middlewares_1.sessionMiddleware)
42
44
  .use(middlewares_1.someSecurity)
43
45
  .use(middlewares_1.prepareState)
44
46
  .use(geo_1.geoFilter)
47
+ .use(ip_1.trackIpsMw)
45
48
  .use(middlewares_1.gzipper)
46
49
  .use(middlewares_1.paramsDecoder) // must be done before plugins, so they can manipulate params
47
50
  .use(middlewares_1.headRequests)
@@ -52,7 +55,7 @@ exports.app.use(middlewares_1.sessionMiddleware)
52
55
  .use((0, koa_mount_1.default)(const_1.API_URI, (0, apiMiddleware_1.apiMiddleware)({ ...frontEndApis_1.frontEndApis, ...adminApis_1.adminApis })))
53
56
  .use(serveGuiAndSharedFiles_1.serveGuiAndSharedFiles)
54
57
  .on('error', errorHandler);
55
- events_1.default.emit('app', exports.app);
58
+ persistence_1.storedMap.once('open', () => events_1.default.emit('app', exports.app));
56
59
  function errorHandler(err) {
57
60
  const { code } = err;
58
61
  if (const_1.DEV && code === 'ENOENT' && err.path.endsWith('sockjs-node'))
@@ -64,8 +67,8 @@ function errorHandler(err) {
64
67
  return; // someone interrupted, don't care
65
68
  console.error(new Date().toLocaleString('en-uk'), 'server error', err);
66
69
  }
67
- process.on('uncaughtException', err => {
68
- if (err.syscall !== 'watch')
70
+ process.on('uncaughtException', (err) => {
71
+ if (err.syscall !== 'watch' && err.code !== 'ECONNRESET')
69
72
  console.error("uncaught:", err);
70
73
  });
71
74
  (0, config_1.defineConfig)('proxies', 0).sub(n => {
package/src/ip.js ADDED
@@ -0,0 +1,27 @@
1
+ "use strict";
2
+ // This file is part of HFS - Copyright 2021, Massimo Melina <a@rejetto.com> - License https://www.gnu.org/licenses/gpl-3.0.txt
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.trackIpsMw = exports.ips = void 0;
5
+ const config_1 = require("./config");
6
+ const kvstorage_1 = require("@rejetto/kvstorage");
7
+ const misc_1 = require("./misc");
8
+ const first_1 = require("./first");
9
+ const trackIps = (0, config_1.defineConfig)(misc_1.CFG.track_ips, true);
10
+ exports.ips = new kvstorage_1.KvStorage({
11
+ defaultPutDelay: misc_1.MINUTE,
12
+ maxPutDelay: 10 * misc_1.MINUTE,
13
+ maxPutDelayCreate: 0,
14
+ });
15
+ (0, first_1.onProcessExit)(() => exports.ips.flush());
16
+ const trackIpsMw = async (ctx, next) => {
17
+ if (trackIps.get() && !(0, misc_1.isLocalHost)(ctx))
18
+ exports.ips.put(ctx.ip, { ts: new Date, country: ctx.state.connection.country });
19
+ await next();
20
+ };
21
+ exports.trackIpsMw = trackIpsMw;
22
+ trackIps.sub(v => {
23
+ if (v)
24
+ exports.ips.open('ips.kv');
25
+ else
26
+ exports.ips.close();
27
+ });
package/src/listen.js CHANGED
@@ -144,8 +144,9 @@ const considerHttps = (0, misc_1.debounceAsync)(async () => {
144
144
  }
145
145
  }
146
146
  catch (e) {
147
+ httpsSrv || (httpsSrv = Object.assign(https.createServer({}), { name: 'https' })); // a dummy container, in case creation failed because of certificate errors
147
148
  httpsSrv.error = "bad private key or certificate";
148
- console.log("failed to create https server: check your private key and certificate", String(e));
149
+ console.error("failed to create https server: check your private key and certificate", e.message);
149
150
  return;
150
151
  }
151
152
  port = await startServer(httpsSrv, { port, host: listenInterface.get() });
@@ -153,7 +154,7 @@ const considerHttps = (0, misc_1.debounceAsync)(async () => {
153
154
  return;
154
155
  httpsSrv.on('connection', connections_1.newConnection);
155
156
  printUrls(httpsSrv.name);
156
- events_1.default.emit('https ready');
157
+ events_1.default.emit('httpsReady');
157
158
  nat_1.defaultBaseUrl.proto = 'https';
158
159
  nat_1.defaultBaseUrl.port = (_f = getCurrentPort(httpsSrv)) !== null && _f !== void 0 ? _f : 0;
159
160
  });
package/src/log.js CHANGED
@@ -153,7 +153,7 @@ const logMw = async (ctx, next) => {
153
153
  });
154
154
  };
155
155
  exports.logMw = logMw;
156
- events_1.default.on('app', () => {
156
+ events_1.default.once('app', () => {
157
157
  index_1.app.context.logExtra = function (anything, params) {
158
158
  lodash_1.default.merge(this.state, { logExtra: { ...anything, params } }); // params will be considered as parameters of the API
159
159
  };
@@ -48,7 +48,7 @@ const headRequests = async (ctx, next) => {
48
48
  };
49
49
  exports.headRequests = headRequests;
50
50
  let proxyDetected;
51
- const someSecurity = async (ctx, next) => {
51
+ const someSecurity = (ctx, next) => {
52
52
  ctx.request.ip = (0, connections_1.normalizeIp)(ctx.ip);
53
53
  // don't allow sessions to change ip
54
54
  const ss = ctx.session;
@@ -145,7 +145,7 @@ exports.paramsDecoder = paramsDecoder;
145
145
  // But koa-session doesn't support 2 cookies, so I made this hacky solution: keep track of the options object, to modify the key at run-time.
146
146
  let internalSessionMw;
147
147
  let options;
148
- events_1.default.on('app', () => // wait for app to be defined
148
+ events_1.default.once('app', () => // wait for app to be defined
149
149
  internalSessionMw = (0, koa_session_1.default)(options = { signed: true, rolling: true, sameSite: 'lax' }, index_1.app));
150
150
  const sessionMiddleware = (ctx, next) => {
151
151
  options.key = 'hfs_' + ctx.protocol;
package/src/misc.js CHANGED
@@ -18,11 +18,12 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
18
18
  return (mod && mod.__esModule) ? mod : { "default": mod };
19
19
  };
20
20
  Object.defineProperty(exports, "__esModule", { value: true });
21
- exports.apiAssertTypes = exports.AsapStream = exports.asyncGeneratorToReadable = exports.same = exports.makeNetMatcher = exports.isLocalHost = exports.pattern2filter = exports.onFirstEvent = exports.onProcessExit = void 0;
21
+ exports.apiAssertTypes = exports.AsapStream = exports.asyncGeneratorToReadable = exports.same = exports.makeNetMatcher = exports.isLocalHost = exports.pattern2filter = void 0;
22
22
  const path_1 = require("path");
23
23
  const assert_1 = __importDefault(require("assert"));
24
24
  __exportStar(require("./util-http"), exports);
25
25
  __exportStar(require("./util-files"), exports);
26
+ __exportStar(require("./fileAttr"), exports);
26
27
  __exportStar(require("./cross"), exports);
27
28
  __exportStar(require("./debounceAsync"), exports);
28
29
  const stream_1 = require("stream");
@@ -31,24 +32,6 @@ const apiMiddleware_1 = require("./apiMiddleware");
31
32
  const const_1 = require("./const");
32
33
  const cross_1 = require("./cross");
33
34
  const net_1 = require("net");
34
- const cbs = new Set();
35
- function onProcessExit(cb) {
36
- cbs.add(cb);
37
- return () => cbs.delete(cb);
38
- }
39
- exports.onProcessExit = onProcessExit;
40
- onFirstEvent(process, ['exit', 'SIGQUIT', 'SIGTERM', 'SIGINT', 'SIGHUP'], signal => Promise.allSettled(Array.from(cbs).map(cb => cb(signal))).then(() => process.exit(0)));
41
- function onFirstEvent(emitter, events, cb) {
42
- let already = false;
43
- for (const e of events)
44
- emitter.once(e, (...args) => {
45
- if (already)
46
- return;
47
- already = true;
48
- cb(...args);
49
- });
50
- }
51
- exports.onFirstEvent = onFirstEvent;
52
35
  function pattern2filter(pattern) {
53
36
  const matcher = (0, cross_1.makeMatcher)(pattern.includes('*') ? pattern // if you specify *, we'll respect its position
54
37
  : pattern.split('|').map(x => `*${x}*`).join('|'));
@@ -134,9 +117,8 @@ class AsapStream extends stream_1.Readable {
134
117
  exports.AsapStream = AsapStream;
135
118
  function apiAssertTypes(paramsByType) {
136
119
  for (const [types, params] of Object.entries(paramsByType))
137
- for (const type of types.split('_'))
138
- for (const [name, val] of Object.entries(params))
139
- if (type === 'array' ? !Array.isArray(val) : typeof val !== type)
140
- throw new apiMiddleware_1.ApiError(const_1.HTTP_BAD_REQUEST, 'bad ' + name);
120
+ for (const [name, val] of Object.entries(params))
121
+ if (!types.split('_').some(type => type === 'array' ? Array.isArray(val) : typeof val === type))
122
+ throw new apiMiddleware_1.ApiError(const_1.HTTP_BAD_REQUEST, 'bad ' + name);
141
123
  }
142
124
  exports.apiAssertTypes = apiAssertTypes;
@@ -0,0 +1,14 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.storedMap = void 0;
4
+ const kvstorage_1 = require("@rejetto/kvstorage");
5
+ const misc_1 = require("./misc");
6
+ const first_1 = require("./first");
7
+ exports.storedMap = new kvstorage_1.KvStorage({
8
+ defaultPutDelay: 5000,
9
+ maxPutDelay: misc_1.MINUTE,
10
+ maxPutDelayCreate: 1000,
11
+ rewriteLater: true
12
+ });
13
+ exports.storedMap.open('data.kv');
14
+ (0, first_1.onProcessExit)(() => exports.storedMap.flush());