BlueGit

timfa filemanager

Files

filemanager / tests / files.routes.test.js

files.routes.test.js

files.routes.test.js 23.2 KiB Download Raw
1'use strict';
2
3const express = require('express');
4const fs = require('fs');
5const http = require('http');
6const os = require('os');
7const path = require('path');
8const { once } = require('events');
9
10let mockPaths = [];
11let mockRootAliases = {};
12let mockUser = { username: 'admin', isAdmin: true, permissions: {} };
13let mockThumbPath = null;
14let mockFolderImages = [];
15let mockFolderIconFile = null;
16let lastFolderIconAssignment = undefined;
17
18jest.mock('../server/db', () =>
19{
20 const { Database } = require('node-sqlite3-wasm');
21 let db;
22 function getDb ()
23 {
24 if (!db)
25 {
26 db = new Database(':memory:');
27 db.exec(`
28 CREATE TABLE IF NOT EXISTS users (
29 id INTEGER PRIMARY KEY AUTOINCREMENT,
30 username TEXT UNIQUE NOT NULL,
31 password_hash TEXT NOT NULL,
32 is_admin INTEGER NOT NULL DEFAULT 0,
33 permissions TEXT NOT NULL DEFAULT '{}'
34 );
35 CREATE TABLE IF NOT EXISTS file_meta (
36 file_path TEXT PRIMARY KEY,
37 uploader TEXT NOT NULL DEFAULT '',
38 downloaders TEXT NOT NULL DEFAULT '[]'
39 );
40 `);
41 }
42 return db;
43 }
44 return { getDb, initDb: getDb };
45});
46
47jest.mock('../server/config', () => ({
48 loadConfig: () => ({ port: 3000, paths: [...mockPaths], rootAliases: { ...mockRootAliases } }),
49 saveConfig: (config) =>
50 {
51 mockPaths = [...(config.paths || [])];
52 mockRootAliases = { ...(config.rootAliases || {}) };
53 },
54 getEffectivePaths: (paths) => paths,
55 getAllowedRoot: (targetPath, roots) =>
56 {
57 const path = require('path');
58 const absTarget = path.resolve(String(targetPath || ''));
59 return roots.find((root) =>
60 {
61 const absRoot = path.resolve(root);
62 return absTarget === absRoot || absTarget.startsWith(absRoot + path.sep);
63 }) || null;
64 },
65}));
66
67jest.mock('../server/auth', () => ({
68 requireAuth: (req, res, next) => { req.user = mockUser; next(); },
69}));
70
71jest.mock('../server/thumbnail-cache', () => ({
72 getCachedThumbnailInfo: async () =>
73 {
74 if (!mockThumbPath) return null;
75 return { thumbPath: mockThumbPath, contentType: 'image/webp' };
76 },
77 getImagesWithThumbnailsInDir: async () => mockFolderImages.slice(),
78 getFolderIconSourceFile: async () => mockFolderIconFile,
79 setFolderIconAssignment: async (folderPath, imagePath) =>
80 {
81 lastFolderIconAssignment = { folderPath, imagePath };
82 },
83}));
84
85const filesRoutes = require('../server/routes/files');
86const { getDb } = require('../server/db');
87
88let server;
89let baseUrl;
90let rootDir;
91
92beforeAll(async () =>
93{
94 rootDir = fs.mkdtempSync(path.join(os.tmpdir(), 'filemanager-files-routes-'));
95 mockPaths = [rootDir];
96
97 const app = express();
98 app.use(express.json());
99 app.use('/api/files', filesRoutes);
100 app.use((err, req, res, next) =>
101 {
102 res.status(err.status || 500).json({ error: err.message || 'Internal error' });
103 });
104
105 server = http.createServer(app);
106 server.listen(0);
107 await once(server, 'listening');
108 baseUrl = `http://127.0.0.1:${server.address().port}`;
109});
110
111afterAll(() =>
112{
113 server.close();
114 fs.rmSync(rootDir, { recursive: true, force: true });
115});
116
117beforeEach(() =>
118{
119 fs.rmSync(rootDir, { recursive: true, force: true });
120 fs.mkdirSync(rootDir, { recursive: true });
121 mockRootAliases = {};
122 mockUser = { username: 'admin', isAdmin: true, permissions: {} };
123 mockThumbPath = null;
124 mockFolderImages = [];
125 mockFolderIconFile = null;
126 lastFolderIconAssignment = undefined;
127 const db = getDb();
128 db.prepare('DELETE FROM file_meta').run([]);
129 db.prepare('DELETE FROM users').run([]);
130});
131
132function req (method, routePath, body)
133{
134 const payload = body ? JSON.stringify(body) : undefined;
135 return new Promise((resolve, reject) =>
136 {
137 const request = http.request(baseUrl + routePath, {
138 method,
139 headers: {
140 'Content-Type': 'application/json',
141 ...(payload ? { 'Content-Length': Buffer.byteLength(payload) } : {}),
142 },
143 }, res =>
144 {
145 let data = '';
146 res.on('data', chunk => data += chunk);
147 res.on('end', () => resolve({ status: res.statusCode, body: JSON.parse(data) }));
148 });
149 request.on('error', reject);
150 if (payload) request.write(payload);
151 request.end();
152 });
153}
154
155function reqRaw (method, routePath)
156{
157 return new Promise((resolve, reject) =>
158 {
159 const request = http.request(baseUrl + routePath, { method }, res =>
160 {
161 const chunks = [];
162 res.on('data', chunk => chunks.push(Buffer.from(chunk)));
163 res.on('end', () => resolve({
164 status: res.statusCode,
165 headers: res.headers,
166 body: Buffer.concat(chunks),
167 }));
168 });
169 request.on('error', reject);
170 request.end();
171 });
172}
173
174function reqMultipart (routePath, files, extraHeaders = {})
175{
176 const boundary = '----filemanager-test-boundary';
177 const buffers = [];
178
179 for (const file of files)
180 {
181 buffers.push(Buffer.from(
182 `--${boundary}\r\n`
183 + `Content-Disposition: form-data; name="files"; filename="${file.name}"\r\n`
184 + `Content-Type: ${file.type || 'application/octet-stream'}\r\n\r\n`
185 ));
186 buffers.push(Buffer.isBuffer(file.content) ? file.content : Buffer.from(String(file.content)));
187 buffers.push(Buffer.from('\r\n'));
188 }
189
190 buffers.push(Buffer.from(`--${boundary}--\r\n`));
191 const payload = Buffer.concat(buffers);
192
193 return new Promise((resolve, reject) =>
194 {
195 const request = http.request(baseUrl + routePath, {
196 method: 'POST',
197 headers: {
198 'Content-Type': `multipart/form-data; boundary=${boundary}`,
199 'Content-Length': payload.length,
200 ...extraHeaders,
201 },
202 }, res =>
203 {
204 let data = '';
205 res.on('data', chunk => data += chunk);
206 res.on('end', () => resolve({ status: res.statusCode, body: JSON.parse(data) }));
207 });
208 request.on('error', reject);
209 request.write(payload);
210 request.end();
211 });
212}
213
214function abortMultipartUpload (routePath, file)
215{
216 const boundary = '----filemanager-test-boundary-abort';
217 const header = Buffer.from(
218 `--${boundary}\r\n`
219 + `Content-Disposition: form-data; name="files"; filename="${file.name}"\r\n`
220 + `Content-Type: ${file.type || 'application/octet-stream'}\r\n\r\n`
221 );
222 const chunk = Buffer.isBuffer(file.content) ? file.content : Buffer.from(String(file.content));
223
224 return new Promise((resolve) =>
225 {
226 const request = http.request(baseUrl + routePath, {
227 method: 'POST',
228 headers: {
229 'Content-Type': `multipart/form-data; boundary=${boundary}`,
230 },
231 });
232
233 let settled = false;
234 const finish = () =>
235 {
236 if (settled) return;
237 settled = true;
238 resolve();
239 };
240
241 request.on('error', finish);
242 request.on('close', finish);
243 request.write(header);
244 request.write(chunk);
245 setTimeout(() => request.destroy(), 20);
246 });
247}
248
249async function waitFor(predicate, timeoutMs = 500)
250{
251 const start = Date.now();
252 while (Date.now() - start < timeoutMs)
253 {
254 if (predicate()) return;
255 await new Promise(resolve => setTimeout(resolve, 10));
256 }
257 throw new Error('Timed out waiting for condition.');
258}
259
260describe('POST /api/files/upload', () =>
261{
262 test('stores a completed upload under its final name', async () =>
263 {
264 const { status, body } = await reqMultipart(`/api/files/upload?dir=${encodeURIComponent(rootDir)}`, [
265 { name: 'hello.txt', content: 'hello world', type: 'text/plain' },
266 ]);
267
268 expect(status).toBe(200);
269 expect(body.uploaded).toEqual(['hello.txt']);
270 expect(fs.readFileSync(path.join(rootDir, 'hello.txt'), 'utf8')).toBe('hello world');
271
272 const meta = getDb().prepare('SELECT * FROM file_meta WHERE file_path = ?')
273 .get([path.join(rootDir, 'hello.txt')]);
274 expect(meta).toMatchObject({ uploader: 'admin' });
275 });
276
277 test('removes partial files when the upload connection aborts', async () =>
278 {
279 await abortMultipartUpload(`/api/files/upload?dir=${encodeURIComponent(rootDir)}`, {
280 name: 'partial.txt',
281 content: Buffer.alloc(256 * 1024, 'a'),
282 type: 'text/plain',
283 });
284
285 await waitFor(() => fs.readdirSync(rootDir).length === 0);
286
287 expect(fs.existsSync(path.join(rootDir, 'partial.txt'))).toBe(false);
288 expect(fs.readdirSync(rootDir)).toEqual([]);
289
290 const meta = getDb().prepare('SELECT * FROM file_meta WHERE file_path = ?')
291 .get([path.join(rootDir, 'partial.txt')]);
292 expect(meta).toBeFalsy();
293 });
294});
295
296describe('POST /api/files/move', () =>
297{
298 test('moves a file into another folder and rewrites metadata', async () =>
299 {
300 const from = path.join(rootDir, 'alpha.txt');
301 const toDir = path.join(rootDir, 'folder');
302 fs.writeFileSync(from, 'hello');
303 fs.mkdirSync(toDir);
304
305 getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders) VALUES (?, ?, ?)')
306 .run([from, 'admin', '["alice"]']);
307
308 const { status, body } = await req('POST', '/api/files/move', { from, toDir });
309
310 expect(status).toBe(200);
311 expect(body.ok).toBe(true);
312 expect(fs.existsSync(from)).toBe(false);
313 expect(fs.existsSync(path.join(toDir, 'alpha.txt'))).toBe(true);
314
315 const meta = getDb().prepare('SELECT * FROM file_meta WHERE file_path = ?').get([path.join(toDir, 'alpha.txt')]);
316 expect(meta).toMatchObject({ uploader: 'admin', downloaders: '["alice"]' });
317 });
318
319 test('moves a folder into another folder and rewrites descendant metadata', async () =>
320 {
321 const fromDir = path.join(rootDir, 'src-folder');
322 const nestedFile = path.join(fromDir, 'child.txt');
323 const toDir = path.join(rootDir, 'dest-folder');
324 fs.mkdirSync(fromDir);
325 fs.mkdirSync(toDir);
326 fs.writeFileSync(nestedFile, 'hello');
327
328 getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders) VALUES (?, ?, ?)')
329 .run([nestedFile, 'admin', '[]']);
330
331 const { status } = await req('POST', '/api/files/move', { from: fromDir, toDir });
332
333 expect(status).toBe(200);
334 expect(fs.existsSync(fromDir)).toBe(false);
335 expect(fs.existsSync(path.join(toDir, 'src-folder', 'child.txt'))).toBe(true);
336
337 const movedMeta = getDb().prepare('SELECT * FROM file_meta WHERE file_path = ?')
338 .get([path.join(toDir, 'src-folder', 'child.txt')]);
339 expect(movedMeta).toBeTruthy();
340 });
341
342 test('rejects moving a folder into itself', async () =>
343 {
344 const fromDir = path.join(rootDir, 'src-folder');
345 const childDir = path.join(fromDir, 'child');
346 fs.mkdirSync(childDir, { recursive: true });
347
348 const { status, body } = await req('POST', '/api/files/move', { from: fromDir, toDir: childDir });
349
350 expect(status).toBe(400);
351 expect(body.error).toMatch(/folder into itself/i);
352 });
353
354 test('overwrites an existing destination when conflict strategy is overwrite', async () =>
355 {
356 const sourceFile = path.join(rootDir, 'source.txt');
357 const destinationDir = path.join(rootDir, 'dest');
358 fs.mkdirSync(destinationDir);
359 fs.writeFileSync(sourceFile, 'new-content');
360 fs.writeFileSync(path.join(destinationDir, 'source.txt'), 'old-content');
361
362 const { status, body } = await req('POST', '/api/files/move', {
363 from: sourceFile,
364 toDir: destinationDir,
365 conflict: 'overwrite',
366 });
367
368 expect(status).toBe(200);
369 expect(body.conflictResolution).toBe('overwrite');
370 expect(fs.existsSync(sourceFile)).toBe(false);
371 expect(fs.readFileSync(path.join(destinationDir, 'source.txt'), 'utf8')).toBe('new-content');
372 });
373
374 test('renames destination when conflict strategy is rename', async () =>
375 {
376 const sourceFile = path.join(rootDir, 'report.txt');
377 const destinationDir = path.join(rootDir, 'dest');
378 fs.mkdirSync(destinationDir);
379 fs.writeFileSync(sourceFile, 'latest');
380 fs.writeFileSync(path.join(destinationDir, 'report.txt'), 'existing');
381
382 const { status, body } = await req('POST', '/api/files/move', {
383 from: sourceFile,
384 toDir: destinationDir,
385 conflict: 'rename',
386 });
387
388 expect(status).toBe(200);
389 expect(body.conflictResolution).toBe('rename');
390 expect(path.basename(body.path)).toBe('report (1).txt');
391 expect(fs.readFileSync(body.path, 'utf8')).toBe('latest');
392 expect(fs.readFileSync(path.join(destinationDir, 'report.txt'), 'utf8')).toBe('existing');
393 });
394});
395
396describe('root alias endpoints', () =>
397{
398 test('GET /api/files/roots returns alias label and original name', async () =>
399 {
400 mockRootAliases = { [path.resolve(rootDir)]: 'Workspace' };
401
402 const { status, body } = await req('GET', '/api/files/roots');
403
404 expect(status).toBe(200);
405 expect(body.roots).toHaveLength(1);
406 expect(body.roots[0]).toMatchObject({
407 path: rootDir,
408 label: 'Workspace',
409 alias: 'Workspace',
410 originalName: path.basename(rootDir),
411 });
412 });
413
414 test('POST /api/files/root-alias stores alias without renaming filesystem path', async () =>
415 {
416 const originalBase = path.basename(rootDir);
417 const { status, body } = await req('POST', '/api/files/root-alias', {
418 rootPath: rootDir,
419 alias: 'Shared Files',
420 });
421
422 expect(status).toBe(200);
423 expect(body.ok).toBe(true);
424 expect(body.root).toMatchObject({
425 path: rootDir,
426 label: 'Shared Files',
427 alias: 'Shared Files',
428 originalName: originalBase,
429 });
430 expect(fs.existsSync(rootDir)).toBe(true);
431
432 const afterRoots = await req('GET', '/api/files/roots');
433 expect(afterRoots.status).toBe(200);
434 expect(afterRoots.body.roots[0].label).toBe('Shared Files');
435 expect(afterRoots.body.roots[0].originalName).toBe(originalBase);
436 });
437
438 test('POST /api/files/root-alias rejects non-root paths', async () =>
439 {
440 const nested = path.join(rootDir, 'sub');
441 fs.mkdirSync(nested, { recursive: true });
442
443 const { status } = await req('POST', '/api/files/root-alias', {
444 rootPath: nested,
445 alias: 'Nested',
446 });
447
448 expect(status).toBe(400);
449 });
450});
451
452describe('GET /api/files/thumbnail', () =>
453{
454 test('returns 404 while cached thumbnail is not ready', async () =>
455 {
456 const source = path.join(rootDir, 'photo.jpg');
457 fs.writeFileSync(source, 'not-an-image');
458
459 const { status, body } = await req('GET', `/api/files/thumbnail?file=${encodeURIComponent(source)}`);
460 expect(status).toBe(404);
461 expect(body.error).toMatch(/not ready/i);
462 });
463
464 test('serves cached thumbnail file when available', async () =>
465 {
466 const source = path.join(rootDir, 'photo.jpg');
467 const thumb = path.join(rootDir, 'photo-thumb.webp');
468 fs.writeFileSync(source, 'not-an-image');
469 fs.writeFileSync(thumb, 'webp-bytes');
470 mockThumbPath = thumb;
471
472 const response = await reqRaw('GET', `/api/files/thumbnail?file=${encodeURIComponent(source)}`);
473 expect(response.status).toBe(200);
474 expect(String(response.headers['content-type'] || '')).toContain('image/webp');
475 expect(response.body.toString('utf8')).toBe('webp-bytes');
476 });
477});
478
479describe('GET /api/files/root-access', () =>
480{
481 test('returns users with R/R+W modes for an exact root path', async () =>
482 {
483 const label = path.basename(rootDir);
484 const db = getDb();
485 db.prepare('INSERT INTO users (username, password_hash, is_admin, permissions) VALUES (?, ?, ?, ?)')
486 .run(['admin', 'x', 1, '{}']);
487 db.prepare('INSERT INTO users (username, password_hash, is_admin, permissions) VALUES (?, ?, ?, ?)')
488 .run(['alice', 'x', 0, JSON.stringify({ [label]: { read: true, write: false } })]);
489 db.prepare('INSERT INTO users (username, password_hash, is_admin, permissions) VALUES (?, ?, ?, ?)')
490 .run(['bob', 'x', 0, JSON.stringify({ [label]: { read: true, write: true } })]);
491 db.prepare('INSERT INTO users (username, password_hash, is_admin, permissions) VALUES (?, ?, ?, ?)')
492 .run(['charlie', 'x', 0, JSON.stringify({ other: { read: true, write: false } })]);
493
494 const { status, body } = await req('GET', `/api/files/root-access?rootPath=${encodeURIComponent(rootDir)}`);
495 expect(status).toBe(200);
496 expect(body.root).toMatchObject({ path: rootDir, originalName: label });
497 expect(body.users).toEqual([
498 { username: 'admin', mode: 'R+W' },
499 { username: 'bob', mode: 'R+W' },
500 { username: 'alice', mode: 'R' },
501 ]);
502 });
503
504 test('rejects non-exact nested root paths', async () =>
505 {
506 const nested = path.join(rootDir, 'sub');
507 fs.mkdirSync(nested, { recursive: true });
508
509 const { status } = await req('GET', `/api/files/root-access?rootPath=${encodeURIComponent(nested)}`);
510 expect(status).toBe(400);
511 });
512});
513
514describe('folder icon endpoints', () =>
515{
516 test('GET /api/files/folder-images returns images that have cached thumbnails', async () =>
517 {
518 const subDir = path.join(rootDir, 'photos');
519 fs.mkdirSync(subDir);
520 const imgPath = path.join(subDir, 'a.jpg');
521 fs.writeFileSync(imgPath, 'img');
522
523 mockFolderImages = [{ filePath: imgPath, thumbRelPath: 'thumbs/a.jpg.webp' }];
524
525 const { status, body } = await req('GET', `/api/files/folder-images?dir=${encodeURIComponent(rootDir)}`);
526 expect(status).toBe(200);
527 expect(body.images).toHaveLength(1);
528 expect(body.images[0].filePath).toBe(imgPath);
529 });
530
531 test('GET /api/files/folder-images returns empty list when no thumbnails available', async () =>
532 {
533 mockFolderImages = [];
534
535 const { status, body } = await req('GET', `/api/files/folder-images?dir=${encodeURIComponent(rootDir)}`);
536 expect(status).toBe(200);
537 expect(body.images).toEqual([]);
538 });
539
540 test('GET /api/files/folder-icon returns null when no icon available', async () =>
541 {
542 mockFolderIconFile = null;
543
544 const { status, body } = await req('GET', `/api/files/folder-icon?dir=${encodeURIComponent(rootDir)}`);
545 expect(status).toBe(200);
546 expect(body.icon).toBeNull();
547 });
548
549 test('GET /api/files/folder-icon returns source file path when icon is available', async () =>
550 {
551 const imgPath = path.join(rootDir, 'cover.jpg');
552 fs.writeFileSync(imgPath, 'img');
553 mockFolderIconFile = imgPath;
554
555 const { status, body } = await req('GET', `/api/files/folder-icon?dir=${encodeURIComponent(rootDir)}`);
556 expect(status).toBe(200);
557 expect(body.icon).toMatchObject({ filePath: imgPath });
558 });
559
560 test('POST /api/files/folder-icon sets explicit assignment when thumbnail is ready', async () =>
561 {
562 const imgPath = path.join(rootDir, 'cover.jpg');
563 const thumbFile = path.join(rootDir, 'cover.webp');
564 fs.writeFileSync(imgPath, 'img');
565 fs.writeFileSync(thumbFile, 'webp');
566 mockThumbPath = thumbFile;
567
568 const { status, body } = await req('POST', '/api/files/folder-icon', {
569 folderPath: rootDir,
570 imagePath: imgPath,
571 });
572 expect(status).toBe(200);
573 expect(body.ok).toBe(true);
574 expect(lastFolderIconAssignment).toEqual({ folderPath: rootDir, imagePath: imgPath });
575 });
576
577 test('POST /api/files/folder-icon rejects image without cached thumbnail', async () =>
578 {
579 const imgPath = path.join(rootDir, 'missing.jpg');
580 fs.writeFileSync(imgPath, 'img');
581 mockThumbPath = null;
582
583 const { status, body } = await req('POST', '/api/files/folder-icon', {
584 folderPath: rootDir,
585 imagePath: imgPath,
586 });
587 expect(status).toBe(404);
588 expect(body.error).toMatch(/thumbnail not ready/i);
589 });
590
591 test('POST /api/files/folder-icon clears assignment when imagePath is null', async () =>
592 {
593 const { status, body } = await req('POST', '/api/files/folder-icon', {
594 folderPath: rootDir,
595 imagePath: null,
596 });
597 expect(status).toBe(200);
598 expect(body.ok).toBe(true);
599 expect(lastFolderIconAssignment).toEqual({ folderPath: rootDir, imagePath: null });
600 });
601
602 test('POST /api/files/folder-icon returns 403 for read-only user', async () =>
603 {
604 const label = path.basename(rootDir);
605 mockUser = {
606 username: 'reader',
607 isAdmin: false,
608 permissions: { [label]: { read: true, write: false } },
609 };
610
611 const imgPath = path.join(rootDir, 'photo.jpg');
612 fs.writeFileSync(imgPath, 'img');
613
614 const { status } = await req('POST', '/api/files/folder-icon', {
615 folderPath: rootDir,
616 imagePath: imgPath,
617 });
618 expect(status).toBe(403);
619 });
620});
621
622// ---------------------------------------------------------------------------
623// GET /api/files/download-zip
624// ---------------------------------------------------------------------------
625describe('GET /api/files/download-zip', () =>
626{
627 beforeEach(() =>
628 {
629 mockUser = { username: 'admin', isAdmin: true, permissions: {} };
630 });
631
632 test('streams a valid zip for an accessible directory', async () =>
633 {
634 const subDir = path.join(rootDir, 'zipme');
635 fs.mkdirSync(subDir);
636 fs.writeFileSync(path.join(subDir, 'file.txt'), 'content');
637
638 const { status, headers, body: buf } = await reqRaw('GET', `/api/files/download-zip?dir=${encodeURIComponent(subDir)}`);
639 expect(status).toBe(200);
640
641 const ct = headers['content-type'] || '';
642 expect(ct.includes('zip') || ct.includes('octet')).toBe(true);
643
644 // ZIP magic bytes PK\x03\x04
645 expect(buf[0]).toBe(0x50);
646 expect(buf[1]).toBe(0x4b);
647 }, 20000);
648
649 test('returns 400 when dir param is missing', async () =>
650 {
651 const { status } = await req('GET', '/api/files/download-zip');
652 expect(status).toBe(400);
653 });
654
655 test('returns 404 for a non-existent directory', async () =>
656 {
657 const missing = path.join(rootDir, 'ghost');
658 const { status } = await req('GET', `/api/files/download-zip?dir=${encodeURIComponent(missing)}`);
659 expect(status).toBe(404);
660 });
661
662 test('returns 403 for path outside configured roots', async () =>
663 {
664 const { status } = await req('GET', `/api/files/download-zip?dir=${encodeURIComponent(os.tmpdir())}`);
665 expect(status).toBe(403);
666 });
667});