-
-
Notifications
You must be signed in to change notification settings - Fork 58
Expand file tree
/
Copy pathindex.ts
More file actions
363 lines (294 loc) · 11.7 KB
/
Copy pathindex.ts
File metadata and controls
363 lines (294 loc) · 11.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
import express, { Response } from 'express';
import Formidable from 'formidable';
import { createReadStream } from 'node:fs';
import { join, basename, relative, resolve as resolvePath } from 'node:path';
import assert from 'node:assert';
import * as fs from 'node:fs/promises';
import morgan from 'morgan';
import asyncHandler from 'express-async-handler';
import archiver from 'archiver';
import pMap from 'p-map';
import os from 'node:os';
import contentDisposition from 'content-disposition';
import { createProxyMiddleware } from 'http-proxy-middleware';
import clipboardy from 'clipboardy';
import bodyParser from 'body-parser';
import filenamify from 'filenamify';
import stream from 'node:stream/promises';
import parseRange from 'range-parser';
import isPathInside from 'is-path-inside';
import basicAuth from 'basic-auth';
import { timingSafeEqual } from 'node:crypto';
import Ffmpeg from './ffmpeg.js';
export { default as parseArgs } from './args.js';
const maxFields = 1000;
const debug = false;
const pathExists = (path: string) => fs.access(path, fs.constants.F_OK).then(() => true).catch(() => false);
export default ({ sharedPath: sharedPathIn, port, maxUploadSize, zipCompressionLevel, devMode, auth, ffmpegPath, webPath }: {
sharedPath: string | undefined,
port: number,
maxUploadSize: number,
zipCompressionLevel: number,
devMode: boolean,
auth?: { username: string, password: string } | undefined,
ffmpegPath: string,
webPath: string,
}) => {
const ffmpeg = Ffmpeg({ ffmpegPath });
// console.log({ sharedPath: sharedPathIn, port, maxUploadSize, zipCompressionLevel });
const sharedPath = sharedPathIn ? resolvePath(sharedPathIn) : process.cwd();
function arePathsEqual(path1: string, path2: string) {
return relative(path1, path2) === '';
}
async function getFileAbsPath(relPath: string | undefined) {
if (relPath == null) return sharedPath;
const absPath = join(sharedPath, join('/', relPath));
const realPath = await fs.realpath(absPath);
assert(isPathInside(realPath, sharedPath) || arePathsEqual(realPath, sharedPath), `Path must be within shared path ${realPath} ${sharedPath}`);
return realPath;
}
const app = express();
app.use((req, res, next) => {
if (auth != null) {
const authRes = basicAuth(req);
try {
assert(authRes);
assert(timingSafeEqual(Buffer.from(authRes.name, 'utf8'), Buffer.from(auth.username, 'utf8'))
&& timingSafeEqual(Buffer.from(authRes.pass, 'utf8'), Buffer.from(auth.password, 'utf8')));
} catch {
res.set('WWW-Authenticate', 'Basic realm="ezshare"');
res.status(401).send('Authentication required.');
return;
}
}
next();
});
if (debug) app.use(morgan('dev'));
// NOTE: Must support non latin characters
app.post('/api/upload', bodyParser.json(), asyncHandler(async (req, res) => {
// console.log(req.headers)
const uploadDirPathIn = req.query['path'] || '/';
assert(typeof uploadDirPathIn === 'string');
const uploadDirPath = await getFileAbsPath(uploadDirPathIn);
// parse a file upload
const form = Formidable({
keepExtensions: true,
uploadDir: uploadDirPath,
maxFileSize: maxUploadSize,
maxFields,
});
form.parse(req, async (err, _fields, { files: filesIn }) => {
if (err) {
console.error('Upload failed', err);
res.status(400).send({ error: { message: err.message } });
return;
}
if (filesIn) {
const files = Array.isArray(filesIn) ? filesIn : [filesIn];
// console.log(JSON.stringify({ fields, files }, null, 2));
console.log('Uploaded files to', uploadDirPath);
files.forEach((f) => console.log(f.originalFilename, `(${f.size} bytes)`));
await pMap(files, async (file) => {
try {
const targetPath = join(uploadDirPath, filenamify(file.originalFilename ?? 'file', { maxLength: 255 }));
if (!(await pathExists(targetPath))) await fs.rename(file.filepath, targetPath); // to prevent overwrites
} catch (err2) {
console.error(`Failed to rename ${file.originalFilename}`, err2);
}
}, { concurrency: 10 });
}
res.end();
});
}));
app.delete('/api/delete', asyncHandler(async (req, res) => {
const { path: filePath } = req.query;
// Ensure path is provided and is a string
assert(typeof filePath === 'string', 'Path must be a string');
// Use existing helper to resolve path and check security (prevents directory traversal)
const absPath = await getFileAbsPath(filePath);
// prevent deleting the root shared folder
if (absPath === sharedPath) {
res.status(403).json({ error: 'Cannot delete root directory' });
return;
}
console.log('Deleting file:', absPath);
await fs.unlink(absPath);
res.json({ success: true });
}));
// NOTE: Must support non latin characters
app.post('/api/paste', bodyParser.urlencoded({ extended: false }), asyncHandler(async (req, res) => {
// eslint-disable-next-line unicorn/prefer-ternary
if (req.body.saveAsFile === 'true') {
await fs.writeFile(join(sharedPath, `client-clipboard-${Date.now()}.txt`), req.body.clipboard);
} else {
await clipboardy.write(req.body.clipboard);
}
res.end();
}));
// NOTE: Must support non latin characters
app.post('/api/copy', asyncHandler(async (_req, res) => {
res.send(await clipboardy.read());
}));
async function serveDirZip(filePath: string, res: Response) {
const archive = archiver('zip', {
zlib: { level: zipCompressionLevel },
});
res.writeHead(200, {
'Content-Type': 'application/zip',
// NOTE: Must support non latin characters
'Content-disposition': contentDisposition(`${basename(filePath)}.zip`),
});
const promise = stream.pipeline(archive, res);
archive.directory(filePath, basename(filePath));
archive.finalize();
await promise;
}
async function serveResumableFileDownload({ filePath, range, res, forceDownload }: {
filePath: string,
range: string | undefined,
res: Response,
forceDownload: boolean,
}) {
if (forceDownload) {
// Set the filename in the Content-disposition header
res.set('Content-disposition', contentDisposition(basename(filePath)));
}
const { size: fileSize } = await fs.stat(filePath);
if (range) {
const subranges = parseRange(fileSize, range);
assert(typeof subranges !== 'number');
if (subranges.type !== 'bytes') throw new Error(`Invalid range type ${subranges.type}`);
if (subranges.length !== 1) throw new Error('Only a single range is supported');
const { start, end } = subranges[0]!;
const contentLength = (end - start) + 1;
// Set headers for resumable download
res.status(206).set({
'Content-Range': `bytes ${start}-${end}/${fileSize}`,
'Accept-Ranges': 'bytes',
'Content-Length': contentLength,
'Content-Type': 'application/octet-stream',
});
await stream.pipeline(createReadStream(filePath, { start, end }), res);
} else {
// Standard download without resuming
res.set({
// 'Content-Type': 'application/octet-stream',
'Content-Length': fileSize,
});
await stream.pipeline(createReadStream(filePath), res);
}
}
app.get('/api/download', asyncHandler(async (req, res) => {
const { f } = req.query;
assert(typeof f === 'string');
const filePath = await getFileAbsPath(f);
const forceDownload = req.query['forceDownload'] === 'true';
const lstat = await fs.lstat(filePath);
if (lstat.isDirectory()) {
await serveDirZip(filePath, res);
} else {
const { range } = req.headers;
await serveResumableFileDownload({ filePath, range, res, forceDownload });
}
}));
app.get('/api/thumbnail', asyncHandler(async (req, res) => {
const { f } = req.query;
assert(typeof f === 'string');
const filePath = await getFileAbsPath(f);
// todo limit concurrency?
if (!ffmpeg.hasFfmpeg()) {
res.status(500).end();
return;
}
const thumbnail = await ffmpeg.renderThumbnail(filePath);
res.set('Cache-Control', 'private, max-age=300');
res.set('Content-Type', 'image/jpeg');
res.send(Buffer.from(thumbnail));
}));
app.get('/api/browse', asyncHandler(async (req, res) => {
const browseRelPath = req.query['p'] || '/';
assert(typeof browseRelPath === 'string');
const browseAbsPath = await getFileAbsPath(browseRelPath);
let readdirEntries = await fs.readdir(browseAbsPath, { withFileTypes: true });
readdirEntries = readdirEntries.sort(({ name: a }, { name: b }) => new Intl.Collator(undefined, { numeric: true }).compare(a, b));
const entries = (await pMap(readdirEntries, async (entry) => {
try {
// TODO what if a file called ".."
const entryRelPath = join(browseRelPath, entry.name);
const entryAbsPath = join(browseAbsPath, entry.name);
const entryRealPath = await fs.realpath(entryAbsPath);
if (!entryRealPath.startsWith(sharedPath)) {
console.warn('Ignoring symlink pointing outside shared path', entryRealPath);
return [];
}
const stat = await fs.lstat(entryRealPath);
const isDir = stat.isDirectory();
return [{
path: entryRelPath,
isDir,
fileName: entry.name,
}];
} catch (err) {
console.warn((err as Error).message);
// https://github.com/mifi/ezshare/issues/29
return [];
}
}, { concurrency: 10 })).flat();
res.send({
files: [
{ path: join(browseRelPath, '..'), fileName: '..', isDir: true },
...entries,
],
cwd: browseRelPath,
sharedPath,
});
}));
app.get('/api/zip-files', asyncHandler(async (req, res) => {
const zipFileName = `${new Date().toISOString().replace(/^(\d+-\d+-\d+)T(\d+):(\d+):(\d+).*$/, '$1 $2.$3.$3')}.zip`;
const { files: filesJson } = req.query;
assert(typeof filesJson === 'string');
const files = JSON.parse(filesJson) as unknown;
assert(Array.isArray(files));
const archive = archiver('zip', { zlib: { level: zipCompressionLevel } });
res.writeHead(200, {
'Content-Type': 'application/zip',
// NOTE: Must support non latin characters
'Content-Disposition': contentDisposition(zipFileName),
});
const promise = stream.pipeline(archive, res);
await pMap(files, async (file: unknown) => {
assert(typeof file === 'string');
const absPath = await getFileAbsPath(file);
// Add each file to the archive:
archive.file(absPath, { name: file });
}, { concurrency: 1 });
archive.finalize();
await promise;
}));
function getUrls() {
const interfaces = os.networkInterfaces();
return Object.values(interfaces).flatMap((addresses) => (addresses != null ? addresses : [])).filter(({ family, address }) => family === 'IPv4' && address !== '127.0.0.1').map(({ address }) => `http://${address}:${port}/`);
}
let started = false;
async function startServer() {
assert(!started, 'Server already started');
started = true;
// Serving the frontend depending on dev/production
if (devMode) {
app.use('/', createProxyMiddleware({ target: 'http://localhost:3000', ws: true }));
} else {
app.use('/', express.static(webPath));
// Default fallback to index.html because it's a SPA (so user can open any deep link)
app.use('*', (_req, res) => res.sendFile(join(webPath, 'index.html')));
}
return new Promise<void>((resolve) => {
app.listen(port, resolve);
});
}
return {
runStartupCheck: ffmpeg.runStartupCheck,
getUrls,
start: startServer,
sharedPath,
};
};