BlueGit

timfa filemanager

Files

filemanager / tests / share.routes.test.js

share.routes.test.js

Fix My Folder access paths
timfa Tim Falken · pushed by timfa · 6 months ago
7c87f490 History
share.routes.test.js 17.8 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 mockUserPath = null;
12let mockUser = { username: 'testuser', isAdmin: true, permissions: {} };
13let mockVideoStreamSession = null;
14let mockVideoStreamAsset = null;
15
16jest.mock('../server/db', () =>
17{
18 const { Database } = require('node-sqlite3-wasm');
19 let db;
20 function getDb ()
21 {
22 if (!db)
23 {
24 db = new Database(':memory:');
25 db.exec(`
26 CREATE TABLE IF NOT EXISTS share_tokens (
27 token TEXT PRIMARY KEY,
28 file_path TEXT NOT NULL,
29 is_dir INTEGER NOT NULL DEFAULT 0,
30 created_by TEXT NOT NULL,
31 created_at INTEGER NOT NULL,
32 expires_at INTEGER NOT NULL
33 );
34 `);
35 }
36 return db;
37 }
38 return { getDb, initDb: getDb };
39});
40
41jest.mock('../server/config', () => ({
42 loadConfig: () => ({ port: 3000, paths: [...mockPaths], userPath: mockUserPath, rootAliases: {} }),
43 saveConfig: jest.fn(),
44 getEffectivePaths: (paths) => paths,
45 getAllowedRoot: (targetPath, roots) =>
46 {
47 const pathMod = require('path');
48 const absTarget = pathMod.resolve(String(targetPath || ''));
49 return roots.find((root) =>
50 {
51 const absRoot = pathMod.resolve(root);
52 return absTarget === absRoot || absTarget.startsWith(absRoot + pathMod.sep);
53 }) || null;
54 },
55}));
56
57jest.mock('../server/auth', () => ({
58 requireAuth: (req, res, next) => { req.user = mockUser; next(); },
59}));
60
61jest.mock('../server/video-stream', () => ({
62 createVideoStreamSession: jest.fn(async () =>
63 {
64 if (mockVideoStreamSession instanceof Error) throw mockVideoStreamSession;
65 return mockVideoStreamSession || { sessionId: 'share-video-session', subtitleTracks: [] };
66 }),
67 sendVideoStreamAsset: jest.fn(async (sessionId, assetPath, req, res) =>
68 {
69 if (typeof mockVideoStreamAsset === 'function')
70 {
71 await mockVideoStreamAsset(sessionId, assetPath, req, res);
72 return;
73 }
74 res.type('application/vnd.apple.mpegurl').send('#EXTM3U\n');
75 }),
76}));
77
78const shareRoutes = require('../server/routes/share');
79const { getDb } = require('../server/db');
80
81let server;
82let baseUrl;
83let rootDir;
84
85function get (p) { return fetch(baseUrl + p); }
86function post (p, body) {
87 return fetch(baseUrl + p, {
88 method: 'POST',
89 headers: { 'Content-Type': 'application/json' },
90 body: JSON.stringify(body),
91 });
92}
93
94beforeAll(async () =>
95{
96 rootDir = fs.mkdtempSync(path.join(os.tmpdir(), 'filemanager-share-test-'));
97 mockPaths = [rootDir];
98
99 const app = express();
100 app.use(express.json());
101 app.use('/api/share', shareRoutes);
102 app.use((err, req, res, _next) =>
103 {
104 res.status(err.status || 500).json({ error: err.message || 'Internal error' });
105 });
106
107 server = http.createServer(app);
108 server.listen(0);
109 await once(server, 'listening');
110 baseUrl = `http://127.0.0.1:${server.address().port}`;
111});
112
113afterAll(() =>
114{
115 server.close();
116 fs.rmSync(rootDir, { recursive: true, force: true });
117});
118
119beforeEach(() =>
120{
121 fs.rmSync(rootDir, { recursive: true, force: true });
122 fs.mkdirSync(rootDir, { recursive: true });
123 if (mockUserPath)
124 {
125 fs.rmSync(mockUserPath, { recursive: true, force: true });
126 fs.mkdirSync(mockUserPath, { recursive: true });
127 }
128 mockUserPath = null;
129 mockVideoStreamSession = null;
130 mockVideoStreamAsset = null;
131 // Reset DB between tests
132 const db = getDb();
133 db.exec('DELETE FROM share_tokens');
134});
135
136// ---------------------------------------------------------------------------
137// POST /api/share/create
138// ---------------------------------------------------------------------------
139describe('POST /api/share/create', () =>
140{
141 test('creates a token for a file', async () =>
142 {
143 const filePath = path.join(rootDir, 'hello.txt');
144 fs.writeFileSync(filePath, 'hello');
145
146 const res = await post('/api/share/create', { filePath });
147 expect(res.status).toBe(200);
148 const body = await res.json();
149 expect(typeof body.token).toBe('string');
150 expect(body.token).toHaveLength(64); // 32 bytes hex
151 expect(typeof body.expiresAt).toBe('number');
152 expect(body.expiresAt).toBeGreaterThan(Date.now());
153 });
154
155 test('creates a token for a directory', async () =>
156 {
157 const dirPath = path.join(rootDir, 'subdir');
158 fs.mkdirSync(dirPath);
159
160 const res = await post('/api/share/create', { filePath: dirPath });
161 expect(res.status).toBe(200);
162 const body = await res.json();
163 expect(typeof body.token).toBe('string');
164 });
165
166 test('returns 400 when filePath is missing', async () =>
167 {
168 const res = await post('/api/share/create', {});
169 expect(res.status).toBe(400);
170 });
171
172 test('returns 403 when path is outside configured roots', async () =>
173 {
174 const res = await post('/api/share/create', { filePath: os.tmpdir() });
175 expect(res.status).toBe(403);
176 });
177
178 test('returns 404 when file does not exist', async () =>
179 {
180 const res = await post('/api/share/create', { filePath: path.join(rootDir, 'missing.txt') });
181 expect(res.status).toBe(404);
182 });
183
184 test('creates a token for a file inside My Folder', async () =>
185 {
186 const userFolderBase = fs.mkdtempSync(path.join(os.tmpdir(), 'filemanager-share-userfolders-'));
187 const userFolder = path.join(userFolderBase, 'testuser');
188 const filePath = path.join(userFolder, 'private.txt');
189
190 mockUserPath = userFolderBase;
191 mockUser = { username: 'testuser', isAdmin: false, permissions: {} };
192 fs.mkdirSync(userFolder, { recursive: true });
193 fs.writeFileSync(filePath, 'private');
194
195 try
196 {
197 const res = await post('/api/share/create', { filePath });
198 expect(res.status).toBe(200);
199 const body = await res.json();
200 expect(typeof body.token).toBe('string');
201 } finally
202 {
203 fs.rmSync(userFolderBase, { recursive: true, force: true });
204 }
205 });
206});
207
208// ---------------------------------------------------------------------------
209// GET /api/share/info/:token
210// ---------------------------------------------------------------------------
211describe('GET /api/share/info/:token', () =>
212{
213 function insertToken ({ token, filePath, isDir = 0, expiresAt = Date.now() + 86400000 })
214 {
215 getDb().prepare(
216 'INSERT INTO share_tokens (token, file_path, is_dir, created_by, created_at, expires_at) VALUES (?,?,?,?,?,?)',
217 ).run([token, filePath, isDir, 'testuser', Date.now(), expiresAt]);
218 }
219
220 test('returns file info for a valid token', async () =>
221 {
222 const filePath = path.join(rootDir, 'info.txt');
223 fs.writeFileSync(filePath, 'data');
224 insertToken({ token: 'aaaa', filePath });
225
226 const res = await get('/api/share/info/aaaa');
227 expect(res.status).toBe(200);
228 const body = await res.json();
229 expect(body.name).toBe('info.txt');
230 expect(body.isDir).toBe(false);
231 expect(typeof body.expiresAt).toBe('number');
232 });
233
234 test('returns isDir=true for directory tokens', async () =>
235 {
236 const dirPath = path.join(rootDir, 'mydir');
237 fs.mkdirSync(dirPath);
238 insertToken({ token: 'bbbb', filePath: dirPath, isDir: 1 });
239
240 const res = await get('/api/share/info/bbbb');
241 expect(res.status).toBe(200);
242 const body = await res.json();
243 expect(body.isDir).toBe(true);
244 });
245
246 test('returns 404 for unknown token', async () =>
247 {
248 const res = await get('/api/share/info/unknowntoken');
249 expect(res.status).toBe(404);
250 });
251
252 test('returns 410 for expired token', async () =>
253 {
254 const filePath = path.join(rootDir, 'exp.txt');
255 fs.writeFileSync(filePath, 'x');
256 insertToken({ token: 'cccc', filePath, expiresAt: Date.now() - 1000 });
257
258 const res = await get('/api/share/info/cccc');
259 expect(res.status).toBe(410);
260 });
261});
262
263// ---------------------------------------------------------------------------
264// GET /api/share/preview/:token
265// ---------------------------------------------------------------------------
266describe('GET /api/share/preview/:token', () =>
267{
268 function insertToken ({ token, filePath, isDir = 0, expiresAt = Date.now() + 86400000 })
269 {
270 getDb().prepare(
271 'INSERT INTO share_tokens (token, file_path, is_dir, created_by, created_at, expires_at) VALUES (?,?,?,?,?,?)',
272 ).run([token, filePath, isDir, 'testuser', Date.now(), expiresAt]);
273 }
274
275 test('streams file content for a valid file token', async () =>
276 {
277 const filePath = path.join(rootDir, 'preview.txt');
278 fs.writeFileSync(filePath, 'preview content');
279 insertToken({ token: 'prev1', filePath });
280
281 const res = await get('/api/share/preview/prev1');
282 expect(res.status).toBe(200);
283 const text = await res.text();
284 expect(text).toBe('preview content');
285 });
286
287 test('returns 400 when token points to a directory', async () =>
288 {
289 const dirPath = path.join(rootDir, 'previewdir');
290 fs.mkdirSync(dirPath);
291 insertToken({ token: 'prev2', filePath: dirPath, isDir: 1 });
292
293 const res = await get('/api/share/preview/prev2');
294 expect(res.status).toBe(400);
295 });
296
297 test('returns 410 for expired token', async () =>
298 {
299 const filePath = path.join(rootDir, 'ep.txt');
300 fs.writeFileSync(filePath, 'x');
301 insertToken({ token: 'prev3', filePath, expiresAt: Date.now() - 1 });
302
303 const res = await get('/api/share/preview/prev3');
304 expect(res.status).toBe(410);
305 });
306});
307
308describe('GET /api/share/video-stream/:token', () =>
309{
310 function insertToken ({ token, filePath, isDir = 0, expiresAt = Date.now() + 86400000 })
311 {
312 getDb().prepare(
313 'INSERT INTO share_tokens (token, file_path, is_dir, created_by, created_at, expires_at) VALUES (?,?,?,?,?,?)',
314 ).run([token, filePath, isDir, 'testuser', Date.now(), expiresAt]);
315 }
316
317 test('creates a stream session for a shared video', async () =>
318 {
319 const filePath = path.join(rootDir, 'movie.mkv');
320 fs.writeFileSync(filePath, 'video');
321 insertToken({ token: 'stream1', filePath });
322 mockVideoStreamSession = {
323 sessionId: 'share-sess-1',
324 durationSeconds: 42.25,
325 subtitleTracks: [{ fileName: 'subtitle-0.vtt', label: 'English', language: 'eng', isDefault: true }],
326 };
327
328 const res = await get('/api/share/video-stream/stream1');
329 expect(res.status).toBe(200);
330 const body = await res.json();
331 expect(body.playlistUrl).toBe('/api/share/video-stream/session/share-sess-1/master.m3u8');
332 expect(body.durationSeconds).toBe(42.25);
333 expect(body.subtitleTracks).toEqual([
334 {
335 label: 'English',
336 language: 'eng',
337 default: true,
338 src: '/api/share/video-stream/session/share-sess-1/subtitle-0.vtt',
339 },
340 ]);
341 });
342
343 test('serves stream assets from an existing share session', async () =>
344 {
345 mockVideoStreamAsset = async (_sessionId, _assetPath, _req, res) =>
346 {
347 res.type('application/vnd.apple.mpegurl').send('#EXTM3U\n');
348 };
349
350 const res = await get('/api/share/video-stream/session/share-sess-1/master.m3u8');
351 expect(res.status).toBe(200);
352 expect(await res.text()).toBe('#EXTM3U\n');
353 });
354});
355
356// ---------------------------------------------------------------------------
357// GET /api/share/download/:token
358// ---------------------------------------------------------------------------
359describe('GET /api/share/download/:token', () =>
360{
361 function insertToken ({ token, filePath, isDir = 0, expiresAt = Date.now() + 86400000 })
362 {
363 getDb().prepare(
364 'INSERT INTO share_tokens (token, file_path, is_dir, created_by, created_at, expires_at) VALUES (?,?,?,?,?,?)',
365 ).run([token, filePath, isDir, 'testuser', Date.now(), expiresAt]);
366 }
367
368 test('downloads a file', async () =>
369 {
370 const filePath = path.join(rootDir, 'dl.txt');
371 fs.writeFileSync(filePath, 'download me');
372 insertToken({ token: 'dl01', filePath });
373
374 const res = await get('/api/share/download/dl01');
375 expect(res.status).toBe(200);
376 const text = await res.text();
377 expect(text).toBe('download me');
378 });
379
380 test('downloads a directory as zip', async () =>
381 {
382 const dirPath = path.join(rootDir, 'zipit');
383 fs.mkdirSync(dirPath);
384 fs.writeFileSync(path.join(dirPath, 'a.txt'), 'aaa');
385 insertToken({ token: 'dl02', filePath: dirPath, isDir: 1 });
386
387 const res = await get('/api/share/download/dl02');
388 expect(res.status).toBe(200);
389 const ct = res.headers.get('content-type') || '';
390 // Express sends application/zip or application/octet-stream for .zip downloads
391 expect(ct.includes('zip') || ct.includes('octet')).toBe(true);
392 const buf = await res.arrayBuffer();
393 // ZIP magic bytes: PK\x03\x04
394 expect(new Uint8Array(buf.slice(0, 4))).toEqual(new Uint8Array([0x50, 0x4b, 0x03, 0x04]));
395 });
396
397 test('returns 410 for expired token', async () =>
398 {
399 const filePath = path.join(rootDir, 'edl.txt');
400 fs.writeFileSync(filePath, 'x');
401 insertToken({ token: 'dl03', filePath, expiresAt: Date.now() - 1 });
402
403 const res = await get('/api/share/download/dl03');
404 expect(res.status).toBe(410);
405 });
406
407 test('returns 404 for unknown token', async () =>
408 {
409 const res = await get('/api/share/download/nosuchtoken');
410 expect(res.status).toBe(404);
411 });
412});
413
414// ---------------------------------------------------------------------------
415// pruneZipCache
416// ---------------------------------------------------------------------------
417describe('pruneZipCache', () =>
418{
419 test('deletes zip files older than 1 day', () =>
420 {
421 const { pruneZipCache, ZIP_CACHE_DIR } = require('../server/routes/share');
422 fs.mkdirSync(ZIP_CACHE_DIR, { recursive: true });
423
424 const oldZip = path.join(ZIP_CACHE_DIR, 'old.zip');
425 fs.writeFileSync(oldZip, 'fake zip');
426 // Back-date the mtime by 25 hours
427 const pastTime = new Date(Date.now() - 25 * 60 * 60 * 1000);
428 fs.utimesSync(oldZip, pastTime, pastTime);
429
430 const freshZip = path.join(ZIP_CACHE_DIR, 'fresh.zip');
431 fs.writeFileSync(freshZip, 'fake fresh zip');
432
433 pruneZipCache();
434
435 expect(fs.existsSync(oldZip)).toBe(false);
436 expect(fs.existsSync(freshZip)).toBe(true);
437
438 // Cleanup
439 try { fs.unlinkSync(freshZip); } catch { /* ignore */ }
440 });
441});
442
443// ---------------------------------------------------------------------------
444// buildShareOpenGraphPage
445// ---------------------------------------------------------------------------
446describe('buildShareOpenGraphPage', () =>
447{
448 const { buildShareOpenGraphPage } = require('../server/routes/share');
449
450 const mockReq = {
451 protocol: 'https',
452 get: (header) =>
453 {
454 if (header === 'host') return 'example.com';
455 return null;
456 },
457 };
458
459 function insertToken ({ token, filePath, isDir = 0, expiresAt = Date.now() + 86400000 })
460 {
461 getDb()
462 .prepare('INSERT OR REPLACE INTO share_tokens (token, file_path, is_dir, created_by, created_at, expires_at) VALUES (?,?,?,?,?,?)')
463 .run([token, filePath, isDir, 'testuser', Date.now(), expiresAt]);
464 }
465
466 test('returns HTML page containing correct og:title for a valid file token', () =>
467 {
468 insertToken({ token: 'og-valid', filePath: '/data/report.pdf' });
469 const html = buildShareOpenGraphPage('og-valid', mockReq);
470 expect(html).toContain('<meta property="og:title" content="report.pdf"');
471 expect(html).toContain('<title>report.pdf</title>');
472 });
473
474 test('includes og:image and summary_large_image twitter:card for image files', () =>
475 {
476 insertToken({ token: 'og-img', filePath: '/data/photo.jpg' });
477 const html = buildShareOpenGraphPage('og-img', mockReq);
478 expect(html).toContain('property="og:image"');
479 expect(html).toContain('/api/share/preview/og-img');
480 expect(html).toContain('summary_large_image');
481 });
482
483 test('includes og:image for png files', () =>
484 {
485 insertToken({ token: 'og-png', filePath: '/data/banner.png' });
486 const html = buildShareOpenGraphPage('og-png', mockReq);
487 expect(html).toContain('property="og:image"');
488 });
489
490 test('includes og:image for webp files', () =>
491 {
492 insertToken({ token: 'og-webp', filePath: '/data/thumb.webp' });
493 const html = buildShareOpenGraphPage('og-webp', mockReq);
494 expect(html).toContain('property="og:image"');
495 });
496
497 test('does not include og:image for non-image files and uses summary twitter:card', () =>
498 {
499 insertToken({ token: 'og-video', filePath: '/data/movie.mkv' });
500 const html = buildShareOpenGraphPage('og-video', mockReq);
501 expect(html).not.toContain('property="og:image"');
502 expect(html).toContain('content="summary"');
503 });
504
505 test('does not include og:image for directory tokens', () =>
506 {
507 insertToken({ token: 'og-dir', filePath: '/data/photos', isDir: 1 });
508 const html = buildShareOpenGraphPage('og-dir', mockReq);
509 expect(html).not.toContain('property="og:image"');
510 });
511
512 test('returns "Link Expired" in og:title for an expired token', () =>
513 {
514 insertToken({ token: 'og-exp', filePath: '/data/old.jpg', expiresAt: Date.now() - 1000 });
515 const html = buildShareOpenGraphPage('og-exp', mockReq);
516 expect(html).toContain('content="Link Expired"');
517 expect(html).not.toContain('property="og:image"');
518 });
519
520 test('returns "Link Not Found" in og:title for an unknown token', () =>
521 {
522 const html = buildShareOpenGraphPage('does-not-exist', mockReq);
523 expect(html).toContain('content="Link Not Found"');
524 });
525
526 test('includes og:url pointing to the share page', () =>
527 {
528 insertToken({ token: 'og-url', filePath: '/data/file.txt' });
529 const html = buildShareOpenGraphPage('og-url', mockReq);
530 expect(html).toContain('https://example.com/share/og-url');
531 });
532
533 test('og:description mentions validity for a valid token', () =>
534 {
535 insertToken({ token: 'og-desc', filePath: '/data/doc.pdf', expiresAt: Date.now() + 7200000 });
536 const html = buildShareOpenGraphPage('og-desc', mockReq);
537 expect(html).toContain('Valid for');
538 });
539
540 test('retains the full share page client JS (not a bare meta-only response)', () =>
541 {
542 insertToken({ token: 'og-full', filePath: '/data/file.txt' });
543 const html = buildShareOpenGraphPage('og-full', mockReq);
544 // The interactive share page JS should still be present.
545 expect(html).toContain('api/share/info/');
546 });
547});