BlueGit

timfa filemanager

Files

filemanager / tests / share.routes.test.js

share.routes.test.js

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