BlueGit

timfa filemanager

Files

filemanager / tests / files.routes.test.js

files.routes.test.js

79ac5be9 History
files.routes.test.js 52.1 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 recursive chmod', () =>
693{
694 test('GET /api/files/list applies recursive chmod when enabled', async () =>
695 {
696 const nestedDir = path.join(rootDir, 'locked');
697 const nestedFile = path.join(nestedDir, 'data.txt');
698 fs.mkdirSync(nestedDir, { recursive: true });
699 fs.writeFileSync(nestedFile, 'hello');
700
701 fs.chmodSync(rootDir, 0o700);
702 fs.chmodSync(nestedDir, 0o700);
703 fs.chmodSync(nestedFile, 0o600);
704
705 process.env.FILEMANAGER_LIST_ACCESS_CHMOD = '1';
706
707 const listRes = await req('GET', `/api/files/list?dir=${encodeURIComponent(rootDir)}`);
708 expect(listRes.status).toBe(200);
709
710 const rootMode = fs.statSync(rootDir).mode & 0o777;
711 const dirMode = fs.statSync(nestedDir).mode & 0o777;
712 const fileMode = fs.statSync(nestedFile).mode & 0o777;
713
714 expect(rootMode).toBe(0o777);
715 expect(dirMode).toBe(0o777);
716 expect(fileMode).toBe(0o666);
717 });
718
719 test('GET /api/files/list leaves permissions unchanged when disabled', async () =>
720 {
721 const nestedDir = path.join(rootDir, 'locked');
722 const nestedFile = path.join(nestedDir, 'data.txt');
723 fs.mkdirSync(nestedDir, { recursive: true });
724 fs.writeFileSync(nestedFile, 'hello');
725
726 fs.chmodSync(rootDir, 0o700);
727 fs.chmodSync(nestedDir, 0o700);
728 fs.chmodSync(nestedFile, 0o600);
729
730 const listRes = await req('GET', `/api/files/list?dir=${encodeURIComponent(rootDir)}`);
731 expect(listRes.status).toBe(200);
732
733 const rootMode = fs.statSync(rootDir).mode & 0o777;
734 const dirMode = fs.statSync(nestedDir).mode & 0o777;
735 const fileMode = fs.statSync(nestedFile).mode & 0o777;
736
737 expect(rootMode).toBe(0o700);
738 expect(dirMode).toBe(0o700);
739 expect(fileMode).toBe(0o600);
740 });
741});
742
743describe('subtitle debug cache access', () =>
744{
745 test('admins can browse the subtitle debug cache folder', async () =>
746 {
747 const logDir = path.join(os.tmpdir(), 'filemanager-subtitle-debug-logs');
748 fs.rmSync(logDir, { recursive: true, force: true });
749 fs.mkdirSync(logDir, { recursive: true });
750 fs.writeFileSync(path.join(logDir, '2026-05-25-sample-subtitlelog.txt'), 'hello');
751
752 mockUser = {
753 username: 'admin',
754 isAdmin: true,
755 permissions: {},
756 };
757
758 try
759 {
760 const listRes = await req('GET', `/api/files/list?dir=${encodeURIComponent(logDir)}`);
761 expect(listRes.status).toBe(200);
762 expect(Array.isArray(listRes.body.items)).toBe(true);
763 expect(listRes.body.items.some((item) => item.name === '2026-05-25-sample-subtitlelog.txt')).toBe(true);
764 } finally
765 {
766 fs.rmSync(logDir, { recursive: true, force: true });
767 }
768 });
769
770 test('non-admin users cannot browse the subtitle debug cache folder', async () =>
771 {
772 const logDir = path.join(os.tmpdir(), 'filemanager-subtitle-debug-logs');
773 fs.rmSync(logDir, { recursive: true, force: true });
774 fs.mkdirSync(logDir, { recursive: true });
775
776 mockUser = {
777 username: 'alice',
778 isAdmin: false,
779 permissions: {},
780 };
781
782 try
783 {
784 const listRes = await req('GET', `/api/files/list?dir=${encodeURIComponent(logDir)}`);
785 expect(listRes.status).toBe(403);
786 } finally
787 {
788 fs.rmSync(logDir, { recursive: true, force: true });
789 }
790 });
791});
792
793describe('folder icon endpoints', () =>
794{
795 test('GET /api/files/folder-images returns files that have cached thumbnails', async () =>
796 {
797 const subDir = path.join(rootDir, 'photos');
798 fs.mkdirSync(subDir);
799 const imgPath = path.join(subDir, 'a.jpg');
800 fs.writeFileSync(imgPath, 'img');
801
802 mockFolderImages = [{ filePath: imgPath, thumbRelPath: 'thumbs/a.jpg.webp' }];
803
804 const { status, body } = await req('GET', `/api/files/folder-images?dir=${encodeURIComponent(rootDir)}`);
805 expect(status).toBe(200);
806 expect(body.images).toHaveLength(1);
807 expect(body.images[0].filePath).toBe(imgPath);
808 });
809
810 test('GET /api/files/folder-images includes video files with cached thumbnails', async () =>
811 {
812 const videoPath = path.join(rootDir, 'photos', 'clip.mp4');
813 fs.mkdirSync(path.dirname(videoPath), { recursive: true });
814 fs.writeFileSync(videoPath, 'video');
815
816 mockFolderImages = [{ filePath: videoPath, thumbRelPath: 'thumbs/clip.mp4.webp' }];
817
818 const { status, body } = await req('GET', `/api/files/folder-images?dir=${encodeURIComponent(rootDir)}`);
819 expect(status).toBe(200);
820 expect(body.images).toEqual([{ filePath: videoPath }]);
821 });
822
823 test('GET /api/files/folder-images returns empty list when no thumbnails available', async () =>
824 {
825 mockFolderImages = [];
826
827 const { status, body } = await req('GET', `/api/files/folder-images?dir=${encodeURIComponent(rootDir)}`);
828 expect(status).toBe(200);
829 expect(body.images).toEqual([]);
830 });
831
832 test('GET /api/files/folder-icon returns null when no icon available', async () =>
833 {
834 mockFolderIconFile = null;
835
836 const { status, body } = await req('GET', `/api/files/folder-icon?dir=${encodeURIComponent(rootDir)}`);
837 expect(status).toBe(200);
838 expect(body.icon).toBeNull();
839 });
840
841 test('GET /api/files/folder-icon returns source file path when icon is available', async () =>
842 {
843 const imgPath = path.join(rootDir, 'cover.jpg');
844 fs.writeFileSync(imgPath, 'img');
845 mockFolderIconFile = imgPath;
846
847 const { status, body } = await req('GET', `/api/files/folder-icon?dir=${encodeURIComponent(rootDir)}`);
848 expect(status).toBe(200);
849 expect(body.icon).toMatchObject({ filePath: imgPath });
850 });
851
852 test('POST /api/files/folder-icon sets explicit assignment when thumbnail is ready', async () =>
853 {
854 const imgPath = path.join(rootDir, 'cover.jpg');
855 const thumbFile = path.join(rootDir, 'cover.webp');
856 fs.writeFileSync(imgPath, 'img');
857 fs.writeFileSync(thumbFile, 'webp');
858 mockThumbPath = thumbFile;
859
860 const { status, body } = await req('POST', '/api/files/folder-icon', {
861 folderPath: rootDir,
862 imagePath: imgPath,
863 });
864 expect(status).toBe(200);
865 expect(body.ok).toBe(true);
866 expect(lastFolderIconAssignment).toEqual({ folderPath: rootDir, imagePath: imgPath });
867 });
868
869 test('POST /api/files/folder-icon rejects image without cached thumbnail', async () =>
870 {
871 const imgPath = path.join(rootDir, 'missing.jpg');
872 fs.writeFileSync(imgPath, 'img');
873 mockThumbPath = null;
874
875 const { status, body } = await req('POST', '/api/files/folder-icon', {
876 folderPath: rootDir,
877 imagePath: imgPath,
878 });
879 expect(status).toBe(404);
880 expect(body.error).toMatch(/thumbnail not ready/i);
881 });
882
883 test('POST /api/files/folder-icon clears assignment when imagePath is null', async () =>
884 {
885 const { status, body } = await req('POST', '/api/files/folder-icon', {
886 folderPath: rootDir,
887 imagePath: null,
888 });
889 expect(status).toBe(200);
890 expect(body.ok).toBe(true);
891 expect(lastFolderIconAssignment).toEqual({ folderPath: rootDir, imagePath: null });
892 });
893
894 test('POST /api/files/folder-icon returns 403 for read-only user', async () =>
895 {
896 const label = path.basename(rootDir);
897 mockUser = {
898 username: 'reader',
899 isAdmin: false,
900 permissions: { [label]: { read: true, write: false } },
901 };
902
903 const imgPath = path.join(rootDir, 'photo.jpg');
904 fs.writeFileSync(imgPath, 'img');
905
906 const { status } = await req('POST', '/api/files/folder-icon', {
907 folderPath: rootDir,
908 imagePath: imgPath,
909 });
910 expect(status).toBe(403);
911 });
912});
913
914describe('file search endpoint', () =>
915{
916 test('GET /api/files/search returns fuzzy-matched files across folders', async () =>
917 {
918 const movieDir = path.join(rootDir, 'Movies');
919 const docsDir = path.join(rootDir, 'Docs');
920 fs.mkdirSync(movieDir, { recursive: true });
921 fs.mkdirSync(docsDir, { recursive: true });
922 fs.writeFileSync(path.join(movieDir, 'Dragon Ball Super.mkv'), 'vid');
923 fs.writeFileSync(path.join(docsDir, 'notes.txt'), 'txt');
924
925 const { status, body } = await req('GET', '/api/files/search?query=dbs');
926 expect(status).toBe(200);
927 expect(body.query).toBe('dbs');
928 expect(body.results.length).toBeGreaterThan(0);
929 expect(body.results[0].name).toBe('Dragon Ball Super.mkv');
930 });
931
932 test('GET /api/files/search returns 400 when query is missing', async () =>
933 {
934 const { status } = await req('GET', '/api/files/search');
935 expect(status).toBe(400);
936 });
937});
938
939describe('image search endpoint', () =>
940{
941 test('GET /api/files/search-images returns thumbnailed image matches only', async () =>
942 {
943 const picsDir = path.join(rootDir, 'Pictures');
944 fs.mkdirSync(picsDir, { recursive: true });
945 fs.writeFileSync(path.join(picsDir, 'dragon-cover.jpg'), 'img');
946 fs.writeFileSync(path.join(picsDir, 'dragon-notes.txt'), 'txt');
947
948 const thumbPath = path.join(rootDir, 'thumb.webp');
949 fs.writeFileSync(thumbPath, 'thumb');
950 mockThumbPath = thumbPath;
951
952 const { status, body } = await req('GET', '/api/files/search-images?query=dragon');
953 expect(status).toBe(200);
954 expect(body.results.length).toBe(1);
955 expect(body.results[0].name).toBe('dragon-cover.jpg');
956 });
957
958 test('GET /api/files/search-images returns 400 for short queries', async () =>
959 {
960 const { status } = await req('GET', '/api/files/search-images?query=a');
961 expect(status).toBe(400);
962 });
963});
964
965describe('global favicon endpoints', () =>
966{
967 test('GET /api/files/global-favicon returns null when unset', async () =>
968 {
969 const { status, body } = await req('GET', '/api/files/global-favicon');
970 expect(status).toBe(200);
971 expect(body.favicon).toBeNull();
972 });
973
974 test('POST /api/files/global-favicon stores selected image path', async () =>
975 {
976 const imgPath = path.join(rootDir, 'cover.jpg');
977 const thumbPath = path.join(rootDir, 'cover.webp');
978 fs.writeFileSync(imgPath, 'img');
979 fs.writeFileSync(thumbPath, 'thumb');
980 mockThumbPath = thumbPath;
981
982 const { status, body } = await req('POST', '/api/files/global-favicon', { imagePath: imgPath });
983 expect(status).toBe(200);
984 expect(body.ok).toBe(true);
985 expect(mockGlobalFaviconPath).toBe(imgPath);
986
987 const fetched = await req('GET', '/api/files/global-favicon');
988 expect(fetched.status).toBe(200);
989 expect(fetched.body.favicon).toEqual({ filePath: imgPath });
990 });
991
992 test('POST /api/files/global-favicon clears the configured favicon', async () =>
993 {
994 mockGlobalFaviconPath = path.join(rootDir, 'old.jpg');
995
996 const { status, body } = await req('POST', '/api/files/global-favicon', { imagePath: null });
997 expect(status).toBe(200);
998 expect(body.ok).toBe(true);
999 expect(mockGlobalFaviconPath).toBeNull();
1000 });
1001
1002 test('POST /api/files/global-favicon is admin-only', async () =>
1003 {
1004 mockUser = { username: 'reader', isAdmin: false, permissions: {} };
1005 const imgPath = path.join(rootDir, 'cover.jpg');
1006 fs.writeFileSync(imgPath, 'img');
1007
1008 const { status } = await req('POST', '/api/files/global-favicon', { imagePath: imgPath });
1009 expect(status).toBe(403);
1010 });
1011});
1012
1013// ---------------------------------------------------------------------------
1014// GET /api/files/download-zip
1015// ---------------------------------------------------------------------------
1016describe('GET /api/files/download-zip', () =>
1017{
1018 beforeEach(() =>
1019 {
1020 mockUser = { username: 'admin', isAdmin: true, permissions: {} };
1021 });
1022
1023 test('streams a valid zip for an accessible directory', async () =>
1024 {
1025 const subDir = path.join(rootDir, 'zipme');
1026 fs.mkdirSync(subDir);
1027 fs.writeFileSync(path.join(subDir, 'file.txt'), 'content');
1028
1029 const { status, headers, body: buf } = await reqRaw('GET', `/api/files/download-zip?dir=${encodeURIComponent(subDir)}`);
1030 expect(status).toBe(200);
1031
1032 const ct = headers['content-type'] || '';
1033 expect(ct.includes('zip') || ct.includes('octet')).toBe(true);
1034
1035 // ZIP magic bytes PK\x03\x04
1036 expect(buf[0]).toBe(0x50);
1037 expect(buf[1]).toBe(0x4b);
1038 }, 20000);
1039
1040 test('returns 400 when dir param is missing', async () =>
1041 {
1042 const { status } = await req('GET', '/api/files/download-zip');
1043 expect(status).toBe(400);
1044 });
1045
1046 test('returns 404 for a non-existent directory', async () =>
1047 {
1048 const missing = path.join(rootDir, 'ghost');
1049 const { status } = await req('GET', `/api/files/download-zip?dir=${encodeURIComponent(missing)}`);
1050 expect(status).toBe(404);
1051 });
1052
1053 test('returns 403 for path outside configured roots', async () =>
1054 {
1055 const { status } = await req('GET', `/api/files/download-zip?dir=${encodeURIComponent(os.tmpdir())}`);
1056 expect(status).toBe(403);
1057 });
1058});
1059
1060describe('video streaming routes', () =>
1061{
1062 test('POST /api/files/video-stream creates a short-lived playlist session', async () =>
1063 {
1064 const filePath = path.join(rootDir, 'clip.mkv');
1065 fs.writeFileSync(filePath, 'video');
1066 mockVideoStreamSession = {
1067 sessionId: 'sess-123',
1068 durationSeconds: 42.25,
1069 videoWidth: 1920,
1070 videoHeight: 1080,
1071 subtitleTracks: [{ fileName: 'subtitle-0.vtt', label: 'English', language: 'eng', isDefault: true }],
1072 };
1073
1074 const { status, body } = await req('POST', '/api/files/video-stream', { filePath });
1075
1076 expect(status).toBe(200);
1077 expect(body.playlistUrl).toBe('/api/files/video-stream/sess-123/master.m3u8');
1078 expect(body.durationSeconds).toBe(42.25);
1079 expect(body.videoWidth).toBe(1920);
1080 expect(body.videoHeight).toBe(1080);
1081 expect(body.subtitleSummary).toEqual({ total: 0, converted: 0, imageBased: 0, skipped: 0 });
1082 expect(body.subtitleTracks).toEqual([
1083 {
1084 label: 'English',
1085 language: 'eng',
1086 default: true,
1087 src: '/api/files/video-stream/sess-123/subtitle-0.vtt',
1088 },
1089 ]);
1090 });
1091
1092 test('GET /api/files/video-stream/:sessionId/:assetPath serves HLS assets', async () =>
1093 {
1094 mockVideoStreamAsset = async (_sessionId, _assetPath, _req, res) =>
1095 {
1096 res.type('text/vtt').send('WEBVTT\n');
1097 };
1098
1099 const { status, headers, body } = await reqRaw('GET', '/api/files/video-stream/sess-123/subtitle-0.vtt');
1100
1101 expect(status).toBe(200);
1102 expect(headers['content-type']).toMatch(/text\/vtt/);
1103 expect(body.toString()).toBe('WEBVTT\n');
1104 });
1105
1106 test('DELETE /api/files/video-stream/:sessionId releases an active stream session', async () =>
1107 {
1108 const { status, body } = await req('DELETE', '/api/files/video-stream/sess-123');
1109
1110 expect(status).toBe(200);
1111 expect(body).toEqual({ ok: true });
1112 expect(releasedVideoStreamSessionId).toBe('sess-123');
1113 });
1114
1115 test('GET /api/files/video-stream-subtitle-frame returns rendered PNG frames', async () =>
1116 {
1117 const filePath = path.join(rootDir, 'clip.mkv');
1118 fs.writeFileSync(filePath, 'video');
1119 mockSubtitleFrameResult = {
1120 frame: Buffer.from('png-data'),
1121 left: 100,
1122 top: 50,
1123 width: 320,
1124 height: 180,
1125 canvasWidth: 640,
1126 canvasHeight: 360,
1127 startTimeSeconds: 1.5,
1128 endTimeSeconds: 3.2,
1129 };
1130
1131 const { status, headers, body } = await reqRaw(
1132 'GET',
1133 `/api/files/video-stream-subtitle-frame?filePath=${encodeURIComponent(filePath)}&streamIndex=0&timeSeconds=2.5&videoWidth=1920&videoHeight=1080`
1134 );
1135
1136 expect(status).toBe(200);
1137 expect(headers['content-type']).toMatch(/image\/png/);
1138 expect(headers['x-subtitle-frame-status']).toBe('ok');
1139 expect(headers['x-subtitle-frame-left']).toBe('100');
1140 expect(headers['x-subtitle-frame-top']).toBe('50');
1141 expect(headers['x-subtitle-frame-width']).toBe('320');
1142 expect(headers['x-subtitle-frame-height']).toBe('180');
1143 expect(headers['x-subtitle-frame-canvas-width']).toBe('640');
1144 expect(headers['x-subtitle-frame-canvas-height']).toBe('360');
1145 expect(headers['x-subtitle-frame-start-time']).toBe('1.5');
1146 expect(headers['x-subtitle-frame-end-time']).toBe('3.2');
1147 expect(Number(headers['x-subtitle-request-received-at-ms'])).toBeGreaterThan(0);
1148 expect(Number(headers['x-subtitle-response-sent-at-ms'])).toBeGreaterThan(0);
1149 expect(body.equals(Buffer.from('png-data'))).toBe(true);
1150 });
1151
1152 test('POST /api/files/video-stream-subtitle-log persists subtitle debug batches', async () =>
1153 {
1154 const filePath = path.join(rootDir, 'movie.mkv');
1155 fs.writeFileSync(filePath, 'video');
1156 const { appendSubtitleDebugEntries } = require('../server/subtitle-debug-log');
1157
1158 const { status, body } = await req('POST', '/api/files/video-stream-subtitle-log', {
1159 filePath,
1160 sessionId: 'sess-123',
1161 entries: [
1162 { loggedAtMs: 1000, eventType: 'subtitle_png_requested' },
1163 ],
1164 });
1165
1166 expect(status).toBe(200);
1167 expect(body).toEqual({ ok: true });
1168 expect(appendSubtitleDebugEntries).toHaveBeenCalledWith(expect.objectContaining({
1169 videoName: 'movie.mkv',
1170 context: expect.objectContaining({
1171 filePath,
1172 sessionId: 'sess-123',
1173 source: 'app',
1174 }),
1175 }));
1176 });
1177
1178 test('GET /api/files/video-stream-subtitle-frame returns 204 with none status when no subtitle is active', async () =>
1179 {
1180 const filePath = path.join(rootDir, 'clip.mkv');
1181 fs.writeFileSync(filePath, 'video');
1182 mockSubtitleFrameResult = null;
1183
1184 const { status, headers, body } = await reqRaw(
1185 'GET',
1186 `/api/files/video-stream-subtitle-frame?filePath=${encodeURIComponent(filePath)}&streamIndex=0&timeSeconds=2.5`
1187 );
1188
1189 expect(status).toBe(204);
1190 expect(headers['x-subtitle-frame-status']).toBe('none');
1191 expect(body.length).toBe(0);
1192 });
1193
1194 test('GET /api/files/video-stream-subtitle-frame returns 204 when rendering fails', async () =>
1195 {
1196 const filePath = path.join(rootDir, 'clip.mkv');
1197 fs.writeFileSync(filePath, 'video');
1198 mockSubtitleFrameError = new Error('decode failed');
1199
1200 const { status, headers, body } = await reqRaw(
1201 'GET',
1202 `/api/files/video-stream-subtitle-frame?filePath=${encodeURIComponent(filePath)}&streamIndex=0&timeSeconds=2.5`
1203 );
1204
1205 expect(status).toBe(204);
1206 expect(headers['x-subtitle-frame-status']).toBe('error');
1207 expect(body.length).toBe(0);
1208 });
1209
1210 test('POST /api/files/watch-progress stores per-user watched status by thresholds', async () =>
1211 {
1212 const filePath = path.join(rootDir, 'clip.mkv');
1213 fs.writeFileSync(filePath, 'video');
1214
1215 let result = await req('POST', '/api/files/watch-progress', { filePath, progress: 0.15 });
1216 expect(result.status).toBe(200);
1217 expect(result.body).toMatchObject({ ok: true, updated: true, status: 'partway' });
1218
1219 // A lower progress update should not downgrade the status.
1220 result = await req('POST', '/api/files/watch-progress', { filePath, progress: 0.2 });
1221 expect(result.status).toBe(200);
1222 expect(result.body).toMatchObject({ ok: true, updated: false, status: 'partway' });
1223
1224 result = await req('GET', `/api/files/meta?file=${encodeURIComponent(filePath)}`);
1225 expect(result.status).toBe(200);
1226 expect(result.body.watchedBy).toEqual({ admin: 'partway' });
1227
1228 result = await req('POST', '/api/files/watch-progress', { filePath, progress: 0.75 });
1229 expect(result.status).toBe(200);
1230 expect(result.body).toMatchObject({ ok: true, updated: true, status: 'fully' });
1231
1232 result = await req('GET', `/api/files/meta?file=${encodeURIComponent(filePath)}`);
1233 expect(result.status).toBe(200);
1234 expect(result.body.watchedBy).toEqual({ admin: 'fully' });
1235 });
1236
1237 test('POST /api/files/watched-statuses returns bulk watched statuses for accessible files', async () =>
1238 {
1239 const clipA = path.join(rootDir, 'clip-a.mkv');
1240 const clipB = path.join(rootDir, 'clip-b.mkv');
1241 const clipC = path.join(rootDir, 'clip-c.mkv');
1242 fs.writeFileSync(clipA, 'a');
1243 fs.writeFileSync(clipB, 'b');
1244 fs.writeFileSync(clipC, 'c');
1245
1246 const db = getDb();
1247 db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders, watched_by) VALUES (?, ?, ?, ?)')
1248 .run([clipA, '', '[]', JSON.stringify({ admin: 'fully' })]);
1249 db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders, watched_by) VALUES (?, ?, ?, ?)')
1250 .run([clipB, '', '[]', JSON.stringify({ admin: 'partway' })]);
1251 db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders, watched_by) VALUES (?, ?, ?, ?)')
1252 .run([clipC, '', '[]', JSON.stringify({ admin: 'none' })]);
1253
1254 const { status, body } = await req('POST', '/api/files/watched-statuses', {
1255 filePaths: [clipA, clipB, clipC],
1256 });
1257
1258 expect(status).toBe(200);
1259 expect(body.statuses).toEqual({
1260 [clipA]: 'fully',
1261 [clipB]: 'partway',
1262 });
1263 });
1264
1265 test('POST /api/files/watched-statuses validates filePaths input', async () =>
1266 {
1267 const { status, body } = await req('POST', '/api/files/watched-statuses', { filePaths: 'nope' });
1268 expect(status).toBe(400);
1269 expect(body.error).toMatch(/filePaths array is required/i);
1270 });
1271});
1272
1273describe('SHA-256 hashing and duplicate detection', () =>
1274{
1275 test('POST /api/files/upload stores sha256 hash for uploaded files', async () =>
1276 {
1277 const { status } = await reqMultipart(`/api/files/upload?dir=${encodeURIComponent(rootDir)}`, [
1278 { name: 'hashme.txt', content: 'hello hash', type: 'text/plain' },
1279 ]);
1280 expect(status).toBe(200);
1281
1282 const meta = getDb().prepare('SELECT sha256 FROM file_meta WHERE file_path = ?')
1283 .get([path.join(rootDir, 'hashme.txt')]);
1284 expect(meta).toBeTruthy();
1285 // SHA-256 is a 64-char hex string.
1286 expect(meta.sha256).toMatch(/^[0-9a-f]{64}$/);
1287 });
1288
1289 test('POST /api/files/upload stores uploaded_at for uploaded files', async () =>
1290 {
1291 const { status } = await reqMultipart(`/api/files/upload?dir=${encodeURIComponent(rootDir)}`, [
1292 { name: 'uploaded-at.txt', content: 'hello', type: 'text/plain' },
1293 ]);
1294 expect(status).toBe(200);
1295
1296 const meta = getDb().prepare('SELECT uploaded_at FROM file_meta WHERE file_path = ?')
1297 .get([path.join(rootDir, 'uploaded-at.txt')]);
1298 expect(meta).toBeTruthy();
1299 expect(String(meta.uploaded_at || '')).toMatch(/^\d{4}-\d{2}-\d{2}T/);
1300 });
1301
1302 test('GET /api/files/meta returns sha256 and computes it lazily when missing', async () =>
1303 {
1304 const filePath = path.join(rootDir, 'lazy.txt');
1305 fs.writeFileSync(filePath, 'lazy content');
1306
1307 // Insert a row without a hash to simulate a pre-existing file.
1308 getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders) VALUES (?, ?, ?)')
1309 .run([filePath, 'admin', '[]']);
1310
1311 const { status, body } = await req('GET', `/api/files/meta?file=${encodeURIComponent(filePath)}`);
1312 expect(status).toBe(200);
1313 expect(body.sha256).toMatch(/^[0-9a-f]{64}$/);
1314
1315 // Verify it was persisted.
1316 const row = getDb().prepare('SELECT sha256 FROM file_meta WHERE file_path = ?').get([filePath]);
1317 expect(row.sha256).toBe(body.sha256);
1318 });
1319
1320 test('GET /api/files/meta backfills uploaded_at when missing', async () =>
1321 {
1322 const filePath = path.join(rootDir, 'legacy.txt');
1323 fs.writeFileSync(filePath, 'legacy');
1324
1325 getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders) VALUES (?, ?, ?)')
1326 .run([filePath, 'admin', '[]']);
1327
1328 const { status, body } = await req('GET', `/api/files/meta?file=${encodeURIComponent(filePath)}`);
1329 expect(status).toBe(200);
1330 expect(String(body.uploadedAt || '')).toMatch(/^\d{4}-\d{2}-\d{2}T/);
1331
1332 const row = getDb().prepare('SELECT uploaded_at FROM file_meta WHERE file_path = ?').get([filePath]);
1333 expect(String(row.uploaded_at || '')).toBe(String(body.uploadedAt || ''));
1334 });
1335
1336 test('GET /api/files/duplicates returns other files with the same hash', async () =>
1337 {
1338 const content = 'duplicate content';
1339 const fileA = path.join(rootDir, 'dup-a.txt');
1340 const fileB = path.join(rootDir, 'dup-b.txt');
1341 fs.writeFileSync(fileA, content);
1342 fs.writeFileSync(fileB, content);
1343
1344 // Compute the expected hash.
1345 const crypto = require('crypto');
1346 const expectedHash = crypto.createHash('sha256').update(content).digest('hex');
1347
1348 getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders, sha256) VALUES (?, ?, ?, ?)')
1349 .run([fileA, 'admin', '[]', expectedHash]);
1350 getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders, sha256) VALUES (?, ?, ?, ?)')
1351 .run([fileB, 'admin', '[]', expectedHash]);
1352
1353 const { status, body } = await req('GET', `/api/files/duplicates?file=${encodeURIComponent(fileA)}`);
1354 expect(status).toBe(200);
1355 expect(body.duplicates).toHaveLength(1);
1356 expect(body.duplicates[0].path).toBe(fileB);
1357 expect(body.duplicates[0].name).toBe('dup-b.txt');
1358 });
1359
1360 test('GET /api/files/duplicates returns empty list when no hash is stored', async () =>
1361 {
1362 const filePath = path.join(rootDir, 'nohash.txt');
1363 fs.writeFileSync(filePath, 'no hash yet');
1364
1365 getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders) VALUES (?, ?, ?)')
1366 .run([filePath, 'admin', '[]']);
1367
1368 const { status, body } = await req('GET', `/api/files/duplicates?file=${encodeURIComponent(filePath)}`);
1369 expect(status).toBe(200);
1370 expect(body.duplicates).toEqual([]);
1371 });
1372
1373 test('GET /api/files/duplicates excludes files outside accessible roots', async () =>
1374 {
1375 const content = 'secret dupe';
1376 const accessible = path.join(rootDir, 'visible.txt');
1377 const outsideRoot = path.join(os.tmpdir(), 'outside.txt');
1378 fs.writeFileSync(accessible, content);
1379
1380 const crypto = require('crypto');
1381 const hash = crypto.createHash('sha256').update(content).digest('hex');
1382
1383 getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders, sha256) VALUES (?, ?, ?, ?)')
1384 .run([accessible, 'admin', '[]', hash]);
1385 // Insert a row for a path that is NOT inside any configured root.
1386 getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders, sha256) VALUES (?, ?, ?, ?)')
1387 .run([outsideRoot, 'admin', '[]', hash]);
1388
1389 const { status, body } = await req('GET', `/api/files/duplicates?file=${encodeURIComponent(accessible)}`);
1390 expect(status).toBe(200);
1391 expect(body.duplicates.every(d => d.path !== outsideRoot)).toBe(true);
1392 });
1393
1394 test('POST /api/files/move preserves sha256 after rename', async () =>
1395 {
1396 const from = path.join(rootDir, 'withHash.txt');
1397 const toDir = path.join(rootDir, 'subfolder');
1398 fs.writeFileSync(from, 'content');
1399 fs.mkdirSync(toDir);
1400
1401 const hash = 'a'.repeat(64);
1402 getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders, sha256) VALUES (?, ?, ?, ?)')
1403 .run([from, 'admin', '[]', hash]);
1404
1405 const { status } = await req('POST', '/api/files/move', { from, toDir });
1406 expect(status).toBe(200);
1407
1408 const meta = getDb().prepare('SELECT sha256 FROM file_meta WHERE file_path = ?')
1409 .get([path.join(toDir, 'withHash.txt')]);
1410 expect(meta.sha256).toBe(hash);
1411 });
1412});