BlueGit

timfa filemanager

Files

filemanager / tests / files.routes.test.js

files.routes.test.js

files.routes.test.js 9.3 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;
14
15jest.mock('../server/db', () =>
16{
17 const { Database } = require('node-sqlite3-wasm');
18 let db;
19 function getDb ()
20 {
21 if (!db)
22 {
23 db = new Database(':memory:');
24 db.exec(`
25 CREATE TABLE IF NOT EXISTS file_meta (
26 file_path TEXT PRIMARY KEY,
27 uploader TEXT NOT NULL DEFAULT '',
28 downloaders TEXT NOT NULL DEFAULT '[]'
29 );
30 `);
31 }
32 return db;
33 }
34 return { getDb, initDb: getDb };
35});
36
37jest.mock('../server/config', () => ({
38 loadConfig: () => ({ port: 3000, paths: [...mockPaths], rootAliases: { ...mockRootAliases } }),
39 saveConfig: (config) =>
40 {
41 mockPaths = [...(config.paths || [])];
42 mockRootAliases = { ...(config.rootAliases || {}) };
43 },
44 getEffectivePaths: (paths) => paths,
45 getAllowedRoot: (targetPath, roots) =>
46 {
47 const path = require('path');
48 const absTarget = path.resolve(String(targetPath || ''));
49 return roots.find((root) =>
50 {
51 const absRoot = path.resolve(root);
52 return absTarget === absRoot || absTarget.startsWith(absRoot + path.sep);
53 }) || null;
54 },
55}));
56
57jest.mock('../server/auth', () => ({
58 requireAuth: (req, res, next) => { req.user = mockUser; next(); },
59}));
60
61jest.mock('../server/thumbnail-cache', () => ({
62 getCachedThumbnailInfo: async () =>
63 {
64 if (!mockThumbPath) return null;
65 return { thumbPath: mockThumbPath, contentType: 'image/webp' };
66 },
67}));
68
69const filesRoutes = require('../server/routes/files');
70const { getDb } = require('../server/db');
71
72let server;
73let baseUrl;
74let rootDir;
75
76beforeAll(async () =>
77{
78 rootDir = fs.mkdtempSync(path.join(os.tmpdir(), 'filemanager-files-routes-'));
79 mockPaths = [rootDir];
80
81 const app = express();
82 app.use(express.json());
83 app.use('/api/files', filesRoutes);
84 app.use((err, req, res, next) =>
85 {
86 res.status(err.status || 500).json({ error: err.message || 'Internal error' });
87 });
88
89 server = http.createServer(app);
90 server.listen(0);
91 await once(server, 'listening');
92 baseUrl = `http://127.0.0.1:${server.address().port}`;
93});
94
95afterAll(() =>
96{
97 server.close();
98 fs.rmSync(rootDir, { recursive: true, force: true });
99});
100
101beforeEach(() =>
102{
103 fs.rmSync(rootDir, { recursive: true, force: true });
104 fs.mkdirSync(rootDir, { recursive: true });
105 mockRootAliases = {};
106 mockUser = { username: 'admin', isAdmin: true, permissions: {} };
107 mockThumbPath = null;
108 const db = getDb();
109 db.prepare('DELETE FROM file_meta').run([]);
110});
111
112function req (method, routePath, body)
113{
114 const payload = body ? JSON.stringify(body) : undefined;
115 return new Promise((resolve, reject) =>
116 {
117 const request = http.request(baseUrl + routePath, {
118 method,
119 headers: {
120 'Content-Type': 'application/json',
121 ...(payload ? { 'Content-Length': Buffer.byteLength(payload) } : {}),
122 },
123 }, res =>
124 {
125 let data = '';
126 res.on('data', chunk => data += chunk);
127 res.on('end', () => resolve({ status: res.statusCode, body: JSON.parse(data) }));
128 });
129 request.on('error', reject);
130 if (payload) request.write(payload);
131 request.end();
132 });
133}
134
135function reqRaw (method, routePath)
136{
137 return new Promise((resolve, reject) =>
138 {
139 const request = http.request(baseUrl + routePath, { method }, res =>
140 {
141 const chunks = [];
142 res.on('data', chunk => chunks.push(Buffer.from(chunk)));
143 res.on('end', () => resolve({
144 status: res.statusCode,
145 headers: res.headers,
146 body: Buffer.concat(chunks),
147 }));
148 });
149 request.on('error', reject);
150 request.end();
151 });
152}
153
154describe('POST /api/files/move', () =>
155{
156 test('moves a file into another folder and rewrites metadata', async () =>
157 {
158 const from = path.join(rootDir, 'alpha.txt');
159 const toDir = path.join(rootDir, 'folder');
160 fs.writeFileSync(from, 'hello');
161 fs.mkdirSync(toDir);
162
163 getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders) VALUES (?, ?, ?)')
164 .run([from, 'admin', '["alice"]']);
165
166 const { status, body } = await req('POST', '/api/files/move', { from, toDir });
167
168 expect(status).toBe(200);
169 expect(body.ok).toBe(true);
170 expect(fs.existsSync(from)).toBe(false);
171 expect(fs.existsSync(path.join(toDir, 'alpha.txt'))).toBe(true);
172
173 const meta = getDb().prepare('SELECT * FROM file_meta WHERE file_path = ?').get([path.join(toDir, 'alpha.txt')]);
174 expect(meta).toMatchObject({ uploader: 'admin', downloaders: '["alice"]' });
175 });
176
177 test('moves a folder into another folder and rewrites descendant metadata', async () =>
178 {
179 const fromDir = path.join(rootDir, 'src-folder');
180 const nestedFile = path.join(fromDir, 'child.txt');
181 const toDir = path.join(rootDir, 'dest-folder');
182 fs.mkdirSync(fromDir);
183 fs.mkdirSync(toDir);
184 fs.writeFileSync(nestedFile, 'hello');
185
186 getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders) VALUES (?, ?, ?)')
187 .run([nestedFile, 'admin', '[]']);
188
189 const { status } = await req('POST', '/api/files/move', { from: fromDir, toDir });
190
191 expect(status).toBe(200);
192 expect(fs.existsSync(fromDir)).toBe(false);
193 expect(fs.existsSync(path.join(toDir, 'src-folder', 'child.txt'))).toBe(true);
194
195 const movedMeta = getDb().prepare('SELECT * FROM file_meta WHERE file_path = ?')
196 .get([path.join(toDir, 'src-folder', 'child.txt')]);
197 expect(movedMeta).toBeTruthy();
198 });
199
200 test('rejects moving a folder into itself', async () =>
201 {
202 const fromDir = path.join(rootDir, 'src-folder');
203 const childDir = path.join(fromDir, 'child');
204 fs.mkdirSync(childDir, { recursive: true });
205
206 const { status, body } = await req('POST', '/api/files/move', { from: fromDir, toDir: childDir });
207
208 expect(status).toBe(400);
209 expect(body.error).toMatch(/folder into itself/i);
210 });
211});
212
213describe('root alias endpoints', () =>
214{
215 test('GET /api/files/roots returns alias label and original name', async () =>
216 {
217 mockRootAliases = { [path.resolve(rootDir)]: 'Workspace' };
218
219 const { status, body } = await req('GET', '/api/files/roots');
220
221 expect(status).toBe(200);
222 expect(body.roots).toHaveLength(1);
223 expect(body.roots[0]).toMatchObject({
224 path: rootDir,
225 label: 'Workspace',
226 alias: 'Workspace',
227 originalName: path.basename(rootDir),
228 });
229 });
230
231 test('POST /api/files/root-alias stores alias without renaming filesystem path', async () =>
232 {
233 const originalBase = path.basename(rootDir);
234 const { status, body } = await req('POST', '/api/files/root-alias', {
235 rootPath: rootDir,
236 alias: 'Shared Files',
237 });
238
239 expect(status).toBe(200);
240 expect(body.ok).toBe(true);
241 expect(body.root).toMatchObject({
242 path: rootDir,
243 label: 'Shared Files',
244 alias: 'Shared Files',
245 originalName: originalBase,
246 });
247 expect(fs.existsSync(rootDir)).toBe(true);
248
249 const afterRoots = await req('GET', '/api/files/roots');
250 expect(afterRoots.status).toBe(200);
251 expect(afterRoots.body.roots[0].label).toBe('Shared Files');
252 expect(afterRoots.body.roots[0].originalName).toBe(originalBase);
253 });
254
255 test('POST /api/files/root-alias rejects non-root paths', async () =>
256 {
257 const nested = path.join(rootDir, 'sub');
258 fs.mkdirSync(nested, { recursive: true });
259
260 const { status } = await req('POST', '/api/files/root-alias', {
261 rootPath: nested,
262 alias: 'Nested',
263 });
264
265 expect(status).toBe(400);
266 });
267});
268
269describe('GET /api/files/thumbnail', () =>
270{
271 test('returns 404 while cached thumbnail is not ready', async () =>
272 {
273 const source = path.join(rootDir, 'photo.jpg');
274 fs.writeFileSync(source, 'not-an-image');
275
276 const { status, body } = await req('GET', `/api/files/thumbnail?file=${encodeURIComponent(source)}`);
277 expect(status).toBe(404);
278 expect(body.error).toMatch(/not ready/i);
279 });
280
281 test('serves cached thumbnail file when available', async () =>
282 {
283 const source = path.join(rootDir, 'photo.jpg');
284 const thumb = path.join(rootDir, 'photo-thumb.webp');
285 fs.writeFileSync(source, 'not-an-image');
286 fs.writeFileSync(thumb, 'webp-bytes');
287 mockThumbPath = thumb;
288
289 const response = await reqRaw('GET', `/api/files/thumbnail?file=${encodeURIComponent(source)}`);
290 expect(response.status).toBe(200);
291 expect(String(response.headers['content-type'] || '')).toContain('image/webp');
292 expect(response.body.toString('utf8')).toBe('webp-bytes');
293 });
294});