BlueGit

timfa filemanager

Files

filemanager / tests / files.routes.test.js

files.routes.test.js

e2b05e95 History
files.routes.test.js 52.6 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 mockRootAliases = {};
13let mockGlobalFaviconPath = null;
14let mockUser = { username: 'admin', isAdmin: true, permissions: {} };
15let mockThumbPath = null;
16let mockFolderImages = [];
17let mockFolderIconFile = null;
18let lastFolderIconAssignment = undefined;
19let mockVideoStreamSession = null;
20let mockVideoStreamAsset = null;
21let releasedVideoStreamSessionId = null;
22let mockSubtitleFrameResult = null;
23let mockSubtitleFrameError = null;
24const mockSubtitleDebugLogDir = path.join(os.tmpdir(), 'filemanager-subtitle-debug-logs');
25
26jest.mock('../server/db', () =>
27{
28 const { Database } = require('node-sqlite3-wasm');
29 let db;
30 function getDb ()
31 {
32 if (!db)
33 {
34 db = new Database(':memory:');
35 db.exec(`
36 CREATE TABLE IF NOT EXISTS users (
37 id INTEGER PRIMARY KEY AUTOINCREMENT,
38 username TEXT UNIQUE NOT NULL,
39 password_hash TEXT NOT NULL,
40 is_admin INTEGER NOT NULL DEFAULT 0,
41 permissions TEXT NOT NULL DEFAULT '{}'
42 );
43 CREATE TABLE IF NOT EXISTS file_meta (
44 file_path TEXT PRIMARY KEY,
45 uploader TEXT NOT NULL DEFAULT '',
46 downloaders TEXT NOT NULL DEFAULT '[]',
47 watched_by TEXT NOT NULL DEFAULT '{}',
48 uploaded_at TEXT,
49 sha256 TEXT
50 );
51 CREATE INDEX IF NOT EXISTS idx_file_meta_sha256 ON file_meta(sha256);
52 `);
53 }
54 return db;
55 }
56 return { getDb, initDb: getDb };
57});
58
59jest.mock('../server/config', () => ({
60 loadConfig: () => ({
61 port: 3000,
62 paths: [...mockPaths],
63 userPath: mockUserPath,
64 rootAliases: { ...mockRootAliases },
65 globalFaviconPath: mockGlobalFaviconPath,
66 }),
67 saveConfig: (config) =>
68 {
69 mockPaths = [...(config.paths || [])];
70 mockRootAliases = { ...(config.rootAliases || {}) };
71 mockGlobalFaviconPath = config.globalFaviconPath || null;
72 },
73 getEffectivePaths: (paths) => paths,
74 getAllowedRoot: (targetPath, roots) =>
75 {
76 const path = require('path');
77 const absTarget = path.resolve(String(targetPath || ''));
78 return roots.find((root) =>
79 {
80 const absRoot = path.resolve(root);
81 return absTarget === absRoot || absTarget.startsWith(absRoot + path.sep);
82 }) || null;
83 },
84}));
85
86jest.mock('../server/auth', () => ({
87 requireAuth: (req, res, next) => { req.user = mockUser; next(); },
88}));
89
90jest.mock('../server/thumbnail-cache', () => ({
91 getCachedThumbnailInfo: async () =>
92 {
93 if (!mockThumbPath) return null;
94 return { thumbPath: mockThumbPath, contentType: 'image/webp' };
95 },
96 getFilesWithThumbnailsInDir: async () => mockFolderImages.slice(),
97 getFolderIconSourceFile: async () => mockFolderIconFile,
98 setFolderIconAssignment: async (folderPath, imagePath) =>
99 {
100 lastFolderIconAssignment = { folderPath, imagePath };
101 },
102}));
103
104jest.mock('../server/video-stream', () => ({
105 createVideoStreamSession: jest.fn(async () =>
106 {
107 if (mockVideoStreamSession instanceof Error) throw mockVideoStreamSession;
108 return mockVideoStreamSession || { sessionId: 'video-session', subtitleTracks: [] };
109 }),
110 sendVideoStreamAsset: jest.fn(async (sessionId, assetPath, req, res) =>
111 {
112 if (typeof mockVideoStreamAsset === 'function')
113 {
114 await mockVideoStreamAsset(sessionId, assetPath, req, res);
115 return;
116 }
117 res.type('application/vnd.apple.mpegurl').send('#EXTM3U\n');
118 }),
119 releaseVideoStreamSession: jest.fn((sessionId) =>
120 {
121 releasedVideoStreamSessionId = String(sessionId || '');
122 return true;
123 }),
124}));
125
126jest.mock('../server/image-subtitles', () => ({
127 renderImageSubtitleFrame: jest.fn(async () =>
128 {
129 if (mockSubtitleFrameError) throw mockSubtitleFrameError;
130 return mockSubtitleFrameResult;
131 }),
132}));
133
134jest.mock('../server/subtitle-debug-log', () => ({
135 SUBTITLE_DEBUG_LOG_DIR: mockSubtitleDebugLogDir,
136 appendSubtitleDebugEntries: jest.fn(),
137}));
138
139const filesRoutes = require('../server/routes/files');
140const { getDb } = require('../server/db');
141
142let server;
143let baseUrl;
144let rootDir;
145
146beforeAll(async () =>
147{
148 rootDir = fs.mkdtempSync(path.join(os.tmpdir(), 'filemanager-files-routes-'));
149 mockPaths = [rootDir];
150
151 const app = express();
152 app.use(express.json());
153 app.use('/api/files', filesRoutes);
154 app.use((err, req, res, next) =>
155 {
156 res.status(err.status || 500).json({ error: err.message || 'Internal error' });
157 });
158
159 server = http.createServer(app);
160 server.listen(0);
161 await once(server, 'listening');
162 baseUrl = `http://127.0.0.1:${server.address().port}`;
163});
164
165afterAll(() =>
166{
167 server.close();
168 fs.rmSync(rootDir, { recursive: true, force: true });
169});
170
171beforeEach(() =>
172{
173 delete process.env.FILEMANAGER_LIST_ACCESS_CHMOD;
174 delete process.env.FILEMANAGER_LIST_ACCESS_CHMOD_DIR_MODE;
175 delete process.env.FILEMANAGER_LIST_ACCESS_CHMOD_FILE_MODE;
176
177 fs.rmSync(rootDir, { recursive: true, force: true });
178 fs.mkdirSync(rootDir, { recursive: true });
179 if (mockUserPath)
180 {
181 fs.rmSync(mockUserPath, { recursive: true, force: true });
182 fs.mkdirSync(mockUserPath, { recursive: true });
183 }
184 mockRootAliases = {};
185 mockGlobalFaviconPath = null;
186 mockUserPath = null;
187 mockUser = { username: 'admin', isAdmin: true, permissions: {} };
188 mockThumbPath = null;
189 mockFolderImages = [];
190 mockFolderIconFile = null;
191 lastFolderIconAssignment = undefined;
192 mockVideoStreamSession = null;
193 mockVideoStreamAsset = null;
194 releasedVideoStreamSessionId = null;
195 mockSubtitleFrameResult = null;
196 mockSubtitleFrameError = null;
197 const db = getDb();
198 db.prepare('DELETE FROM file_meta').run([]);
199 db.prepare('DELETE FROM users').run([]);
200});
201
202function req (method, routePath, body)
203{
204 const payload = body ? JSON.stringify(body) : undefined;
205 return new Promise((resolve, reject) =>
206 {
207 const request = http.request(baseUrl + routePath, {
208 method,
209 headers: {
210 'Content-Type': 'application/json',
211 ...(payload ? { 'Content-Length': Buffer.byteLength(payload) } : {}),
212 },
213 }, res =>
214 {
215 let data = '';
216 res.on('data', chunk => data += chunk);
217 res.on('end', () => resolve({ status: res.statusCode, body: JSON.parse(data) }));
218 });
219 request.on('error', reject);
220 if (payload) request.write(payload);
221 request.end();
222 });
223}
224
225function reqRaw (method, routePath)
226{
227 return new Promise((resolve, reject) =>
228 {
229 const request = http.request(baseUrl + routePath, { method }, res =>
230 {
231 const chunks = [];
232 res.on('data', chunk => chunks.push(Buffer.from(chunk)));
233 res.on('end', () => resolve({
234 status: res.statusCode,
235 headers: res.headers,
236 body: Buffer.concat(chunks),
237 }));
238 });
239 request.on('error', reject);
240 request.end();
241 });
242}
243
244function reqMultipart (routePath, files, extraHeaders = {})
245{
246 const boundary = '----filemanager-test-boundary';
247 const buffers = [];
248
249 for (const file of files)
250 {
251 buffers.push(Buffer.from(
252 `--${boundary}\r\n`
253 + `Content-Disposition: form-data; name="files"; filename="${file.name}"\r\n`
254 + `Content-Type: ${file.type || 'application/octet-stream'}\r\n\r\n`
255 ));
256 buffers.push(Buffer.isBuffer(file.content) ? file.content : Buffer.from(String(file.content)));
257 buffers.push(Buffer.from('\r\n'));
258 }
259
260 buffers.push(Buffer.from(`--${boundary}--\r\n`));
261 const payload = Buffer.concat(buffers);
262
263 return new Promise((resolve, reject) =>
264 {
265 const request = http.request(baseUrl + routePath, {
266 method: 'POST',
267 headers: {
268 'Content-Type': `multipart/form-data; boundary=${boundary}`,
269 'Content-Length': payload.length,
270 ...extraHeaders,
271 },
272 }, res =>
273 {
274 let data = '';
275 res.on('data', chunk => data += chunk);
276 res.on('end', () => resolve({ status: res.statusCode, body: JSON.parse(data) }));
277 });
278 request.on('error', reject);
279 request.write(payload);
280 request.end();
281 });
282}
283
284function abortMultipartUpload (routePath, file)
285{
286 const boundary = '----filemanager-test-boundary-abort';
287 const header = Buffer.from(
288 `--${boundary}\r\n`
289 + `Content-Disposition: form-data; name="files"; filename="${file.name}"\r\n`
290 + `Content-Type: ${file.type || 'application/octet-stream'}\r\n\r\n`
291 );
292 const chunk = Buffer.isBuffer(file.content) ? file.content : Buffer.from(String(file.content));
293
294 return new Promise((resolve) =>
295 {
296 const request = http.request(baseUrl + routePath, {
297 method: 'POST',
298 headers: {
299 'Content-Type': `multipart/form-data; boundary=${boundary}`,
300 },
301 });
302
303 let settled = false;
304 const finish = () =>
305 {
306 if (settled) return;
307 settled = true;
308 resolve();
309 };
310
311 request.on('error', finish);
312 request.on('close', finish);
313 request.write(header);
314 request.write(chunk);
315 setTimeout(() => request.destroy(), 20);
316 });
317}
318
319async function waitFor (predicate, timeoutMs = 500)
320{
321 const start = Date.now();
322 while (Date.now() - start < timeoutMs)
323 {
324 if (predicate()) return;
325 await new Promise(resolve => setTimeout(resolve, 10));
326 }
327 throw new Error('Timed out waiting for condition.');
328}
329
330describe('POST /api/files/upload', () =>
331{
332 test('stores a completed upload under its final name', async () =>
333 {
334 const { status, body } = await reqMultipart(`/api/files/upload?dir=${encodeURIComponent(rootDir)}`, [
335 { name: 'hello.txt', content: 'hello world', type: 'text/plain' },
336 ]);
337
338 expect(status).toBe(200);
339 expect(body.uploaded).toEqual(['hello.txt']);
340 expect(fs.readFileSync(path.join(rootDir, 'hello.txt'), 'utf8')).toBe('hello world');
341
342 const meta = getDb().prepare('SELECT * FROM file_meta WHERE file_path = ?')
343 .get([path.join(rootDir, 'hello.txt')]);
344 expect(meta).toMatchObject({ uploader: 'admin' });
345 });
346
347 test('removes partial files when the upload connection aborts', async () =>
348 {
349 await abortMultipartUpload(`/api/files/upload?dir=${encodeURIComponent(rootDir)}`, {
350 name: 'partial.txt',
351 content: Buffer.alloc(256 * 1024, 'a'),
352 type: 'text/plain',
353 });
354
355 await waitFor(() => fs.readdirSync(rootDir).length === 0);
356
357 expect(fs.existsSync(path.join(rootDir, 'partial.txt'))).toBe(false);
358 expect(fs.readdirSync(rootDir)).toEqual([]);
359
360 const meta = getDb().prepare('SELECT * FROM file_meta WHERE file_path = ?')
361 .get([path.join(rootDir, 'partial.txt')]);
362 expect(meta).toBeFalsy();
363 });
364});
365
366describe('POST /api/files/move', () =>
367{
368 test('moves a file into another folder and rewrites metadata', async () =>
369 {
370 const from = path.join(rootDir, 'alpha.txt');
371 const toDir = path.join(rootDir, 'folder');
372 fs.writeFileSync(from, 'hello');
373 fs.mkdirSync(toDir);
374 const uploadedAt = '2026-05-18T12:00:00.000Z';
375
376 getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders, watched_by, uploaded_at, sha256) VALUES (?, ?, ?, ?, ?, ?)')
377 .run([from, 'admin', '["alice"]', '{"admin":"partway"}', uploadedAt, 'abc123']);
378
379 const { status, body } = await req('POST', '/api/files/move', { from, toDir });
380
381 expect(status).toBe(200);
382 expect(body.ok).toBe(true);
383 expect(fs.existsSync(from)).toBe(false);
384 expect(fs.existsSync(path.join(toDir, 'alpha.txt'))).toBe(true);
385
386 const meta = getDb().prepare('SELECT * FROM file_meta WHERE file_path = ?').get([path.join(toDir, 'alpha.txt')]);
387 expect(meta).toMatchObject({
388 uploader: 'admin',
389 downloaders: '["alice"]',
390 watched_by: '{"admin":"partway"}',
391 uploaded_at: uploadedAt,
392 sha256: 'abc123',
393 });
394 });
395
396 test('moves a folder into another folder and rewrites descendant metadata', async () =>
397 {
398 const fromDir = path.join(rootDir, 'src-folder');
399 const nestedFile = path.join(fromDir, 'child.txt');
400 const toDir = path.join(rootDir, 'dest-folder');
401 fs.mkdirSync(fromDir);
402 fs.mkdirSync(toDir);
403 fs.writeFileSync(nestedFile, 'hello');
404
405 getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders) VALUES (?, ?, ?)')
406 .run([nestedFile, 'admin', '[]']);
407
408 const { status } = await req('POST', '/api/files/move', { from: fromDir, toDir });
409
410 expect(status).toBe(200);
411 expect(fs.existsSync(fromDir)).toBe(false);
412 expect(fs.existsSync(path.join(toDir, 'src-folder', 'child.txt'))).toBe(true);
413
414 const movedMeta = getDb().prepare('SELECT * FROM file_meta WHERE file_path = ?')
415 .get([path.join(toDir, 'src-folder', 'child.txt')]);
416 expect(movedMeta).toBeTruthy();
417 });
418
419 test('rejects moving a folder into itself', async () =>
420 {
421 const fromDir = path.join(rootDir, 'src-folder');
422 const childDir = path.join(fromDir, 'child');
423 fs.mkdirSync(childDir, { recursive: true });
424
425 const { status, body } = await req('POST', '/api/files/move', { from: fromDir, toDir: childDir });
426
427 expect(status).toBe(400);
428 expect(body.error).toMatch(/folder into itself/i);
429 });
430
431 test('overwrites an existing destination when conflict strategy is overwrite', async () =>
432 {
433 const sourceFile = path.join(rootDir, 'source.txt');
434 const destinationDir = path.join(rootDir, 'dest');
435 fs.mkdirSync(destinationDir);
436 fs.writeFileSync(sourceFile, 'new-content');
437 fs.writeFileSync(path.join(destinationDir, 'source.txt'), 'old-content');
438
439 const { status, body } = await req('POST', '/api/files/move', {
440 from: sourceFile,
441 toDir: destinationDir,
442 conflict: 'overwrite',
443 });
444
445 expect(status).toBe(200);
446 expect(body.conflictResolution).toBe('overwrite');
447 expect(fs.existsSync(sourceFile)).toBe(false);
448 expect(fs.readFileSync(path.join(destinationDir, 'source.txt'), 'utf8')).toBe('new-content');
449 });
450
451 test('renames destination when conflict strategy is rename', async () =>
452 {
453 const sourceFile = path.join(rootDir, 'report.txt');
454 const destinationDir = path.join(rootDir, 'dest');
455 fs.mkdirSync(destinationDir);
456 fs.writeFileSync(sourceFile, 'latest');
457 fs.writeFileSync(path.join(destinationDir, 'report.txt'), 'existing');
458
459 const { status, body } = await req('POST', '/api/files/move', {
460 from: sourceFile,
461 toDir: destinationDir,
462 conflict: 'rename',
463 });
464
465 expect(status).toBe(200);
466 expect(body.conflictResolution).toBe('rename');
467 expect(path.basename(body.path)).toBe('report (1).txt');
468 expect(fs.readFileSync(body.path, 'utf8')).toBe('latest');
469 expect(fs.readFileSync(path.join(destinationDir, 'report.txt'), 'utf8')).toBe('existing');
470 });
471
472 test('moves a file into My Folder when rename falls back across filesystems', async () =>
473 {
474 const sourceFile = path.join(rootDir, 'cross-root.txt');
475 const userFolderBase = fs.mkdtempSync(path.join(os.tmpdir(), 'filemanager-userfolders-'));
476 const userFolder = path.join(userFolderBase, 'alice');
477
478 mockPaths = [rootDir];
479 mockUserPath = userFolderBase;
480 mockUser = {
481 username: 'alice',
482 isAdmin: false,
483 permissions: {
484 [path.basename(rootDir)]: { read: true, write: true },
485 },
486 };
487
488 fs.writeFileSync(sourceFile, 'hello');
489 fs.mkdirSync(userFolder, { recursive: true });
490
491 const originalRenameSync = fs.renameSync;
492 fs.renameSync = (from, to) =>
493 {
494 const err = new Error('cross-device move');
495 err.code = 'EXDEV';
496 throw err;
497 };
498
499 try
500 {
501 const { status, body } = await req('POST', '/api/files/move', { from: sourceFile, toDir: userFolder });
502
503 expect(status).toBe(200);
504 expect(body.path).toBe(path.join(userFolder, 'cross-root.txt'));
505 expect(fs.existsSync(sourceFile)).toBe(false);
506 expect(fs.readFileSync(path.join(userFolder, 'cross-root.txt'), 'utf8')).toBe('hello');
507 } finally
508 {
509 fs.renameSync = originalRenameSync;
510 fs.rmSync(userFolderBase, { recursive: true, force: true });
511 }
512 });
513});
514
515describe('root alias endpoints', () =>
516{
517 test('GET /api/files/roots returns alias label and original name', async () =>
518 {
519 mockRootAliases = { [path.resolve(rootDir)]: 'Workspace' };
520
521 const { status, body } = await req('GET', '/api/files/roots');
522
523 expect(status).toBe(200);
524 expect(body.roots).toHaveLength(1);
525 expect(body.roots[0]).toMatchObject({
526 path: rootDir,
527 label: 'Workspace',
528 alias: 'Workspace',
529 originalName: path.basename(rootDir),
530 });
531 });
532
533 test('POST /api/files/root-alias stores alias without renaming filesystem path', async () =>
534 {
535 const originalBase = path.basename(rootDir);
536 const { status, body } = await req('POST', '/api/files/root-alias', {
537 rootPath: rootDir,
538 alias: 'Shared Files',
539 });
540
541 expect(status).toBe(200);
542 expect(body.ok).toBe(true);
543 expect(body.root).toMatchObject({
544 path: rootDir,
545 label: 'Shared Files',
546 alias: 'Shared Files',
547 originalName: originalBase,
548 });
549 expect(fs.existsSync(rootDir)).toBe(true);
550
551 const afterRoots = await req('GET', '/api/files/roots');
552 expect(afterRoots.status).toBe(200);
553 expect(afterRoots.body.roots[0].label).toBe('Shared Files');
554 expect(afterRoots.body.roots[0].originalName).toBe(originalBase);
555 });
556
557 test('POST /api/files/root-alias rejects non-root paths', async () =>
558 {
559 const nested = path.join(rootDir, 'sub');
560 fs.mkdirSync(nested, { recursive: true });
561
562 const { status } = await req('POST', '/api/files/root-alias', {
563 rootPath: nested,
564 alias: 'Nested',
565 });
566
567 expect(status).toBe(400);
568 });
569});
570
571describe('GET /api/files/thumbnail', () =>
572{
573 test('returns 404 while cached thumbnail is not ready', async () =>
574 {
575 const source = path.join(rootDir, 'photo.jpg');
576 fs.writeFileSync(source, 'not-an-image');
577
578 const { status, body } = await req('GET', `/api/files/thumbnail?file=${encodeURIComponent(source)}`);
579 expect(status).toBe(404);
580 expect(body.error).toMatch(/not ready/i);
581 });
582
583 test('serves cached thumbnail file when available', async () =>
584 {
585 const source = path.join(rootDir, 'photo.jpg');
586 const thumb = path.join(rootDir, 'photo-thumb.webp');
587 fs.writeFileSync(source, 'not-an-image');
588 fs.writeFileSync(thumb, 'webp-bytes');
589 mockThumbPath = thumb;
590
591 const response = await reqRaw('GET', `/api/files/thumbnail?file=${encodeURIComponent(source)}`);
592 expect(response.status).toBe(200);
593 expect(String(response.headers['content-type'] || '')).toContain('image/webp');
594 expect(response.body.toString('utf8')).toBe('webp-bytes');
595 });
596});
597
598describe('GET /api/files/root-access', () =>
599{
600 test('returns users with R/R+W modes for an exact root path', async () =>
601 {
602 const label = path.basename(rootDir);
603 const db = getDb();
604 db.prepare('INSERT INTO users (username, password_hash, is_admin, permissions) VALUES (?, ?, ?, ?)')
605 .run(['admin', 'x', 1, '{}']);
606 db.prepare('INSERT INTO users (username, password_hash, is_admin, permissions) VALUES (?, ?, ?, ?)')
607 .run(['alice', 'x', 0, JSON.stringify({ [label]: { read: true, write: false } })]);
608 db.prepare('INSERT INTO users (username, password_hash, is_admin, permissions) VALUES (?, ?, ?, ?)')
609 .run(['bob', 'x', 0, JSON.stringify({ [label]: { read: true, write: true } })]);
610 db.prepare('INSERT INTO users (username, password_hash, is_admin, permissions) VALUES (?, ?, ?, ?)')
611 .run(['charlie', 'x', 0, JSON.stringify({ other: { read: true, write: false } })]);
612
613 const { status, body } = await req('GET', `/api/files/root-access?rootPath=${encodeURIComponent(rootDir)}`);
614 expect(status).toBe(200);
615 expect(body.root).toMatchObject({ path: rootDir, originalName: label });
616 expect(body.users).toEqual([
617 { username: 'admin', mode: 'R+W' },
618 { username: 'bob', mode: 'R+W' },
619 { username: 'alice', mode: 'R' },
620 ]);
621 });
622
623 test('rejects non-exact nested root paths', async () =>
624 {
625 const nested = path.join(rootDir, 'sub');
626 fs.mkdirSync(nested, { recursive: true });
627
628 const { status } = await req('GET', `/api/files/root-access?rootPath=${encodeURIComponent(nested)}`);
629 expect(status).toBe(400);
630 });
631});
632
633describe('orphaned user folder access', () =>
634{
635 test('admins can read and write in orphaned user folders', async () =>
636 {
637 const userFolderBase = fs.mkdtempSync(path.join(os.tmpdir(), 'filemanager-userfolders-'));
638 const orphanFolder = path.join(userFolderBase, 'ghost-user');
639 fs.mkdirSync(orphanFolder, { recursive: true });
640 fs.writeFileSync(path.join(orphanFolder, 'notes.txt'), 'hello');
641
642 mockUserPath = userFolderBase;
643 mockUser = {
644 username: 'admin',
645 isAdmin: true,
646 permissions: {},
647 };
648
649 try
650 {
651 const listRes = await req('GET', `/api/files/list?dir=${encodeURIComponent(orphanFolder)}`);
652 expect(listRes.status).toBe(200);
653 expect(Array.isArray(listRes.body.items)).toBe(true);
654 expect(listRes.body.items.some((item) => item.name === 'notes.txt')).toBe(true);
655
656 const mkdirRes = await req('POST', '/api/files/mkdir', {
657 dir: orphanFolder,
658 name: 'created-by-admin',
659 });
660 expect(mkdirRes.status).toBe(200);
661 expect(fs.existsSync(path.join(orphanFolder, 'created-by-admin'))).toBe(true);
662 } finally
663 {
664 fs.rmSync(userFolderBase, { recursive: true, force: true });
665 }
666 });
667
668 test('non-admin users cannot access orphaned user folders', async () =>
669 {
670 const userFolderBase = fs.mkdtempSync(path.join(os.tmpdir(), 'filemanager-userfolders-'));
671 const orphanFolder = path.join(userFolderBase, 'ghost-user');
672 fs.mkdirSync(orphanFolder, { recursive: true });
673
674 mockUserPath = userFolderBase;
675 mockUser = {
676 username: 'alice',
677 isAdmin: false,
678 permissions: {},
679 };
680
681 try
682 {
683 const listRes = await req('GET', `/api/files/list?dir=${encodeURIComponent(orphanFolder)}`);
684 expect(listRes.status).toBe(403);
685 } finally
686 {
687 fs.rmSync(userFolderBase, { recursive: true, force: true });
688 }
689 });
690});
691
692describe('list access chmod', () =>
693{
694 test('GET /api/files/list applies chmod to opened folder and direct children when enabled', async () =>
695 {
696 const nestedDir = path.join(rootDir, 'locked');
697 const nestedFile = path.join(nestedDir, 'data.txt');
698 const deepDir = path.join(nestedDir, 'deep');
699 const deepFile = path.join(deepDir, 'deep.txt');
700 fs.mkdirSync(nestedDir, { recursive: true });
701 fs.mkdirSync(deepDir, { recursive: true });
702 fs.writeFileSync(nestedFile, 'hello');
703 fs.writeFileSync(deepFile, 'deep');
704
705 fs.chmodSync(rootDir, 0o700);
706 fs.chmodSync(nestedDir, 0o700);
707 fs.chmodSync(nestedFile, 0o600);
708 fs.chmodSync(deepDir, 0o700);
709 fs.chmodSync(deepFile, 0o600);
710
711 process.env.FILEMANAGER_LIST_ACCESS_CHMOD = '1';
712
713 const listRes = await req('GET', `/api/files/list?dir=${encodeURIComponent(rootDir)}`);
714 expect(listRes.status).toBe(200);
715
716 const rootMode = fs.statSync(rootDir).mode & 0o777;
717 const dirMode = fs.statSync(nestedDir).mode & 0o777;
718 const fileMode = fs.statSync(nestedFile).mode & 0o777;
719 const deepDirMode = fs.statSync(deepDir).mode & 0o777;
720 const deepFileMode = fs.statSync(deepFile).mode & 0o777;
721
722 expect(rootMode).toBe(0o777);
723 expect(dirMode).toBe(0o777);
724 expect(fileMode).toBe(0o600);
725 expect(deepDirMode).toBe(0o700);
726 expect(deepFileMode).toBe(0o600);
727 });
728
729 test('GET /api/files/list leaves permissions unchanged when disabled', async () =>
730 {
731 const nestedDir = path.join(rootDir, 'locked');
732 const nestedFile = path.join(nestedDir, 'data.txt');
733 fs.mkdirSync(nestedDir, { recursive: true });
734 fs.writeFileSync(nestedFile, 'hello');
735
736 fs.chmodSync(rootDir, 0o700);
737 fs.chmodSync(nestedDir, 0o700);
738 fs.chmodSync(nestedFile, 0o600);
739
740 const listRes = await req('GET', `/api/files/list?dir=${encodeURIComponent(rootDir)}`);
741 expect(listRes.status).toBe(200);
742
743 const rootMode = fs.statSync(rootDir).mode & 0o777;
744 const dirMode = fs.statSync(nestedDir).mode & 0o777;
745 const fileMode = fs.statSync(nestedFile).mode & 0o777;
746
747 expect(rootMode).toBe(0o700);
748 expect(dirMode).toBe(0o700);
749 expect(fileMode).toBe(0o600);
750 });
751});
752
753describe('subtitle debug cache access', () =>
754{
755 test('admins can browse the subtitle debug cache folder', async () =>
756 {
757 const logDir = path.join(os.tmpdir(), 'filemanager-subtitle-debug-logs');
758 fs.rmSync(logDir, { recursive: true, force: true });
759 fs.mkdirSync(logDir, { recursive: true });
760 fs.writeFileSync(path.join(logDir, '2026-05-25-sample-subtitlelog.txt'), 'hello');
761
762 mockUser = {
763 username: 'admin',
764 isAdmin: true,
765 permissions: {},
766 };
767
768 try
769 {
770 const listRes = await req('GET', `/api/files/list?dir=${encodeURIComponent(logDir)}`);
771 expect(listRes.status).toBe(200);
772 expect(Array.isArray(listRes.body.items)).toBe(true);
773 expect(listRes.body.items.some((item) => item.name === '2026-05-25-sample-subtitlelog.txt')).toBe(true);
774 } finally
775 {
776 fs.rmSync(logDir, { recursive: true, force: true });
777 }
778 });
779
780 test('non-admin users cannot browse the subtitle debug cache folder', async () =>
781 {
782 const logDir = path.join(os.tmpdir(), 'filemanager-subtitle-debug-logs');
783 fs.rmSync(logDir, { recursive: true, force: true });
784 fs.mkdirSync(logDir, { recursive: true });
785
786 mockUser = {
787 username: 'alice',
788 isAdmin: false,
789 permissions: {},
790 };
791
792 try
793 {
794 const listRes = await req('GET', `/api/files/list?dir=${encodeURIComponent(logDir)}`);
795 expect(listRes.status).toBe(403);
796 } finally
797 {
798 fs.rmSync(logDir, { recursive: true, force: true });
799 }
800 });
801});
802
803describe('folder icon endpoints', () =>
804{
805 test('GET /api/files/folder-images returns files that have cached thumbnails', async () =>
806 {
807 const subDir = path.join(rootDir, 'photos');
808 fs.mkdirSync(subDir);
809 const imgPath = path.join(subDir, 'a.jpg');
810 fs.writeFileSync(imgPath, 'img');
811
812 mockFolderImages = [{ filePath: imgPath, thumbRelPath: 'thumbs/a.jpg.webp' }];
813
814 const { status, body } = await req('GET', `/api/files/folder-images?dir=${encodeURIComponent(rootDir)}`);
815 expect(status).toBe(200);
816 expect(body.images).toHaveLength(1);
817 expect(body.images[0].filePath).toBe(imgPath);
818 });
819
820 test('GET /api/files/folder-images includes video files with cached thumbnails', async () =>
821 {
822 const videoPath = path.join(rootDir, 'photos', 'clip.mp4');
823 fs.mkdirSync(path.dirname(videoPath), { recursive: true });
824 fs.writeFileSync(videoPath, 'video');
825
826 mockFolderImages = [{ filePath: videoPath, thumbRelPath: 'thumbs/clip.mp4.webp' }];
827
828 const { status, body } = await req('GET', `/api/files/folder-images?dir=${encodeURIComponent(rootDir)}`);
829 expect(status).toBe(200);
830 expect(body.images).toEqual([{ filePath: videoPath }]);
831 });
832
833 test('GET /api/files/folder-images returns empty list when no thumbnails available', async () =>
834 {
835 mockFolderImages = [];
836
837 const { status, body } = await req('GET', `/api/files/folder-images?dir=${encodeURIComponent(rootDir)}`);
838 expect(status).toBe(200);
839 expect(body.images).toEqual([]);
840 });
841
842 test('GET /api/files/folder-icon returns null when no icon available', async () =>
843 {
844 mockFolderIconFile = null;
845
846 const { status, body } = await req('GET', `/api/files/folder-icon?dir=${encodeURIComponent(rootDir)}`);
847 expect(status).toBe(200);
848 expect(body.icon).toBeNull();
849 });
850
851 test('GET /api/files/folder-icon returns source file path when icon is available', async () =>
852 {
853 const imgPath = path.join(rootDir, 'cover.jpg');
854 fs.writeFileSync(imgPath, 'img');
855 mockFolderIconFile = imgPath;
856
857 const { status, body } = await req('GET', `/api/files/folder-icon?dir=${encodeURIComponent(rootDir)}`);
858 expect(status).toBe(200);
859 expect(body.icon).toMatchObject({ filePath: imgPath });
860 });
861
862 test('POST /api/files/folder-icon sets explicit assignment when thumbnail is ready', async () =>
863 {
864 const imgPath = path.join(rootDir, 'cover.jpg');
865 const thumbFile = path.join(rootDir, 'cover.webp');
866 fs.writeFileSync(imgPath, 'img');
867 fs.writeFileSync(thumbFile, 'webp');
868 mockThumbPath = thumbFile;
869
870 const { status, body } = await req('POST', '/api/files/folder-icon', {
871 folderPath: rootDir,
872 imagePath: imgPath,
873 });
874 expect(status).toBe(200);
875 expect(body.ok).toBe(true);
876 expect(lastFolderIconAssignment).toEqual({ folderPath: rootDir, imagePath: imgPath });
877 });
878
879 test('POST /api/files/folder-icon rejects image without cached thumbnail', async () =>
880 {
881 const imgPath = path.join(rootDir, 'missing.jpg');
882 fs.writeFileSync(imgPath, 'img');
883 mockThumbPath = null;
884
885 const { status, body } = await req('POST', '/api/files/folder-icon', {
886 folderPath: rootDir,
887 imagePath: imgPath,
888 });
889 expect(status).toBe(404);
890 expect(body.error).toMatch(/thumbnail not ready/i);
891 });
892
893 test('POST /api/files/folder-icon clears assignment when imagePath is null', async () =>
894 {
895 const { status, body } = await req('POST', '/api/files/folder-icon', {
896 folderPath: rootDir,
897 imagePath: null,
898 });
899 expect(status).toBe(200);
900 expect(body.ok).toBe(true);
901 expect(lastFolderIconAssignment).toEqual({ folderPath: rootDir, imagePath: null });
902 });
903
904 test('POST /api/files/folder-icon returns 403 for read-only user', async () =>
905 {
906 const label = path.basename(rootDir);
907 mockUser = {
908 username: 'reader',
909 isAdmin: false,
910 permissions: { [label]: { read: true, write: false } },
911 };
912
913 const imgPath = path.join(rootDir, 'photo.jpg');
914 fs.writeFileSync(imgPath, 'img');
915
916 const { status } = await req('POST', '/api/files/folder-icon', {
917 folderPath: rootDir,
918 imagePath: imgPath,
919 });
920 expect(status).toBe(403);
921 });
922});
923
924describe('file search endpoint', () =>
925{
926 test('GET /api/files/search returns fuzzy-matched files across folders', async () =>
927 {
928 const movieDir = path.join(rootDir, 'Movies');
929 const docsDir = path.join(rootDir, 'Docs');
930 fs.mkdirSync(movieDir, { recursive: true });
931 fs.mkdirSync(docsDir, { recursive: true });
932 fs.writeFileSync(path.join(movieDir, 'Dragon Ball Super.mkv'), 'vid');
933 fs.writeFileSync(path.join(docsDir, 'notes.txt'), 'txt');
934
935 const { status, body } = await req('GET', '/api/files/search?query=dbs');
936 expect(status).toBe(200);
937 expect(body.query).toBe('dbs');
938 expect(body.results.length).toBeGreaterThan(0);
939 expect(body.results[0].name).toBe('Dragon Ball Super.mkv');
940 });
941
942 test('GET /api/files/search returns 400 when query is missing', async () =>
943 {
944 const { status } = await req('GET', '/api/files/search');
945 expect(status).toBe(400);
946 });
947});
948
949describe('image search endpoint', () =>
950{
951 test('GET /api/files/search-images returns thumbnailed image matches only', async () =>
952 {
953 const picsDir = path.join(rootDir, 'Pictures');
954 fs.mkdirSync(picsDir, { recursive: true });
955 fs.writeFileSync(path.join(picsDir, 'dragon-cover.jpg'), 'img');
956 fs.writeFileSync(path.join(picsDir, 'dragon-notes.txt'), 'txt');
957
958 const thumbPath = path.join(rootDir, 'thumb.webp');
959 fs.writeFileSync(thumbPath, 'thumb');
960 mockThumbPath = thumbPath;
961
962 const { status, body } = await req('GET', '/api/files/search-images?query=dragon');
963 expect(status).toBe(200);
964 expect(body.results.length).toBe(1);
965 expect(body.results[0].name).toBe('dragon-cover.jpg');
966 });
967
968 test('GET /api/files/search-images returns 400 for short queries', async () =>
969 {
970 const { status } = await req('GET', '/api/files/search-images?query=a');
971 expect(status).toBe(400);
972 });
973});
974
975describe('global favicon endpoints', () =>
976{
977 test('GET /api/files/global-favicon returns null when unset', async () =>
978 {
979 const { status, body } = await req('GET', '/api/files/global-favicon');
980 expect(status).toBe(200);
981 expect(body.favicon).toBeNull();
982 });
983
984 test('POST /api/files/global-favicon stores selected image path', async () =>
985 {
986 const imgPath = path.join(rootDir, 'cover.jpg');
987 const thumbPath = path.join(rootDir, 'cover.webp');
988 fs.writeFileSync(imgPath, 'img');
989 fs.writeFileSync(thumbPath, 'thumb');
990 mockThumbPath = thumbPath;
991
992 const { status, body } = await req('POST', '/api/files/global-favicon', { imagePath: imgPath });
993 expect(status).toBe(200);
994 expect(body.ok).toBe(true);
995 expect(mockGlobalFaviconPath).toBe(imgPath);
996
997 const fetched = await req('GET', '/api/files/global-favicon');
998 expect(fetched.status).toBe(200);
999 expect(fetched.body.favicon).toEqual({ filePath: imgPath });
1000 });
1001
1002 test('POST /api/files/global-favicon clears the configured favicon', async () =>
1003 {
1004 mockGlobalFaviconPath = path.join(rootDir, 'old.jpg');
1005
1006 const { status, body } = await req('POST', '/api/files/global-favicon', { imagePath: null });
1007 expect(status).toBe(200);
1008 expect(body.ok).toBe(true);
1009 expect(mockGlobalFaviconPath).toBeNull();
1010 });
1011
1012 test('POST /api/files/global-favicon is admin-only', async () =>
1013 {
1014 mockUser = { username: 'reader', isAdmin: false, permissions: {} };
1015 const imgPath = path.join(rootDir, 'cover.jpg');
1016 fs.writeFileSync(imgPath, 'img');
1017
1018 const { status } = await req('POST', '/api/files/global-favicon', { imagePath: imgPath });
1019 expect(status).toBe(403);
1020 });
1021});
1022
1023// ---------------------------------------------------------------------------
1024// GET /api/files/download-zip
1025// ---------------------------------------------------------------------------
1026describe('GET /api/files/download-zip', () =>
1027{
1028 beforeEach(() =>
1029 {
1030 mockUser = { username: 'admin', isAdmin: true, permissions: {} };
1031 });
1032
1033 test('streams a valid zip for an accessible directory', async () =>
1034 {
1035 const subDir = path.join(rootDir, 'zipme');
1036 fs.mkdirSync(subDir);
1037 fs.writeFileSync(path.join(subDir, 'file.txt'), 'content');
1038
1039 const { status, headers, body: buf } = await reqRaw('GET', `/api/files/download-zip?dir=${encodeURIComponent(subDir)}`);
1040 expect(status).toBe(200);
1041
1042 const ct = headers['content-type'] || '';
1043 expect(ct.includes('zip') || ct.includes('octet')).toBe(true);
1044
1045 // ZIP magic bytes PK\x03\x04
1046 expect(buf[0]).toBe(0x50);
1047 expect(buf[1]).toBe(0x4b);
1048 }, 20000);
1049
1050 test('returns 400 when dir param is missing', async () =>
1051 {
1052 const { status } = await req('GET', '/api/files/download-zip');
1053 expect(status).toBe(400);
1054 });
1055
1056 test('returns 404 for a non-existent directory', async () =>
1057 {
1058 const missing = path.join(rootDir, 'ghost');
1059 const { status } = await req('GET', `/api/files/download-zip?dir=${encodeURIComponent(missing)}`);
1060 expect(status).toBe(404);
1061 });
1062
1063 test('returns 403 for path outside configured roots', async () =>
1064 {
1065 const { status } = await req('GET', `/api/files/download-zip?dir=${encodeURIComponent(os.tmpdir())}`);
1066 expect(status).toBe(403);
1067 });
1068});
1069
1070describe('video streaming routes', () =>
1071{
1072 test('POST /api/files/video-stream creates a short-lived playlist session', async () =>
1073 {
1074 const filePath = path.join(rootDir, 'clip.mkv');
1075 fs.writeFileSync(filePath, 'video');
1076 mockVideoStreamSession = {
1077 sessionId: 'sess-123',
1078 durationSeconds: 42.25,
1079 videoWidth: 1920,
1080 videoHeight: 1080,
1081 subtitleTracks: [{ fileName: 'subtitle-0.vtt', label: 'English', language: 'eng', isDefault: true }],
1082 };
1083
1084 const { status, body } = await req('POST', '/api/files/video-stream', { filePath });
1085
1086 expect(status).toBe(200);
1087 expect(body.playlistUrl).toBe('/api/files/video-stream/sess-123/master.m3u8');
1088 expect(body.durationSeconds).toBe(42.25);
1089 expect(body.videoWidth).toBe(1920);
1090 expect(body.videoHeight).toBe(1080);
1091 expect(body.subtitleSummary).toEqual({ total: 0, converted: 0, imageBased: 0, skipped: 0 });
1092 expect(body.subtitleTracks).toEqual([
1093 {
1094 label: 'English',
1095 language: 'eng',
1096 default: true,
1097 src: '/api/files/video-stream/sess-123/subtitle-0.vtt',
1098 },
1099 ]);
1100 });
1101
1102 test('GET /api/files/video-stream/:sessionId/:assetPath serves HLS assets', async () =>
1103 {
1104 mockVideoStreamAsset = async (_sessionId, _assetPath, _req, res) =>
1105 {
1106 res.type('text/vtt').send('WEBVTT\n');
1107 };
1108
1109 const { status, headers, body } = await reqRaw('GET', '/api/files/video-stream/sess-123/subtitle-0.vtt');
1110
1111 expect(status).toBe(200);
1112 expect(headers['content-type']).toMatch(/text\/vtt/);
1113 expect(body.toString()).toBe('WEBVTT\n');
1114 });
1115
1116 test('DELETE /api/files/video-stream/:sessionId releases an active stream session', async () =>
1117 {
1118 const { status, body } = await req('DELETE', '/api/files/video-stream/sess-123');
1119
1120 expect(status).toBe(200);
1121 expect(body).toEqual({ ok: true });
1122 expect(releasedVideoStreamSessionId).toBe('sess-123');
1123 });
1124
1125 test('GET /api/files/video-stream-subtitle-frame returns rendered PNG frames', async () =>
1126 {
1127 const filePath = path.join(rootDir, 'clip.mkv');
1128 fs.writeFileSync(filePath, 'video');
1129 mockSubtitleFrameResult = {
1130 frame: Buffer.from('png-data'),
1131 left: 100,
1132 top: 50,
1133 width: 320,
1134 height: 180,
1135 canvasWidth: 640,
1136 canvasHeight: 360,
1137 startTimeSeconds: 1.5,
1138 endTimeSeconds: 3.2,
1139 };
1140
1141 const { status, headers, body } = await reqRaw(
1142 'GET',
1143 `/api/files/video-stream-subtitle-frame?filePath=${encodeURIComponent(filePath)}&streamIndex=0&timeSeconds=2.5&videoWidth=1920&videoHeight=1080`
1144 );
1145
1146 expect(status).toBe(200);
1147 expect(headers['content-type']).toMatch(/image\/png/);
1148 expect(headers['x-subtitle-frame-status']).toBe('ok');
1149 expect(headers['x-subtitle-frame-left']).toBe('100');
1150 expect(headers['x-subtitle-frame-top']).toBe('50');
1151 expect(headers['x-subtitle-frame-width']).toBe('320');
1152 expect(headers['x-subtitle-frame-height']).toBe('180');
1153 expect(headers['x-subtitle-frame-canvas-width']).toBe('640');
1154 expect(headers['x-subtitle-frame-canvas-height']).toBe('360');
1155 expect(headers['x-subtitle-frame-start-time']).toBe('1.5');
1156 expect(headers['x-subtitle-frame-end-time']).toBe('3.2');
1157 expect(Number(headers['x-subtitle-request-received-at-ms'])).toBeGreaterThan(0);
1158 expect(Number(headers['x-subtitle-response-sent-at-ms'])).toBeGreaterThan(0);
1159 expect(body.equals(Buffer.from('png-data'))).toBe(true);
1160 });
1161
1162 test('POST /api/files/video-stream-subtitle-log persists subtitle debug batches', async () =>
1163 {
1164 const filePath = path.join(rootDir, 'movie.mkv');
1165 fs.writeFileSync(filePath, 'video');
1166 const { appendSubtitleDebugEntries } = require('../server/subtitle-debug-log');
1167
1168 const { status, body } = await req('POST', '/api/files/video-stream-subtitle-log', {
1169 filePath,
1170 sessionId: 'sess-123',
1171 entries: [
1172 { loggedAtMs: 1000, eventType: 'subtitle_png_requested' },
1173 ],
1174 });
1175
1176 expect(status).toBe(200);
1177 expect(body).toEqual({ ok: true });
1178 expect(appendSubtitleDebugEntries).toHaveBeenCalledWith(expect.objectContaining({
1179 videoName: 'movie.mkv',
1180 context: expect.objectContaining({
1181 filePath,
1182 sessionId: 'sess-123',
1183 source: 'app',
1184 }),
1185 }));
1186 });
1187
1188 test('GET /api/files/video-stream-subtitle-frame returns 204 with none status when no subtitle is active', async () =>
1189 {
1190 const filePath = path.join(rootDir, 'clip.mkv');
1191 fs.writeFileSync(filePath, 'video');
1192 mockSubtitleFrameResult = null;
1193
1194 const { status, headers, body } = await reqRaw(
1195 'GET',
1196 `/api/files/video-stream-subtitle-frame?filePath=${encodeURIComponent(filePath)}&streamIndex=0&timeSeconds=2.5`
1197 );
1198
1199 expect(status).toBe(204);
1200 expect(headers['x-subtitle-frame-status']).toBe('none');
1201 expect(body.length).toBe(0);
1202 });
1203
1204 test('GET /api/files/video-stream-subtitle-frame returns 204 when rendering fails', async () =>
1205 {
1206 const filePath = path.join(rootDir, 'clip.mkv');
1207 fs.writeFileSync(filePath, 'video');
1208 mockSubtitleFrameError = new Error('decode failed');
1209
1210 const { status, headers, body } = await reqRaw(
1211 'GET',
1212 `/api/files/video-stream-subtitle-frame?filePath=${encodeURIComponent(filePath)}&streamIndex=0&timeSeconds=2.5`
1213 );
1214
1215 expect(status).toBe(204);
1216 expect(headers['x-subtitle-frame-status']).toBe('error');
1217 expect(body.length).toBe(0);
1218 });
1219
1220 test('POST /api/files/watch-progress stores per-user watched status by thresholds', async () =>
1221 {
1222 const filePath = path.join(rootDir, 'clip.mkv');
1223 fs.writeFileSync(filePath, 'video');
1224
1225 let result = await req('POST', '/api/files/watch-progress', { filePath, progress: 0.15 });
1226 expect(result.status).toBe(200);
1227 expect(result.body).toMatchObject({ ok: true, updated: true, status: 'partway' });
1228
1229 // A lower progress update should not downgrade the status.
1230 result = await req('POST', '/api/files/watch-progress', { filePath, progress: 0.2 });
1231 expect(result.status).toBe(200);
1232 expect(result.body).toMatchObject({ ok: true, updated: false, status: 'partway' });
1233
1234 result = await req('GET', `/api/files/meta?file=${encodeURIComponent(filePath)}`);
1235 expect(result.status).toBe(200);
1236 expect(result.body.watchedBy).toEqual({ admin: 'partway' });
1237
1238 result = await req('POST', '/api/files/watch-progress', { filePath, progress: 0.75 });
1239 expect(result.status).toBe(200);
1240 expect(result.body).toMatchObject({ ok: true, updated: true, status: 'fully' });
1241
1242 result = await req('GET', `/api/files/meta?file=${encodeURIComponent(filePath)}`);
1243 expect(result.status).toBe(200);
1244 expect(result.body.watchedBy).toEqual({ admin: 'fully' });
1245 });
1246
1247 test('POST /api/files/watched-statuses returns bulk watched statuses for accessible files', async () =>
1248 {
1249 const clipA = path.join(rootDir, 'clip-a.mkv');
1250 const clipB = path.join(rootDir, 'clip-b.mkv');
1251 const clipC = path.join(rootDir, 'clip-c.mkv');
1252 fs.writeFileSync(clipA, 'a');
1253 fs.writeFileSync(clipB, 'b');
1254 fs.writeFileSync(clipC, 'c');
1255
1256 const db = getDb();
1257 db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders, watched_by) VALUES (?, ?, ?, ?)')
1258 .run([clipA, '', '[]', JSON.stringify({ admin: 'fully' })]);
1259 db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders, watched_by) VALUES (?, ?, ?, ?)')
1260 .run([clipB, '', '[]', JSON.stringify({ admin: 'partway' })]);
1261 db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders, watched_by) VALUES (?, ?, ?, ?)')
1262 .run([clipC, '', '[]', JSON.stringify({ admin: 'none' })]);
1263
1264 const { status, body } = await req('POST', '/api/files/watched-statuses', {
1265 filePaths: [clipA, clipB, clipC],
1266 });
1267
1268 expect(status).toBe(200);
1269 expect(body.statuses).toEqual({
1270 [clipA]: 'fully',
1271 [clipB]: 'partway',
1272 });
1273 });
1274
1275 test('POST /api/files/watched-statuses validates filePaths input', async () =>
1276 {
1277 const { status, body } = await req('POST', '/api/files/watched-statuses', { filePaths: 'nope' });
1278 expect(status).toBe(400);
1279 expect(body.error).toMatch(/filePaths array is required/i);
1280 });
1281});
1282
1283describe('SHA-256 hashing and duplicate detection', () =>
1284{
1285 test('POST /api/files/upload stores sha256 hash for uploaded files', async () =>
1286 {
1287 const { status } = await reqMultipart(`/api/files/upload?dir=${encodeURIComponent(rootDir)}`, [
1288 { name: 'hashme.txt', content: 'hello hash', type: 'text/plain' },
1289 ]);
1290 expect(status).toBe(200);
1291
1292 const meta = getDb().prepare('SELECT sha256 FROM file_meta WHERE file_path = ?')
1293 .get([path.join(rootDir, 'hashme.txt')]);
1294 expect(meta).toBeTruthy();
1295 // SHA-256 is a 64-char hex string.
1296 expect(meta.sha256).toMatch(/^[0-9a-f]{64}$/);
1297 });
1298
1299 test('POST /api/files/upload stores uploaded_at for uploaded files', async () =>
1300 {
1301 const { status } = await reqMultipart(`/api/files/upload?dir=${encodeURIComponent(rootDir)}`, [
1302 { name: 'uploaded-at.txt', content: 'hello', type: 'text/plain' },
1303 ]);
1304 expect(status).toBe(200);
1305
1306 const meta = getDb().prepare('SELECT uploaded_at FROM file_meta WHERE file_path = ?')
1307 .get([path.join(rootDir, 'uploaded-at.txt')]);
1308 expect(meta).toBeTruthy();
1309 expect(String(meta.uploaded_at || '')).toMatch(/^\d{4}-\d{2}-\d{2}T/);
1310 });
1311
1312 test('GET /api/files/meta returns sha256 and computes it lazily when missing', async () =>
1313 {
1314 const filePath = path.join(rootDir, 'lazy.txt');
1315 fs.writeFileSync(filePath, 'lazy content');
1316
1317 // Insert a row without a hash to simulate a pre-existing file.
1318 getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders) VALUES (?, ?, ?)')
1319 .run([filePath, 'admin', '[]']);
1320
1321 const { status, body } = await req('GET', `/api/files/meta?file=${encodeURIComponent(filePath)}`);
1322 expect(status).toBe(200);
1323 expect(body.sha256).toMatch(/^[0-9a-f]{64}$/);
1324
1325 // Verify it was persisted.
1326 const row = getDb().prepare('SELECT sha256 FROM file_meta WHERE file_path = ?').get([filePath]);
1327 expect(row.sha256).toBe(body.sha256);
1328 });
1329
1330 test('GET /api/files/meta backfills uploaded_at when missing', async () =>
1331 {
1332 const filePath = path.join(rootDir, 'legacy.txt');
1333 fs.writeFileSync(filePath, 'legacy');
1334
1335 getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders) VALUES (?, ?, ?)')
1336 .run([filePath, 'admin', '[]']);
1337
1338 const { status, body } = await req('GET', `/api/files/meta?file=${encodeURIComponent(filePath)}`);
1339 expect(status).toBe(200);
1340 expect(String(body.uploadedAt || '')).toMatch(/^\d{4}-\d{2}-\d{2}T/);
1341
1342 const row = getDb().prepare('SELECT uploaded_at FROM file_meta WHERE file_path = ?').get([filePath]);
1343 expect(String(row.uploaded_at || '')).toBe(String(body.uploadedAt || ''));
1344 });
1345
1346 test('GET /api/files/duplicates returns other files with the same hash', async () =>
1347 {
1348 const content = 'duplicate content';
1349 const fileA = path.join(rootDir, 'dup-a.txt');
1350 const fileB = path.join(rootDir, 'dup-b.txt');
1351 fs.writeFileSync(fileA, content);
1352 fs.writeFileSync(fileB, content);
1353
1354 // Compute the expected hash.
1355 const crypto = require('crypto');
1356 const expectedHash = crypto.createHash('sha256').update(content).digest('hex');
1357
1358 getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders, sha256) VALUES (?, ?, ?, ?)')
1359 .run([fileA, 'admin', '[]', expectedHash]);
1360 getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders, sha256) VALUES (?, ?, ?, ?)')
1361 .run([fileB, 'admin', '[]', expectedHash]);
1362
1363 const { status, body } = await req('GET', `/api/files/duplicates?file=${encodeURIComponent(fileA)}`);
1364 expect(status).toBe(200);
1365 expect(body.duplicates).toHaveLength(1);
1366 expect(body.duplicates[0].path).toBe(fileB);
1367 expect(body.duplicates[0].name).toBe('dup-b.txt');
1368 });
1369
1370 test('GET /api/files/duplicates returns empty list when no hash is stored', async () =>
1371 {
1372 const filePath = path.join(rootDir, 'nohash.txt');
1373 fs.writeFileSync(filePath, 'no hash yet');
1374
1375 getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders) VALUES (?, ?, ?)')
1376 .run([filePath, 'admin', '[]']);
1377
1378 const { status, body } = await req('GET', `/api/files/duplicates?file=${encodeURIComponent(filePath)}`);
1379 expect(status).toBe(200);
1380 expect(body.duplicates).toEqual([]);
1381 });
1382
1383 test('GET /api/files/duplicates excludes files outside accessible roots', async () =>
1384 {
1385 const content = 'secret dupe';
1386 const accessible = path.join(rootDir, 'visible.txt');
1387 const outsideRoot = path.join(os.tmpdir(), 'outside.txt');
1388 fs.writeFileSync(accessible, content);
1389
1390 const crypto = require('crypto');
1391 const hash = crypto.createHash('sha256').update(content).digest('hex');
1392
1393 getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders, sha256) VALUES (?, ?, ?, ?)')
1394 .run([accessible, 'admin', '[]', hash]);
1395 // Insert a row for a path that is NOT inside any configured root.
1396 getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders, sha256) VALUES (?, ?, ?, ?)')
1397 .run([outsideRoot, 'admin', '[]', hash]);
1398
1399 const { status, body } = await req('GET', `/api/files/duplicates?file=${encodeURIComponent(accessible)}`);
1400 expect(status).toBe(200);
1401 expect(body.duplicates.every(d => d.path !== outsideRoot)).toBe(true);
1402 });
1403
1404 test('POST /api/files/move preserves sha256 after rename', async () =>
1405 {
1406 const from = path.join(rootDir, 'withHash.txt');
1407 const toDir = path.join(rootDir, 'subfolder');
1408 fs.writeFileSync(from, 'content');
1409 fs.mkdirSync(toDir);
1410
1411 const hash = 'a'.repeat(64);
1412 getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders, sha256) VALUES (?, ?, ?, ?)')
1413 .run([from, 'admin', '[]', hash]);
1414
1415 const { status } = await req('POST', '/api/files/move', { from, toDir });
1416 expect(status).toBe(200);
1417
1418 const meta = getDb().prepare('SELECT sha256 FROM file_meta WHERE file_path = ?')
1419 .get([path.join(toDir, 'withHash.txt')]);
1420 expect(meta.sha256).toBe(hash);
1421 });
1422});