BlueGit

timfa filemanager

Files

filemanager / tests / share.routes.test.js

share.routes.test.js

share.routes.test.js 10.5 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 mockUser = { username: 'testuser', isAdmin: true, permissions: {} };
12
13jest.mock('../server/db', () =>
14{
15 const { Database } = require('node-sqlite3-wasm');
16 let db;
17 function getDb ()
18 {
19 if (!db)
20 {
21 db = new Database(':memory:');
22 db.exec(`
23 CREATE TABLE IF NOT EXISTS share_tokens (
24 token TEXT PRIMARY KEY,
25 file_path TEXT NOT NULL,
26 is_dir INTEGER NOT NULL DEFAULT 0,
27 created_by TEXT NOT NULL,
28 created_at INTEGER NOT NULL,
29 expires_at INTEGER NOT NULL
30 );
31 `);
32 }
33 return db;
34 }
35 return { getDb, initDb: getDb };
36});
37
38jest.mock('../server/config', () => ({
39 loadConfig: () => ({ port: 3000, paths: [...mockPaths], rootAliases: {} }),
40 saveConfig: jest.fn(),
41 getEffectivePaths: (paths) => paths,
42 getAllowedRoot: (targetPath, roots) =>
43 {
44 const pathMod = require('path');
45 const absTarget = pathMod.resolve(String(targetPath || ''));
46 return roots.find((root) =>
47 {
48 const absRoot = pathMod.resolve(root);
49 return absTarget === absRoot || absTarget.startsWith(absRoot + pathMod.sep);
50 }) || null;
51 },
52}));
53
54jest.mock('../server/auth', () => ({
55 requireAuth: (req, res, next) => { req.user = mockUser; next(); },
56}));
57
58const shareRoutes = require('../server/routes/share');
59const { getDb } = require('../server/db');
60
61let server;
62let baseUrl;
63let rootDir;
64
65function get (p) { return fetch(baseUrl + p); }
66function post (p, body) {
67 return fetch(baseUrl + p, {
68 method: 'POST',
69 headers: { 'Content-Type': 'application/json' },
70 body: JSON.stringify(body),
71 });
72}
73
74beforeAll(async () =>
75{
76 rootDir = fs.mkdtempSync(path.join(os.tmpdir(), 'filemanager-share-test-'));
77 mockPaths = [rootDir];
78
79 const app = express();
80 app.use(express.json());
81 app.use('/api/share', shareRoutes);
82 app.use((err, req, res, _next) =>
83 {
84 res.status(err.status || 500).json({ error: err.message || 'Internal error' });
85 });
86
87 server = http.createServer(app);
88 server.listen(0);
89 await once(server, 'listening');
90 baseUrl = `http://127.0.0.1:${server.address().port}`;
91});
92
93afterAll(() =>
94{
95 server.close();
96 fs.rmSync(rootDir, { recursive: true, force: true });
97});
98
99beforeEach(() =>
100{
101 fs.rmSync(rootDir, { recursive: true, force: true });
102 fs.mkdirSync(rootDir, { recursive: true });
103 // Reset DB between tests
104 const db = getDb();
105 db.exec('DELETE FROM share_tokens');
106});
107
108// ---------------------------------------------------------------------------
109// POST /api/share/create
110// ---------------------------------------------------------------------------
111describe('POST /api/share/create', () =>
112{
113 test('creates a token for a file', async () =>
114 {
115 const filePath = path.join(rootDir, 'hello.txt');
116 fs.writeFileSync(filePath, 'hello');
117
118 const res = await post('/api/share/create', { filePath });
119 expect(res.status).toBe(200);
120 const body = await res.json();
121 expect(typeof body.token).toBe('string');
122 expect(body.token).toHaveLength(64); // 32 bytes hex
123 expect(typeof body.expiresAt).toBe('number');
124 expect(body.expiresAt).toBeGreaterThan(Date.now());
125 });
126
127 test('creates a token for a directory', async () =>
128 {
129 const dirPath = path.join(rootDir, 'subdir');
130 fs.mkdirSync(dirPath);
131
132 const res = await post('/api/share/create', { filePath: dirPath });
133 expect(res.status).toBe(200);
134 const body = await res.json();
135 expect(typeof body.token).toBe('string');
136 });
137
138 test('returns 400 when filePath is missing', async () =>
139 {
140 const res = await post('/api/share/create', {});
141 expect(res.status).toBe(400);
142 });
143
144 test('returns 403 when path is outside configured roots', async () =>
145 {
146 const res = await post('/api/share/create', { filePath: os.tmpdir() });
147 expect(res.status).toBe(403);
148 });
149
150 test('returns 404 when file does not exist', async () =>
151 {
152 const res = await post('/api/share/create', { filePath: path.join(rootDir, 'missing.txt') });
153 expect(res.status).toBe(404);
154 });
155});
156
157// ---------------------------------------------------------------------------
158// GET /api/share/info/:token
159// ---------------------------------------------------------------------------
160describe('GET /api/share/info/:token', () =>
161{
162 function insertToken ({ token, filePath, isDir = 0, expiresAt = Date.now() + 86400000 })
163 {
164 getDb().prepare(
165 'INSERT INTO share_tokens (token, file_path, is_dir, created_by, created_at, expires_at) VALUES (?,?,?,?,?,?)',
166 ).run([token, filePath, isDir, 'testuser', Date.now(), expiresAt]);
167 }
168
169 test('returns file info for a valid token', async () =>
170 {
171 const filePath = path.join(rootDir, 'info.txt');
172 fs.writeFileSync(filePath, 'data');
173 insertToken({ token: 'aaaa', filePath });
174
175 const res = await get('/api/share/info/aaaa');
176 expect(res.status).toBe(200);
177 const body = await res.json();
178 expect(body.name).toBe('info.txt');
179 expect(body.isDir).toBe(false);
180 expect(typeof body.expiresAt).toBe('number');
181 });
182
183 test('returns isDir=true for directory tokens', async () =>
184 {
185 const dirPath = path.join(rootDir, 'mydir');
186 fs.mkdirSync(dirPath);
187 insertToken({ token: 'bbbb', filePath: dirPath, isDir: 1 });
188
189 const res = await get('/api/share/info/bbbb');
190 expect(res.status).toBe(200);
191 const body = await res.json();
192 expect(body.isDir).toBe(true);
193 });
194
195 test('returns 404 for unknown token', async () =>
196 {
197 const res = await get('/api/share/info/unknowntoken');
198 expect(res.status).toBe(404);
199 });
200
201 test('returns 410 for expired token', async () =>
202 {
203 const filePath = path.join(rootDir, 'exp.txt');
204 fs.writeFileSync(filePath, 'x');
205 insertToken({ token: 'cccc', filePath, expiresAt: Date.now() - 1000 });
206
207 const res = await get('/api/share/info/cccc');
208 expect(res.status).toBe(410);
209 });
210});
211
212// ---------------------------------------------------------------------------
213// GET /api/share/preview/:token
214// ---------------------------------------------------------------------------
215describe('GET /api/share/preview/:token', () =>
216{
217 function insertToken ({ token, filePath, isDir = 0, expiresAt = Date.now() + 86400000 })
218 {
219 getDb().prepare(
220 'INSERT INTO share_tokens (token, file_path, is_dir, created_by, created_at, expires_at) VALUES (?,?,?,?,?,?)',
221 ).run([token, filePath, isDir, 'testuser', Date.now(), expiresAt]);
222 }
223
224 test('streams file content for a valid file token', async () =>
225 {
226 const filePath = path.join(rootDir, 'preview.txt');
227 fs.writeFileSync(filePath, 'preview content');
228 insertToken({ token: 'prev1', filePath });
229
230 const res = await get('/api/share/preview/prev1');
231 expect(res.status).toBe(200);
232 const text = await res.text();
233 expect(text).toBe('preview content');
234 });
235
236 test('returns 400 when token points to a directory', async () =>
237 {
238 const dirPath = path.join(rootDir, 'previewdir');
239 fs.mkdirSync(dirPath);
240 insertToken({ token: 'prev2', filePath: dirPath, isDir: 1 });
241
242 const res = await get('/api/share/preview/prev2');
243 expect(res.status).toBe(400);
244 });
245
246 test('returns 410 for expired token', async () =>
247 {
248 const filePath = path.join(rootDir, 'ep.txt');
249 fs.writeFileSync(filePath, 'x');
250 insertToken({ token: 'prev3', filePath, expiresAt: Date.now() - 1 });
251
252 const res = await get('/api/share/preview/prev3');
253 expect(res.status).toBe(410);
254 });
255});
256
257// ---------------------------------------------------------------------------
258// GET /api/share/download/:token
259// ---------------------------------------------------------------------------
260describe('GET /api/share/download/:token', () =>
261{
262 function insertToken ({ token, filePath, isDir = 0, expiresAt = Date.now() + 86400000 })
263 {
264 getDb().prepare(
265 'INSERT INTO share_tokens (token, file_path, is_dir, created_by, created_at, expires_at) VALUES (?,?,?,?,?,?)',
266 ).run([token, filePath, isDir, 'testuser', Date.now(), expiresAt]);
267 }
268
269 test('downloads a file', async () =>
270 {
271 const filePath = path.join(rootDir, 'dl.txt');
272 fs.writeFileSync(filePath, 'download me');
273 insertToken({ token: 'dl01', filePath });
274
275 const res = await get('/api/share/download/dl01');
276 expect(res.status).toBe(200);
277 const text = await res.text();
278 expect(text).toBe('download me');
279 });
280
281 test('downloads a directory as zip', async () =>
282 {
283 const dirPath = path.join(rootDir, 'zipit');
284 fs.mkdirSync(dirPath);
285 fs.writeFileSync(path.join(dirPath, 'a.txt'), 'aaa');
286 insertToken({ token: 'dl02', filePath: dirPath, isDir: 1 });
287
288 const res = await get('/api/share/download/dl02');
289 expect(res.status).toBe(200);
290 const ct = res.headers.get('content-type') || '';
291 // Express sends application/zip or application/octet-stream for .zip downloads
292 expect(ct.includes('zip') || ct.includes('octet')).toBe(true);
293 const buf = await res.arrayBuffer();
294 // ZIP magic bytes: PK\x03\x04
295 expect(new Uint8Array(buf.slice(0, 4))).toEqual(new Uint8Array([0x50, 0x4b, 0x03, 0x04]));
296 });
297
298 test('returns 410 for expired token', async () =>
299 {
300 const filePath = path.join(rootDir, 'edl.txt');
301 fs.writeFileSync(filePath, 'x');
302 insertToken({ token: 'dl03', filePath, expiresAt: Date.now() - 1 });
303
304 const res = await get('/api/share/download/dl03');
305 expect(res.status).toBe(410);
306 });
307
308 test('returns 404 for unknown token', async () =>
309 {
310 const res = await get('/api/share/download/nosuchtoken');
311 expect(res.status).toBe(404);
312 });
313});
314
315// ---------------------------------------------------------------------------
316// pruneZipCache
317// ---------------------------------------------------------------------------
318describe('pruneZipCache', () =>
319{
320 test('deletes zip files older than 1 day', () =>
321 {
322 const { pruneZipCache, ZIP_CACHE_DIR } = require('../server/routes/share');
323 fs.mkdirSync(ZIP_CACHE_DIR, { recursive: true });
324
325 const oldZip = path.join(ZIP_CACHE_DIR, 'old.zip');
326 fs.writeFileSync(oldZip, 'fake zip');
327 // Back-date the mtime by 25 hours
328 const pastTime = new Date(Date.now() - 25 * 60 * 60 * 1000);
329 fs.utimesSync(oldZip, pastTime, pastTime);
330
331 const freshZip = path.join(ZIP_CACHE_DIR, 'fresh.zip');
332 fs.writeFileSync(freshZip, 'fake fresh zip');
333
334 pruneZipCache();
335
336 expect(fs.existsSync(oldZip)).toBe(false);
337 expect(fs.existsSync(freshZip)).toBe(true);
338
339 // Cleanup
340 try { fs.unlinkSync(freshZip); } catch { /* ignore */ }
341 });
342});