BlueGit

timfa filemanager

Files

filemanager / tests / files.routes.test.js

files.routes.test.js

files.routes.test.js 15.7 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
174describe('POST /api/files/move', () =>
175{
176 test('moves a file into another folder and rewrites metadata', async () =>
177 {
178 const from = path.join(rootDir, 'alpha.txt');
179 const toDir = path.join(rootDir, 'folder');
180 fs.writeFileSync(from, 'hello');
181 fs.mkdirSync(toDir);
182
183 getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders) VALUES (?, ?, ?)')
184 .run([from, 'admin', '["alice"]']);
185
186 const { status, body } = await req('POST', '/api/files/move', { from, toDir });
187
188 expect(status).toBe(200);
189 expect(body.ok).toBe(true);
190 expect(fs.existsSync(from)).toBe(false);
191 expect(fs.existsSync(path.join(toDir, 'alpha.txt'))).toBe(true);
192
193 const meta = getDb().prepare('SELECT * FROM file_meta WHERE file_path = ?').get([path.join(toDir, 'alpha.txt')]);
194 expect(meta).toMatchObject({ uploader: 'admin', downloaders: '["alice"]' });
195 });
196
197 test('moves a folder into another folder and rewrites descendant metadata', async () =>
198 {
199 const fromDir = path.join(rootDir, 'src-folder');
200 const nestedFile = path.join(fromDir, 'child.txt');
201 const toDir = path.join(rootDir, 'dest-folder');
202 fs.mkdirSync(fromDir);
203 fs.mkdirSync(toDir);
204 fs.writeFileSync(nestedFile, 'hello');
205
206 getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders) VALUES (?, ?, ?)')
207 .run([nestedFile, 'admin', '[]']);
208
209 const { status } = await req('POST', '/api/files/move', { from: fromDir, toDir });
210
211 expect(status).toBe(200);
212 expect(fs.existsSync(fromDir)).toBe(false);
213 expect(fs.existsSync(path.join(toDir, 'src-folder', 'child.txt'))).toBe(true);
214
215 const movedMeta = getDb().prepare('SELECT * FROM file_meta WHERE file_path = ?')
216 .get([path.join(toDir, 'src-folder', 'child.txt')]);
217 expect(movedMeta).toBeTruthy();
218 });
219
220 test('rejects moving a folder into itself', async () =>
221 {
222 const fromDir = path.join(rootDir, 'src-folder');
223 const childDir = path.join(fromDir, 'child');
224 fs.mkdirSync(childDir, { recursive: true });
225
226 const { status, body } = await req('POST', '/api/files/move', { from: fromDir, toDir: childDir });
227
228 expect(status).toBe(400);
229 expect(body.error).toMatch(/folder into itself/i);
230 });
231});
232
233describe('root alias endpoints', () =>
234{
235 test('GET /api/files/roots returns alias label and original name', async () =>
236 {
237 mockRootAliases = { [path.resolve(rootDir)]: 'Workspace' };
238
239 const { status, body } = await req('GET', '/api/files/roots');
240
241 expect(status).toBe(200);
242 expect(body.roots).toHaveLength(1);
243 expect(body.roots[0]).toMatchObject({
244 path: rootDir,
245 label: 'Workspace',
246 alias: 'Workspace',
247 originalName: path.basename(rootDir),
248 });
249 });
250
251 test('POST /api/files/root-alias stores alias without renaming filesystem path', async () =>
252 {
253 const originalBase = path.basename(rootDir);
254 const { status, body } = await req('POST', '/api/files/root-alias', {
255 rootPath: rootDir,
256 alias: 'Shared Files',
257 });
258
259 expect(status).toBe(200);
260 expect(body.ok).toBe(true);
261 expect(body.root).toMatchObject({
262 path: rootDir,
263 label: 'Shared Files',
264 alias: 'Shared Files',
265 originalName: originalBase,
266 });
267 expect(fs.existsSync(rootDir)).toBe(true);
268
269 const afterRoots = await req('GET', '/api/files/roots');
270 expect(afterRoots.status).toBe(200);
271 expect(afterRoots.body.roots[0].label).toBe('Shared Files');
272 expect(afterRoots.body.roots[0].originalName).toBe(originalBase);
273 });
274
275 test('POST /api/files/root-alias rejects non-root paths', async () =>
276 {
277 const nested = path.join(rootDir, 'sub');
278 fs.mkdirSync(nested, { recursive: true });
279
280 const { status } = await req('POST', '/api/files/root-alias', {
281 rootPath: nested,
282 alias: 'Nested',
283 });
284
285 expect(status).toBe(400);
286 });
287});
288
289describe('GET /api/files/thumbnail', () =>
290{
291 test('returns 404 while cached thumbnail is not ready', async () =>
292 {
293 const source = path.join(rootDir, 'photo.jpg');
294 fs.writeFileSync(source, 'not-an-image');
295
296 const { status, body } = await req('GET', `/api/files/thumbnail?file=${encodeURIComponent(source)}`);
297 expect(status).toBe(404);
298 expect(body.error).toMatch(/not ready/i);
299 });
300
301 test('serves cached thumbnail file when available', async () =>
302 {
303 const source = path.join(rootDir, 'photo.jpg');
304 const thumb = path.join(rootDir, 'photo-thumb.webp');
305 fs.writeFileSync(source, 'not-an-image');
306 fs.writeFileSync(thumb, 'webp-bytes');
307 mockThumbPath = thumb;
308
309 const response = await reqRaw('GET', `/api/files/thumbnail?file=${encodeURIComponent(source)}`);
310 expect(response.status).toBe(200);
311 expect(String(response.headers['content-type'] || '')).toContain('image/webp');
312 expect(response.body.toString('utf8')).toBe('webp-bytes');
313 });
314});
315
316describe('GET /api/files/root-access', () =>
317{
318 test('returns users with R/R+W modes for an exact root path', async () =>
319 {
320 const label = path.basename(rootDir);
321 const db = getDb();
322 db.prepare('INSERT INTO users (username, password_hash, is_admin, permissions) VALUES (?, ?, ?, ?)')
323 .run(['admin', 'x', 1, '{}']);
324 db.prepare('INSERT INTO users (username, password_hash, is_admin, permissions) VALUES (?, ?, ?, ?)')
325 .run(['alice', 'x', 0, JSON.stringify({ [label]: { read: true, write: false } })]);
326 db.prepare('INSERT INTO users (username, password_hash, is_admin, permissions) VALUES (?, ?, ?, ?)')
327 .run(['bob', 'x', 0, JSON.stringify({ [label]: { read: true, write: true } })]);
328 db.prepare('INSERT INTO users (username, password_hash, is_admin, permissions) VALUES (?, ?, ?, ?)')
329 .run(['charlie', 'x', 0, JSON.stringify({ other: { read: true, write: false } })]);
330
331 const { status, body } = await req('GET', `/api/files/root-access?rootPath=${encodeURIComponent(rootDir)}`);
332 expect(status).toBe(200);
333 expect(body.root).toMatchObject({ path: rootDir, originalName: label });
334 expect(body.users).toEqual([
335 { username: 'admin', mode: 'R+W' },
336 { username: 'bob', mode: 'R+W' },
337 { username: 'alice', mode: 'R' },
338 ]);
339 });
340
341 test('rejects non-exact nested root paths', async () =>
342 {
343 const nested = path.join(rootDir, 'sub');
344 fs.mkdirSync(nested, { recursive: true });
345
346 const { status } = await req('GET', `/api/files/root-access?rootPath=${encodeURIComponent(nested)}`);
347 expect(status).toBe(400);
348 });
349});
350
351describe('folder icon endpoints', () =>
352{
353 test('GET /api/files/folder-images returns images that have cached thumbnails', async () =>
354 {
355 const subDir = path.join(rootDir, 'photos');
356 fs.mkdirSync(subDir);
357 const imgPath = path.join(subDir, 'a.jpg');
358 fs.writeFileSync(imgPath, 'img');
359
360 mockFolderImages = [{ filePath: imgPath, thumbRelPath: 'thumbs/a.jpg.webp' }];
361
362 const { status, body } = await req('GET', `/api/files/folder-images?dir=${encodeURIComponent(rootDir)}`);
363 expect(status).toBe(200);
364 expect(body.images).toHaveLength(1);
365 expect(body.images[0].filePath).toBe(imgPath);
366 });
367
368 test('GET /api/files/folder-images returns empty list when no thumbnails available', async () =>
369 {
370 mockFolderImages = [];
371
372 const { status, body } = await req('GET', `/api/files/folder-images?dir=${encodeURIComponent(rootDir)}`);
373 expect(status).toBe(200);
374 expect(body.images).toEqual([]);
375 });
376
377 test('GET /api/files/folder-icon returns null when no icon available', async () =>
378 {
379 mockFolderIconFile = null;
380
381 const { status, body } = await req('GET', `/api/files/folder-icon?dir=${encodeURIComponent(rootDir)}`);
382 expect(status).toBe(200);
383 expect(body.icon).toBeNull();
384 });
385
386 test('GET /api/files/folder-icon returns source file path when icon is available', async () =>
387 {
388 const imgPath = path.join(rootDir, 'cover.jpg');
389 fs.writeFileSync(imgPath, 'img');
390 mockFolderIconFile = imgPath;
391
392 const { status, body } = await req('GET', `/api/files/folder-icon?dir=${encodeURIComponent(rootDir)}`);
393 expect(status).toBe(200);
394 expect(body.icon).toMatchObject({ filePath: imgPath });
395 });
396
397 test('POST /api/files/folder-icon sets explicit assignment when thumbnail is ready', async () =>
398 {
399 const imgPath = path.join(rootDir, 'cover.jpg');
400 const thumbFile = path.join(rootDir, 'cover.webp');
401 fs.writeFileSync(imgPath, 'img');
402 fs.writeFileSync(thumbFile, 'webp');
403 mockThumbPath = thumbFile;
404
405 const { status, body } = await req('POST', '/api/files/folder-icon', {
406 folderPath: rootDir,
407 imagePath: imgPath,
408 });
409 expect(status).toBe(200);
410 expect(body.ok).toBe(true);
411 expect(lastFolderIconAssignment).toEqual({ folderPath: rootDir, imagePath: imgPath });
412 });
413
414 test('POST /api/files/folder-icon rejects image without cached thumbnail', async () =>
415 {
416 const imgPath = path.join(rootDir, 'missing.jpg');
417 fs.writeFileSync(imgPath, 'img');
418 mockThumbPath = null;
419
420 const { status, body } = await req('POST', '/api/files/folder-icon', {
421 folderPath: rootDir,
422 imagePath: imgPath,
423 });
424 expect(status).toBe(404);
425 expect(body.error).toMatch(/thumbnail not ready/i);
426 });
427
428 test('POST /api/files/folder-icon clears assignment when imagePath is null', async () =>
429 {
430 const { status, body } = await req('POST', '/api/files/folder-icon', {
431 folderPath: rootDir,
432 imagePath: null,
433 });
434 expect(status).toBe(200);
435 expect(body.ok).toBe(true);
436 expect(lastFolderIconAssignment).toEqual({ folderPath: rootDir, imagePath: null });
437 });
438
439 test('POST /api/files/folder-icon returns 403 for read-only user', async () =>
440 {
441 const label = path.basename(rootDir);
442 mockUser = {
443 username: 'reader',
444 isAdmin: false,
445 permissions: { [label]: { read: true, write: false } },
446 };
447
448 const imgPath = path.join(rootDir, 'photo.jpg');
449 fs.writeFileSync(imgPath, 'img');
450
451 const { status } = await req('POST', '/api/files/folder-icon', {
452 folderPath: rootDir,
453 imagePath: imgPath,
454 });
455 expect(status).toBe(403);
456 });
457});