hfs 0.50.4 → 0.51.0-beta4

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.
Files changed (44) hide show
  1. package/README.md +2 -0
  2. package/admin/assets/index-101ecc9e.js +808 -0
  3. package/admin/assets/{index-bb75b3fc.css → index-65d16f45.css} +1 -1
  4. package/{frontend/assets/sha512-e82b909a.js → admin/assets/sha512-a1b6cce6.js} +1 -1
  5. package/admin/index.html +2 -2
  6. package/frontend/assets/index-a452a199.css +1 -0
  7. package/frontend/assets/index-dea364e7.js +95 -0
  8. package/{admin/assets/sha512-1694c0eb.js → frontend/assets/sha512-6365fe60.js} +1 -1
  9. package/frontend/fontello.css +4 -1
  10. package/frontend/fontello.woff2 +0 -0
  11. package/frontend/index.html +2 -2
  12. package/package.json +3 -2
  13. package/src/adminApis.js +3 -1
  14. package/src/api.auth.js +6 -1
  15. package/src/{api.file_list.js → api.get_file_list.js} +11 -7
  16. package/src/api.monitor.js +1 -34
  17. package/src/api.vfs.js +2 -5
  18. package/src/apiMiddleware.js +1 -1
  19. package/src/comments.js +1 -1
  20. package/src/const.js +5 -2
  21. package/src/cross-const.js +3 -4
  22. package/src/cross.js +56 -7
  23. package/src/debounceAsync.js +3 -3
  24. package/src/errorPages.js +1 -1
  25. package/src/frontEndApis.js +21 -2
  26. package/src/index.js +2 -0
  27. package/src/lang.js +10 -2
  28. package/src/langs/hfs-lang-it.json +10 -6
  29. package/src/listen.js +1 -2
  30. package/src/log.js +20 -5
  31. package/src/middlewares.js +12 -6
  32. package/src/misc.js +4 -14
  33. package/src/roots.js +47 -0
  34. package/src/serveFile.js +40 -4
  35. package/src/serveGuiFiles.js +2 -2
  36. package/src/update.js +7 -6
  37. package/src/upload.js +10 -5
  38. package/src/util-files.js +7 -6
  39. package/src/vfs.js +38 -28
  40. package/src/zip.js +2 -2
  41. package/admin/assets/index-a24642bd.js +0 -807
  42. package/frontend/assets/index-b90320b6.css +0 -1
  43. package/frontend/assets/index-e6ecc47c.js +0 -94
  44. package/plugins/vhosting/plugin.js +0 -62
package/src/log.js CHANGED
@@ -38,6 +38,8 @@ const util_files_1 = require("./util-files");
38
38
  const auth_1 = require("./auth");
39
39
  const misc_1 = require("./misc");
40
40
  const events_1 = __importDefault(require("./events"));
41
+ const connections_1 = require("./connections");
42
+ const index_1 = require("./index");
41
43
  class Logger {
42
44
  constructor(name) {
43
45
  this.name = name;
@@ -80,6 +82,7 @@ errorLogFile.sub(path => {
80
82
  });
81
83
  const logRotation = (0, config_1.defineConfig)('log_rotation', 'weekly');
82
84
  const dontLogNet = (0, config_1.defineConfig)('dont_log_net', '127.0.0.1|::1', v => (0, misc_1.makeNetMatcher)(v));
85
+ const logUA = (0, config_1.defineConfig)('log_ua', false);
83
86
  const debounce = lodash_1.default.debounce(cb => cb(), 1000);
84
87
  const logMw = async (ctx, next) => {
85
88
  const now = new Date();
@@ -89,7 +92,7 @@ const logMw = async (ctx, next) => {
89
92
  ctx.state.completed = Promise.race([(0, stream_1.once)(ctx.res, 'finish'), (0, stream_1.once)(ctx.res, 'close')]);
90
93
  ctx.state.completed.then(() => {
91
94
  var _a, _b, _c, _d;
92
- if (ctx.state.dont_log)
95
+ if (ctx.state.dontLog)
93
96
  return;
94
97
  if (dontLogNet.compiled()(ctx.ip))
95
98
  return;
@@ -125,16 +128,28 @@ const logMw = async (ctx, next) => {
125
128
  const user = (0, auth_1.getCurrentUsername)(ctx);
126
129
  const length = (_c = ctx.state.length) !== null && _c !== void 0 ? _c : ctx.length;
127
130
  const uri = ctx.originalUrl;
128
- const extra = ctx.state.includesLastByte && ctx.vfsNode && ctx.res.finished && { dl: 1 }
129
- || ctx.state.uploadPath && { ul: ctx.state.uploadPath, size: ctx.state.uploadSize }
130
- || undefined;
131
+ ctx.logExtra(ctx.state.includesLastByte && ctx.vfsNode && ctx.res.finished && { dl: 1 }
132
+ || ctx.state.uploadSize !== undefined && { size: ctx.state.uploadSize, ul: ctx.state.uploads });
133
+ const conn = (0, connections_1.getConnection)(ctx);
134
+ if (conn === null || conn === void 0 ? void 0 : conn.country)
135
+ ctx.logExtra({ country: conn.country });
136
+ if (logUA.get())
137
+ ctx.logExtra({ ua: ctx.get('user-agent') || undefined });
138
+ const extra = ctx.state.logExtra;
131
139
  events_1.default.emit(logger.name, Object.assign(lodash_1.default.pick(ctx, ['ip', 'method', 'status']), { length, user, ts: now, uri, extra }));
132
140
  debounce(() => // once in a while we check if the file is still good (not deleted, etc), or we'll reopen it
133
141
  (0, promises_1.stat)(logger.path).catch(() => logger.reopen())); // async = smoother but we may lose some entries
134
- stream.write(util.format(format, ctx.ip, user || '-', date, ctx.method, uri, ctx.req.httpVersion, ctx.status, (_d = length === null || length === void 0 ? void 0 : length.toString()) !== null && _d !== void 0 ? _d : '-', extra ? JSON.stringify(JSON.stringify(extra)) : ''));
142
+ stream.write(util.format(format, ctx.ip, user || '-', date, ctx.method, uri, ctx.req.httpVersion, ctx.status, (_d = length === null || length === void 0 ? void 0 : length.toString()) !== null && _d !== void 0 ? _d : '-', lodash_1.default.isEmpty(extra) ? '' : JSON.stringify(JSON.stringify(extra))));
135
143
  });
136
144
  };
137
145
  exports.logMw = logMw;
146
+ events_1.default.on('app', () => {
147
+ index_1.app.context.logExtra = function (o) {
148
+ var _a;
149
+ if (o)
150
+ Object.assign((_a = this.state).logExtra || (_a.logExtra = {}), o);
151
+ };
152
+ });
138
153
  function doubleDigit(n) {
139
154
  return n > 9 ? n : '0' + n;
140
155
  }
@@ -96,6 +96,7 @@ const serveGuiAndSharedFiles = async (ctx, next) => {
96
96
  const folder = await (0, vfs_1.urlToNode)((0, path_1.dirname)(decPath), ctx, vfs_1.vfs, v => rest = v + '/' + rest);
97
97
  if (!folder)
98
98
  return (0, errorPages_1.sendErrorPage)(ctx, const_1.HTTP_NOT_FOUND);
99
+ ctx.state.uploadPath = decPath;
99
100
  const dest = (0, upload_1.uploadWriter)(folder, rest, ctx);
100
101
  if (dest) {
101
102
  await (0, promises_1.pipeline)(ctx.req, dest);
@@ -112,11 +113,16 @@ const serveGuiAndSharedFiles = async (ctx, next) => {
112
113
  if (ctx.request.type !== 'multipart/form-data')
113
114
  return ctx.status = const_1.HTTP_BAD_REQUEST;
114
115
  ctx.body = {};
116
+ ctx.state.uploads = [];
115
117
  const form = (0, formidable_1.default)({
116
118
  maxFileSize: Infinity,
117
119
  allowEmptyFiles: true,
118
- //@ts-ignore wrong in the .d.ts file
119
- fileWriteStreamHandler: f => (0, upload_1.uploadWriter)(node, f.originalFilename, ctx)
120
+ fileWriteStreamHandler: f => {
121
+ const fn = f.originalFilename;
122
+ ctx.state.uploadPath = decodeURI(ctx.path) + fn;
123
+ ctx.state.uploads.push(fn);
124
+ return (0, upload_1.uploadWriter)(node, fn, ctx) || new stream_1.Writable();
125
+ }
120
126
  });
121
127
  return new Promise(res => form.parse(ctx.req, err => {
122
128
  if (err)
@@ -159,7 +165,7 @@ async function sendFolderList(node, ctx) {
159
165
  || URL.protocol + '//' + URL.host + ctx.state.revProxyPath;
160
166
  prepend = base + ctx.originalUrl.split('?')[0];
161
167
  }
162
- const walker = (0, vfs_1.walkNode)(node, ctx, depth === '*' ? Infinity : Number(depth));
168
+ const walker = (0, vfs_1.walkNode)(node, { ctx, depth: depth === '*' ? Infinity : Number(depth) });
163
169
  ctx.body = (0, misc_1.asyncGeneratorToReadable)((0, misc_1.filterMapGenerator)(walker, async (el) => {
164
170
  const isFolder = await (0, vfs_1.nodeIsDirectory)(el);
165
171
  return !folders && isFolder ? undefined
@@ -187,7 +193,7 @@ const someSecurity = async (ctx, next) => {
187
193
  // we have some dev-proxies to ignore
188
194
  && !(const_1.DEV && [process.env.FRONTEND_PROXY, process.env.ADMIN_PROXY].includes(ctx.get('X-Forwarded-port')))) {
189
195
  proxyDetected = ctx;
190
- ctx.state.when = new Date();
196
+ ctx.state.whenProxyDetected = new Date();
191
197
  }
192
198
  }
193
199
  catch (_a) {
@@ -200,7 +206,7 @@ const someSecurity = async (ctx, next) => {
200
206
  exports.someSecurity = someSecurity;
201
207
  // limited to http proxies
202
208
  function getProxyDetected() {
203
- if ((proxyDetected === null || proxyDetected === void 0 ? void 0 : proxyDetected.state.when) < Date.now() - misc_1.DAY)
209
+ if ((proxyDetected === null || proxyDetected === void 0 ? void 0 : proxyDetected.state.whenProxyDetected) < Date.now() - misc_1.DAY)
204
210
  proxyDetected = undefined;
205
211
  return !ignoreProxies.get() && proxyDetected
206
212
  && { from: proxyDetected.ip, for: proxyDetected.get('X-Forwarded-For') };
@@ -214,10 +220,10 @@ const prepareState = async (ctx, next) => {
214
220
  ctx.session.maxAge = exports.sessionDuration.compiled();
215
221
  }
216
222
  // calculate these once and for all
223
+ const conn = ctx.state.connection = (0, connections_1.socket2connection)(ctx.socket);
217
224
  const a = ctx.state.account = await urlLogin() || await getHttpAccount() || (0, perm_1.getAccount)((_a = ctx.session) === null || _a === void 0 ? void 0 : _a.username, false);
218
225
  if (a && !(0, perm_1.accountCanLogin)(a))
219
226
  ctx.state.account = undefined;
220
- const conn = ctx.state.connection = (0, connections_1.socket2connection)(ctx.socket);
221
227
  ctx.state.revProxyPath = ctx.get('x-forwarded-prefix');
222
228
  ctx.state.browsing = undefined;
223
229
  if (conn)
package/src/misc.js CHANGED
@@ -18,7 +18,7 @@ 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.matches = exports.makeMatcher = exports.makeNetMatcher = exports.isLocalHost = exports.onOff = exports.pattern2filter = exports.onFirstEvent = exports.onProcessExit = void 0;
21
+ exports.apiAssertTypes = exports.AsapStream = exports.asyncGeneratorToReadable = exports.same = exports.makeNetMatcher = exports.isLocalHost = exports.onOff = exports.pattern2filter = exports.onFirstEvent = exports.onProcessExit = void 0;
22
22
  const path_1 = require("path");
23
23
  const lodash_1 = __importDefault(require("lodash"));
24
24
  const assert_1 = __importDefault(require("assert"));
@@ -27,7 +27,6 @@ __exportStar(require("./util-files"), exports);
27
27
  __exportStar(require("./cross"), exports);
28
28
  __exportStar(require("./debounceAsync"), exports);
29
29
  const stream_1 = require("stream");
30
- const micromatch_1 = require("micromatch");
31
30
  const node_net_1 = require("node:net");
32
31
  const apiMiddleware_1 = require("./apiMiddleware");
33
32
  const const_1 = require("./const");
@@ -79,7 +78,7 @@ function makeNetMatcher(mask, emptyMaskReturns = false) {
79
78
  if (!mask)
80
79
  return () => emptyMaskReturns;
81
80
  if (!mask.includes('/'))
82
- return makeMatcher(mask);
81
+ return (0, cross_1.makeMatcher)(mask);
83
82
  const all = mask.split('|');
84
83
  const neg = ((_a = all[0]) === null || _a === void 0 ? void 0 : _a[0]) === '!';
85
84
  if (neg)
@@ -105,15 +104,6 @@ exports.makeNetMatcher = makeNetMatcher;
105
104
  function parseAddress(s) {
106
105
  return new node_net_1.SocketAddress({ address: s, family: (0, net_1.isIPv6)(s) ? 'ipv6' : 'ipv4' });
107
106
  }
108
- function makeMatcher(mask, emptyMaskReturns = false) {
109
- return mask ? (0, micromatch_1.matcher)(mask.replace(/^(!)?/, '$1(') + ')', { nocase: true }) // adding () will allow us to use the pipe at root level
110
- : () => emptyMaskReturns;
111
- }
112
- exports.makeMatcher = makeMatcher;
113
- function matches(s, mask, emptyMaskReturns = false) {
114
- return makeMatcher(mask, emptyMaskReturns)(s); // adding () will allow us to use the pipe at root level
115
- }
116
- exports.matches = matches;
117
107
  function same(a, b) {
118
108
  try {
119
109
  assert_1.default.deepStrictEqual(a, b);
@@ -146,7 +136,7 @@ class AsapStream extends stream_1.Readable {
146
136
  return;
147
137
  this.finished = true;
148
138
  for (const p of this.promises)
149
- p.then(data => this.push(data), e => this.emit('error', e));
139
+ p.then(x => x !== undefined && this.push(x), e => this.emit('error', e));
150
140
  Promise.allSettled(this.promises).then(() => this.push(null));
151
141
  }
152
142
  }
@@ -155,7 +145,7 @@ function apiAssertTypes(paramsByType) {
155
145
  for (const [types, params] of Object.entries(paramsByType))
156
146
  for (const type of types.split('_'))
157
147
  for (const [name, val] of Object.entries(params))
158
- if (typeof val !== type)
148
+ if (type === 'array' ? !Array.isArray(val) : typeof val !== type)
159
149
  throw new apiMiddleware_1.ApiError(const_1.HTTP_BAD_REQUEST, 'bad ' + name);
160
150
  }
161
151
  exports.apiAssertTypes = apiAssertTypes;
package/src/roots.js ADDED
@@ -0,0 +1,47 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.rootsMiddleware = exports.roots = void 0;
4
+ const config_1 = require("./config");
5
+ const misc_1 = require("./misc");
6
+ const connections_1 = require("./connections");
7
+ exports.roots = (0, config_1.defineConfig)(misc_1.CFG.roots, [], list => {
8
+ const matchers = list.map((row) => typeof (row === null || row === void 0 ? void 0 : row.host) === 'string' ? (0, misc_1.makeMatcher)(row.host) : () => false);
9
+ return (host) => list[matchers.findIndex(m => m(host))];
10
+ });
11
+ const rootsMandatory = (0, config_1.defineConfig)(misc_1.CFG.roots_mandatory, false);
12
+ const rootsMiddleware = (ctx, next) => (() => {
13
+ var _a;
14
+ let params; // undefined if we are not going to work on api parameters
15
+ if (ctx.path.startsWith(misc_1.SPECIAL_URI)) { // special uris should be excluded...
16
+ if (!ctx.path.startsWith(misc_1.API_URI))
17
+ return; // ...unless it's an api
18
+ let { referer } = ctx.headers;
19
+ referer && (referer = new URL(referer).pathname);
20
+ if (referer === null || referer === void 0 ? void 0 : referer.startsWith(ctx.state.revProxyPath + misc_1.ADMIN_URI))
21
+ return; // exclude apis for admin-panel
22
+ params = ctx.params || ctx.query; // for api we'll translate params
23
+ }
24
+ if (!((_a = exports.roots.get()) === null || _a === void 0 ? void 0 : _a.length))
25
+ return;
26
+ const row = exports.roots.compiled()(ctx.host);
27
+ if (!row) {
28
+ if (!rootsMandatory.get() || (0, misc_1.isLocalHost)(ctx))
29
+ return;
30
+ (0, connections_1.disconnect)(ctx);
31
+ return true; // true will avoid calling next
32
+ }
33
+ const { root = '' } = row;
34
+ if (!root || root === '/')
35
+ return;
36
+ if (!params) {
37
+ ctx.path = join(root, ctx.path);
38
+ return;
39
+ }
40
+ for (const [k, v] of Object.entries(params))
41
+ if (k.startsWith('uri'))
42
+ params[k] = Array.isArray(v) ? v.map(x => join(root, x)) : join(root, v);
43
+ })() || next();
44
+ exports.rootsMiddleware = rootsMiddleware;
45
+ function join(a, b) {
46
+ return a + (b && b[0] !== '/' ? '/' : '') + b;
47
+ }
package/src/serveFile.js CHANGED
@@ -12,12 +12,17 @@ const mime_types_1 = __importDefault(require("mime-types"));
12
12
  const config_1 = require("./config");
13
13
  const misc_1 = require("./misc");
14
14
  const lodash_1 = __importDefault(require("lodash"));
15
- const path_1 = __importDefault(require("path"));
15
+ const path_1 = require("path");
16
16
  const util_1 = require("util");
17
17
  const connections_1 = require("./connections");
18
+ const auth_1 = require("./auth");
19
+ const errorPages_1 = require("./errorPages");
18
20
  const allowedReferer = (0, config_1.defineConfig)('allowed_referer', '');
19
- function serveFileNode(ctx, node) {
20
- var _a;
21
+ const limitDownloads = downloadLimiter((0, config_1.defineConfig)(misc_1.CFG.max_downloads, 0), () => true);
22
+ const limitDownloadsPerIp = downloadLimiter((0, config_1.defineConfig)(misc_1.CFG.max_downloads_per_ip, 0), ctx => ctx.ip);
23
+ const limitDownloadsPerAccount = downloadLimiter((0, config_1.defineConfig)(misc_1.CFG.max_downloads_per_account, 0), ctx => (0, auth_1.getCurrentUsername)(ctx) || undefined);
24
+ async function serveFileNode(ctx, node) {
25
+ var _a, _b;
21
26
  const { source, mime } = node;
22
27
  const name = (0, vfs_1.getNodeName)(node);
23
28
  const mimeString = typeof mime === 'string' ? mime
@@ -28,6 +33,9 @@ function serveFileNode(ctx, node) {
28
33
  && !(0, misc_1.matches)(ref, allowedReferer.get()))
29
34
  return ctx.status = const_1.HTTP_FORBIDDEN;
30
35
  }
36
+ if ((_b = await limitDownloadsPerAccount(ctx) // returning false will not execute other limits
37
+ ) !== null && _b !== void 0 ? _b : (await limitDownloads(ctx) || await limitDownloadsPerIp(ctx)))
38
+ return;
31
39
  ctx.vfsNode = node; // useful to tell service files from files shared by the user
32
40
  if ('dl' in ctx.query) // please, download
33
41
  ctx.attachment(name);
@@ -46,7 +54,7 @@ const mimeCfg = (0, config_1.defineConfig)('mime', { '*': const_1.MIME_AUTO }, o
46
54
  async function serveFile(ctx, source, mime, content) {
47
55
  if (!source)
48
56
  return;
49
- const fn = path_1.default.basename(source);
57
+ const fn = (0, path_1.basename)(source);
50
58
  mime = mime !== null && mime !== void 0 ? mime : mimeCfg.compiled()(fn);
51
59
  if (mime === const_1.MIME_AUTO)
52
60
  mime = mime_types_1.default.lookup(source) || '';
@@ -118,3 +126,31 @@ function getRange(ctx, totalSize) {
118
126
  return { start, end };
119
127
  }
120
128
  exports.getRange = getRange;
129
+ function downloadLimiter(configMax, cbKey) {
130
+ const map = new Map();
131
+ return (ctx) => {
132
+ const k = cbKey(ctx);
133
+ if (k === undefined)
134
+ return; // undefined = skip limit
135
+ const max = configMax.get();
136
+ if (!max)
137
+ return;
138
+ const now = map.get(k) || 0;
139
+ if (now >= max)
140
+ return tooMany();
141
+ map.set(k, now + 1);
142
+ ctx.req.on('close', () => {
143
+ const n = map.get(k);
144
+ if (n > 1)
145
+ map.set(k, n - 1);
146
+ else
147
+ map.delete(k);
148
+ });
149
+ return false; // limit is enforced but passed
150
+ async function tooMany() {
151
+ ctx.set('retry-after', '3600');
152
+ await (0, errorPages_1.sendErrorPage)(ctx, const_1.HTTP_TOO_MANY_REQUESTS);
153
+ return true;
154
+ }
155
+ };
156
+ }
@@ -52,7 +52,7 @@ function serveStatic(uri) {
52
52
  (0, vanilla_1.subscribe)(customHtml_1.customHtmlState, () => cache = {}); // reset cache at every change
53
53
  return async (ctx) => {
54
54
  if (!logGui.get())
55
- ctx.state.dont_log = true;
55
+ ctx.state.dontLog = true;
56
56
  if (ctx.method === 'OPTIONS') {
57
57
  ctx.status = const_1.HTTP_NO_CONTENT;
58
58
  ctx.set({ Allow: 'OPTIONS, GET' });
@@ -166,7 +166,7 @@ function serveProxied(port, uri) {
166
166
  }));
167
167
  return function (ctx, next) {
168
168
  if (!logGui.get())
169
- ctx.state.dont_log = true;
169
+ ctx.state.dontLog = true;
170
170
  return proxy(ctx, next);
171
171
  };
172
172
  }
package/src/update.js CHANGED
@@ -63,15 +63,16 @@ function updateSupported() {
63
63
  return const_1.IS_BINARY;
64
64
  }
65
65
  exports.updateSupported = updateSupported;
66
- async function update(tag = '') {
66
+ async function update(tagOrUrl = '') {
67
67
  if (!updateSupported())
68
68
  throw "only binary versions supports automatic update for now";
69
- let updateSource = await localUpdateAvailable() && (0, fs_1.createReadStream)(LOCAL_UPDATE);
69
+ let updateSource = tagOrUrl.includes('://') ? await (0, misc_1.httpStream)(tagOrUrl)
70
+ : await localUpdateAvailable() && (0, fs_1.createReadStream)(LOCAL_UPDATE);
70
71
  if (!updateSource) {
71
- if (/^\d/.test(tag)) // work even if the tag is passed without the initial 'v' (useful for console commands)
72
- tag = 'v' + tag;
73
- const update = !tag ? (await getUpdates())[0]
74
- : await (0, github_1.getRepoInfo)(const_1.HFS_REPO + '/releases/tags/' + tag).catch(e => {
72
+ if (/^\d/.test(tagOrUrl)) // work even if the tag is passed without the initial 'v' (useful for console commands)
73
+ tagOrUrl = 'v' + tagOrUrl;
74
+ const update = !tagOrUrl ? (await getUpdates())[0]
75
+ : await (0, github_1.getRepoInfo)(const_1.HFS_REPO + '/releases/tags/' + tagOrUrl).catch(e => {
75
76
  if (e.message === '404')
76
77
  console.error("version not found");
77
78
  else
package/src/upload.js CHANGED
@@ -3,7 +3,7 @@ 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.uploadWriter = exports.getUploadMeta = exports.minAvailableMb = exports.deleteUnfinishedUploadsAfter = void 0;
6
+ exports.uploadWriter = exports.getUploadMeta = exports.dontOverwriteUploading = exports.minAvailableMb = exports.deleteUnfinishedUploadsAfter = void 0;
7
7
  const vfs_1 = require("./vfs");
8
8
  const const_1 = require("./const");
9
9
  const path_1 = require("path");
@@ -18,7 +18,7 @@ const auth_1 = require("./auth");
18
18
  const comments_1 = require("./comments");
19
19
  exports.deleteUnfinishedUploadsAfter = (0, config_1.defineConfig)('delete_unfinished_uploads_after', 86400);
20
20
  exports.minAvailableMb = (0, config_1.defineConfig)('min_available_mb', 100);
21
- const dontOverwriteUploading = (0, config_1.defineConfig)('dont_overwrite_uploading', false);
21
+ exports.dontOverwriteUploading = (0, config_1.defineConfig)('dont_overwrite_uploading', false);
22
22
  const waitingToBeDeleted = {};
23
23
  const ATTR_UPLOADER = 'uploader';
24
24
  function getUploadMeta(path) {
@@ -89,8 +89,7 @@ function uploadWriter(base, path, ctx) {
89
89
  ret.once('close', async () => {
90
90
  if (!ctx.req.aborted) {
91
91
  let dest = fullPath;
92
- await setUploadMeta(tempName, ctx);
93
- if (dontOverwriteUploading.get() && fs_1.default.existsSync(dest)) {
92
+ if (exports.dontOverwriteUploading.get() && fs_1.default.existsSync(dest) && !overwriteAnyway()) {
94
93
  const ext = (0, path_1.extname)(dest);
95
94
  const base = dest.slice(0, -ext.length);
96
95
  let i = 1;
@@ -99,6 +98,7 @@ function uploadWriter(base, path, ctx) {
99
98
  while (fs_1.default.existsSync(dest));
100
99
  }
101
100
  return fs_1.default.rename(tempName, dest, err => {
101
+ setUploadMeta(err ? tempName : dest, ctx);
102
102
  if (err)
103
103
  console.error("couldn't rename temp to", dest, String(err));
104
104
  else if (ctx.query.comment)
@@ -115,6 +115,12 @@ function uploadWriter(base, path, ctx) {
115
115
  delayedDelete(tempName, sec);
116
116
  });
117
117
  return ret;
118
+ function overwriteAnyway() {
119
+ if (ctx.query.overwrite === undefined)
120
+ return;
121
+ const n = (0, vfs_1.getNodeByName)(path, base);
122
+ return n && (0, vfs_1.hasPermission)(n, 'can_delete', ctx);
123
+ }
118
124
  function trackProgress() {
119
125
  let lastGot = 0;
120
126
  let lastGotTime = 0;
@@ -122,7 +128,6 @@ function uploadWriter(base, path, ctx) {
122
128
  if (!conn)
123
129
  return () => { };
124
130
  const opTotal = reqSize + resume;
125
- ctx.state.uploadPath = ctx.path + path;
126
131
  ctx.state.uploadSize = opTotal;
127
132
  (0, connections_1.updateConnection)(conn, { ctx, op: 'upload', opTotal, opOffset: resume / opTotal });
128
133
  const h = setInterval(() => {
package/src/util-files.js CHANGED
@@ -103,14 +103,15 @@ function adjustStaticPathForGlob(path) {
103
103
  return fast_glob_1.default.escapePath(path.replace(/\\/g, '/'));
104
104
  }
105
105
  exports.adjustStaticPathForGlob = adjustStaticPathForGlob;
106
- async function* dirStream(path, deep = 0) {
106
+ async function* dirStream(path, { depth = 0, onlyFiles = false, onlyFolders = false } = {}) {
107
107
  if (!await isDirectory(path))
108
108
  throw Error('ENOTDIR');
109
- const dirStream = fast_glob_1.default.stream(deep ? '**/*' : '*', {
109
+ const dirStream = fast_glob_1.default.stream(depth ? '**/*' : '*', {
110
110
  cwd: path,
111
111
  dot: true,
112
- deep: deep + 1,
113
- onlyFiles: false,
112
+ deep: depth + 1,
113
+ onlyFiles,
114
+ onlyDirectories: onlyFolders,
114
115
  suppressErrors: true,
115
116
  objectMode: true,
116
117
  });
@@ -128,9 +129,9 @@ async function* dirStream(path, deep = 0) {
128
129
  if (!const_1.IS_WINDOWS)
129
130
  return;
130
131
  const winPath = path.replace(/\//g, '\\');
131
- const out = await (0, util_os_1.runCmd)('dir', ['/ah', '/b', deep ? '/s' : '/c', winPath]) // cannot pass '', so we pass /c as a noop parameter
132
+ const out = await (0, util_os_1.runCmd)('dir', ['/ah', '/b', depth ? '/s' : '/c', winPath]) // cannot pass '', so we pass /c as a noop parameter
132
133
  .catch(() => ''); // error in case of no matching file
133
- return out.split('\r\n').slice(0, -1).map(x => !deep ? x : x.slice(winPath.length + 1).replace(/\\/g, '/'));
134
+ return out.split('\r\n').slice(0, -1).map(x => !depth ? x : x.slice(winPath.length + 1).replace(/\\/g, '/'));
134
135
  }
135
136
  }
136
137
  exports.dirStream = dirStream;
package/src/vfs.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.parentMaskApplier = exports.masksCouldGivePermission = exports.walkNode = exports.statusCodeForMissingPerm = exports.hasPermission = exports.nodeIsLink = exports.nodeIsDirectory = exports.getNodeName = exports.saveVfs = exports.vfs = exports.urlToNode = exports.applyParentToChild = exports.isSameFilenameAs = exports.permsFromParent = void 0;
7
+ exports.parentMaskApplier = exports.masksCouldGivePermission = exports.walkNode = exports.statusCodeForMissingPerm = exports.hasPermission = exports.nodeIsLink = exports.nodeIsDirectory = exports.getNodeName = exports.saveVfs = exports.vfs = exports.getNodeByName = exports.urlToNode = exports.applyParentToChild = exports.isSameFilenameAs = exports.permsFromParent = void 0;
8
8
  const promises_1 = __importDefault(require("fs/promises"));
9
9
  const path_1 = require("path");
10
10
  const misc_1 = require("./misc");
@@ -68,7 +68,6 @@ function applyParentToChild(child, parent, name) {
68
68
  }
69
69
  exports.applyParentToChild = applyParentToChild;
70
70
  async function urlToNode(url, ctx, parent = exports.vfs, getRest) {
71
- var _a;
72
71
  let initialSlashes = 0;
73
72
  while (url[initialSlashes] === '/')
74
73
  initialSlashes++;
@@ -77,18 +76,41 @@ async function urlToNode(url, ctx, parent = exports.vfs, getRest) {
77
76
  if (!name)
78
77
  return parent;
79
78
  const rest = nextSlash < 0 ? '' : url.slice(nextSlash + 1, url.endsWith('/') ? -1 : undefined);
80
- if ((0, misc_1.dirTraversal)(name) || /[\\/]/.test(name)) {
81
- if (ctx)
82
- ctx.status = const_1.HTTP_FOOL;
79
+ const ret = getNodeByName(name, parent);
80
+ if (!ret)
81
+ return;
82
+ if (ret === null || ret === void 0 ? void 0 : ret.original)
83
+ return urlToNode(rest, ctx, ret, getRest);
84
+ if (parent.default)
85
+ inheritFromParent({ mime: { '*': const_1.MIME_AUTO } }, ret);
86
+ if (rest)
87
+ return urlToNode(rest, ctx, ret, getRest);
88
+ if (ret.source)
89
+ try {
90
+ const st = await promises_1.default.stat(ret.source); // check existence
91
+ ret.isFolder = st.isDirectory();
92
+ }
93
+ catch (_a) {
94
+ if (!getRest)
95
+ return;
96
+ const rest = ret.source.slice(parent.source.length); // parent has source, otherwise !ret.source || ret.original
97
+ getRest((0, misc_1.removeStarting)('/', rest));
98
+ return parent;
99
+ }
100
+ return ret;
101
+ }
102
+ exports.urlToNode = urlToNode;
103
+ function getNodeByName(name, parent) {
104
+ var _a;
105
+ if ((0, misc_1.dirTraversal)(name) || /[\\/]/.test(name))
83
106
  return;
84
- }
85
107
  // does the tree node have a child that goes by this name?
86
108
  const child = (_a = parent.children) === null || _a === void 0 ? void 0 : _a.find(isSameFilenameAs(name));
87
109
  if (!child && !parent.source)
88
110
  return; // on tree or on disk, or it doesn't exist
89
111
  const ret = applyParentToChild(child, parent, name);
90
112
  if (child)
91
- return urlToNode(rest, ctx, ret, getRest);
113
+ return ret;
92
114
  let onDisk = name;
93
115
  if (parent.rename) { // reverse the mapping
94
116
  for (const [from, to] of Object.entries(parent.rename))
@@ -99,24 +121,9 @@ async function urlToNode(url, ctx, parent = exports.vfs, getRest) {
99
121
  ret.rename = renameUnderPath(parent.rename, name);
100
122
  }
101
123
  ret.source = (0, misc_1.enforceFinal)('/', parent.source) + onDisk;
102
- if (parent.default)
103
- inheritFromParent({ mime: { '*': const_1.MIME_AUTO } }, ret);
104
- if (rest)
105
- return urlToNode(rest, ctx, ret, getRest);
106
- if (ret.source)
107
- try {
108
- const st = await promises_1.default.stat(ret.source); // check existence
109
- ret.isFolder = st.isDirectory();
110
- }
111
- catch (_b) {
112
- if (!getRest)
113
- return;
114
- getRest(onDisk);
115
- return parent;
116
- }
117
124
  return ret;
118
125
  }
119
- exports.urlToNode = urlToNode;
126
+ exports.getNodeByName = getNodeByName;
120
127
  exports.vfs = {};
121
128
  (0, config_1.defineConfig)('vfs', {}).sub(data => exports.vfs = (function recur(node) {
122
129
  if (node.children)
@@ -135,12 +142,14 @@ function getNodeName(node) {
135
142
  if (!source)
136
143
  return ''; // should happen only for root
137
144
  if (source === '/')
138
- return 'root';
145
+ return 'root'; // better name than
139
146
  if (/^[a-zA-Z]:\\?$/.test(source))
140
147
  return source.slice(0, 2); // exclude trailing slash
141
148
  const base = (0, path_1.basename)(source);
142
149
  if (/^[./\\]*$/.test(base)) // if empty or special-chars-only
143
150
  return (0, path_1.basename)((0, path_1.resolve)(source)); // resolve to try to get more
151
+ if (base.includes('\\')) // source was Windows but now we are running posix. This probably happens only debugging, so it's DX
152
+ return source.slice(source.lastIndexOf('\\') + 1);
144
153
  return base;
145
154
  }
146
155
  exports.getNodeName = getNodeName;
@@ -195,8 +204,7 @@ function statusCodeForMissingPerm(node, perm, ctx, assign = true) {
195
204
  }
196
205
  exports.statusCodeForMissingPerm = statusCodeForMissingPerm;
197
206
  // it's responsibility of the caller to verify you have list permission on parent, as callers have different needs.
198
- // Too many parameters: consider object, but benchmark against degraded recursion on huge folders.
199
- async function* walkNode(parent, ctx, depth = 0, prefixPath = '', requiredPerm) {
207
+ async function* walkNode(parent, { ctx, depth = Infinity, prefixPath = '', requiredPerm, onlyFolders = false } = {}) {
200
208
  var _a;
201
209
  const { children, source } = parent;
202
210
  const took = prefixPath ? undefined : new Set();
@@ -204,6 +212,8 @@ async function* walkNode(parent, ctx, depth = 0, prefixPath = '', requiredPerm)
204
212
  const parentsCache = new Map(); // we use this only if depth > 0
205
213
  if (children)
206
214
  for (const child of children) {
215
+ if (onlyFolders && !await nodeIsDirectory(child))
216
+ continue;
207
217
  const nodeName = getNodeName(child);
208
218
  const name = prefixPath + nodeName;
209
219
  took === null || took === void 0 ? void 0 : took.add(name);
@@ -223,7 +233,7 @@ async function* walkNode(parent, ctx, depth = 0, prefixPath = '', requiredPerm)
223
233
  parentsCache.set(name, item);
224
234
  inheritMasks(item, parent, nodeName);
225
235
  if (!ctx || hasPermission(item, 'can_list', ctx)) // check perm before recursion
226
- yield* walkNode(item, ctx, depth - 1, name + '/', requiredPerm);
236
+ yield* walkNode(item, { ctx, depth: depth - 1, prefixPath: name + '/', requiredPerm, onlyFolders });
227
237
  }
228
238
  if (!source)
229
239
  return;
@@ -235,7 +245,7 @@ async function* walkNode(parent, ctx, depth = 0, prefixPath = '', requiredPerm)
235
245
  let lastDir = prefixPath.slice(0, -1) || '.';
236
246
  parentsCache.set(lastDir, parent);
237
247
  // it's important to keep using dirStream in deep-mode, as it is manyfold faster (it parallelizes)
238
- for await (const [path, isFolder] of (0, misc_1.dirStream)(source, depth)) {
248
+ for await (const [path, isFolder] of (0, misc_1.dirStream)(source, { depth, onlyFolders })) {
239
249
  if (ctx === null || ctx === void 0 ? void 0 : ctx.req.aborted)
240
250
  return;
241
251
  const name = prefixPath + (((_a = parent.rename) === null || _a === void 0 ? void 0 : _a[path]) || path);
package/src/zip.js CHANGED
@@ -24,7 +24,7 @@ async function zipStreamFromFolder(node, ctx) {
24
24
  const name = (list === null || list === void 0 ? void 0 : list.length) === 1 ? decodeURIComponent((0, path_1.basename)(list[0])) : (0, vfs_1.getNodeName)(node);
25
25
  ctx.attachment(((0, misc_1.isWindowsDrive)(name) ? name[0] : (name || 'archive')) + '.zip');
26
26
  const filter = (0, misc_1.pattern2filter)(String(ctx.query.search || ''));
27
- const walker = !list ? (0, vfs_1.walkNode)(node, ctx, Infinity, '', 'can_archive')
27
+ const walker = !list ? (0, vfs_1.walkNode)(node, { ctx, requiredPerm: 'can_archive' })
28
28
  : (async function* () {
29
29
  for await (const uri of list) {
30
30
  const subNode = await (0, vfs_1.urlToNode)(uri, ctx, node);
@@ -33,7 +33,7 @@ async function zipStreamFromFolder(node, ctx) {
33
33
  if (await (0, vfs_1.nodeIsDirectory)(subNode)) { // a directory needs to walked
34
34
  if ((0, vfs_1.hasPermission)(subNode, 'can_list', ctx)) {
35
35
  yield subNode; // it could be empty
36
- yield* (0, vfs_1.walkNode)(subNode, ctx, Infinity, decodeURI(uri) + '/', 'can_archive');
36
+ yield* (0, vfs_1.walkNode)(subNode, { ctx, prefixPath: decodeURI(uri) + '/', requiredPerm: 'can_archive' });
37
37
  }
38
38
  continue;
39
39
  }