BlueGit

timfa filemanager

Files

filemanager / tests / share.routes.test.js

share.routes.test.js

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