BlueGit

timfa filemanager

Files

filemanager / tests / files.routes.test.js

files.routes.test.js

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